1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gmain.c: Main loop abstraction, timeouts, and idle functions
5  * Copyright 1998 Owen Taylor
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 /*
22  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
23  * file for a list of people on the GLib Team.  See the ChangeLog
24  * files for a list of changes.  These files are distributed with
25  * GLib at ftp://ftp.gtk.org/pub/gtk/.
26  */
27 
28 /*
29  * MT safe
30  */
31 
32 #include "config.h"
33 #include "glibconfig.h"
34 #include "glib_trace.h"
35 
36 /* Uncomment the next line (and the corresponding line in gpoll.c) to
37  * enable debugging printouts if the environment variable
38  * G_MAIN_POLL_DEBUG is set to some value.
39  */
40 /* #define G_MAIN_POLL_DEBUG */
41 
42 #ifdef _WIN32
43 /* Always enable debugging printout on Windows, as it is more often
44  * needed there...
45  */
46 #define G_MAIN_POLL_DEBUG
47 #endif
48 
49 #ifdef G_OS_UNIX
50 #include "glib-unix.h"
51 #include <pthread.h>
52 #ifdef HAVE_EVENTFD
53 #include <sys/eventfd.h>
54 #endif
55 #endif
56 
57 #include <signal.h>
58 #include <sys/types.h>
59 #include <time.h>
60 #include <stdlib.h>
61 #ifdef HAVE_SYS_TIME_H
62 #include <sys/time.h>
63 #endif /* HAVE_SYS_TIME_H */
64 #ifdef G_OS_UNIX
65 #include <unistd.h>
66 #endif /* G_OS_UNIX */
67 #include <errno.h>
68 #include <string.h>
69 
70 #ifdef G_OS_WIN32
71 #define STRICT
72 #include <windows.h>
73 #endif /* G_OS_WIN32 */
74 
75 #ifdef HAVE_MACH_MACH_TIME_H
76 #include <mach/mach_time.h>
77 #endif
78 
79 #include "glib_trace.h"
80 
81 #include "gmain.h"
82 
83 #include "garray.h"
84 #include "giochannel.h"
85 #include "ghash.h"
86 #include "ghook.h"
87 #include "gqueue.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
90 #include "gthreadprivate.h"
91 #include "gtrace-private.h"
92 
93 #ifdef G_OS_WIN32
94 #include "gwin32.h"
95 #endif
96 
97 #ifdef  G_MAIN_POLL_DEBUG
98 #include "gtimer.h"
99 #endif
100 
101 #include "gwakeup.h"
102 #include "gmain-internal.h"
103 #include "glib-init.h"
104 #include "glib-private.h"
105 
106 /**
107  * SECTION:main
108  * @title: The Main Event Loop
109  * @short_description: manages all available sources of events
110  *
111  * The main event loop manages all the available sources of events for
112  * GLib and GTK+ applications. These events can come from any number of
113  * different types of sources such as file descriptors (plain files,
114  * pipes or sockets) and timeouts. New types of event sources can also
115  * be added using g_source_attach().
116  *
117  * To allow multiple independent sets of sources to be handled in
118  * different threads, each source is associated with a #GMainContext.
119  * A #GMainContext can only be running in a single thread, but
120  * sources can be added to it and removed from it from other threads. All
121  * functions which operate on a #GMainContext or a built-in #GSource are
122  * thread-safe.
123  *
124  * Each event source is assigned a priority. The default priority,
125  * %G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
126  * Values greater than 0 denote lower priorities. Events from high priority
127  * sources are always processed before events from lower priority sources.
128  *
129  * Idle functions can also be added, and assigned a priority. These will
130  * be run whenever no events with a higher priority are ready to be processed.
131  *
132  * The #GMainLoop data type represents a main event loop. A GMainLoop is
133  * created with g_main_loop_new(). After adding the initial event sources,
134  * g_main_loop_run() is called. This continuously checks for new events from
135  * each of the event sources and dispatches them. Finally, the processing of
136  * an event from one of the sources leads to a call to g_main_loop_quit() to
137  * exit the main loop, and g_main_loop_run() returns.
138  *
139  * It is possible to create new instances of #GMainLoop recursively.
140  * This is often used in GTK+ applications when showing modal dialog
141  * boxes. Note that event sources are associated with a particular
142  * #GMainContext, and will be checked and dispatched for all main
143  * loops associated with that GMainContext.
144  *
145  * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
146  * gtk_main_quit() and gtk_events_pending().
147  *
148  * ## Creating new source types
149  *
150  * One of the unusual features of the #GMainLoop functionality
151  * is that new types of event source can be created and used in
152  * addition to the builtin type of event source. A new event source
153  * type is used for handling GDK events. A new source type is created
154  * by "deriving" from the #GSource structure. The derived type of
155  * source is represented by a structure that has the #GSource structure
156  * as a first element, and other elements specific to the new source
157  * type. To create an instance of the new source type, call
158  * g_source_new() passing in the size of the derived structure and
159  * a table of functions. These #GSourceFuncs determine the behavior of
160  * the new source type.
161  *
162  * New source types basically interact with the main context
163  * in two ways. Their prepare function in #GSourceFuncs can set a timeout
164  * to determine the maximum amount of time that the main loop will sleep
165  * before checking the source again. In addition, or as well, the source
166  * can add file descriptors to the set that the main context checks using
167  * g_source_add_poll().
168  *
169  * ## Customizing the main loop iteration
170  *
171  * Single iterations of a #GMainContext can be run with
172  * g_main_context_iteration(). In some cases, more detailed control
173  * of exactly how the details of the main loop work is desired, for
174  * instance, when integrating the #GMainLoop with an external main loop.
175  * In such cases, you can call the component functions of
176  * g_main_context_iteration() directly. These functions are
177  * g_main_context_prepare(), g_main_context_query(),
178  * g_main_context_check() and g_main_context_dispatch().
179  *
180  * ## State of a Main Context # {#mainloop-states}
181  *
182  * The operation of these functions can best be seen in terms
183  * of a state diagram, as shown in this image.
184  *
185  * ![](mainloop-states.gif)
186  *
187  * On UNIX, the GLib mainloop is incompatible with fork(). Any program
188  * using the mainloop must either exec() or exit() from the child
189  * without returning to the mainloop.
190  *
191  * ## Memory management of sources # {#mainloop-memory-management}
192  *
193  * There are two options for memory management of the user data passed to a
194  * #GSource to be passed to its callback on invocation. This data is provided
195  * in calls to g_timeout_add(), g_timeout_add_full(), g_idle_add(), etc. and
196  * more generally, using g_source_set_callback(). This data is typically an
197  * object which ‘owns’ the timeout or idle callback, such as a widget or a
198  * network protocol implementation. In many cases, it is an error for the
199  * callback to be invoked after this owning object has been destroyed, as that
200  * results in use of freed memory.
201  *
202  * The first, and preferred, option is to store the source ID returned by
203  * functions such as g_timeout_add() or g_source_attach(), and explicitly
204  * remove that source from the main context using g_source_remove() when the
205  * owning object is finalized. This ensures that the callback can only be
206  * invoked while the object is still alive.
207  *
208  * The second option is to hold a strong reference to the object in the
209  * callback, and to release it in the callback’s #GDestroyNotify. This ensures
210  * that the object is kept alive until after the source is finalized, which is
211  * guaranteed to be after it is invoked for the final time. The #GDestroyNotify
212  * is another callback passed to the ‘full’ variants of #GSource functions (for
213  * example, g_timeout_add_full()). It is called when the source is finalized,
214  * and is designed for releasing references like this.
215  *
216  * One important caveat of this second approach is that it will keep the object
217  * alive indefinitely if the main loop is stopped before the #GSource is
218  * invoked, which may be undesirable.
219  */
220 
221 /* Types */
222 
223 typedef struct _GTimeoutSource GTimeoutSource;
224 typedef struct _GChildWatchSource GChildWatchSource;
225 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
226 typedef struct _GPollRec GPollRec;
227 typedef struct _GSourceCallback GSourceCallback;
228 
229 typedef enum
230 {
231   G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
232   G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
233   G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
234 } GSourceFlags;
235 
236 typedef struct _GSourceList GSourceList;
237 
238 struct _GSourceList
239 {
240   GSource *head, *tail;
241   gint priority;
242 };
243 
244 typedef struct _GMainWaiter GMainWaiter;
245 
246 struct _GMainWaiter
247 {
248   GCond *cond;
249   GMutex *mutex;
250 };
251 
252 typedef struct _GMainDispatch GMainDispatch;
253 
254 struct _GMainDispatch
255 {
256   gint depth;
257   GSource *source;
258 };
259 
260 #ifdef G_MAIN_POLL_DEBUG
261 gboolean _g_main_poll_debug = FALSE;
262 #endif
263 
264 struct _GMainContext
265 {
266   /* The following lock is used for both the list of sources
267    * and the list of poll records
268    */
269   GMutex mutex;
270   GCond cond;
271   GThread *owner;
272   guint owner_count;
273   GSList *waiters;
274 
275   gint ref_count;  /* (atomic) */
276 
277   GHashTable *sources;              /* guint -> GSource */
278 
279   GPtrArray *pending_dispatches;
280   gint timeout;			/* Timeout for current iteration */
281 
282   guint next_id;
283   GList *source_lists;
284   gint in_check_or_prepare;
285 
286   GPollRec *poll_records;
287   guint n_poll_records;
288   GPollFD *cached_poll_array;
289   guint cached_poll_array_size;
290 
291   GWakeup *wakeup;
292 
293   GPollFD wake_up_rec;
294 
295 /* Flag indicating whether the set of fd's changed during a poll */
296   gboolean poll_changed;
297 
298   GPollFunc poll_func;
299 
300   gint64   time;
301   gboolean time_is_fresh;
302 };
303 
304 struct _GSourceCallback
305 {
306   gint ref_count;  /* (atomic) */
307   GSourceFunc func;
308   gpointer    data;
309   GDestroyNotify notify;
310 };
311 
312 struct _GMainLoop
313 {
314   GMainContext *context;
315   gboolean is_running; /* (atomic) */
316   gint ref_count;  /* (atomic) */
317 };
318 
319 struct _GTimeoutSource
320 {
321   GSource     source;
322   /* Measured in seconds if 'seconds' is TRUE, or milliseconds otherwise. */
323   guint       interval;
324   gboolean    seconds;
325 };
326 
327 struct _GChildWatchSource
328 {
329   GSource     source;
330   GPid        pid;
331   gint        child_status;
332 #ifdef G_OS_WIN32
333   GPollFD     poll;
334 #else /* G_OS_WIN32 */
335   gboolean    child_exited; /* (atomic) */
336 #endif /* G_OS_WIN32 */
337 };
338 
339 struct _GUnixSignalWatchSource
340 {
341   GSource     source;
342   int         signum;
343   gboolean    pending; /* (atomic) */
344 };
345 
346 struct _GPollRec
347 {
348   GPollFD *fd;
349   GPollRec *prev;
350   GPollRec *next;
351   gint priority;
352 };
353 
354 struct _GSourcePrivate
355 {
356   GSList *child_sources;
357   GSource *parent_source;
358 
359   gint64 ready_time;
360 
361   /* This is currently only used on UNIX, but we always declare it (and
362    * let it remain empty on Windows) to avoid #ifdef all over the place.
363    */
364   GSList *fds;
365 
366   GSourceDisposeFunc dispose;
367 
368   gboolean static_name;
369 };
370 
371 typedef struct _GSourceIter
372 {
373   GMainContext *context;
374   gboolean may_modify;
375   GList *current_list;
376   GSource *source;
377 } GSourceIter;
378 
379 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
380 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
381 #define G_THREAD_SELF g_thread_self ()
382 
383 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
384 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
385 
386 /* Forward declarations */
387 
388 static void g_source_unref_internal             (GSource      *source,
389 						 GMainContext *context,
390 						 gboolean      have_lock);
391 static void g_source_destroy_internal           (GSource      *source,
392 						 GMainContext *context,
393 						 gboolean      have_lock);
394 static void g_source_set_priority_unlocked      (GSource      *source,
395 						 GMainContext *context,
396 						 gint          priority);
397 static void g_child_source_remove_internal      (GSource      *child_source,
398                                                  GMainContext *context);
399 
400 static void g_main_context_poll                 (GMainContext *context,
401 						 gint          timeout,
402 						 gint          priority,
403 						 GPollFD      *fds,
404 						 gint          n_fds);
405 static void g_main_context_add_poll_unlocked    (GMainContext *context,
406 						 gint          priority,
407 						 GPollFD      *fd);
408 static void g_main_context_remove_poll_unlocked (GMainContext *context,
409 						 GPollFD      *fd);
410 
411 static void     g_source_iter_init  (GSourceIter   *iter,
412 				     GMainContext  *context,
413 				     gboolean       may_modify);
414 static gboolean g_source_iter_next  (GSourceIter   *iter,
415 				     GSource      **source);
416 static void     g_source_iter_clear (GSourceIter   *iter);
417 
418 static gboolean g_timeout_dispatch (GSource     *source,
419 				    GSourceFunc  callback,
420 				    gpointer     user_data);
421 static gboolean g_child_watch_prepare  (GSource     *source,
422 				        gint        *timeout);
423 static gboolean g_child_watch_check    (GSource     *source);
424 static gboolean g_child_watch_dispatch (GSource     *source,
425 					GSourceFunc  callback,
426 					gpointer     user_data);
427 static void     g_child_watch_finalize (GSource     *source);
428 #ifdef G_OS_UNIX
429 static void g_unix_signal_handler (int signum);
430 static gboolean g_unix_signal_watch_prepare  (GSource     *source,
431 					      gint        *timeout);
432 static gboolean g_unix_signal_watch_check    (GSource     *source);
433 static gboolean g_unix_signal_watch_dispatch (GSource     *source,
434 					      GSourceFunc  callback,
435 					      gpointer     user_data);
436 static void     g_unix_signal_watch_finalize  (GSource     *source);
437 #endif
438 static gboolean g_idle_prepare     (GSource     *source,
439 				    gint        *timeout);
440 static gboolean g_idle_check       (GSource     *source);
441 static gboolean g_idle_dispatch    (GSource     *source,
442 				    GSourceFunc  callback,
443 				    gpointer     user_data);
444 
445 static void block_source (GSource *source);
446 
447 static GMainContext *glib_worker_context;
448 
449 #ifndef G_OS_WIN32
450 
451 
452 /* UNIX signals work by marking one of these variables then waking the
453  * worker context to check on them and dispatch accordingly.
454  *
455  * Both variables must be accessed using atomic primitives, unless those atomic
456  * primitives are implemented using fallback mutexes (as those aren’t safe in
457  * an interrupt context).
458  *
459  * If using atomic primitives, the variables must be of type `int` (so they’re
460  * the right size for the atomic primitives). Otherwise, use `sig_atomic_t` if
461  * it’s available, which is guaranteed to be async-signal-safe (but it’s *not*
462  * guaranteed to be thread-safe, which is why we use atomic primitives if
463  * possible).
464  *
465  * Typically, `sig_atomic_t` is a typedef to `int`, but that’s not the case on
466  * FreeBSD, so we can’t use it unconditionally if it’s defined.
467  */
468 #if (defined(G_ATOMIC_LOCK_FREE) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) || !defined(HAVE_SIG_ATOMIC_T)
469 static volatile int unix_signal_pending[NSIG];
470 static volatile int any_unix_signal_pending;
471 #else
472 static volatile sig_atomic_t unix_signal_pending[NSIG];
473 static volatile sig_atomic_t any_unix_signal_pending;
474 #endif
475 
476 /* Guards all the data below */
477 G_LOCK_DEFINE_STATIC (unix_signal_lock);
478 static guint unix_signal_refcount[NSIG];
479 static GSList *unix_signal_watches;
480 static GSList *unix_child_watches;
481 
482 GSourceFuncs g_unix_signal_funcs =
483 {
484   g_unix_signal_watch_prepare,
485   g_unix_signal_watch_check,
486   g_unix_signal_watch_dispatch,
487   g_unix_signal_watch_finalize,
488   NULL, NULL
489 };
490 #endif /* !G_OS_WIN32 */
491 G_LOCK_DEFINE_STATIC (main_context_list);
492 static GSList *main_context_list = NULL;
493 
494 GSourceFuncs g_timeout_funcs =
495 {
496   NULL, /* prepare */
497   NULL, /* check */
498   g_timeout_dispatch,
499   NULL, NULL, NULL
500 };
501 
502 GSourceFuncs g_child_watch_funcs =
503 {
504   g_child_watch_prepare,
505   g_child_watch_check,
506   g_child_watch_dispatch,
507   g_child_watch_finalize,
508   NULL, NULL
509 };
510 
511 GSourceFuncs g_idle_funcs =
512 {
513   g_idle_prepare,
514   g_idle_check,
515   g_idle_dispatch,
516   NULL, NULL, NULL
517 };
518 
519 /**
520  * g_main_context_ref:
521  * @context: a #GMainContext
522  *
523  * Increases the reference count on a #GMainContext object by one.
524  *
525  * Returns: the @context that was passed in (since 2.6)
526  **/
527 GMainContext *
g_main_context_ref(GMainContext * context)528 g_main_context_ref (GMainContext *context)
529 {
530   g_return_val_if_fail (context != NULL, NULL);
531   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
532 
533   g_atomic_int_inc (&context->ref_count);
534 
535   return context;
536 }
537 
538 static inline void
poll_rec_list_free(GMainContext * context,GPollRec * list)539 poll_rec_list_free (GMainContext *context,
540 		    GPollRec     *list)
541 {
542   g_slice_free_chain (GPollRec, list, next);
543 }
544 
545 /**
546  * g_main_context_unref:
547  * @context: a #GMainContext
548  *
549  * Decreases the reference count on a #GMainContext object by one. If
550  * the result is zero, free the context and free all associated memory.
551  **/
552 void
g_main_context_unref(GMainContext * context)553 g_main_context_unref (GMainContext *context)
554 {
555   GSourceIter iter;
556   GSource *source;
557   GList *sl_iter;
558   GSList *s_iter, *remaining_sources = NULL;
559   GSourceList *list;
560   guint i;
561 
562   g_return_if_fail (context != NULL);
563   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
564 
565   if (!g_atomic_int_dec_and_test (&context->ref_count))
566     return;
567 
568   G_LOCK (main_context_list);
569   main_context_list = g_slist_remove (main_context_list, context);
570   G_UNLOCK (main_context_list);
571 
572   /* Free pending dispatches */
573   for (i = 0; i < context->pending_dispatches->len; i++)
574     g_source_unref_internal (context->pending_dispatches->pdata[i], context, FALSE);
575 
576   /* g_source_iter_next() assumes the context is locked. */
577   LOCK_CONTEXT (context);
578 
579   /* First collect all remaining sources from the sources lists and store a
580    * new reference in a separate list. Also set the context of the sources
581    * to NULL so that they can't access a partially destroyed context anymore.
582    *
583    * We have to do this first so that we have a strong reference to all
584    * sources and destroying them below does not also free them, and so that
585    * none of the sources can access the context from their finalize/dispose
586    * functions. */
587   g_source_iter_init (&iter, context, FALSE);
588   while (g_source_iter_next (&iter, &source))
589     {
590       source->context = NULL;
591       remaining_sources = g_slist_prepend (remaining_sources, g_source_ref (source));
592     }
593   g_source_iter_clear (&iter);
594 
595   /* Next destroy all sources. As we still hold a reference to all of them,
596    * this won't cause any of them to be freed yet and especially prevents any
597    * source that unrefs another source from its finalize function to be freed.
598    */
599   for (s_iter = remaining_sources; s_iter; s_iter = s_iter->next)
600     {
601       source = s_iter->data;
602       g_source_destroy_internal (source, context, TRUE);
603     }
604 
605   for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
606     {
607       list = sl_iter->data;
608       g_slice_free (GSourceList, list);
609     }
610   g_list_free (context->source_lists);
611 
612   g_hash_table_destroy (context->sources);
613 
614   UNLOCK_CONTEXT (context);
615   g_mutex_clear (&context->mutex);
616 
617   g_ptr_array_free (context->pending_dispatches, TRUE);
618   g_free (context->cached_poll_array);
619 
620   poll_rec_list_free (context, context->poll_records);
621 
622   g_wakeup_free (context->wakeup);
623   g_cond_clear (&context->cond);
624 
625   g_free (context);
626 
627   /* And now finally get rid of our references to the sources. This will cause
628    * them to be freed unless something else still has a reference to them. Due
629    * to setting the context pointers in the sources to NULL above, this won't
630    * ever access the context or the internal linked list inside the GSource.
631    * We already removed the sources completely from the context above. */
632   for (s_iter = remaining_sources; s_iter; s_iter = s_iter->next)
633     {
634       source = s_iter->data;
635       g_source_unref_internal (source, NULL, FALSE);
636     }
637   g_slist_free (remaining_sources);
638 }
639 
640 /* Helper function used by mainloop/overflow test.
641  */
642 GMainContext *
g_main_context_new_with_next_id(guint next_id)643 g_main_context_new_with_next_id (guint next_id)
644 {
645   GMainContext *ret = g_main_context_new ();
646 
647   ret->next_id = next_id;
648 
649   return ret;
650 }
651 
652 /**
653  * g_main_context_new:
654  *
655  * Creates a new #GMainContext structure.
656  *
657  * Returns: the new #GMainContext
658  **/
659 GMainContext *
g_main_context_new(void)660 g_main_context_new (void)
661 {
662   static gsize initialised;
663   GMainContext *context;
664 
665   if (g_once_init_enter (&initialised))
666     {
667 #ifdef G_MAIN_POLL_DEBUG
668       if (g_getenv ("G_MAIN_POLL_DEBUG") != NULL)
669         _g_main_poll_debug = TRUE;
670 #endif
671 
672       g_once_init_leave (&initialised, TRUE);
673     }
674 
675   context = g_new0 (GMainContext, 1);
676 
677   TRACE (GLIB_MAIN_CONTEXT_NEW (context));
678 
679   g_mutex_init (&context->mutex);
680   g_cond_init (&context->cond);
681 
682   context->sources = g_hash_table_new (NULL, NULL);
683   context->owner = NULL;
684   context->waiters = NULL;
685 
686   context->ref_count = 1;
687 
688   context->next_id = 1;
689 
690   context->source_lists = NULL;
691 
692   context->poll_func = g_poll;
693 
694   context->cached_poll_array = NULL;
695   context->cached_poll_array_size = 0;
696 
697   context->pending_dispatches = g_ptr_array_new ();
698 
699   context->time_is_fresh = FALSE;
700 
701   context->wakeup = g_wakeup_new ();
702   g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
703   g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
704 
705   G_LOCK (main_context_list);
706   main_context_list = g_slist_append (main_context_list, context);
707 
708 #ifdef G_MAIN_POLL_DEBUG
709   if (_g_main_poll_debug)
710     g_print ("created context=%p\n", context);
711 #endif
712 
713   G_UNLOCK (main_context_list);
714 
715   return context;
716 }
717 
718 /**
719  * g_main_context_default:
720  *
721  * Returns the global default main context. This is the main context
722  * used for main loop functions when a main loop is not explicitly
723  * specified, and corresponds to the "main" main loop. See also
724  * g_main_context_get_thread_default().
725  *
726  * Returns: (transfer none): the global default main context.
727  **/
728 GMainContext *
g_main_context_default(void)729 g_main_context_default (void)
730 {
731   static GMainContext *default_main_context = NULL;
732 
733   if (g_once_init_enter (&default_main_context))
734     {
735       GMainContext *context;
736 
737       context = g_main_context_new ();
738 
739       TRACE (GLIB_MAIN_CONTEXT_DEFAULT (context));
740 
741 #ifdef G_MAIN_POLL_DEBUG
742       if (_g_main_poll_debug)
743         g_print ("default context=%p\n", context);
744 #endif
745 
746       g_once_init_leave (&default_main_context, context);
747     }
748 
749   return default_main_context;
750 }
751 
752 static void
free_context(gpointer data)753 free_context (gpointer data)
754 {
755   GMainContext *context = data;
756 
757   TRACE (GLIB_MAIN_CONTEXT_FREE (context));
758 
759   g_main_context_release (context);
760   if (context)
761     g_main_context_unref (context);
762 }
763 
764 static void
free_context_stack(gpointer data)765 free_context_stack (gpointer data)
766 {
767   g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
768 }
769 
770 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
771 
772 /**
773  * g_main_context_push_thread_default:
774  * @context: (nullable): a #GMainContext, or %NULL for the global default context
775  *
776  * Acquires @context and sets it as the thread-default context for the
777  * current thread. This will cause certain asynchronous operations
778  * (such as most [gio][gio]-based I/O) which are
779  * started in this thread to run under @context and deliver their
780  * results to its main loop, rather than running under the global
781  * default context in the main thread. Note that calling this function
782  * changes the context returned by g_main_context_get_thread_default(),
783  * not the one returned by g_main_context_default(), so it does not affect
784  * the context used by functions like g_idle_add().
785  *
786  * Normally you would call this function shortly after creating a new
787  * thread, passing it a #GMainContext which will be run by a
788  * #GMainLoop in that thread, to set a new default context for all
789  * async operations in that thread. In this case you may not need to
790  * ever call g_main_context_pop_thread_default(), assuming you want the
791  * new #GMainContext to be the default for the whole lifecycle of the
792  * thread.
793  *
794  * If you don't have control over how the new thread was created (e.g.
795  * in the new thread isn't newly created, or if the thread life
796  * cycle is managed by a #GThreadPool), it is always suggested to wrap
797  * the logic that needs to use the new #GMainContext inside a
798  * g_main_context_push_thread_default() / g_main_context_pop_thread_default()
799  * pair, otherwise threads that are re-used will end up never explicitly
800  * releasing the #GMainContext reference they hold.
801  *
802  * In some cases you may want to schedule a single operation in a
803  * non-default context, or temporarily use a non-default context in
804  * the main thread. In that case, you can wrap the call to the
805  * asynchronous operation inside a
806  * g_main_context_push_thread_default() /
807  * g_main_context_pop_thread_default() pair, but it is up to you to
808  * ensure that no other asynchronous operations accidentally get
809  * started while the non-default context is active.
810  *
811  * Beware that libraries that predate this function may not correctly
812  * handle being used from a thread with a thread-default context. Eg,
813  * see g_file_supports_thread_contexts().
814  *
815  * Since: 2.22
816  **/
817 void
g_main_context_push_thread_default(GMainContext * context)818 g_main_context_push_thread_default (GMainContext *context)
819 {
820   GQueue *stack;
821   gboolean acquired_context;
822 
823   acquired_context = g_main_context_acquire (context);
824   g_return_if_fail (acquired_context);
825 
826   if (context == g_main_context_default ())
827     context = NULL;
828   else if (context)
829     g_main_context_ref (context);
830 
831   stack = g_private_get (&thread_context_stack);
832   if (!stack)
833     {
834       stack = g_queue_new ();
835       g_private_set (&thread_context_stack, stack);
836     }
837 
838   g_queue_push_head (stack, context);
839 
840   TRACE (GLIB_MAIN_CONTEXT_PUSH_THREAD_DEFAULT (context));
841 }
842 
843 /**
844  * g_main_context_pop_thread_default:
845  * @context: (nullable): a #GMainContext object, or %NULL
846  *
847  * Pops @context off the thread-default context stack (verifying that
848  * it was on the top of the stack).
849  *
850  * Since: 2.22
851  **/
852 void
g_main_context_pop_thread_default(GMainContext * context)853 g_main_context_pop_thread_default (GMainContext *context)
854 {
855   GQueue *stack;
856 
857   if (context == g_main_context_default ())
858     context = NULL;
859 
860   stack = g_private_get (&thread_context_stack);
861 
862   g_return_if_fail (stack != NULL);
863   g_return_if_fail (g_queue_peek_head (stack) == context);
864 
865   TRACE (GLIB_MAIN_CONTEXT_POP_THREAD_DEFAULT (context));
866 
867   g_queue_pop_head (stack);
868 
869   g_main_context_release (context);
870   if (context)
871     g_main_context_unref (context);
872 }
873 
874 /**
875  * g_main_context_get_thread_default:
876  *
877  * Gets the thread-default #GMainContext for this thread. Asynchronous
878  * operations that want to be able to be run in contexts other than
879  * the default one should call this method or
880  * g_main_context_ref_thread_default() to get a #GMainContext to add
881  * their #GSources to. (Note that even in single-threaded
882  * programs applications may sometimes want to temporarily push a
883  * non-default context, so it is not safe to assume that this will
884  * always return %NULL if you are running in the default thread.)
885  *
886  * If you need to hold a reference on the context, use
887  * g_main_context_ref_thread_default() instead.
888  *
889  * Returns: (transfer none) (nullable): the thread-default #GMainContext, or
890  * %NULL if the thread-default context is the global default context.
891  *
892  * Since: 2.22
893  **/
894 GMainContext *
g_main_context_get_thread_default(void)895 g_main_context_get_thread_default (void)
896 {
897   GQueue *stack;
898 
899   stack = g_private_get (&thread_context_stack);
900   if (stack)
901     return g_queue_peek_head (stack);
902   else
903     return NULL;
904 }
905 
906 /**
907  * g_main_context_ref_thread_default:
908  *
909  * Gets the thread-default #GMainContext for this thread, as with
910  * g_main_context_get_thread_default(), but also adds a reference to
911  * it with g_main_context_ref(). In addition, unlike
912  * g_main_context_get_thread_default(), if the thread-default context
913  * is the global default context, this will return that #GMainContext
914  * (with a ref added to it) rather than returning %NULL.
915  *
916  * Returns: (transfer full): the thread-default #GMainContext. Unref
917  *     with g_main_context_unref() when you are done with it.
918  *
919  * Since: 2.32
920  */
921 GMainContext *
g_main_context_ref_thread_default(void)922 g_main_context_ref_thread_default (void)
923 {
924   GMainContext *context;
925 
926   context = g_main_context_get_thread_default ();
927   if (!context)
928     context = g_main_context_default ();
929   return g_main_context_ref (context);
930 }
931 
932 /* Hooks for adding to the main loop */
933 
934 /**
935  * g_source_new:
936  * @source_funcs: structure containing functions that implement
937  *                the sources behavior.
938  * @struct_size: size of the #GSource structure to create.
939  *
940  * Creates a new #GSource structure. The size is specified to
941  * allow creating structures derived from #GSource that contain
942  * additional data. The size passed in must be at least
943  * `sizeof (GSource)`.
944  *
945  * The source will not initially be associated with any #GMainContext
946  * and must be added to one with g_source_attach() before it will be
947  * executed.
948  *
949  * Returns: the newly-created #GSource.
950  **/
951 GSource *
g_source_new(GSourceFuncs * source_funcs,guint struct_size)952 g_source_new (GSourceFuncs *source_funcs,
953 	      guint         struct_size)
954 {
955   GSource *source;
956 
957   g_return_val_if_fail (source_funcs != NULL, NULL);
958   g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
959 
960   source = (GSource*) g_malloc0 (struct_size);
961   source->priv = g_slice_new0 (GSourcePrivate);
962   source->source_funcs = source_funcs;
963   source->ref_count = 1;
964 
965   source->priority = G_PRIORITY_DEFAULT;
966 
967   source->flags = G_HOOK_FLAG_ACTIVE;
968 
969   source->priv->ready_time = -1;
970 
971   /* NULL/0 initialization for all other fields */
972 
973   TRACE (GLIB_SOURCE_NEW (source, source_funcs->prepare, source_funcs->check,
974                           source_funcs->dispatch, source_funcs->finalize,
975                           struct_size));
976 
977   return source;
978 }
979 
980 /**
981  * g_source_set_dispose_function:
982  * @source: A #GSource to set the dispose function on
983  * @dispose: #GSourceDisposeFunc to set on the source
984  *
985  * Set @dispose as dispose function on @source. @dispose will be called once
986  * the reference count of @source reaches 0 but before any of the state of the
987  * source is freed, especially before the finalize function is called.
988  *
989  * This means that at this point @source is still a valid #GSource and it is
990  * allow for the reference count to increase again until @dispose returns.
991  *
992  * The dispose function can be used to clear any "weak" references to the
993  * @source in other data structures in a thread-safe way where it is possible
994  * for another thread to increase the reference count of @source again while
995  * it is being freed.
996  *
997  * The finalize function can not be used for this purpose as at that point
998  * @source is already partially freed and not valid anymore.
999  *
1000  * This should only ever be called from #GSource implementations.
1001  *
1002  * Since: 2.64
1003  **/
1004 void
g_source_set_dispose_function(GSource * source,GSourceDisposeFunc dispose)1005 g_source_set_dispose_function (GSource            *source,
1006 			       GSourceDisposeFunc  dispose)
1007 {
1008   g_return_if_fail (source != NULL);
1009   g_return_if_fail (source->priv->dispose == NULL);
1010   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1011   source->priv->dispose = dispose;
1012 }
1013 
1014 /* Holds context's lock */
1015 static void
g_source_iter_init(GSourceIter * iter,GMainContext * context,gboolean may_modify)1016 g_source_iter_init (GSourceIter  *iter,
1017 		    GMainContext *context,
1018 		    gboolean      may_modify)
1019 {
1020   iter->context = context;
1021   iter->current_list = NULL;
1022   iter->source = NULL;
1023   iter->may_modify = may_modify;
1024 }
1025 
1026 /* Holds context's lock */
1027 static gboolean
g_source_iter_next(GSourceIter * iter,GSource ** source)1028 g_source_iter_next (GSourceIter *iter, GSource **source)
1029 {
1030   GSource *next_source;
1031 
1032   if (iter->source)
1033     next_source = iter->source->next;
1034   else
1035     next_source = NULL;
1036 
1037   if (!next_source)
1038     {
1039       if (iter->current_list)
1040 	iter->current_list = iter->current_list->next;
1041       else
1042 	iter->current_list = iter->context->source_lists;
1043 
1044       if (iter->current_list)
1045 	{
1046 	  GSourceList *source_list = iter->current_list->data;
1047 
1048 	  next_source = source_list->head;
1049 	}
1050     }
1051 
1052   /* Note: unreffing iter->source could potentially cause its
1053    * GSourceList to be removed from source_lists (if iter->source is
1054    * the only source in its list, and it is destroyed), so we have to
1055    * keep it reffed until after we advance iter->current_list, above.
1056    *
1057    * Also we first have to ref the next source before unreffing the
1058    * previous one as unreffing the previous source can potentially
1059    * free the next one.
1060    */
1061   if (next_source && iter->may_modify)
1062     g_source_ref (next_source);
1063 
1064   if (iter->source && iter->may_modify)
1065     g_source_unref_internal (iter->source, iter->context, TRUE);
1066   iter->source = next_source;
1067 
1068   *source = iter->source;
1069   return *source != NULL;
1070 }
1071 
1072 /* Holds context's lock. Only necessary to call if you broke out of
1073  * the g_source_iter_next() loop early.
1074  */
1075 static void
g_source_iter_clear(GSourceIter * iter)1076 g_source_iter_clear (GSourceIter *iter)
1077 {
1078   if (iter->source && iter->may_modify)
1079     {
1080       g_source_unref_internal (iter->source, iter->context, TRUE);
1081       iter->source = NULL;
1082     }
1083 }
1084 
1085 /* Holds context's lock
1086  */
1087 static GSourceList *
find_source_list_for_priority(GMainContext * context,gint priority,gboolean create)1088 find_source_list_for_priority (GMainContext *context,
1089 			       gint          priority,
1090 			       gboolean      create)
1091 {
1092   GList *iter, *last;
1093   GSourceList *source_list;
1094 
1095   last = NULL;
1096   for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
1097     {
1098       source_list = iter->data;
1099 
1100       if (source_list->priority == priority)
1101 	return source_list;
1102 
1103       if (source_list->priority > priority)
1104 	{
1105 	  if (!create)
1106 	    return NULL;
1107 
1108 	  source_list = g_slice_new0 (GSourceList);
1109 	  source_list->priority = priority;
1110 	  context->source_lists = g_list_insert_before (context->source_lists,
1111 							iter,
1112 							source_list);
1113 	  return source_list;
1114 	}
1115     }
1116 
1117   if (!create)
1118     return NULL;
1119 
1120   source_list = g_slice_new0 (GSourceList);
1121   source_list->priority = priority;
1122 
1123   if (!last)
1124     context->source_lists = g_list_append (NULL, source_list);
1125   else
1126     {
1127       /* This just appends source_list to the end of
1128        * context->source_lists without having to walk the list again.
1129        */
1130       last = g_list_append (last, source_list);
1131       (void) last;
1132     }
1133   return source_list;
1134 }
1135 
1136 /* Holds context's lock
1137  */
1138 static void
source_add_to_context(GSource * source,GMainContext * context)1139 source_add_to_context (GSource      *source,
1140 		       GMainContext *context)
1141 {
1142   GSourceList *source_list;
1143   GSource *prev, *next;
1144 
1145   source_list = find_source_list_for_priority (context, source->priority, TRUE);
1146 
1147   if (source->priv->parent_source)
1148     {
1149       g_assert (source_list->head != NULL);
1150 
1151       /* Put the source immediately before its parent */
1152       prev = source->priv->parent_source->prev;
1153       next = source->priv->parent_source;
1154     }
1155   else
1156     {
1157       prev = source_list->tail;
1158       next = NULL;
1159     }
1160 
1161   source->next = next;
1162   if (next)
1163     next->prev = source;
1164   else
1165     source_list->tail = source;
1166 
1167   source->prev = prev;
1168   if (prev)
1169     prev->next = source;
1170   else
1171     source_list->head = source;
1172 }
1173 
1174 /* Holds context's lock
1175  */
1176 static void
source_remove_from_context(GSource * source,GMainContext * context)1177 source_remove_from_context (GSource      *source,
1178 			    GMainContext *context)
1179 {
1180   GSourceList *source_list;
1181 
1182   source_list = find_source_list_for_priority (context, source->priority, FALSE);
1183   g_return_if_fail (source_list != NULL);
1184 
1185   if (source->prev)
1186     source->prev->next = source->next;
1187   else
1188     source_list->head = source->next;
1189 
1190   if (source->next)
1191     source->next->prev = source->prev;
1192   else
1193     source_list->tail = source->prev;
1194 
1195   source->prev = NULL;
1196   source->next = NULL;
1197 
1198   if (source_list->head == NULL)
1199     {
1200       context->source_lists = g_list_remove (context->source_lists, source_list);
1201       g_slice_free (GSourceList, source_list);
1202     }
1203 }
1204 
1205 static guint
g_source_attach_unlocked(GSource * source,GMainContext * context,gboolean do_wakeup)1206 g_source_attach_unlocked (GSource      *source,
1207                           GMainContext *context,
1208                           gboolean      do_wakeup)
1209 {
1210   GSList *tmp_list;
1211   guint id;
1212 
1213   /* The counter may have wrapped, so we must ensure that we do not
1214    * reuse the source id of an existing source.
1215    */
1216   do
1217     id = context->next_id++;
1218   while (id == 0 || g_hash_table_contains (context->sources, GUINT_TO_POINTER (id)));
1219 
1220   source->context = context;
1221   source->source_id = id;
1222   g_source_ref (source);
1223 
1224   g_hash_table_insert (context->sources, GUINT_TO_POINTER (id), source);
1225 
1226   source_add_to_context (source, context);
1227 
1228   if (!SOURCE_BLOCKED (source))
1229     {
1230       tmp_list = source->poll_fds;
1231       while (tmp_list)
1232         {
1233           g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1234           tmp_list = tmp_list->next;
1235         }
1236 
1237       for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1238         g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1239     }
1240 
1241   tmp_list = source->priv->child_sources;
1242   while (tmp_list)
1243     {
1244       g_source_attach_unlocked (tmp_list->data, context, FALSE);
1245       tmp_list = tmp_list->next;
1246     }
1247 
1248   /* If another thread has acquired the context, wake it up since it
1249    * might be in poll() right now.
1250    */
1251   if (do_wakeup && context->owner && context->owner != G_THREAD_SELF)
1252     g_wakeup_signal (context->wakeup);
1253 
1254   g_trace_mark (G_TRACE_CURRENT_TIME, 0,
1255                 "GLib", "g_source_attach",
1256                 "%s to context %p",
1257                 (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
1258                 context);
1259 
1260   return source->source_id;
1261 }
1262 
1263 /**
1264  * g_source_attach:
1265  * @source: a #GSource
1266  * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
1267  *
1268  * Adds a #GSource to a @context so that it will be executed within
1269  * that context. Remove it by calling g_source_destroy().
1270  *
1271  * This function is safe to call from any thread, regardless of which thread
1272  * the @context is running in.
1273  *
1274  * Returns: the ID (greater than 0) for the source within the
1275  *   #GMainContext.
1276  **/
1277 guint
g_source_attach(GSource * source,GMainContext * context)1278 g_source_attach (GSource      *source,
1279 		 GMainContext *context)
1280 {
1281   guint result = 0;
1282 
1283   g_return_val_if_fail (source != NULL, 0);
1284   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
1285   g_return_val_if_fail (source->context == NULL, 0);
1286   g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1287 
1288   if (!context)
1289     context = g_main_context_default ();
1290 
1291   LOCK_CONTEXT (context);
1292 
1293   result = g_source_attach_unlocked (source, context, TRUE);
1294 
1295   TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source), source, context,
1296                                   result));
1297 
1298   UNLOCK_CONTEXT (context);
1299 
1300   return result;
1301 }
1302 
1303 static void
g_source_destroy_internal(GSource * source,GMainContext * context,gboolean have_lock)1304 g_source_destroy_internal (GSource      *source,
1305 			   GMainContext *context,
1306 			   gboolean      have_lock)
1307 {
1308   TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source), source,
1309                                    context));
1310 
1311   if (!have_lock)
1312     LOCK_CONTEXT (context);
1313 
1314   if (!SOURCE_DESTROYED (source))
1315     {
1316       GSList *tmp_list;
1317       gpointer old_cb_data;
1318       GSourceCallbackFuncs *old_cb_funcs;
1319 
1320       source->flags &= ~G_HOOK_FLAG_ACTIVE;
1321 
1322       old_cb_data = source->callback_data;
1323       old_cb_funcs = source->callback_funcs;
1324 
1325       source->callback_data = NULL;
1326       source->callback_funcs = NULL;
1327 
1328       if (old_cb_funcs)
1329 	{
1330 	  UNLOCK_CONTEXT (context);
1331 	  old_cb_funcs->unref (old_cb_data);
1332 	  LOCK_CONTEXT (context);
1333 	}
1334 
1335       if (!SOURCE_BLOCKED (source))
1336 	{
1337 	  tmp_list = source->poll_fds;
1338 	  while (tmp_list)
1339 	    {
1340 	      g_main_context_remove_poll_unlocked (context, tmp_list->data);
1341 	      tmp_list = tmp_list->next;
1342 	    }
1343 
1344           for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1345             g_main_context_remove_poll_unlocked (context, tmp_list->data);
1346 	}
1347 
1348       while (source->priv->child_sources)
1349         g_child_source_remove_internal (source->priv->child_sources->data, context);
1350 
1351       if (source->priv->parent_source)
1352         g_child_source_remove_internal (source, context);
1353 
1354       g_source_unref_internal (source, context, TRUE);
1355     }
1356 
1357   if (!have_lock)
1358     UNLOCK_CONTEXT (context);
1359 }
1360 
1361 /**
1362  * g_source_destroy:
1363  * @source: a #GSource
1364  *
1365  * Removes a source from its #GMainContext, if any, and mark it as
1366  * destroyed.  The source cannot be subsequently added to another
1367  * context. It is safe to call this on sources which have already been
1368  * removed from their context.
1369  *
1370  * This does not unref the #GSource: if you still hold a reference, use
1371  * g_source_unref() to drop it.
1372  *
1373  * This function is safe to call from any thread, regardless of which thread
1374  * the #GMainContext is running in.
1375  *
1376  * If the source is currently attached to a #GMainContext, destroying it
1377  * will effectively unset the callback similar to calling g_source_set_callback().
1378  * This can mean, that the data's #GDestroyNotify gets called right away.
1379  */
1380 void
g_source_destroy(GSource * source)1381 g_source_destroy (GSource *source)
1382 {
1383   GMainContext *context;
1384 
1385   g_return_if_fail (source != NULL);
1386   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1387 
1388   context = source->context;
1389 
1390   if (context)
1391     g_source_destroy_internal (source, context, FALSE);
1392   else
1393     source->flags &= ~G_HOOK_FLAG_ACTIVE;
1394 }
1395 
1396 /**
1397  * g_source_get_id:
1398  * @source: a #GSource
1399  *
1400  * Returns the numeric ID for a particular source. The ID of a source
1401  * is a positive integer which is unique within a particular main loop
1402  * context. The reverse
1403  * mapping from ID to source is done by g_main_context_find_source_by_id().
1404  *
1405  * You can only call this function while the source is associated to a
1406  * #GMainContext instance; calling this function before g_source_attach()
1407  * or after g_source_destroy() yields undefined behavior. The ID returned
1408  * is unique within the #GMainContext instance passed to g_source_attach().
1409  *
1410  * Returns: the ID (greater than 0) for the source
1411  **/
1412 guint
g_source_get_id(GSource * source)1413 g_source_get_id (GSource *source)
1414 {
1415   guint result;
1416 
1417   g_return_val_if_fail (source != NULL, 0);
1418   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
1419   g_return_val_if_fail (source->context != NULL, 0);
1420 
1421   LOCK_CONTEXT (source->context);
1422   result = source->source_id;
1423   UNLOCK_CONTEXT (source->context);
1424 
1425   return result;
1426 }
1427 
1428 /**
1429  * g_source_get_context:
1430  * @source: a #GSource
1431  *
1432  * Gets the #GMainContext with which the source is associated.
1433  *
1434  * You can call this on a source that has been destroyed, provided
1435  * that the #GMainContext it was attached to still exists (in which
1436  * case it will return that #GMainContext). In particular, you can
1437  * always call this function on the source returned from
1438  * g_main_current_source(). But calling this function on a source
1439  * whose #GMainContext has been destroyed is an error.
1440  *
1441  * Returns: (transfer none) (nullable): the #GMainContext with which the
1442  *               source is associated, or %NULL if the context has not
1443  *               yet been added to a source.
1444  **/
1445 GMainContext *
g_source_get_context(GSource * source)1446 g_source_get_context (GSource *source)
1447 {
1448   g_return_val_if_fail (source != NULL, NULL);
1449   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, NULL);
1450   g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1451 
1452   return source->context;
1453 }
1454 
1455 /**
1456  * g_source_add_poll:
1457  * @source:a #GSource
1458  * @fd: a #GPollFD structure holding information about a file
1459  *      descriptor to watch.
1460  *
1461  * Adds a file descriptor to the set of file descriptors polled for
1462  * this source. This is usually combined with g_source_new() to add an
1463  * event source. The event source's check function will typically test
1464  * the @revents field in the #GPollFD struct and return %TRUE if events need
1465  * to be processed.
1466  *
1467  * This API is only intended to be used by implementations of #GSource.
1468  * Do not call this API on a #GSource that you did not create.
1469  *
1470  * Using this API forces the linear scanning of event sources on each
1471  * main loop iteration.  Newly-written event sources should try to use
1472  * g_source_add_unix_fd() instead of this API.
1473  **/
1474 void
g_source_add_poll(GSource * source,GPollFD * fd)1475 g_source_add_poll (GSource *source,
1476 		   GPollFD *fd)
1477 {
1478   GMainContext *context;
1479 
1480   g_return_if_fail (source != NULL);
1481   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1482   g_return_if_fail (fd != NULL);
1483   g_return_if_fail (!SOURCE_DESTROYED (source));
1484 
1485   context = source->context;
1486 
1487   if (context)
1488     LOCK_CONTEXT (context);
1489 
1490   source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1491 
1492   if (context)
1493     {
1494       if (!SOURCE_BLOCKED (source))
1495 	g_main_context_add_poll_unlocked (context, source->priority, fd);
1496       UNLOCK_CONTEXT (context);
1497     }
1498 }
1499 
1500 /**
1501  * g_source_remove_poll:
1502  * @source:a #GSource
1503  * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1504  *
1505  * Removes a file descriptor from the set of file descriptors polled for
1506  * this source.
1507  *
1508  * This API is only intended to be used by implementations of #GSource.
1509  * Do not call this API on a #GSource that you did not create.
1510  **/
1511 void
g_source_remove_poll(GSource * source,GPollFD * fd)1512 g_source_remove_poll (GSource *source,
1513 		      GPollFD *fd)
1514 {
1515   GMainContext *context;
1516 
1517   g_return_if_fail (source != NULL);
1518   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1519   g_return_if_fail (fd != NULL);
1520   g_return_if_fail (!SOURCE_DESTROYED (source));
1521 
1522   context = source->context;
1523 
1524   if (context)
1525     LOCK_CONTEXT (context);
1526 
1527   source->poll_fds = g_slist_remove (source->poll_fds, fd);
1528 
1529   if (context)
1530     {
1531       if (!SOURCE_BLOCKED (source))
1532 	g_main_context_remove_poll_unlocked (context, fd);
1533       UNLOCK_CONTEXT (context);
1534     }
1535 }
1536 
1537 /**
1538  * g_source_add_child_source:
1539  * @source:a #GSource
1540  * @child_source: a second #GSource that @source should "poll"
1541  *
1542  * Adds @child_source to @source as a "polled" source; when @source is
1543  * added to a #GMainContext, @child_source will be automatically added
1544  * with the same priority, when @child_source is triggered, it will
1545  * cause @source to dispatch (in addition to calling its own
1546  * callback), and when @source is destroyed, it will destroy
1547  * @child_source as well. (@source will also still be dispatched if
1548  * its own prepare/check functions indicate that it is ready.)
1549  *
1550  * If you don't need @child_source to do anything on its own when it
1551  * triggers, you can call g_source_set_dummy_callback() on it to set a
1552  * callback that does nothing (except return %TRUE if appropriate).
1553  *
1554  * @source will hold a reference on @child_source while @child_source
1555  * is attached to it.
1556  *
1557  * This API is only intended to be used by implementations of #GSource.
1558  * Do not call this API on a #GSource that you did not create.
1559  *
1560  * Since: 2.28
1561  **/
1562 void
g_source_add_child_source(GSource * source,GSource * child_source)1563 g_source_add_child_source (GSource *source,
1564 			   GSource *child_source)
1565 {
1566   GMainContext *context;
1567 
1568   g_return_if_fail (source != NULL);
1569   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1570   g_return_if_fail (child_source != NULL);
1571   g_return_if_fail (g_atomic_int_get (&child_source->ref_count) > 0);
1572   g_return_if_fail (!SOURCE_DESTROYED (source));
1573   g_return_if_fail (!SOURCE_DESTROYED (child_source));
1574   g_return_if_fail (child_source->context == NULL);
1575   g_return_if_fail (child_source->priv->parent_source == NULL);
1576 
1577   context = source->context;
1578 
1579   if (context)
1580     LOCK_CONTEXT (context);
1581 
1582   TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source, child_source));
1583 
1584   source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1585 						 g_source_ref (child_source));
1586   child_source->priv->parent_source = source;
1587   g_source_set_priority_unlocked (child_source, NULL, source->priority);
1588   if (SOURCE_BLOCKED (source))
1589     block_source (child_source);
1590 
1591   if (context)
1592     {
1593       g_source_attach_unlocked (child_source, context, TRUE);
1594       UNLOCK_CONTEXT (context);
1595     }
1596 }
1597 
1598 static void
g_child_source_remove_internal(GSource * child_source,GMainContext * context)1599 g_child_source_remove_internal (GSource *child_source,
1600                                 GMainContext *context)
1601 {
1602   GSource *parent_source = child_source->priv->parent_source;
1603 
1604   parent_source->priv->child_sources =
1605     g_slist_remove (parent_source->priv->child_sources, child_source);
1606   child_source->priv->parent_source = NULL;
1607 
1608   g_source_destroy_internal (child_source, context, TRUE);
1609   g_source_unref_internal (child_source, context, TRUE);
1610 }
1611 
1612 /**
1613  * g_source_remove_child_source:
1614  * @source:a #GSource
1615  * @child_source: a #GSource previously passed to
1616  *     g_source_add_child_source().
1617  *
1618  * Detaches @child_source from @source and destroys it.
1619  *
1620  * This API is only intended to be used by implementations of #GSource.
1621  * Do not call this API on a #GSource that you did not create.
1622  *
1623  * Since: 2.28
1624  **/
1625 void
g_source_remove_child_source(GSource * source,GSource * child_source)1626 g_source_remove_child_source (GSource *source,
1627 			      GSource *child_source)
1628 {
1629   GMainContext *context;
1630 
1631   g_return_if_fail (source != NULL);
1632   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1633   g_return_if_fail (child_source != NULL);
1634   g_return_if_fail (g_atomic_int_get (&child_source->ref_count) > 0);
1635   g_return_if_fail (child_source->priv->parent_source == source);
1636   g_return_if_fail (!SOURCE_DESTROYED (source));
1637   g_return_if_fail (!SOURCE_DESTROYED (child_source));
1638 
1639   context = source->context;
1640 
1641   if (context)
1642     LOCK_CONTEXT (context);
1643 
1644   g_child_source_remove_internal (child_source, context);
1645 
1646   if (context)
1647     UNLOCK_CONTEXT (context);
1648 }
1649 
1650 static void
g_source_callback_ref(gpointer cb_data)1651 g_source_callback_ref (gpointer cb_data)
1652 {
1653   GSourceCallback *callback = cb_data;
1654 
1655   g_atomic_int_inc (&callback->ref_count);
1656 }
1657 
1658 static void
g_source_callback_unref(gpointer cb_data)1659 g_source_callback_unref (gpointer cb_data)
1660 {
1661   GSourceCallback *callback = cb_data;
1662 
1663   if (g_atomic_int_dec_and_test (&callback->ref_count))
1664     {
1665       if (callback->notify)
1666         callback->notify (callback->data);
1667       g_free (callback);
1668     }
1669 }
1670 
1671 static void
g_source_callback_get(gpointer cb_data,GSource * source,GSourceFunc * func,gpointer * data)1672 g_source_callback_get (gpointer     cb_data,
1673 		       GSource     *source,
1674 		       GSourceFunc *func,
1675 		       gpointer    *data)
1676 {
1677   GSourceCallback *callback = cb_data;
1678 
1679   *func = callback->func;
1680   *data = callback->data;
1681 }
1682 
1683 static GSourceCallbackFuncs g_source_callback_funcs = {
1684   g_source_callback_ref,
1685   g_source_callback_unref,
1686   g_source_callback_get,
1687 };
1688 
1689 /**
1690  * g_source_set_callback_indirect:
1691  * @source: the source
1692  * @callback_data: pointer to callback data "object"
1693  * @callback_funcs: functions for reference counting @callback_data
1694  *                  and getting the callback and data
1695  *
1696  * Sets the callback function storing the data as a refcounted callback
1697  * "object". This is used internally. Note that calling
1698  * g_source_set_callback_indirect() assumes
1699  * an initial reference count on @callback_data, and thus
1700  * @callback_funcs->unref will eventually be called once more
1701  * than @callback_funcs->ref.
1702  *
1703  * It is safe to call this function multiple times on a source which has already
1704  * been attached to a context. The changes will take effect for the next time
1705  * the source is dispatched after this call returns.
1706  **/
1707 void
g_source_set_callback_indirect(GSource * source,gpointer callback_data,GSourceCallbackFuncs * callback_funcs)1708 g_source_set_callback_indirect (GSource              *source,
1709 				gpointer              callback_data,
1710 				GSourceCallbackFuncs *callback_funcs)
1711 {
1712   GMainContext *context;
1713   gpointer old_cb_data;
1714   GSourceCallbackFuncs *old_cb_funcs;
1715 
1716   g_return_if_fail (source != NULL);
1717   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1718   g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1719 
1720   context = source->context;
1721 
1722   if (context)
1723     LOCK_CONTEXT (context);
1724 
1725   if (callback_funcs != &g_source_callback_funcs)
1726     {
1727       TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source, callback_data,
1728                                                 callback_funcs->ref,
1729                                                 callback_funcs->unref,
1730                                                 callback_funcs->get));
1731     }
1732 
1733   old_cb_data = source->callback_data;
1734   old_cb_funcs = source->callback_funcs;
1735 
1736   source->callback_data = callback_data;
1737   source->callback_funcs = callback_funcs;
1738 
1739   if (context)
1740     UNLOCK_CONTEXT (context);
1741 
1742   if (old_cb_funcs)
1743     old_cb_funcs->unref (old_cb_data);
1744 }
1745 
1746 /**
1747  * g_source_set_callback:
1748  * @source: the source
1749  * @func: a callback function
1750  * @data: the data to pass to callback function
1751  * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1752  *
1753  * Sets the callback function for a source. The callback for a source is
1754  * called from the source's dispatch function.
1755  *
1756  * The exact type of @func depends on the type of source; ie. you
1757  * should not count on @func being called with @data as its first
1758  * parameter. Cast @func with G_SOURCE_FUNC() to avoid warnings about
1759  * incompatible function types.
1760  *
1761  * See [memory management of sources][mainloop-memory-management] for details
1762  * on how to handle memory management of @data.
1763  *
1764  * Typically, you won't use this function. Instead use functions specific
1765  * to the type of source you are using, such as g_idle_add() or g_timeout_add().
1766  *
1767  * It is safe to call this function multiple times on a source which has already
1768  * been attached to a context. The changes will take effect for the next time
1769  * the source is dispatched after this call returns.
1770  *
1771  * Note that g_source_destroy() for a currently attached source has the effect
1772  * of also unsetting the callback.
1773  **/
1774 void
g_source_set_callback(GSource * source,GSourceFunc func,gpointer data,GDestroyNotify notify)1775 g_source_set_callback (GSource        *source,
1776 		       GSourceFunc     func,
1777 		       gpointer        data,
1778 		       GDestroyNotify  notify)
1779 {
1780   GSourceCallback *new_callback;
1781 
1782   g_return_if_fail (source != NULL);
1783   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1784 
1785   TRACE (GLIB_SOURCE_SET_CALLBACK (source, func, data, notify));
1786 
1787   new_callback = g_new (GSourceCallback, 1);
1788 
1789   new_callback->ref_count = 1;
1790   new_callback->func = func;
1791   new_callback->data = data;
1792   new_callback->notify = notify;
1793 
1794   g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1795 }
1796 
1797 
1798 /**
1799  * g_source_set_funcs:
1800  * @source: a #GSource
1801  * @funcs: the new #GSourceFuncs
1802  *
1803  * Sets the source functions (can be used to override
1804  * default implementations) of an unattached source.
1805  *
1806  * Since: 2.12
1807  */
1808 void
g_source_set_funcs(GSource * source,GSourceFuncs * funcs)1809 g_source_set_funcs (GSource     *source,
1810 	           GSourceFuncs *funcs)
1811 {
1812   g_return_if_fail (source != NULL);
1813   g_return_if_fail (source->context == NULL);
1814   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1815   g_return_if_fail (funcs != NULL);
1816 
1817   source->source_funcs = funcs;
1818 }
1819 
1820 static void
g_source_set_priority_unlocked(GSource * source,GMainContext * context,gint priority)1821 g_source_set_priority_unlocked (GSource      *source,
1822 				GMainContext *context,
1823 				gint          priority)
1824 {
1825   GSList *tmp_list;
1826 
1827   g_return_if_fail (source->priv->parent_source == NULL ||
1828 		    source->priv->parent_source->priority == priority);
1829 
1830   TRACE (GLIB_SOURCE_SET_PRIORITY (source, context, priority));
1831 
1832   if (context)
1833     {
1834       /* Remove the source from the context's source and then
1835        * add it back after so it is sorted in the correct place
1836        */
1837       source_remove_from_context (source, source->context);
1838     }
1839 
1840   source->priority = priority;
1841 
1842   if (context)
1843     {
1844       source_add_to_context (source, source->context);
1845 
1846       if (!SOURCE_BLOCKED (source))
1847 	{
1848 	  tmp_list = source->poll_fds;
1849 	  while (tmp_list)
1850 	    {
1851 	      g_main_context_remove_poll_unlocked (context, tmp_list->data);
1852 	      g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1853 
1854 	      tmp_list = tmp_list->next;
1855 	    }
1856 
1857           for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1858             {
1859               g_main_context_remove_poll_unlocked (context, tmp_list->data);
1860               g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1861             }
1862 	}
1863     }
1864 
1865   if (source->priv->child_sources)
1866     {
1867       tmp_list = source->priv->child_sources;
1868       while (tmp_list)
1869 	{
1870 	  g_source_set_priority_unlocked (tmp_list->data, context, priority);
1871 	  tmp_list = tmp_list->next;
1872 	}
1873     }
1874 }
1875 
1876 /**
1877  * g_source_set_priority:
1878  * @source: a #GSource
1879  * @priority: the new priority.
1880  *
1881  * Sets the priority of a source. While the main loop is being run, a
1882  * source will be dispatched if it is ready to be dispatched and no
1883  * sources at a higher (numerically smaller) priority are ready to be
1884  * dispatched.
1885  *
1886  * A child source always has the same priority as its parent.  It is not
1887  * permitted to change the priority of a source once it has been added
1888  * as a child of another source.
1889  **/
1890 void
g_source_set_priority(GSource * source,gint priority)1891 g_source_set_priority (GSource  *source,
1892 		       gint      priority)
1893 {
1894   GMainContext *context;
1895 
1896   g_return_if_fail (source != NULL);
1897   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1898   g_return_if_fail (source->priv->parent_source == NULL);
1899 
1900   context = source->context;
1901 
1902   if (context)
1903     LOCK_CONTEXT (context);
1904   g_source_set_priority_unlocked (source, context, priority);
1905   if (context)
1906     UNLOCK_CONTEXT (context);
1907 }
1908 
1909 /**
1910  * g_source_get_priority:
1911  * @source: a #GSource
1912  *
1913  * Gets the priority of a source.
1914  *
1915  * Returns: the priority of the source
1916  **/
1917 gint
g_source_get_priority(GSource * source)1918 g_source_get_priority (GSource *source)
1919 {
1920   g_return_val_if_fail (source != NULL, 0);
1921   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
1922 
1923   return source->priority;
1924 }
1925 
1926 /**
1927  * g_source_set_ready_time:
1928  * @source: a #GSource
1929  * @ready_time: the monotonic time at which the source will be ready,
1930  *              0 for "immediately", -1 for "never"
1931  *
1932  * Sets a #GSource to be dispatched when the given monotonic time is
1933  * reached (or passed).  If the monotonic time is in the past (as it
1934  * always will be if @ready_time is 0) then the source will be
1935  * dispatched immediately.
1936  *
1937  * If @ready_time is -1 then the source is never woken up on the basis
1938  * of the passage of time.
1939  *
1940  * Dispatching the source does not reset the ready time.  You should do
1941  * so yourself, from the source dispatch function.
1942  *
1943  * Note that if you have a pair of sources where the ready time of one
1944  * suggests that it will be delivered first but the priority for the
1945  * other suggests that it would be delivered first, and the ready time
1946  * for both sources is reached during the same main context iteration,
1947  * then the order of dispatch is undefined.
1948  *
1949  * It is a no-op to call this function on a #GSource which has already been
1950  * destroyed with g_source_destroy().
1951  *
1952  * This API is only intended to be used by implementations of #GSource.
1953  * Do not call this API on a #GSource that you did not create.
1954  *
1955  * Since: 2.36
1956  **/
1957 void
g_source_set_ready_time(GSource * source,gint64 ready_time)1958 g_source_set_ready_time (GSource *source,
1959                          gint64   ready_time)
1960 {
1961   GMainContext *context;
1962 
1963   g_return_if_fail (source != NULL);
1964   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1965 
1966   context = source->context;
1967 
1968   if (context)
1969     LOCK_CONTEXT (context);
1970 
1971   if (source->priv->ready_time == ready_time)
1972     {
1973       if (context)
1974         UNLOCK_CONTEXT (context);
1975 
1976       return;
1977     }
1978 
1979   source->priv->ready_time = ready_time;
1980 
1981   TRACE (GLIB_SOURCE_SET_READY_TIME (source, ready_time));
1982 
1983   if (context)
1984     {
1985       /* Quite likely that we need to change the timeout on the poll */
1986       if (!SOURCE_BLOCKED (source))
1987         g_wakeup_signal (context->wakeup);
1988       UNLOCK_CONTEXT (context);
1989     }
1990 }
1991 
1992 /**
1993  * g_source_get_ready_time:
1994  * @source: a #GSource
1995  *
1996  * Gets the "ready time" of @source, as set by
1997  * g_source_set_ready_time().
1998  *
1999  * Any time before the current monotonic time (including 0) is an
2000  * indication that the source will fire immediately.
2001  *
2002  * Returns: the monotonic ready time, -1 for "never"
2003  **/
2004 gint64
g_source_get_ready_time(GSource * source)2005 g_source_get_ready_time (GSource *source)
2006 {
2007   g_return_val_if_fail (source != NULL, -1);
2008   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, -1);
2009 
2010   return source->priv->ready_time;
2011 }
2012 
2013 /**
2014  * g_source_set_can_recurse:
2015  * @source: a #GSource
2016  * @can_recurse: whether recursion is allowed for this source
2017  *
2018  * Sets whether a source can be called recursively. If @can_recurse is
2019  * %TRUE, then while the source is being dispatched then this source
2020  * will be processed normally. Otherwise, all processing of this
2021  * source is blocked until the dispatch function returns.
2022  **/
2023 void
g_source_set_can_recurse(GSource * source,gboolean can_recurse)2024 g_source_set_can_recurse (GSource  *source,
2025 			  gboolean  can_recurse)
2026 {
2027   GMainContext *context;
2028 
2029   g_return_if_fail (source != NULL);
2030   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2031 
2032   context = source->context;
2033 
2034   if (context)
2035     LOCK_CONTEXT (context);
2036 
2037   if (can_recurse)
2038     source->flags |= G_SOURCE_CAN_RECURSE;
2039   else
2040     source->flags &= ~G_SOURCE_CAN_RECURSE;
2041 
2042   if (context)
2043     UNLOCK_CONTEXT (context);
2044 }
2045 
2046 /**
2047  * g_source_get_can_recurse:
2048  * @source: a #GSource
2049  *
2050  * Checks whether a source is allowed to be called recursively.
2051  * see g_source_set_can_recurse().
2052  *
2053  * Returns: whether recursion is allowed.
2054  **/
2055 gboolean
g_source_get_can_recurse(GSource * source)2056 g_source_get_can_recurse (GSource  *source)
2057 {
2058   g_return_val_if_fail (source != NULL, FALSE);
2059   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, FALSE);
2060 
2061   return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
2062 }
2063 
2064 static void
g_source_set_name_full(GSource * source,const char * name,gboolean is_static)2065 g_source_set_name_full (GSource    *source,
2066                         const char *name,
2067                         gboolean    is_static)
2068 {
2069   GMainContext *context;
2070 
2071   g_return_if_fail (source != NULL);
2072   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2073 
2074   context = source->context;
2075 
2076   if (context)
2077     LOCK_CONTEXT (context);
2078 
2079   TRACE (GLIB_SOURCE_SET_NAME (source, name));
2080 
2081   /* setting back to NULL is allowed, just because it's
2082    * weird if get_name can return NULL but you can't
2083    * set that.
2084    */
2085 
2086   if (!source->priv->static_name)
2087     g_free (source->name);
2088 
2089   if (is_static)
2090     source->name = (char *)name;
2091   else
2092     source->name = g_strdup (name);
2093 
2094   source->priv->static_name = is_static;
2095 
2096   if (context)
2097     UNLOCK_CONTEXT (context);
2098 }
2099 
2100 /**
2101  * g_source_set_name:
2102  * @source: a #GSource
2103  * @name: debug name for the source
2104  *
2105  * Sets a name for the source, used in debugging and profiling.
2106  * The name defaults to #NULL.
2107  *
2108  * The source name should describe in a human-readable way
2109  * what the source does. For example, "X11 event queue"
2110  * or "GTK+ repaint idle handler" or whatever it is.
2111  *
2112  * It is permitted to call this function multiple times, but is not
2113  * recommended due to the potential performance impact.  For example,
2114  * one could change the name in the "check" function of a #GSourceFuncs
2115  * to include details like the event type in the source name.
2116  *
2117  * Use caution if changing the name while another thread may be
2118  * accessing it with g_source_get_name(); that function does not copy
2119  * the value, and changing the value will free it while the other thread
2120  * may be attempting to use it.
2121  *
2122  * Also see g_source_set_static_name().
2123  *
2124  * Since: 2.26
2125  **/
2126 void
g_source_set_name(GSource * source,const char * name)2127 g_source_set_name (GSource    *source,
2128                    const char *name)
2129 {
2130   g_source_set_name_full (source, name, FALSE);
2131 }
2132 
2133 /**
2134  * g_source_set_static_name:
2135  * @source: a #GSource
2136  * @name: debug name for the source
2137  *
2138  * A variant of g_source_set_name() that does not
2139  * duplicate the @name, and can only be used with
2140  * string literals.
2141  *
2142  * Since: 2.70
2143  */
2144 void
g_source_set_static_name(GSource * source,const char * name)2145 g_source_set_static_name (GSource    *source,
2146                           const char *name)
2147 {
2148   g_source_set_name_full (source, name, TRUE);
2149 }
2150 
2151 /**
2152  * g_source_get_name:
2153  * @source: a #GSource
2154  *
2155  * Gets a name for the source, used in debugging and profiling.  The
2156  * name may be #NULL if it has never been set with g_source_set_name().
2157  *
2158  * Returns: (nullable): the name of the source
2159  *
2160  * Since: 2.26
2161  **/
2162 const char *
g_source_get_name(GSource * source)2163 g_source_get_name (GSource *source)
2164 {
2165   g_return_val_if_fail (source != NULL, NULL);
2166   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, NULL);
2167 
2168   return source->name;
2169 }
2170 
2171 /**
2172  * g_source_set_name_by_id:
2173  * @tag: a #GSource ID
2174  * @name: debug name for the source
2175  *
2176  * Sets the name of a source using its ID.
2177  *
2178  * This is a convenience utility to set source names from the return
2179  * value of g_idle_add(), g_timeout_add(), etc.
2180  *
2181  * It is a programmer error to attempt to set the name of a non-existent
2182  * source.
2183  *
2184  * More specifically: source IDs can be reissued after a source has been
2185  * destroyed and therefore it is never valid to use this function with a
2186  * source ID which may have already been removed.  An example is when
2187  * scheduling an idle to run in another thread with g_idle_add(): the
2188  * idle may already have run and been removed by the time this function
2189  * is called on its (now invalid) source ID.  This source ID may have
2190  * been reissued, leading to the operation being performed against the
2191  * wrong source.
2192  *
2193  * Since: 2.26
2194  **/
2195 void
g_source_set_name_by_id(guint tag,const char * name)2196 g_source_set_name_by_id (guint           tag,
2197                          const char     *name)
2198 {
2199   GSource *source;
2200 
2201   g_return_if_fail (tag > 0);
2202 
2203   source = g_main_context_find_source_by_id (NULL, tag);
2204   if (source == NULL)
2205     return;
2206 
2207   g_source_set_name (source, name);
2208 }
2209 
2210 
2211 /**
2212  * g_source_ref:
2213  * @source: a #GSource
2214  *
2215  * Increases the reference count on a source by one.
2216  *
2217  * Returns: @source
2218  **/
2219 GSource *
g_source_ref(GSource * source)2220 g_source_ref (GSource *source)
2221 {
2222   g_return_val_if_fail (source != NULL, NULL);
2223   /* We allow ref_count == 0 here to allow the dispose function to resurrect
2224    * the GSource if needed */
2225   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) >= 0, NULL);
2226 
2227   g_atomic_int_inc (&source->ref_count);
2228 
2229   return source;
2230 }
2231 
2232 /* g_source_unref() but possible to call within context lock
2233  */
2234 static void
g_source_unref_internal(GSource * source,GMainContext * context,gboolean have_lock)2235 g_source_unref_internal (GSource      *source,
2236 			 GMainContext *context,
2237 			 gboolean      have_lock)
2238 {
2239   gpointer old_cb_data = NULL;
2240   GSourceCallbackFuncs *old_cb_funcs = NULL;
2241 
2242   g_return_if_fail (source != NULL);
2243 
2244   if (!have_lock && context)
2245     LOCK_CONTEXT (context);
2246 
2247   if (g_atomic_int_dec_and_test (&source->ref_count))
2248     {
2249       /* If there's a dispose function, call this first */
2250       if (source->priv->dispose)
2251         {
2252           /* Temporarily increase the ref count again so that GSource methods
2253            * can be called from dispose(). */
2254           g_atomic_int_inc (&source->ref_count);
2255           if (context)
2256             UNLOCK_CONTEXT (context);
2257           source->priv->dispose (source);
2258           if (context)
2259             LOCK_CONTEXT (context);
2260 
2261           /* Now the reference count might be bigger than 0 again, in which
2262            * case we simply return from here before freeing the source */
2263           if (!g_atomic_int_dec_and_test (&source->ref_count))
2264             {
2265               if (!have_lock && context)
2266                 UNLOCK_CONTEXT (context);
2267               return;
2268             }
2269         }
2270 
2271       TRACE (GLIB_SOURCE_BEFORE_FREE (source, context,
2272                                       source->source_funcs->finalize));
2273 
2274       old_cb_data = source->callback_data;
2275       old_cb_funcs = source->callback_funcs;
2276 
2277       source->callback_data = NULL;
2278       source->callback_funcs = NULL;
2279 
2280       if (context)
2281 	{
2282 	  if (!SOURCE_DESTROYED (source))
2283 	    g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
2284 	  source_remove_from_context (source, context);
2285 
2286           g_hash_table_remove (context->sources, GUINT_TO_POINTER (source->source_id));
2287 	}
2288 
2289       if (source->source_funcs->finalize)
2290 	{
2291           gint old_ref_count;
2292 
2293           /* Temporarily increase the ref count again so that GSource methods
2294            * can be called from finalize(). */
2295           g_atomic_int_inc (&source->ref_count);
2296 	  if (context)
2297 	    UNLOCK_CONTEXT (context);
2298 	  source->source_funcs->finalize (source);
2299 	  if (context)
2300 	    LOCK_CONTEXT (context);
2301           old_ref_count = g_atomic_int_add (&source->ref_count, -1);
2302           g_warn_if_fail (old_ref_count == 1);
2303 	}
2304 
2305       if (old_cb_funcs)
2306         {
2307           gint old_ref_count;
2308 
2309           /* Temporarily increase the ref count again so that GSource methods
2310            * can be called from callback_funcs.unref(). */
2311           g_atomic_int_inc (&source->ref_count);
2312           if (context)
2313             UNLOCK_CONTEXT (context);
2314 
2315           old_cb_funcs->unref (old_cb_data);
2316 
2317           if (context)
2318             LOCK_CONTEXT (context);
2319           old_ref_count = g_atomic_int_add (&source->ref_count, -1);
2320           g_warn_if_fail (old_ref_count == 1);
2321         }
2322 
2323       if (!source->priv->static_name)
2324         g_free (source->name);
2325       source->name = NULL;
2326 
2327       g_slist_free (source->poll_fds);
2328       source->poll_fds = NULL;
2329 
2330       g_slist_free_full (source->priv->fds, g_free);
2331 
2332       while (source->priv->child_sources)
2333         {
2334           GSource *child_source = source->priv->child_sources->data;
2335 
2336           source->priv->child_sources =
2337             g_slist_remove (source->priv->child_sources, child_source);
2338           child_source->priv->parent_source = NULL;
2339 
2340           g_source_unref_internal (child_source, context, TRUE);
2341         }
2342 
2343       g_slice_free (GSourcePrivate, source->priv);
2344       source->priv = NULL;
2345 
2346       g_free (source);
2347     }
2348 
2349   if (!have_lock && context)
2350     UNLOCK_CONTEXT (context);
2351 }
2352 
2353 /**
2354  * g_source_unref:
2355  * @source: a #GSource
2356  *
2357  * Decreases the reference count of a source by one. If the
2358  * resulting reference count is zero the source and associated
2359  * memory will be destroyed.
2360  **/
2361 void
g_source_unref(GSource * source)2362 g_source_unref (GSource *source)
2363 {
2364   g_return_if_fail (source != NULL);
2365   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2366 
2367   g_source_unref_internal (source, source->context, FALSE);
2368 }
2369 
2370 /**
2371  * g_main_context_find_source_by_id:
2372  * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2373  * @source_id: the source ID, as returned by g_source_get_id().
2374  *
2375  * Finds a #GSource given a pair of context and ID.
2376  *
2377  * It is a programmer error to attempt to look up a non-existent source.
2378  *
2379  * More specifically: source IDs can be reissued after a source has been
2380  * destroyed and therefore it is never valid to use this function with a
2381  * source ID which may have already been removed.  An example is when
2382  * scheduling an idle to run in another thread with g_idle_add(): the
2383  * idle may already have run and been removed by the time this function
2384  * is called on its (now invalid) source ID.  This source ID may have
2385  * been reissued, leading to the operation being performed against the
2386  * wrong source.
2387  *
2388  * Returns: (transfer none): the #GSource
2389  **/
2390 GSource *
g_main_context_find_source_by_id(GMainContext * context,guint source_id)2391 g_main_context_find_source_by_id (GMainContext *context,
2392                                   guint         source_id)
2393 {
2394   GSource *source;
2395 
2396   g_return_val_if_fail (source_id > 0, NULL);
2397 
2398   if (context == NULL)
2399     context = g_main_context_default ();
2400 
2401   LOCK_CONTEXT (context);
2402   source = g_hash_table_lookup (context->sources, GUINT_TO_POINTER (source_id));
2403   UNLOCK_CONTEXT (context);
2404 
2405   if (source && SOURCE_DESTROYED (source))
2406     source = NULL;
2407 
2408   return source;
2409 }
2410 
2411 /**
2412  * g_main_context_find_source_by_funcs_user_data:
2413  * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2414  * @funcs: the @source_funcs passed to g_source_new().
2415  * @user_data: the user data from the callback.
2416  *
2417  * Finds a source with the given source functions and user data.  If
2418  * multiple sources exist with the same source function and user data,
2419  * the first one found will be returned.
2420  *
2421  * Returns: (transfer none): the source, if one was found, otherwise %NULL
2422  **/
2423 GSource *
g_main_context_find_source_by_funcs_user_data(GMainContext * context,GSourceFuncs * funcs,gpointer user_data)2424 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2425 					       GSourceFuncs *funcs,
2426 					       gpointer      user_data)
2427 {
2428   GSourceIter iter;
2429   GSource *source;
2430 
2431   g_return_val_if_fail (funcs != NULL, NULL);
2432 
2433   if (context == NULL)
2434     context = g_main_context_default ();
2435 
2436   LOCK_CONTEXT (context);
2437 
2438   g_source_iter_init (&iter, context, FALSE);
2439   while (g_source_iter_next (&iter, &source))
2440     {
2441       if (!SOURCE_DESTROYED (source) &&
2442 	  source->source_funcs == funcs &&
2443 	  source->callback_funcs)
2444 	{
2445 	  GSourceFunc callback;
2446 	  gpointer callback_data;
2447 
2448 	  source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2449 
2450 	  if (callback_data == user_data)
2451 	    break;
2452 	}
2453     }
2454   g_source_iter_clear (&iter);
2455 
2456   UNLOCK_CONTEXT (context);
2457 
2458   return source;
2459 }
2460 
2461 /**
2462  * g_main_context_find_source_by_user_data:
2463  * @context: a #GMainContext
2464  * @user_data: the user_data for the callback.
2465  *
2466  * Finds a source with the given user data for the callback.  If
2467  * multiple sources exist with the same user data, the first
2468  * one found will be returned.
2469  *
2470  * Returns: (transfer none): the source, if one was found, otherwise %NULL
2471  **/
2472 GSource *
g_main_context_find_source_by_user_data(GMainContext * context,gpointer user_data)2473 g_main_context_find_source_by_user_data (GMainContext *context,
2474 					 gpointer      user_data)
2475 {
2476   GSourceIter iter;
2477   GSource *source;
2478 
2479   if (context == NULL)
2480     context = g_main_context_default ();
2481 
2482   LOCK_CONTEXT (context);
2483 
2484   g_source_iter_init (&iter, context, FALSE);
2485   while (g_source_iter_next (&iter, &source))
2486     {
2487       if (!SOURCE_DESTROYED (source) &&
2488 	  source->callback_funcs)
2489 	{
2490 	  GSourceFunc callback;
2491 	  gpointer callback_data = NULL;
2492 
2493 	  source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2494 
2495 	  if (callback_data == user_data)
2496 	    break;
2497 	}
2498     }
2499   g_source_iter_clear (&iter);
2500 
2501   UNLOCK_CONTEXT (context);
2502 
2503   return source;
2504 }
2505 
2506 /**
2507  * g_source_remove:
2508  * @tag: the ID of the source to remove.
2509  *
2510  * Removes the source with the given ID from the default main context. You must
2511  * use g_source_destroy() for sources added to a non-default main context.
2512  *
2513  * The ID of a #GSource is given by g_source_get_id(), or will be
2514  * returned by the functions g_source_attach(), g_idle_add(),
2515  * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2516  * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2517  * g_io_add_watch_full().
2518  *
2519  * It is a programmer error to attempt to remove a non-existent source.
2520  *
2521  * More specifically: source IDs can be reissued after a source has been
2522  * destroyed and therefore it is never valid to use this function with a
2523  * source ID which may have already been removed.  An example is when
2524  * scheduling an idle to run in another thread with g_idle_add(): the
2525  * idle may already have run and been removed by the time this function
2526  * is called on its (now invalid) source ID.  This source ID may have
2527  * been reissued, leading to the operation being performed against the
2528  * wrong source.
2529  *
2530  * Returns: For historical reasons, this function always returns %TRUE
2531  **/
2532 gboolean
g_source_remove(guint tag)2533 g_source_remove (guint tag)
2534 {
2535   GSource *source;
2536 
2537   g_return_val_if_fail (tag > 0, FALSE);
2538 
2539   source = g_main_context_find_source_by_id (NULL, tag);
2540   if (source)
2541     g_source_destroy (source);
2542   else
2543     g_critical ("Source ID %u was not found when attempting to remove it", tag);
2544 
2545   return source != NULL;
2546 }
2547 
2548 /**
2549  * g_source_remove_by_user_data:
2550  * @user_data: the user_data for the callback.
2551  *
2552  * Removes a source from the default main loop context given the user
2553  * data for the callback. If multiple sources exist with the same user
2554  * data, only one will be destroyed.
2555  *
2556  * Returns: %TRUE if a source was found and removed.
2557  **/
2558 gboolean
g_source_remove_by_user_data(gpointer user_data)2559 g_source_remove_by_user_data (gpointer user_data)
2560 {
2561   GSource *source;
2562 
2563   source = g_main_context_find_source_by_user_data (NULL, user_data);
2564   if (source)
2565     {
2566       g_source_destroy (source);
2567       return TRUE;
2568     }
2569   else
2570     return FALSE;
2571 }
2572 
2573 /**
2574  * g_source_remove_by_funcs_user_data:
2575  * @funcs: The @source_funcs passed to g_source_new()
2576  * @user_data: the user data for the callback
2577  *
2578  * Removes a source from the default main loop context given the
2579  * source functions and user data. If multiple sources exist with the
2580  * same source functions and user data, only one will be destroyed.
2581  *
2582  * Returns: %TRUE if a source was found and removed.
2583  **/
2584 gboolean
g_source_remove_by_funcs_user_data(GSourceFuncs * funcs,gpointer user_data)2585 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2586 				    gpointer      user_data)
2587 {
2588   GSource *source;
2589 
2590   g_return_val_if_fail (funcs != NULL, FALSE);
2591 
2592   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2593   if (source)
2594     {
2595       g_source_destroy (source);
2596       return TRUE;
2597     }
2598   else
2599     return FALSE;
2600 }
2601 
2602 /**
2603  * g_clear_handle_id: (skip)
2604  * @tag_ptr: (not nullable): a pointer to the handler ID
2605  * @clear_func: (not nullable): the function to call to clear the handler
2606  *
2607  * Clears a numeric handler, such as a #GSource ID.
2608  *
2609  * @tag_ptr must be a valid pointer to the variable holding the handler.
2610  *
2611  * If the ID is zero then this function does nothing.
2612  * Otherwise, clear_func() is called with the ID as a parameter, and the tag is
2613  * set to zero.
2614  *
2615  * A macro is also included that allows this function to be used without
2616  * pointer casts.
2617  *
2618  * Since: 2.56
2619  */
2620 #undef g_clear_handle_id
2621 void
g_clear_handle_id(guint * tag_ptr,GClearHandleFunc clear_func)2622 g_clear_handle_id (guint            *tag_ptr,
2623                    GClearHandleFunc  clear_func)
2624 {
2625   guint _handle_id;
2626 
2627   _handle_id = *tag_ptr;
2628   if (_handle_id > 0)
2629     {
2630       *tag_ptr = 0;
2631       clear_func (_handle_id);
2632     }
2633 }
2634 
2635 #ifdef G_OS_UNIX
2636 /**
2637  * g_source_add_unix_fd:
2638  * @source: a #GSource
2639  * @fd: the fd to monitor
2640  * @events: an event mask
2641  *
2642  * Monitors @fd for the IO events in @events.
2643  *
2644  * The tag returned by this function can be used to remove or modify the
2645  * monitoring of the fd using g_source_remove_unix_fd() or
2646  * g_source_modify_unix_fd().
2647  *
2648  * It is not necessary to remove the fd before destroying the source; it
2649  * will be cleaned up automatically.
2650  *
2651  * This API is only intended to be used by implementations of #GSource.
2652  * Do not call this API on a #GSource that you did not create.
2653  *
2654  * As the name suggests, this function is not available on Windows.
2655  *
2656  * Returns: (not nullable): an opaque tag
2657  *
2658  * Since: 2.36
2659  **/
2660 gpointer
g_source_add_unix_fd(GSource * source,gint fd,GIOCondition events)2661 g_source_add_unix_fd (GSource      *source,
2662                       gint          fd,
2663                       GIOCondition  events)
2664 {
2665   GMainContext *context;
2666   GPollFD *poll_fd;
2667 
2668   g_return_val_if_fail (source != NULL, NULL);
2669   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, NULL);
2670   g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2671 
2672   poll_fd = g_new (GPollFD, 1);
2673   poll_fd->fd = fd;
2674   poll_fd->events = events;
2675   poll_fd->revents = 0;
2676 
2677   context = source->context;
2678 
2679   if (context)
2680     LOCK_CONTEXT (context);
2681 
2682   source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2683 
2684   if (context)
2685     {
2686       if (!SOURCE_BLOCKED (source))
2687         g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2688       UNLOCK_CONTEXT (context);
2689     }
2690 
2691   return poll_fd;
2692 }
2693 
2694 /**
2695  * g_source_modify_unix_fd:
2696  * @source: a #GSource
2697  * @tag: (not nullable): the tag from g_source_add_unix_fd()
2698  * @new_events: the new event mask to watch
2699  *
2700  * Updates the event mask to watch for the fd identified by @tag.
2701  *
2702  * @tag is the tag returned from g_source_add_unix_fd().
2703  *
2704  * If you want to remove a fd, don't set its event mask to zero.
2705  * Instead, call g_source_remove_unix_fd().
2706  *
2707  * This API is only intended to be used by implementations of #GSource.
2708  * Do not call this API on a #GSource that you did not create.
2709  *
2710  * As the name suggests, this function is not available on Windows.
2711  *
2712  * Since: 2.36
2713  **/
2714 void
g_source_modify_unix_fd(GSource * source,gpointer tag,GIOCondition new_events)2715 g_source_modify_unix_fd (GSource      *source,
2716                          gpointer      tag,
2717                          GIOCondition  new_events)
2718 {
2719   GMainContext *context;
2720   GPollFD *poll_fd;
2721 
2722   g_return_if_fail (source != NULL);
2723   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2724   g_return_if_fail (g_slist_find (source->priv->fds, tag));
2725 
2726   context = source->context;
2727   poll_fd = tag;
2728 
2729   poll_fd->events = new_events;
2730 
2731   if (context)
2732     g_main_context_wakeup (context);
2733 }
2734 
2735 /**
2736  * g_source_remove_unix_fd:
2737  * @source: a #GSource
2738  * @tag: (not nullable): the tag from g_source_add_unix_fd()
2739  *
2740  * Reverses the effect of a previous call to g_source_add_unix_fd().
2741  *
2742  * You only need to call this if you want to remove an fd from being
2743  * watched while keeping the same source around.  In the normal case you
2744  * will just want to destroy the source.
2745  *
2746  * This API is only intended to be used by implementations of #GSource.
2747  * Do not call this API on a #GSource that you did not create.
2748  *
2749  * As the name suggests, this function is not available on Windows.
2750  *
2751  * Since: 2.36
2752  **/
2753 void
g_source_remove_unix_fd(GSource * source,gpointer tag)2754 g_source_remove_unix_fd (GSource  *source,
2755                          gpointer  tag)
2756 {
2757   GMainContext *context;
2758   GPollFD *poll_fd;
2759 
2760   g_return_if_fail (source != NULL);
2761   g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2762   g_return_if_fail (g_slist_find (source->priv->fds, tag));
2763 
2764   context = source->context;
2765   poll_fd = tag;
2766 
2767   if (context)
2768     LOCK_CONTEXT (context);
2769 
2770   source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2771 
2772   if (context)
2773     {
2774       if (!SOURCE_BLOCKED (source))
2775         g_main_context_remove_poll_unlocked (context, poll_fd);
2776 
2777       UNLOCK_CONTEXT (context);
2778     }
2779 
2780   g_free (poll_fd);
2781 }
2782 
2783 /**
2784  * g_source_query_unix_fd:
2785  * @source: a #GSource
2786  * @tag: (not nullable): the tag from g_source_add_unix_fd()
2787  *
2788  * Queries the events reported for the fd corresponding to @tag on
2789  * @source during the last poll.
2790  *
2791  * The return value of this function is only defined when the function
2792  * is called from the check or dispatch functions for @source.
2793  *
2794  * This API is only intended to be used by implementations of #GSource.
2795  * Do not call this API on a #GSource that you did not create.
2796  *
2797  * As the name suggests, this function is not available on Windows.
2798  *
2799  * Returns: the conditions reported on the fd
2800  *
2801  * Since: 2.36
2802  **/
2803 GIOCondition
g_source_query_unix_fd(GSource * source,gpointer tag)2804 g_source_query_unix_fd (GSource  *source,
2805                         gpointer  tag)
2806 {
2807   GPollFD *poll_fd;
2808 
2809   g_return_val_if_fail (source != NULL, 0);
2810   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
2811   g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2812 
2813   poll_fd = tag;
2814 
2815   return poll_fd->revents;
2816 }
2817 #endif /* G_OS_UNIX */
2818 
2819 /**
2820  * g_get_current_time:
2821  * @result: #GTimeVal structure in which to store current time.
2822  *
2823  * Equivalent to the UNIX gettimeofday() function, but portable.
2824  *
2825  * You may find g_get_real_time() to be more convenient.
2826  *
2827  * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use g_get_real_time()
2828  *    instead.
2829  **/
2830 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
2831 void
g_get_current_time(GTimeVal * result)2832 g_get_current_time (GTimeVal *result)
2833 {
2834   gint64 tv;
2835 
2836   g_return_if_fail (result != NULL);
2837 
2838   tv = g_get_real_time ();
2839 
2840   result->tv_sec = tv / 1000000;
2841   result->tv_usec = tv % 1000000;
2842 }
2843 G_GNUC_END_IGNORE_DEPRECATIONS
2844 
2845 /**
2846  * g_get_real_time:
2847  *
2848  * Queries the system wall-clock time.
2849  *
2850  * This call is functionally equivalent to g_get_current_time() except
2851  * that the return value is often more convenient than dealing with a
2852  * #GTimeVal.
2853  *
2854  * You should only use this call if you are actually interested in the real
2855  * wall-clock time.  g_get_monotonic_time() is probably more useful for
2856  * measuring intervals.
2857  *
2858  * Returns: the number of microseconds since January 1, 1970 UTC.
2859  *
2860  * Since: 2.28
2861  **/
2862 gint64
g_get_real_time(void)2863 g_get_real_time (void)
2864 {
2865 #ifndef G_OS_WIN32
2866   struct timeval r;
2867 
2868   /* this is required on alpha, there the timeval structs are ints
2869    * not longs and a cast only would fail horribly */
2870   gettimeofday (&r, NULL);
2871 
2872   return (((gint64) r.tv_sec) * 1000000) + r.tv_usec;
2873 #else
2874   FILETIME ft;
2875   guint64 time64;
2876 
2877   GetSystemTimeAsFileTime (&ft);
2878   memmove (&time64, &ft, sizeof (FILETIME));
2879 
2880   /* Convert from 100s of nanoseconds since 1601-01-01
2881    * to Unix epoch. This is Y2038 safe.
2882    */
2883   time64 -= G_GINT64_CONSTANT (116444736000000000);
2884   time64 /= 10;
2885 
2886   return time64;
2887 #endif
2888 }
2889 
2890 /**
2891  * g_get_monotonic_time:
2892  *
2893  * Queries the system monotonic time.
2894  *
2895  * The monotonic clock will always increase and doesn't suffer
2896  * discontinuities when the user (or NTP) changes the system time.  It
2897  * may or may not continue to tick during times where the machine is
2898  * suspended.
2899  *
2900  * We try to use the clock that corresponds as closely as possible to
2901  * the passage of time as measured by system calls such as poll() but it
2902  * may not always be possible to do this.
2903  *
2904  * Returns: the monotonic time, in microseconds
2905  *
2906  * Since: 2.28
2907  **/
2908 #if defined (G_OS_WIN32)
2909 /* NOTE:
2910  * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
2911  *
2912  * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
2913  * (ticks_since_boot  / ticks_per_sec) and then multiply would not be accurate enough.
2914  * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
2915  */
2916 static gdouble g_monotonic_usec_per_tick = 0;
2917 
2918 void
g_clock_win32_init(void)2919 g_clock_win32_init (void)
2920 {
2921   LARGE_INTEGER freq;
2922 
2923   if (!QueryPerformanceFrequency (&freq) || freq.QuadPart == 0)
2924     {
2925       /* The documentation says that this should never happen */
2926       g_assert_not_reached ();
2927       return;
2928     }
2929 
2930   g_monotonic_usec_per_tick = (gdouble)G_USEC_PER_SEC / freq.QuadPart;
2931 }
2932 
2933 gint64
g_get_monotonic_time(void)2934 g_get_monotonic_time (void)
2935 {
2936   if (G_LIKELY (g_monotonic_usec_per_tick != 0))
2937     {
2938       LARGE_INTEGER ticks;
2939 
2940       if (QueryPerformanceCounter (&ticks))
2941         return (gint64)(ticks.QuadPart * g_monotonic_usec_per_tick);
2942 
2943       g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
2944       g_monotonic_usec_per_tick = 0;
2945     }
2946 
2947   return 0;
2948 }
2949 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2950 gint64
g_get_monotonic_time(void)2951 g_get_monotonic_time (void)
2952 {
2953   mach_timebase_info_data_t timebase_info;
2954   guint64 val;
2955 
2956   /* we get nanoseconds from mach_absolute_time() using timebase_info */
2957   mach_timebase_info (&timebase_info);
2958   val = mach_absolute_time ();
2959 
2960   if (timebase_info.numer != timebase_info.denom)
2961     {
2962 #ifdef HAVE_UINT128_T
2963       val = ((__uint128_t) val * (__uint128_t) timebase_info.numer) / timebase_info.denom / 1000;
2964 #else
2965       guint64 t_high, t_low;
2966       guint64 result_high, result_low;
2967 
2968       /* 64 bit x 32 bit / 32 bit with 96-bit intermediate
2969        * algorithm lifted from qemu */
2970       t_low = (val & 0xffffffffLL) * (guint64) timebase_info.numer;
2971       t_high = (val >> 32) * (guint64) timebase_info.numer;
2972       t_high += (t_low >> 32);
2973       result_high = t_high / (guint64) timebase_info.denom;
2974       result_low = (((t_high % (guint64) timebase_info.denom) << 32) +
2975                     (t_low & 0xffffffff)) /
2976                    (guint64) timebase_info.denom;
2977       val = ((result_high << 32) | result_low) / 1000;
2978 #endif
2979     }
2980   else
2981     {
2982       /* nanoseconds to microseconds */
2983       val = val / 1000;
2984     }
2985 
2986   return val;
2987 }
2988 #else
2989 gint64
g_get_monotonic_time(void)2990 g_get_monotonic_time (void)
2991 {
2992   struct timespec ts;
2993   gint result;
2994 
2995   result = clock_gettime (CLOCK_MONOTONIC, &ts);
2996 
2997   if G_UNLIKELY (result != 0)
2998     g_error ("GLib requires working CLOCK_MONOTONIC");
2999 
3000   return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
3001 }
3002 #endif
3003 
3004 static void
g_main_dispatch_free(gpointer dispatch)3005 g_main_dispatch_free (gpointer dispatch)
3006 {
3007   g_free (dispatch);
3008 }
3009 
3010 /* Running the main loop */
3011 
3012 static GMainDispatch *
get_dispatch(void)3013 get_dispatch (void)
3014 {
3015   static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
3016   GMainDispatch *dispatch;
3017 
3018   dispatch = g_private_get (&depth_private);
3019 
3020   if (!dispatch)
3021     dispatch = g_private_set_alloc0 (&depth_private, sizeof (GMainDispatch));
3022 
3023   return dispatch;
3024 }
3025 
3026 /**
3027  * g_main_depth:
3028  *
3029  * Returns the depth of the stack of calls to
3030  * g_main_context_dispatch() on any #GMainContext in the current thread.
3031  *  That is, when called from the toplevel, it gives 0. When
3032  * called from within a callback from g_main_context_iteration()
3033  * (or g_main_loop_run(), etc.) it returns 1. When called from within
3034  * a callback to a recursive call to g_main_context_iteration(),
3035  * it returns 2. And so forth.
3036  *
3037  * This function is useful in a situation like the following:
3038  * Imagine an extremely simple "garbage collected" system.
3039  *
3040  * |[<!-- language="C" -->
3041  * static GList *free_list;
3042  *
3043  * gpointer
3044  * allocate_memory (gsize size)
3045  * {
3046  *   gpointer result = g_malloc (size);
3047  *   free_list = g_list_prepend (free_list, result);
3048  *   return result;
3049  * }
3050  *
3051  * void
3052  * free_allocated_memory (void)
3053  * {
3054  *   GList *l;
3055  *   for (l = free_list; l; l = l->next);
3056  *     g_free (l->data);
3057  *   g_list_free (free_list);
3058  *   free_list = NULL;
3059  *  }
3060  *
3061  * [...]
3062  *
3063  * while (TRUE);
3064  *  {
3065  *    g_main_context_iteration (NULL, TRUE);
3066  *    free_allocated_memory();
3067  *   }
3068  * ]|
3069  *
3070  * This works from an application, however, if you want to do the same
3071  * thing from a library, it gets more difficult, since you no longer
3072  * control the main loop. You might think you can simply use an idle
3073  * function to make the call to free_allocated_memory(), but that
3074  * doesn't work, since the idle function could be called from a
3075  * recursive callback. This can be fixed by using g_main_depth()
3076  *
3077  * |[<!-- language="C" -->
3078  * gpointer
3079  * allocate_memory (gsize size)
3080  * {
3081  *   FreeListBlock *block = g_new (FreeListBlock, 1);
3082  *   block->mem = g_malloc (size);
3083  *   block->depth = g_main_depth ();
3084  *   free_list = g_list_prepend (free_list, block);
3085  *   return block->mem;
3086  * }
3087  *
3088  * void
3089  * free_allocated_memory (void)
3090  * {
3091  *   GList *l;
3092  *
3093  *   int depth = g_main_depth ();
3094  *   for (l = free_list; l; );
3095  *     {
3096  *       GList *next = l->next;
3097  *       FreeListBlock *block = l->data;
3098  *       if (block->depth > depth)
3099  *         {
3100  *           g_free (block->mem);
3101  *           g_free (block);
3102  *           free_list = g_list_delete_link (free_list, l);
3103  *         }
3104  *
3105  *       l = next;
3106  *     }
3107  *   }
3108  * ]|
3109  *
3110  * There is a temptation to use g_main_depth() to solve
3111  * problems with reentrancy. For instance, while waiting for data
3112  * to be received from the network in response to a menu item,
3113  * the menu item might be selected again. It might seem that
3114  * one could make the menu item's callback return immediately
3115  * and do nothing if g_main_depth() returns a value greater than 1.
3116  * However, this should be avoided since the user then sees selecting
3117  * the menu item do nothing. Furthermore, you'll find yourself adding
3118  * these checks all over your code, since there are doubtless many,
3119  * many things that the user could do. Instead, you can use the
3120  * following techniques:
3121  *
3122  * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
3123  *    the user from interacting with elements while the main
3124  *    loop is recursing.
3125  *
3126  * 2. Avoid main loop recursion in situations where you can't handle
3127  *    arbitrary  callbacks. Instead, structure your code so that you
3128  *    simply return to the main loop and then get called again when
3129  *    there is more work to do.
3130  *
3131  * Returns: The main loop recursion level in the current thread
3132  */
3133 int
g_main_depth(void)3134 g_main_depth (void)
3135 {
3136   GMainDispatch *dispatch = get_dispatch ();
3137   return dispatch->depth;
3138 }
3139 
3140 /**
3141  * g_main_current_source:
3142  *
3143  * Returns the currently firing source for this thread.
3144  *
3145  * Returns: (transfer none) (nullable): The currently firing source or %NULL.
3146  *
3147  * Since: 2.12
3148  */
3149 GSource *
g_main_current_source(void)3150 g_main_current_source (void)
3151 {
3152   GMainDispatch *dispatch = get_dispatch ();
3153   return dispatch->source;
3154 }
3155 
3156 /**
3157  * g_source_is_destroyed:
3158  * @source: a #GSource
3159  *
3160  * Returns whether @source has been destroyed.
3161  *
3162  * This is important when you operate upon your objects
3163  * from within idle handlers, but may have freed the object
3164  * before the dispatch of your idle handler.
3165  *
3166  * |[<!-- language="C" -->
3167  * static gboolean
3168  * idle_callback (gpointer data)
3169  * {
3170  *   SomeWidget *self = data;
3171  *
3172  *   g_mutex_lock (&self->idle_id_mutex);
3173  *   // do stuff with self
3174  *   self->idle_id = 0;
3175  *   g_mutex_unlock (&self->idle_id_mutex);
3176  *
3177  *   return G_SOURCE_REMOVE;
3178  * }
3179  *
3180  * static void
3181  * some_widget_do_stuff_later (SomeWidget *self)
3182  * {
3183  *   g_mutex_lock (&self->idle_id_mutex);
3184  *   self->idle_id = g_idle_add (idle_callback, self);
3185  *   g_mutex_unlock (&self->idle_id_mutex);
3186  * }
3187  *
3188  * static void
3189  * some_widget_init (SomeWidget *self)
3190  * {
3191  *   g_mutex_init (&self->idle_id_mutex);
3192  *
3193  *   // ...
3194  * }
3195  *
3196  * static void
3197  * some_widget_finalize (GObject *object)
3198  * {
3199  *   SomeWidget *self = SOME_WIDGET (object);
3200  *
3201  *   if (self->idle_id)
3202  *     g_source_remove (self->idle_id);
3203  *
3204  *   g_mutex_clear (&self->idle_id_mutex);
3205  *
3206  *   G_OBJECT_CLASS (parent_class)->finalize (object);
3207  * }
3208  * ]|
3209  *
3210  * This will fail in a multi-threaded application if the
3211  * widget is destroyed before the idle handler fires due
3212  * to the use after free in the callback. A solution, to
3213  * this particular problem, is to check to if the source
3214  * has already been destroy within the callback.
3215  *
3216  * |[<!-- language="C" -->
3217  * static gboolean
3218  * idle_callback (gpointer data)
3219  * {
3220  *   SomeWidget *self = data;
3221  *
3222  *   g_mutex_lock (&self->idle_id_mutex);
3223  *   if (!g_source_is_destroyed (g_main_current_source ()))
3224  *     {
3225  *       // do stuff with self
3226  *     }
3227  *   g_mutex_unlock (&self->idle_id_mutex);
3228  *
3229  *   return FALSE;
3230  * }
3231  * ]|
3232  *
3233  * Calls to this function from a thread other than the one acquired by the
3234  * #GMainContext the #GSource is attached to are typically redundant, as the
3235  * source could be destroyed immediately after this function returns. However,
3236  * once a source is destroyed it cannot be un-destroyed, so this function can be
3237  * used for opportunistic checks from any thread.
3238  *
3239  * Returns: %TRUE if the source has been destroyed
3240  *
3241  * Since: 2.12
3242  */
3243 gboolean
g_source_is_destroyed(GSource * source)3244 g_source_is_destroyed (GSource *source)
3245 {
3246   g_return_val_if_fail (source != NULL, TRUE);
3247   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, TRUE);
3248   return SOURCE_DESTROYED (source);
3249 }
3250 
3251 /* Temporarily remove all this source's file descriptors from the
3252  * poll(), so that if data comes available for one of the file descriptors
3253  * we don't continually spin in the poll()
3254  */
3255 /* HOLDS: source->context's lock */
3256 static void
block_source(GSource * source)3257 block_source (GSource *source)
3258 {
3259   GSList *tmp_list;
3260 
3261   g_return_if_fail (!SOURCE_BLOCKED (source));
3262 
3263   source->flags |= G_SOURCE_BLOCKED;
3264 
3265   if (source->context)
3266     {
3267       tmp_list = source->poll_fds;
3268       while (tmp_list)
3269         {
3270           g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3271           tmp_list = tmp_list->next;
3272         }
3273 
3274       for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3275         g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3276     }
3277 
3278   if (source->priv && source->priv->child_sources)
3279     {
3280       tmp_list = source->priv->child_sources;
3281       while (tmp_list)
3282 	{
3283 	  block_source (tmp_list->data);
3284 	  tmp_list = tmp_list->next;
3285 	}
3286     }
3287 }
3288 
3289 /* HOLDS: source->context's lock */
3290 static void
unblock_source(GSource * source)3291 unblock_source (GSource *source)
3292 {
3293   GSList *tmp_list;
3294 
3295   g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
3296   g_return_if_fail (!SOURCE_DESTROYED (source));
3297 
3298   source->flags &= ~G_SOURCE_BLOCKED;
3299 
3300   tmp_list = source->poll_fds;
3301   while (tmp_list)
3302     {
3303       g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3304       tmp_list = tmp_list->next;
3305     }
3306 
3307   for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3308     g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3309 
3310   if (source->priv && source->priv->child_sources)
3311     {
3312       tmp_list = source->priv->child_sources;
3313       while (tmp_list)
3314 	{
3315 	  unblock_source (tmp_list->data);
3316 	  tmp_list = tmp_list->next;
3317 	}
3318     }
3319 }
3320 
3321 /* HOLDS: context's lock */
3322 static void
g_main_dispatch(GMainContext * context)3323 g_main_dispatch (GMainContext *context)
3324 {
3325   GMainDispatch *current = get_dispatch ();
3326   guint i;
3327 
3328   for (i = 0; i < context->pending_dispatches->len; i++)
3329     {
3330       GSource *source = context->pending_dispatches->pdata[i];
3331 
3332       context->pending_dispatches->pdata[i] = NULL;
3333       g_assert (source);
3334 
3335       source->flags &= ~G_SOURCE_READY;
3336 
3337       if (!SOURCE_DESTROYED (source))
3338 	{
3339 	  gboolean was_in_call;
3340 	  gpointer user_data = NULL;
3341 	  GSourceFunc callback = NULL;
3342 	  GSourceCallbackFuncs *cb_funcs;
3343 	  gpointer cb_data;
3344 	  gboolean need_destroy;
3345 
3346 	  gboolean (*dispatch) (GSource *,
3347 				GSourceFunc,
3348 				gpointer);
3349           GSource *prev_source;
3350           gint64 begin_time_nsec G_GNUC_UNUSED;
3351 
3352 	  dispatch = source->source_funcs->dispatch;
3353 	  cb_funcs = source->callback_funcs;
3354 	  cb_data = source->callback_data;
3355 
3356 	  if (cb_funcs)
3357 	    cb_funcs->ref (cb_data);
3358 
3359 	  if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3360 	    block_source (source);
3361 
3362 	  was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3363 	  source->flags |= G_HOOK_FLAG_IN_CALL;
3364 
3365 	  if (cb_funcs)
3366 	    cb_funcs->get (cb_data, source, &callback, &user_data);
3367 
3368 	  UNLOCK_CONTEXT (context);
3369 
3370           /* These operations are safe because 'current' is thread-local
3371            * and not modified from anywhere but this function.
3372            */
3373           prev_source = current->source;
3374           current->source = source;
3375           current->depth++;
3376 
3377           begin_time_nsec = G_TRACE_CURRENT_TIME;
3378 
3379           TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source), source,
3380                                             dispatch, callback, user_data));
3381           need_destroy = !(* dispatch) (source, callback, user_data);
3382           TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source), source,
3383                                            dispatch, need_destroy));
3384 
3385           g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
3386                         "GLib", "GSource.dispatch",
3387                         "%s ⇒ %s",
3388                         (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
3389                         need_destroy ? "destroy" : "keep");
3390 
3391           current->source = prev_source;
3392           current->depth--;
3393 
3394 	  if (cb_funcs)
3395 	    cb_funcs->unref (cb_data);
3396 
3397  	  LOCK_CONTEXT (context);
3398 
3399 	  if (!was_in_call)
3400 	    source->flags &= ~G_HOOK_FLAG_IN_CALL;
3401 
3402 	  if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3403 	    unblock_source (source);
3404 
3405 	  /* Note: this depends on the fact that we can't switch
3406 	   * sources from one main context to another
3407 	   */
3408 	  if (need_destroy && !SOURCE_DESTROYED (source))
3409 	    {
3410 	      g_assert (source->context == context);
3411 	      g_source_destroy_internal (source, context, TRUE);
3412 	    }
3413 	}
3414 
3415       g_source_unref_internal (source, context, TRUE);
3416     }
3417 
3418   g_ptr_array_set_size (context->pending_dispatches, 0);
3419 }
3420 
3421 /**
3422  * g_main_context_acquire:
3423  * @context: a #GMainContext
3424  *
3425  * Tries to become the owner of the specified context.
3426  * If some other thread is the owner of the context,
3427  * returns %FALSE immediately. Ownership is properly
3428  * recursive: the owner can require ownership again
3429  * and will release ownership when g_main_context_release()
3430  * is called as many times as g_main_context_acquire().
3431  *
3432  * You must be the owner of a context before you
3433  * can call g_main_context_prepare(), g_main_context_query(),
3434  * g_main_context_check(), g_main_context_dispatch().
3435  *
3436  * Returns: %TRUE if the operation succeeded, and
3437  *   this thread is now the owner of @context.
3438  **/
3439 gboolean
g_main_context_acquire(GMainContext * context)3440 g_main_context_acquire (GMainContext *context)
3441 {
3442   gboolean result = FALSE;
3443   GThread *self = G_THREAD_SELF;
3444 
3445   if (context == NULL)
3446     context = g_main_context_default ();
3447 
3448   LOCK_CONTEXT (context);
3449 
3450   if (!context->owner)
3451     {
3452       context->owner = self;
3453       g_assert (context->owner_count == 0);
3454       TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, TRUE  /* success */));
3455     }
3456 
3457   if (context->owner == self)
3458     {
3459       context->owner_count++;
3460       result = TRUE;
3461     }
3462   else
3463     {
3464       TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, FALSE  /* failure */));
3465     }
3466 
3467   UNLOCK_CONTEXT (context);
3468 
3469   return result;
3470 }
3471 
3472 /**
3473  * g_main_context_release:
3474  * @context: a #GMainContext
3475  *
3476  * Releases ownership of a context previously acquired by this thread
3477  * with g_main_context_acquire(). If the context was acquired multiple
3478  * times, the ownership will be released only when g_main_context_release()
3479  * is called as many times as it was acquired.
3480  **/
3481 void
g_main_context_release(GMainContext * context)3482 g_main_context_release (GMainContext *context)
3483 {
3484   if (context == NULL)
3485     context = g_main_context_default ();
3486 
3487   LOCK_CONTEXT (context);
3488 
3489   context->owner_count--;
3490   if (context->owner_count == 0)
3491     {
3492       TRACE (GLIB_MAIN_CONTEXT_RELEASE (context));
3493 
3494       context->owner = NULL;
3495 
3496       if (context->waiters)
3497 	{
3498 	  GMainWaiter *waiter = context->waiters->data;
3499 	  gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3500 	  context->waiters = g_slist_delete_link (context->waiters,
3501 						  context->waiters);
3502 	  if (!loop_internal_waiter)
3503 	    g_mutex_lock (waiter->mutex);
3504 
3505 	  g_cond_signal (waiter->cond);
3506 
3507 	  if (!loop_internal_waiter)
3508 	    g_mutex_unlock (waiter->mutex);
3509 	}
3510     }
3511 
3512   UNLOCK_CONTEXT (context);
3513 }
3514 
3515 static gboolean
g_main_context_wait_internal(GMainContext * context,GCond * cond,GMutex * mutex)3516 g_main_context_wait_internal (GMainContext *context,
3517                               GCond        *cond,
3518                               GMutex       *mutex)
3519 {
3520   gboolean result = FALSE;
3521   GThread *self = G_THREAD_SELF;
3522   gboolean loop_internal_waiter;
3523 
3524   if (context == NULL)
3525     context = g_main_context_default ();
3526 
3527   loop_internal_waiter = (mutex == &context->mutex);
3528 
3529   if (!loop_internal_waiter)
3530     LOCK_CONTEXT (context);
3531 
3532   if (context->owner && context->owner != self)
3533     {
3534       GMainWaiter waiter;
3535 
3536       waiter.cond = cond;
3537       waiter.mutex = mutex;
3538 
3539       context->waiters = g_slist_append (context->waiters, &waiter);
3540 
3541       if (!loop_internal_waiter)
3542         UNLOCK_CONTEXT (context);
3543       g_cond_wait (cond, mutex);
3544       if (!loop_internal_waiter)
3545         LOCK_CONTEXT (context);
3546 
3547       context->waiters = g_slist_remove (context->waiters, &waiter);
3548     }
3549 
3550   if (!context->owner)
3551     {
3552       context->owner = self;
3553       g_assert (context->owner_count == 0);
3554     }
3555 
3556   if (context->owner == self)
3557     {
3558       context->owner_count++;
3559       result = TRUE;
3560     }
3561 
3562   if (!loop_internal_waiter)
3563     UNLOCK_CONTEXT (context);
3564 
3565   return result;
3566 }
3567 
3568 /**
3569  * g_main_context_wait:
3570  * @context: a #GMainContext
3571  * @cond: a condition variable
3572  * @mutex: a mutex, currently held
3573  *
3574  * Tries to become the owner of the specified context,
3575  * as with g_main_context_acquire(). But if another thread
3576  * is the owner, atomically drop @mutex and wait on @cond until
3577  * that owner releases ownership or until @cond is signaled, then
3578  * try again (once) to become the owner.
3579  *
3580  * Returns: %TRUE if the operation succeeded, and
3581  *   this thread is now the owner of @context.
3582  * Deprecated: 2.58: Use g_main_context_is_owner() and separate locking instead.
3583  */
3584 gboolean
g_main_context_wait(GMainContext * context,GCond * cond,GMutex * mutex)3585 g_main_context_wait (GMainContext *context,
3586                      GCond        *cond,
3587                      GMutex       *mutex)
3588 {
3589   if (context == NULL)
3590     context = g_main_context_default ();
3591 
3592   if (G_UNLIKELY (cond != &context->cond || mutex != &context->mutex))
3593     {
3594       static gboolean warned;
3595 
3596       if (!warned)
3597         {
3598           g_critical ("WARNING!! g_main_context_wait() will be removed in a future release.  "
3599                       "If you see this message, please file a bug immediately.");
3600           warned = TRUE;
3601         }
3602     }
3603 
3604   return g_main_context_wait_internal (context, cond, mutex);
3605 }
3606 
3607 /**
3608  * g_main_context_prepare:
3609  * @context: a #GMainContext
3610  * @priority: (out) (optional): location to store priority of highest priority
3611  *            source already ready.
3612  *
3613  * Prepares to poll sources within a main loop. The resulting information
3614  * for polling is determined by calling g_main_context_query ().
3615  *
3616  * You must have successfully acquired the context with
3617  * g_main_context_acquire() before you may call this function.
3618  *
3619  * Returns: %TRUE if some source is ready to be dispatched
3620  *               prior to polling.
3621  **/
3622 gboolean
g_main_context_prepare(GMainContext * context,gint * priority)3623 g_main_context_prepare (GMainContext *context,
3624 			gint         *priority)
3625 {
3626   guint i;
3627   gint n_ready = 0;
3628   gint current_priority = G_MAXINT;
3629   GSource *source;
3630   GSourceIter iter;
3631 
3632   if (context == NULL)
3633     context = g_main_context_default ();
3634 
3635   LOCK_CONTEXT (context);
3636 
3637   context->time_is_fresh = FALSE;
3638 
3639   if (context->in_check_or_prepare)
3640     {
3641       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3642 		 "prepare() member.");
3643       UNLOCK_CONTEXT (context);
3644       return FALSE;
3645     }
3646 
3647   TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context));
3648 
3649 #if 0
3650   /* If recursing, finish up current dispatch, before starting over */
3651   if (context->pending_dispatches)
3652     {
3653       if (dispatch)
3654 	g_main_dispatch (context, &current_time);
3655 
3656       UNLOCK_CONTEXT (context);
3657       return TRUE;
3658     }
3659 #endif
3660 
3661   /* If recursing, clear list of pending dispatches */
3662 
3663   for (i = 0; i < context->pending_dispatches->len; i++)
3664     {
3665       if (context->pending_dispatches->pdata[i])
3666         g_source_unref_internal ((GSource *)context->pending_dispatches->pdata[i], context, TRUE);
3667     }
3668   g_ptr_array_set_size (context->pending_dispatches, 0);
3669 
3670   /* Prepare all sources */
3671 
3672   context->timeout = -1;
3673 
3674   g_source_iter_init (&iter, context, TRUE);
3675   while (g_source_iter_next (&iter, &source))
3676     {
3677       gint source_timeout = -1;
3678 
3679       if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3680 	continue;
3681       if ((n_ready > 0) && (source->priority > current_priority))
3682 	break;
3683 
3684       if (!(source->flags & G_SOURCE_READY))
3685 	{
3686 	  gboolean result;
3687 	  gboolean (* prepare) (GSource  *source,
3688                                 gint     *timeout);
3689 
3690           prepare = source->source_funcs->prepare;
3691 
3692           if (prepare)
3693             {
3694               gint64 begin_time_nsec G_GNUC_UNUSED;
3695 
3696               context->in_check_or_prepare++;
3697               UNLOCK_CONTEXT (context);
3698 
3699               begin_time_nsec = G_TRACE_CURRENT_TIME;
3700 
3701               result = (* prepare) (source, &source_timeout);
3702               TRACE (GLIB_MAIN_AFTER_PREPARE (source, prepare, source_timeout));
3703 
3704               g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
3705                             "GLib", "GSource.prepare",
3706                             "%s ⇒ %s",
3707                             (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
3708                             result ? "ready" : "unready");
3709 
3710               LOCK_CONTEXT (context);
3711               context->in_check_or_prepare--;
3712             }
3713           else
3714             {
3715               source_timeout = -1;
3716               result = FALSE;
3717             }
3718 
3719           if (result == FALSE && source->priv->ready_time != -1)
3720             {
3721               if (!context->time_is_fresh)
3722                 {
3723                   context->time = g_get_monotonic_time ();
3724                   context->time_is_fresh = TRUE;
3725                 }
3726 
3727               if (source->priv->ready_time <= context->time)
3728                 {
3729                   source_timeout = 0;
3730                   result = TRUE;
3731                 }
3732               else
3733                 {
3734                   gint64 timeout;
3735 
3736                   /* rounding down will lead to spinning, so always round up */
3737                   timeout = (source->priv->ready_time - context->time + 999) / 1000;
3738 
3739                   if (source_timeout < 0 || timeout < source_timeout)
3740                     source_timeout = MIN (timeout, G_MAXINT);
3741                 }
3742             }
3743 
3744 	  if (result)
3745 	    {
3746 	      GSource *ready_source = source;
3747 
3748 	      while (ready_source)
3749 		{
3750 		  ready_source->flags |= G_SOURCE_READY;
3751 		  ready_source = ready_source->priv->parent_source;
3752 		}
3753 	    }
3754 	}
3755 
3756       if (source->flags & G_SOURCE_READY)
3757 	{
3758 	  n_ready++;
3759 	  current_priority = source->priority;
3760 	  context->timeout = 0;
3761 	}
3762 
3763       if (source_timeout >= 0)
3764 	{
3765 	  if (context->timeout < 0)
3766 	    context->timeout = source_timeout;
3767 	  else
3768 	    context->timeout = MIN (context->timeout, source_timeout);
3769 	}
3770     }
3771   g_source_iter_clear (&iter);
3772 
3773   TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context, current_priority, n_ready));
3774 
3775   UNLOCK_CONTEXT (context);
3776 
3777   if (priority)
3778     *priority = current_priority;
3779 
3780   return (n_ready > 0);
3781 }
3782 
3783 /**
3784  * g_main_context_query:
3785  * @context: a #GMainContext
3786  * @max_priority: maximum priority source to check
3787  * @timeout_: (out): location to store timeout to be used in polling
3788  * @fds: (out caller-allocates) (array length=n_fds): location to
3789  *       store #GPollFD records that need to be polled.
3790  * @n_fds: (in): length of @fds.
3791  *
3792  * Determines information necessary to poll this main loop. You should
3793  * be careful to pass the resulting @fds array and its length @n_fds
3794  * as is when calling g_main_context_check(), as this function relies
3795  * on assumptions made when the array is filled.
3796  *
3797  * You must have successfully acquired the context with
3798  * g_main_context_acquire() before you may call this function.
3799  *
3800  * Returns: the number of records actually stored in @fds,
3801  *   or, if more than @n_fds records need to be stored, the number
3802  *   of records that need to be stored.
3803  **/
3804 gint
g_main_context_query(GMainContext * context,gint max_priority,gint * timeout,GPollFD * fds,gint n_fds)3805 g_main_context_query (GMainContext *context,
3806 		      gint          max_priority,
3807 		      gint         *timeout,
3808 		      GPollFD      *fds,
3809 		      gint          n_fds)
3810 {
3811   gint n_poll;
3812   GPollRec *pollrec, *lastpollrec;
3813   gushort events;
3814 
3815   LOCK_CONTEXT (context);
3816 
3817   TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context, max_priority));
3818 
3819   /* fds is filled sequentially from poll_records. Since poll_records
3820    * are incrementally sorted by file descriptor identifier, fds will
3821    * also be incrementally sorted.
3822    */
3823   n_poll = 0;
3824   lastpollrec = NULL;
3825   for (pollrec = context->poll_records; pollrec; pollrec = pollrec->next)
3826     {
3827       if (pollrec->priority > max_priority)
3828         continue;
3829 
3830       /* In direct contradiction to the Unix98 spec, IRIX runs into
3831        * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3832        * flags in the events field of the pollfd while it should
3833        * just ignoring them. So we mask them out here.
3834        */
3835       events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3836 
3837       /* This optimization --using the same GPollFD to poll for more
3838        * than one poll record-- relies on the poll records being
3839        * incrementally sorted.
3840        */
3841       if (lastpollrec && pollrec->fd->fd == lastpollrec->fd->fd)
3842         {
3843           if (n_poll - 1 < n_fds)
3844             fds[n_poll - 1].events |= events;
3845         }
3846       else
3847         {
3848           if (n_poll < n_fds)
3849             {
3850               fds[n_poll].fd = pollrec->fd->fd;
3851               fds[n_poll].events = events;
3852               fds[n_poll].revents = 0;
3853             }
3854 
3855           n_poll++;
3856         }
3857 
3858       lastpollrec = pollrec;
3859     }
3860 
3861   context->poll_changed = FALSE;
3862 
3863   if (timeout)
3864     {
3865       *timeout = context->timeout;
3866       if (*timeout != 0)
3867         context->time_is_fresh = FALSE;
3868     }
3869 
3870   TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context, context->timeout,
3871                                         fds, n_poll));
3872 
3873   UNLOCK_CONTEXT (context);
3874 
3875   return n_poll;
3876 }
3877 
3878 /**
3879  * g_main_context_check:
3880  * @context: a #GMainContext
3881  * @max_priority: the maximum numerical priority of sources to check
3882  * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3883  *       the last call to g_main_context_query()
3884  * @n_fds: return value of g_main_context_query()
3885  *
3886  * Passes the results of polling back to the main loop. You should be
3887  * careful to pass @fds and its length @n_fds as received from
3888  * g_main_context_query(), as this functions relies on assumptions
3889  * on how @fds is filled.
3890  *
3891  * You must have successfully acquired the context with
3892  * g_main_context_acquire() before you may call this function.
3893  *
3894  * Returns: %TRUE if some sources are ready to be dispatched.
3895  **/
3896 gboolean
g_main_context_check(GMainContext * context,gint max_priority,GPollFD * fds,gint n_fds)3897 g_main_context_check (GMainContext *context,
3898 		      gint          max_priority,
3899 		      GPollFD      *fds,
3900 		      gint          n_fds)
3901 {
3902   GSource *source;
3903   GSourceIter iter;
3904   GPollRec *pollrec;
3905   gint n_ready = 0;
3906   gint i;
3907 
3908   LOCK_CONTEXT (context);
3909 
3910   if (context->in_check_or_prepare)
3911     {
3912       g_warning ("g_main_context_check() called recursively from within a source's check() or "
3913 		 "prepare() member.");
3914       UNLOCK_CONTEXT (context);
3915       return FALSE;
3916     }
3917 
3918   TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context, max_priority, fds, n_fds));
3919 
3920   for (i = 0; i < n_fds; i++)
3921     {
3922       if (fds[i].fd == context->wake_up_rec.fd)
3923         {
3924           if (fds[i].revents)
3925             {
3926               TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context));
3927               g_wakeup_acknowledge (context->wakeup);
3928             }
3929           break;
3930         }
3931     }
3932 
3933   /* If the set of poll file descriptors changed, bail out
3934    * and let the main loop rerun
3935    */
3936   if (context->poll_changed)
3937     {
3938       TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, 0));
3939 
3940       UNLOCK_CONTEXT (context);
3941       return FALSE;
3942     }
3943 
3944   /* The linear iteration below relies on the assumption that both
3945    * poll records and the fds array are incrementally sorted by file
3946    * descriptor identifier.
3947    */
3948   pollrec = context->poll_records;
3949   i = 0;
3950   while (pollrec && i < n_fds)
3951     {
3952       /* Make sure that fds is sorted by file descriptor identifier. */
3953       g_assert (i <= 0 || fds[i - 1].fd < fds[i].fd);
3954 
3955       /* Skip until finding the first GPollRec matching the current GPollFD. */
3956       while (pollrec && pollrec->fd->fd != fds[i].fd)
3957         pollrec = pollrec->next;
3958 
3959       /* Update all consecutive GPollRecs that match. */
3960       while (pollrec && pollrec->fd->fd == fds[i].fd)
3961         {
3962           if (pollrec->priority <= max_priority)
3963             {
3964               pollrec->fd->revents =
3965                 fds[i].revents & (pollrec->fd->events | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3966             }
3967           pollrec = pollrec->next;
3968         }
3969 
3970       /* Iterate to next GPollFD. */
3971       i++;
3972     }
3973 
3974   g_source_iter_init (&iter, context, TRUE);
3975   while (g_source_iter_next (&iter, &source))
3976     {
3977       if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3978 	continue;
3979       if ((n_ready > 0) && (source->priority > max_priority))
3980 	break;
3981 
3982       if (!(source->flags & G_SOURCE_READY))
3983 	{
3984           gboolean result;
3985           gboolean (* check) (GSource *source);
3986 
3987           check = source->source_funcs->check;
3988 
3989           if (check)
3990             {
3991               gint64 begin_time_nsec G_GNUC_UNUSED;
3992 
3993               /* If the check function is set, call it. */
3994               context->in_check_or_prepare++;
3995               UNLOCK_CONTEXT (context);
3996 
3997               begin_time_nsec = G_TRACE_CURRENT_TIME;
3998 
3999               result = (* check) (source);
4000 
4001               TRACE (GLIB_MAIN_AFTER_CHECK (source, check, result));
4002 
4003               g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
4004                             "GLib", "GSource.check",
4005                             "%s ⇒ %s",
4006                             (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
4007                             result ? "dispatch" : "ignore");
4008 
4009               LOCK_CONTEXT (context);
4010               context->in_check_or_prepare--;
4011             }
4012           else
4013             result = FALSE;
4014 
4015           if (result == FALSE)
4016             {
4017               GSList *tmp_list;
4018 
4019               /* If not already explicitly flagged ready by ->check()
4020                * (or if we have no check) then we can still be ready if
4021                * any of our fds poll as ready.
4022                */
4023               for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
4024                 {
4025                   GPollFD *pollfd = tmp_list->data;
4026 
4027                   if (pollfd->revents)
4028                     {
4029                       result = TRUE;
4030                       break;
4031                     }
4032                 }
4033             }
4034 
4035           if (result == FALSE && source->priv->ready_time != -1)
4036             {
4037               if (!context->time_is_fresh)
4038                 {
4039                   context->time = g_get_monotonic_time ();
4040                   context->time_is_fresh = TRUE;
4041                 }
4042 
4043               if (source->priv->ready_time <= context->time)
4044                 result = TRUE;
4045             }
4046 
4047 	  if (result)
4048 	    {
4049 	      GSource *ready_source = source;
4050 
4051 	      while (ready_source)
4052 		{
4053 		  ready_source->flags |= G_SOURCE_READY;
4054 		  ready_source = ready_source->priv->parent_source;
4055 		}
4056 	    }
4057 	}
4058 
4059       if (source->flags & G_SOURCE_READY)
4060 	{
4061           g_source_ref (source);
4062 	  g_ptr_array_add (context->pending_dispatches, source);
4063 
4064 	  n_ready++;
4065 
4066           /* never dispatch sources with less priority than the first
4067            * one we choose to dispatch
4068            */
4069           max_priority = source->priority;
4070 	}
4071     }
4072   g_source_iter_clear (&iter);
4073 
4074   TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, n_ready));
4075 
4076   UNLOCK_CONTEXT (context);
4077 
4078   return n_ready > 0;
4079 }
4080 
4081 /**
4082  * g_main_context_dispatch:
4083  * @context: a #GMainContext
4084  *
4085  * Dispatches all pending sources.
4086  *
4087  * You must have successfully acquired the context with
4088  * g_main_context_acquire() before you may call this function.
4089  **/
4090 void
g_main_context_dispatch(GMainContext * context)4091 g_main_context_dispatch (GMainContext *context)
4092 {
4093   LOCK_CONTEXT (context);
4094 
4095   TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context));
4096 
4097   if (context->pending_dispatches->len > 0)
4098     {
4099       g_main_dispatch (context);
4100     }
4101 
4102   TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context));
4103 
4104   UNLOCK_CONTEXT (context);
4105 }
4106 
4107 /* HOLDS context lock */
4108 static gboolean
g_main_context_iterate(GMainContext * context,gboolean block,gboolean dispatch,GThread * self)4109 g_main_context_iterate (GMainContext *context,
4110 			gboolean      block,
4111 			gboolean      dispatch,
4112 			GThread      *self)
4113 {
4114   gint max_priority;
4115   gint timeout;
4116   gboolean some_ready;
4117   gint nfds, allocated_nfds;
4118   GPollFD *fds = NULL;
4119   gint64 begin_time_nsec G_GNUC_UNUSED;
4120 
4121   UNLOCK_CONTEXT (context);
4122 
4123   begin_time_nsec = G_TRACE_CURRENT_TIME;
4124 
4125   if (!g_main_context_acquire (context))
4126     {
4127       gboolean got_ownership;
4128 
4129       LOCK_CONTEXT (context);
4130 
4131       if (!block)
4132 	return FALSE;
4133 
4134       got_ownership = g_main_context_wait_internal (context,
4135                                                     &context->cond,
4136                                                     &context->mutex);
4137 
4138       if (!got_ownership)
4139 	return FALSE;
4140     }
4141   else
4142     LOCK_CONTEXT (context);
4143 
4144   if (!context->cached_poll_array)
4145     {
4146       context->cached_poll_array_size = context->n_poll_records;
4147       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
4148     }
4149 
4150   allocated_nfds = context->cached_poll_array_size;
4151   fds = context->cached_poll_array;
4152 
4153   UNLOCK_CONTEXT (context);
4154 
4155   g_main_context_prepare (context, &max_priority);
4156 
4157   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
4158 				       allocated_nfds)) > allocated_nfds)
4159     {
4160       LOCK_CONTEXT (context);
4161       g_free (fds);
4162       context->cached_poll_array_size = allocated_nfds = nfds;
4163       context->cached_poll_array = fds = g_new (GPollFD, nfds);
4164       UNLOCK_CONTEXT (context);
4165     }
4166 
4167   if (!block)
4168     timeout = 0;
4169 
4170   g_main_context_poll (context, timeout, max_priority, fds, nfds);
4171 
4172   some_ready = g_main_context_check (context, max_priority, fds, nfds);
4173 
4174   if (dispatch)
4175     g_main_context_dispatch (context);
4176 
4177   g_main_context_release (context);
4178 
4179   g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
4180                 "GLib", "g_main_context_iterate",
4181                 "Context %p, %s ⇒ %s", context, block ? "blocking" : "non-blocking", some_ready ? "dispatched" : "nothing");
4182 
4183   LOCK_CONTEXT (context);
4184 
4185   return some_ready;
4186 }
4187 
4188 /**
4189  * g_main_context_pending:
4190  * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
4191  *
4192  * Checks if any sources have pending events for the given context.
4193  *
4194  * Returns: %TRUE if events are pending.
4195  **/
4196 gboolean
g_main_context_pending(GMainContext * context)4197 g_main_context_pending (GMainContext *context)
4198 {
4199   gboolean retval;
4200 
4201   if (!context)
4202     context = g_main_context_default();
4203 
4204   LOCK_CONTEXT (context);
4205   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
4206   UNLOCK_CONTEXT (context);
4207 
4208   return retval;
4209 }
4210 
4211 /**
4212  * g_main_context_iteration:
4213  * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
4214  * @may_block: whether the call may block.
4215  *
4216  * Runs a single iteration for the given main loop. This involves
4217  * checking to see if any event sources are ready to be processed,
4218  * then if no events sources are ready and @may_block is %TRUE, waiting
4219  * for a source to become ready, then dispatching the highest priority
4220  * events sources that are ready. Otherwise, if @may_block is %FALSE
4221  * sources are not waited to become ready, only those highest priority
4222  * events sources will be dispatched (if any), that are ready at this
4223  * given moment without further waiting.
4224  *
4225  * Note that even when @may_block is %TRUE, it is still possible for
4226  * g_main_context_iteration() to return %FALSE, since the wait may
4227  * be interrupted for other reasons than an event source becoming ready.
4228  *
4229  * Returns: %TRUE if events were dispatched.
4230  **/
4231 gboolean
g_main_context_iteration(GMainContext * context,gboolean may_block)4232 g_main_context_iteration (GMainContext *context, gboolean may_block)
4233 {
4234   gboolean retval;
4235 
4236   if (!context)
4237     context = g_main_context_default();
4238 
4239   LOCK_CONTEXT (context);
4240   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
4241   UNLOCK_CONTEXT (context);
4242 
4243   return retval;
4244 }
4245 
4246 /**
4247  * g_main_loop_new:
4248  * @context: (nullable): a #GMainContext  (if %NULL, the default context will be used).
4249  * @is_running: set to %TRUE to indicate that the loop is running. This
4250  * is not very important since calling g_main_loop_run() will set this to
4251  * %TRUE anyway.
4252  *
4253  * Creates a new #GMainLoop structure.
4254  *
4255  * Returns: a new #GMainLoop.
4256  **/
4257 GMainLoop *
g_main_loop_new(GMainContext * context,gboolean is_running)4258 g_main_loop_new (GMainContext *context,
4259 		 gboolean      is_running)
4260 {
4261   GMainLoop *loop;
4262 
4263   if (!context)
4264     context = g_main_context_default();
4265 
4266   g_main_context_ref (context);
4267 
4268   loop = g_new0 (GMainLoop, 1);
4269   loop->context = context;
4270   loop->is_running = is_running != FALSE;
4271   loop->ref_count = 1;
4272 
4273   TRACE (GLIB_MAIN_LOOP_NEW (loop, context));
4274 
4275   return loop;
4276 }
4277 
4278 /**
4279  * g_main_loop_ref:
4280  * @loop: a #GMainLoop
4281  *
4282  * Increases the reference count on a #GMainLoop object by one.
4283  *
4284  * Returns: @loop
4285  **/
4286 GMainLoop *
g_main_loop_ref(GMainLoop * loop)4287 g_main_loop_ref (GMainLoop *loop)
4288 {
4289   g_return_val_if_fail (loop != NULL, NULL);
4290   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4291 
4292   g_atomic_int_inc (&loop->ref_count);
4293 
4294   return loop;
4295 }
4296 
4297 /**
4298  * g_main_loop_unref:
4299  * @loop: a #GMainLoop
4300  *
4301  * Decreases the reference count on a #GMainLoop object by one. If
4302  * the result is zero, free the loop and free all associated memory.
4303  **/
4304 void
g_main_loop_unref(GMainLoop * loop)4305 g_main_loop_unref (GMainLoop *loop)
4306 {
4307   g_return_if_fail (loop != NULL);
4308   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4309 
4310   if (!g_atomic_int_dec_and_test (&loop->ref_count))
4311     return;
4312 
4313   g_main_context_unref (loop->context);
4314   g_free (loop);
4315 }
4316 
4317 /**
4318  * g_main_loop_run:
4319  * @loop: a #GMainLoop
4320  *
4321  * Runs a main loop until g_main_loop_quit() is called on the loop.
4322  * If this is called for the thread of the loop's #GMainContext,
4323  * it will process events from the loop, otherwise it will
4324  * simply wait.
4325  **/
4326 void
g_main_loop_run(GMainLoop * loop)4327 g_main_loop_run (GMainLoop *loop)
4328 {
4329   GThread *self = G_THREAD_SELF;
4330 
4331   g_return_if_fail (loop != NULL);
4332   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4333 
4334   if (!g_main_context_acquire (loop->context))
4335     {
4336       gboolean got_ownership = FALSE;
4337 
4338       /* Another thread owns this context */
4339       LOCK_CONTEXT (loop->context);
4340 
4341       g_atomic_int_inc (&loop->ref_count);
4342       g_atomic_int_set (&loop->is_running, TRUE);
4343 
4344       while (g_atomic_int_get (&loop->is_running) && !got_ownership)
4345         got_ownership = g_main_context_wait_internal (loop->context,
4346                                                       &loop->context->cond,
4347                                                       &loop->context->mutex);
4348 
4349       if (!g_atomic_int_get (&loop->is_running))
4350 	{
4351 	  UNLOCK_CONTEXT (loop->context);
4352 	  if (got_ownership)
4353 	    g_main_context_release (loop->context);
4354 	  g_main_loop_unref (loop);
4355 	  return;
4356 	}
4357 
4358       g_assert (got_ownership);
4359     }
4360   else
4361     LOCK_CONTEXT (loop->context);
4362 
4363   if (loop->context->in_check_or_prepare)
4364     {
4365       g_warning ("g_main_loop_run(): called recursively from within a source's "
4366 		 "check() or prepare() member, iteration not possible.");
4367       return;
4368     }
4369 
4370   g_atomic_int_inc (&loop->ref_count);
4371   g_atomic_int_set (&loop->is_running, TRUE);
4372   while (g_atomic_int_get (&loop->is_running))
4373     g_main_context_iterate (loop->context, TRUE, TRUE, self);
4374 
4375   UNLOCK_CONTEXT (loop->context);
4376 
4377   g_main_context_release (loop->context);
4378 
4379   g_main_loop_unref (loop);
4380 }
4381 
4382 /**
4383  * g_main_loop_quit:
4384  * @loop: a #GMainLoop
4385  *
4386  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4387  * for the loop will return.
4388  *
4389  * Note that sources that have already been dispatched when
4390  * g_main_loop_quit() is called will still be executed.
4391  **/
4392 void
g_main_loop_quit(GMainLoop * loop)4393 g_main_loop_quit (GMainLoop *loop)
4394 {
4395   g_return_if_fail (loop != NULL);
4396   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4397 
4398   LOCK_CONTEXT (loop->context);
4399   g_atomic_int_set (&loop->is_running, FALSE);
4400   g_wakeup_signal (loop->context->wakeup);
4401 
4402   g_cond_broadcast (&loop->context->cond);
4403 
4404   UNLOCK_CONTEXT (loop->context);
4405 
4406   TRACE (GLIB_MAIN_LOOP_QUIT (loop));
4407 }
4408 
4409 /**
4410  * g_main_loop_is_running:
4411  * @loop: a #GMainLoop.
4412  *
4413  * Checks to see if the main loop is currently being run via g_main_loop_run().
4414  *
4415  * Returns: %TRUE if the mainloop is currently being run.
4416  **/
4417 gboolean
g_main_loop_is_running(GMainLoop * loop)4418 g_main_loop_is_running (GMainLoop *loop)
4419 {
4420   g_return_val_if_fail (loop != NULL, FALSE);
4421   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
4422 
4423   return g_atomic_int_get (&loop->is_running);
4424 }
4425 
4426 /**
4427  * g_main_loop_get_context:
4428  * @loop: a #GMainLoop.
4429  *
4430  * Returns the #GMainContext of @loop.
4431  *
4432  * Returns: (transfer none): the #GMainContext of @loop
4433  **/
4434 GMainContext *
g_main_loop_get_context(GMainLoop * loop)4435 g_main_loop_get_context (GMainLoop *loop)
4436 {
4437   g_return_val_if_fail (loop != NULL, NULL);
4438   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4439 
4440   return loop->context;
4441 }
4442 
4443 /* HOLDS: context's lock */
4444 static void
g_main_context_poll(GMainContext * context,gint timeout,gint priority,GPollFD * fds,gint n_fds)4445 g_main_context_poll (GMainContext *context,
4446 		     gint          timeout,
4447 		     gint          priority,
4448 		     GPollFD      *fds,
4449 		     gint          n_fds)
4450 {
4451 #ifdef  G_MAIN_POLL_DEBUG
4452   GTimer *poll_timer;
4453   GPollRec *pollrec;
4454   gint i;
4455 #endif
4456 
4457   GPollFunc poll_func;
4458 
4459   if (n_fds || timeout != 0)
4460     {
4461       int ret, errsv;
4462 
4463 #ifdef	G_MAIN_POLL_DEBUG
4464       poll_timer = NULL;
4465       if (_g_main_poll_debug)
4466 	{
4467 	  g_print ("polling context=%p n=%d timeout=%d\n",
4468 		   context, n_fds, timeout);
4469 	  poll_timer = g_timer_new ();
4470 	}
4471 #endif
4472 
4473       LOCK_CONTEXT (context);
4474 
4475       poll_func = context->poll_func;
4476 
4477       UNLOCK_CONTEXT (context);
4478       ret = (*poll_func) (fds, n_fds, timeout);
4479       errsv = errno;
4480       if (ret < 0 && errsv != EINTR)
4481 	{
4482 #ifndef G_OS_WIN32
4483 	  g_warning ("poll(2) failed due to: %s.",
4484 		     g_strerror (errsv));
4485 #else
4486 	  /* If g_poll () returns -1, it has already called g_warning() */
4487 #endif
4488 	}
4489 
4490 #ifdef	G_MAIN_POLL_DEBUG
4491       if (_g_main_poll_debug)
4492 	{
4493 	  LOCK_CONTEXT (context);
4494 
4495 	  g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4496 		   n_fds,
4497 		   timeout,
4498 		   g_timer_elapsed (poll_timer, NULL));
4499 	  g_timer_destroy (poll_timer);
4500 	  pollrec = context->poll_records;
4501 
4502 	  while (pollrec != NULL)
4503 	    {
4504 	      i = 0;
4505 	      while (i < n_fds)
4506 		{
4507 		  if (fds[i].fd == pollrec->fd->fd &&
4508 		      pollrec->fd->events &&
4509 		      fds[i].revents)
4510 		    {
4511 		      g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4512 		      if (fds[i].revents & G_IO_IN)
4513 			g_print ("i");
4514 		      if (fds[i].revents & G_IO_OUT)
4515 			g_print ("o");
4516 		      if (fds[i].revents & G_IO_PRI)
4517 			g_print ("p");
4518 		      if (fds[i].revents & G_IO_ERR)
4519 			g_print ("e");
4520 		      if (fds[i].revents & G_IO_HUP)
4521 			g_print ("h");
4522 		      if (fds[i].revents & G_IO_NVAL)
4523 			g_print ("n");
4524 		      g_print ("]");
4525 		    }
4526 		  i++;
4527 		}
4528 	      pollrec = pollrec->next;
4529 	    }
4530 	  g_print ("\n");
4531 
4532 	  UNLOCK_CONTEXT (context);
4533 	}
4534 #endif
4535     } /* if (n_fds || timeout != 0) */
4536 }
4537 
4538 /**
4539  * g_main_context_add_poll:
4540  * @context: (nullable): a #GMainContext (or %NULL for the default context)
4541  * @fd: a #GPollFD structure holding information about a file
4542  *      descriptor to watch.
4543  * @priority: the priority for this file descriptor which should be
4544  *      the same as the priority used for g_source_attach() to ensure that the
4545  *      file descriptor is polled whenever the results may be needed.
4546  *
4547  * Adds a file descriptor to the set of file descriptors polled for
4548  * this context. This will very seldom be used directly. Instead
4549  * a typical event source will use g_source_add_unix_fd() instead.
4550  **/
4551 void
g_main_context_add_poll(GMainContext * context,GPollFD * fd,gint priority)4552 g_main_context_add_poll (GMainContext *context,
4553 			 GPollFD      *fd,
4554 			 gint          priority)
4555 {
4556   if (!context)
4557     context = g_main_context_default ();
4558 
4559   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4560   g_return_if_fail (fd);
4561 
4562   LOCK_CONTEXT (context);
4563   g_main_context_add_poll_unlocked (context, priority, fd);
4564   UNLOCK_CONTEXT (context);
4565 }
4566 
4567 /* HOLDS: main_loop_lock */
4568 static void
g_main_context_add_poll_unlocked(GMainContext * context,gint priority,GPollFD * fd)4569 g_main_context_add_poll_unlocked (GMainContext *context,
4570 				  gint          priority,
4571 				  GPollFD      *fd)
4572 {
4573   GPollRec *prevrec, *nextrec;
4574   GPollRec *newrec = g_slice_new (GPollRec);
4575 
4576   /* This file descriptor may be checked before we ever poll */
4577   fd->revents = 0;
4578   newrec->fd = fd;
4579   newrec->priority = priority;
4580 
4581   /* Poll records are incrementally sorted by file descriptor identifier. */
4582   prevrec = NULL;
4583   nextrec = context->poll_records;
4584   while (nextrec)
4585     {
4586       if (nextrec->fd->fd > fd->fd)
4587         break;
4588       prevrec = nextrec;
4589       nextrec = nextrec->next;
4590     }
4591 
4592   if (prevrec)
4593     prevrec->next = newrec;
4594   else
4595     context->poll_records = newrec;
4596 
4597   newrec->prev = prevrec;
4598   newrec->next = nextrec;
4599 
4600   if (nextrec)
4601     nextrec->prev = newrec;
4602 
4603   context->n_poll_records++;
4604 
4605   context->poll_changed = TRUE;
4606 
4607   /* Now wake up the main loop if it is waiting in the poll() */
4608   g_wakeup_signal (context->wakeup);
4609 }
4610 
4611 /**
4612  * g_main_context_remove_poll:
4613  * @context:a #GMainContext
4614  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4615  *
4616  * Removes file descriptor from the set of file descriptors to be
4617  * polled for a particular context.
4618  **/
4619 void
g_main_context_remove_poll(GMainContext * context,GPollFD * fd)4620 g_main_context_remove_poll (GMainContext *context,
4621 			    GPollFD      *fd)
4622 {
4623   if (!context)
4624     context = g_main_context_default ();
4625 
4626   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4627   g_return_if_fail (fd);
4628 
4629   LOCK_CONTEXT (context);
4630   g_main_context_remove_poll_unlocked (context, fd);
4631   UNLOCK_CONTEXT (context);
4632 }
4633 
4634 static void
g_main_context_remove_poll_unlocked(GMainContext * context,GPollFD * fd)4635 g_main_context_remove_poll_unlocked (GMainContext *context,
4636 				     GPollFD      *fd)
4637 {
4638   GPollRec *pollrec, *prevrec, *nextrec;
4639 
4640   prevrec = NULL;
4641   pollrec = context->poll_records;
4642 
4643   while (pollrec)
4644     {
4645       nextrec = pollrec->next;
4646       if (pollrec->fd == fd)
4647 	{
4648 	  if (prevrec != NULL)
4649 	    prevrec->next = nextrec;
4650 	  else
4651 	    context->poll_records = nextrec;
4652 
4653 	  if (nextrec != NULL)
4654 	    nextrec->prev = prevrec;
4655 
4656 	  g_slice_free (GPollRec, pollrec);
4657 
4658 	  context->n_poll_records--;
4659 	  break;
4660 	}
4661       prevrec = pollrec;
4662       pollrec = nextrec;
4663     }
4664 
4665   context->poll_changed = TRUE;
4666 
4667   /* Now wake up the main loop if it is waiting in the poll() */
4668   g_wakeup_signal (context->wakeup);
4669 }
4670 
4671 /**
4672  * g_source_get_current_time:
4673  * @source:  a #GSource
4674  * @timeval: #GTimeVal structure in which to store current time.
4675  *
4676  * This function ignores @source and is otherwise the same as
4677  * g_get_current_time().
4678  *
4679  * Deprecated: 2.28: use g_source_get_time() instead
4680  **/
4681 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4682 void
g_source_get_current_time(GSource * source,GTimeVal * timeval)4683 g_source_get_current_time (GSource  *source,
4684 			   GTimeVal *timeval)
4685 {
4686   g_get_current_time (timeval);
4687 }
4688 G_GNUC_END_IGNORE_DEPRECATIONS
4689 
4690 /**
4691  * g_source_get_time:
4692  * @source: a #GSource
4693  *
4694  * Gets the time to be used when checking this source. The advantage of
4695  * calling this function over calling g_get_monotonic_time() directly is
4696  * that when checking multiple sources, GLib can cache a single value
4697  * instead of having to repeatedly get the system monotonic time.
4698  *
4699  * The time here is the system monotonic time, if available, or some
4700  * other reasonable alternative otherwise.  See g_get_monotonic_time().
4701  *
4702  * Returns: the monotonic time in microseconds
4703  *
4704  * Since: 2.28
4705  **/
4706 gint64
g_source_get_time(GSource * source)4707 g_source_get_time (GSource *source)
4708 {
4709   GMainContext *context;
4710   gint64 result;
4711 
4712   g_return_val_if_fail (source != NULL, 0);
4713   g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
4714   g_return_val_if_fail (source->context != NULL, 0);
4715 
4716   context = source->context;
4717 
4718   LOCK_CONTEXT (context);
4719 
4720   if (!context->time_is_fresh)
4721     {
4722       context->time = g_get_monotonic_time ();
4723       context->time_is_fresh = TRUE;
4724     }
4725 
4726   result = context->time;
4727 
4728   UNLOCK_CONTEXT (context);
4729 
4730   return result;
4731 }
4732 
4733 /**
4734  * g_main_context_set_poll_func:
4735  * @context: a #GMainContext
4736  * @func: the function to call to poll all file descriptors
4737  *
4738  * Sets the function to use to handle polling of file descriptors. It
4739  * will be used instead of the poll() system call
4740  * (or GLib's replacement function, which is used where
4741  * poll() isn't available).
4742  *
4743  * This function could possibly be used to integrate the GLib event
4744  * loop with an external event loop.
4745  **/
4746 void
g_main_context_set_poll_func(GMainContext * context,GPollFunc func)4747 g_main_context_set_poll_func (GMainContext *context,
4748 			      GPollFunc     func)
4749 {
4750   if (!context)
4751     context = g_main_context_default ();
4752 
4753   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4754 
4755   LOCK_CONTEXT (context);
4756 
4757   if (func)
4758     context->poll_func = func;
4759   else
4760     context->poll_func = g_poll;
4761 
4762   UNLOCK_CONTEXT (context);
4763 }
4764 
4765 /**
4766  * g_main_context_get_poll_func:
4767  * @context: a #GMainContext
4768  *
4769  * Gets the poll function set by g_main_context_set_poll_func().
4770  *
4771  * Returns: the poll function
4772  **/
4773 GPollFunc
g_main_context_get_poll_func(GMainContext * context)4774 g_main_context_get_poll_func (GMainContext *context)
4775 {
4776   GPollFunc result;
4777 
4778   if (!context)
4779     context = g_main_context_default ();
4780 
4781   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4782 
4783   LOCK_CONTEXT (context);
4784   result = context->poll_func;
4785   UNLOCK_CONTEXT (context);
4786 
4787   return result;
4788 }
4789 
4790 /**
4791  * g_main_context_wakeup:
4792  * @context: a #GMainContext
4793  *
4794  * If @context is currently blocking in g_main_context_iteration()
4795  * waiting for a source to become ready, cause it to stop blocking
4796  * and return.  Otherwise, cause the next invocation of
4797  * g_main_context_iteration() to return without blocking.
4798  *
4799  * This API is useful for low-level control over #GMainContext; for
4800  * example, integrating it with main loop implementations such as
4801  * #GMainLoop.
4802  *
4803  * Another related use for this function is when implementing a main
4804  * loop with a termination condition, computed from multiple threads:
4805  *
4806  * |[<!-- language="C" -->
4807  *   #define NUM_TASKS 10
4808  *   static gint tasks_remaining = NUM_TASKS;  // (atomic)
4809  *   ...
4810  *
4811  *   while (g_atomic_int_get (&tasks_remaining) != 0)
4812  *     g_main_context_iteration (NULL, TRUE);
4813  * ]|
4814  *
4815  * Then in a thread:
4816  * |[<!-- language="C" -->
4817  *   perform_work();
4818  *
4819  *   if (g_atomic_int_dec_and_test (&tasks_remaining))
4820  *     g_main_context_wakeup (NULL);
4821  * ]|
4822  **/
4823 void
g_main_context_wakeup(GMainContext * context)4824 g_main_context_wakeup (GMainContext *context)
4825 {
4826   if (!context)
4827     context = g_main_context_default ();
4828 
4829   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4830 
4831   TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context));
4832 
4833   g_wakeup_signal (context->wakeup);
4834 }
4835 
4836 /**
4837  * g_main_context_is_owner:
4838  * @context: a #GMainContext
4839  *
4840  * Determines whether this thread holds the (recursive)
4841  * ownership of this #GMainContext. This is useful to
4842  * know before waiting on another thread that may be
4843  * blocking to get ownership of @context.
4844  *
4845  * Returns: %TRUE if current thread is owner of @context.
4846  *
4847  * Since: 2.10
4848  **/
4849 gboolean
g_main_context_is_owner(GMainContext * context)4850 g_main_context_is_owner (GMainContext *context)
4851 {
4852   gboolean is_owner;
4853 
4854   if (!context)
4855     context = g_main_context_default ();
4856 
4857   LOCK_CONTEXT (context);
4858   is_owner = context->owner == G_THREAD_SELF;
4859   UNLOCK_CONTEXT (context);
4860 
4861   return is_owner;
4862 }
4863 
4864 /* Timeouts */
4865 
4866 static void
g_timeout_set_expiration(GTimeoutSource * timeout_source,gint64 current_time)4867 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4868                           gint64          current_time)
4869 {
4870   gint64 expiration;
4871 
4872   if (timeout_source->seconds)
4873     {
4874       gint64 remainder;
4875       static gint timer_perturb = -1;
4876 
4877       if (timer_perturb == -1)
4878         {
4879           /*
4880            * we want a per machine/session unique 'random' value; try the dbus
4881            * address first, that has a UUID in it. If there is no dbus, use the
4882            * hostname for hashing.
4883            */
4884           const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4885           if (!session_bus_address)
4886             session_bus_address = g_getenv ("HOSTNAME");
4887           if (session_bus_address)
4888             timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4889           else
4890             timer_perturb = 0;
4891         }
4892 
4893       expiration = current_time + (guint64) timeout_source->interval * 1000 * 1000;
4894 
4895       /* We want the microseconds part of the timeout to land on the
4896        * 'timer_perturb' mark, but we need to make sure we don't try to
4897        * set the timeout in the past.  We do this by ensuring that we
4898        * always only *increase* the expiration time by adding a full
4899        * second in the case that the microsecond portion decreases.
4900        */
4901       expiration -= timer_perturb;
4902 
4903       remainder = expiration % 1000000;
4904       if (remainder >= 1000000/4)
4905         expiration += 1000000;
4906 
4907       expiration -= remainder;
4908       expiration += timer_perturb;
4909     }
4910   else
4911     {
4912       expiration = current_time + (guint64) timeout_source->interval * 1000;
4913     }
4914 
4915   g_source_set_ready_time ((GSource *) timeout_source, expiration);
4916 }
4917 
4918 static gboolean
g_timeout_dispatch(GSource * source,GSourceFunc callback,gpointer user_data)4919 g_timeout_dispatch (GSource     *source,
4920                     GSourceFunc  callback,
4921                     gpointer     user_data)
4922 {
4923   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4924   gboolean again;
4925 
4926   if (!callback)
4927     {
4928       g_warning ("Timeout source dispatched without callback. "
4929                  "You must call g_source_set_callback().");
4930       return FALSE;
4931     }
4932 
4933   again = callback (user_data);
4934 
4935   TRACE (GLIB_TIMEOUT_DISPATCH (source, source->context, callback, user_data, again));
4936 
4937   if (again)
4938     g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4939 
4940   return again;
4941 }
4942 
4943 /**
4944  * g_timeout_source_new:
4945  * @interval: the timeout interval in milliseconds.
4946  *
4947  * Creates a new timeout source.
4948  *
4949  * The source will not initially be associated with any #GMainContext
4950  * and must be added to one with g_source_attach() before it will be
4951  * executed.
4952  *
4953  * The interval given is in terms of monotonic time, not wall clock
4954  * time.  See g_get_monotonic_time().
4955  *
4956  * Returns: the newly-created timeout source
4957  **/
4958 GSource *
g_timeout_source_new(guint interval)4959 g_timeout_source_new (guint interval)
4960 {
4961   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4962   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4963 
4964   timeout_source->interval = interval;
4965   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4966 
4967   return source;
4968 }
4969 
4970 /**
4971  * g_timeout_source_new_seconds:
4972  * @interval: the timeout interval in seconds
4973  *
4974  * Creates a new timeout source.
4975  *
4976  * The source will not initially be associated with any #GMainContext
4977  * and must be added to one with g_source_attach() before it will be
4978  * executed.
4979  *
4980  * The scheduling granularity/accuracy of this timeout source will be
4981  * in seconds.
4982  *
4983  * The interval given is in terms of monotonic time, not wall clock time.
4984  * See g_get_monotonic_time().
4985  *
4986  * Returns: the newly-created timeout source
4987  *
4988  * Since: 2.14
4989  **/
4990 GSource *
g_timeout_source_new_seconds(guint interval)4991 g_timeout_source_new_seconds (guint interval)
4992 {
4993   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4994   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4995 
4996   timeout_source->interval = interval;
4997   timeout_source->seconds = TRUE;
4998 
4999   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
5000 
5001   return source;
5002 }
5003 
5004 
5005 /**
5006  * g_timeout_add_full: (rename-to g_timeout_add)
5007  * @priority: the priority of the timeout source. Typically this will be in
5008  *   the range between %G_PRIORITY_DEFAULT and %G_PRIORITY_HIGH.
5009  * @interval: the time between calls to the function, in milliseconds
5010  *   (1/1000ths of a second)
5011  * @function: function to call
5012  * @data: data to pass to @function
5013  * @notify: (nullable): function to call when the timeout is removed, or %NULL
5014  *
5015  * Sets a function to be called at regular intervals, with the given
5016  * priority.  The function is called repeatedly until it returns
5017  * %FALSE, at which point the timeout is automatically destroyed and
5018  * the function will not be called again.  The @notify function is
5019  * called when the timeout is destroyed.  The first call to the
5020  * function will be at the end of the first @interval.
5021  *
5022  * Note that timeout functions may be delayed, due to the processing of other
5023  * event sources. Thus they should not be relied on for precise timing.
5024  * After each call to the timeout function, the time of the next
5025  * timeout is recalculated based on the current time and the given interval
5026  * (it does not try to 'catch up' time lost in delays).
5027  *
5028  * See [memory management of sources][mainloop-memory-management] for details
5029  * on how to handle the return value and memory management of @data.
5030  *
5031  * This internally creates a main loop source using g_timeout_source_new()
5032  * and attaches it to the global #GMainContext using g_source_attach(), so
5033  * the callback will be invoked in whichever thread is running that main
5034  * context. You can do these steps manually if you need greater control or to
5035  * use a custom main context.
5036  *
5037  * The interval given is in terms of monotonic time, not wall clock time.
5038  * See g_get_monotonic_time().
5039  *
5040  * Returns: the ID (greater than 0) of the event source.
5041  **/
5042 guint
g_timeout_add_full(gint priority,guint interval,GSourceFunc function,gpointer data,GDestroyNotify notify)5043 g_timeout_add_full (gint           priority,
5044 		    guint          interval,
5045 		    GSourceFunc    function,
5046 		    gpointer       data,
5047 		    GDestroyNotify notify)
5048 {
5049   GSource *source;
5050   guint id;
5051 
5052   g_return_val_if_fail (function != NULL, 0);
5053 
5054   source = g_timeout_source_new (interval);
5055 
5056   if (priority != G_PRIORITY_DEFAULT)
5057     g_source_set_priority (source, priority);
5058 
5059   g_source_set_callback (source, function, data, notify);
5060   id = g_source_attach (source, NULL);
5061 
5062   TRACE (GLIB_TIMEOUT_ADD (source, g_main_context_default (), id, priority, interval, function, data));
5063 
5064   g_source_unref (source);
5065 
5066   return id;
5067 }
5068 
5069 /**
5070  * g_timeout_add:
5071  * @interval: the time between calls to the function, in milliseconds
5072  *    (1/1000ths of a second)
5073  * @function: function to call
5074  * @data: data to pass to @function
5075  *
5076  * Sets a function to be called at regular intervals, with the default
5077  * priority, %G_PRIORITY_DEFAULT.
5078  *
5079  * The given @function is called repeatedly until it returns %G_SOURCE_REMOVE
5080  * or %FALSE, at which point the timeout is automatically destroyed and the
5081  * function will not be called again. The first call to the function will be
5082  * at the end of the first @interval.
5083  *
5084  * Note that timeout functions may be delayed, due to the processing of other
5085  * event sources. Thus they should not be relied on for precise timing.
5086  * After each call to the timeout function, the time of the next
5087  * timeout is recalculated based on the current time and the given interval
5088  * (it does not try to 'catch up' time lost in delays).
5089  *
5090  * See [memory management of sources][mainloop-memory-management] for details
5091  * on how to handle the return value and memory management of @data.
5092  *
5093  * If you want to have a timer in the "seconds" range and do not care
5094  * about the exact time of the first call of the timer, use the
5095  * g_timeout_add_seconds() function; this function allows for more
5096  * optimizations and more efficient system power usage.
5097  *
5098  * This internally creates a main loop source using g_timeout_source_new()
5099  * and attaches it to the global #GMainContext using g_source_attach(), so
5100  * the callback will be invoked in whichever thread is running that main
5101  * context. You can do these steps manually if you need greater control or to
5102  * use a custom main context.
5103  *
5104  * It is safe to call this function from any thread.
5105  *
5106  * The interval given is in terms of monotonic time, not wall clock
5107  * time.  See g_get_monotonic_time().
5108  *
5109  * Returns: the ID (greater than 0) of the event source.
5110  **/
5111 guint
g_timeout_add(guint32 interval,GSourceFunc function,gpointer data)5112 g_timeout_add (guint32        interval,
5113 	       GSourceFunc    function,
5114 	       gpointer       data)
5115 {
5116   return g_timeout_add_full (G_PRIORITY_DEFAULT,
5117 			     interval, function, data, NULL);
5118 }
5119 
5120 /**
5121  * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
5122  * @priority: the priority of the timeout source. Typically this will be in
5123  *   the range between %G_PRIORITY_DEFAULT and %G_PRIORITY_HIGH.
5124  * @interval: the time between calls to the function, in seconds
5125  * @function: function to call
5126  * @data: data to pass to @function
5127  * @notify: (nullable): function to call when the timeout is removed, or %NULL
5128  *
5129  * Sets a function to be called at regular intervals, with @priority.
5130  *
5131  * The function is called repeatedly until it returns %G_SOURCE_REMOVE
5132  * or %FALSE, at which point the timeout is automatically destroyed and
5133  * the function will not be called again.
5134  *
5135  * Unlike g_timeout_add(), this function operates at whole second granularity.
5136  * The initial starting point of the timer is determined by the implementation
5137  * and the implementation is expected to group multiple timers together so that
5138  * they fire all at the same time. To allow this grouping, the @interval to the
5139  * first timer is rounded and can deviate up to one second from the specified
5140  * interval. Subsequent timer iterations will generally run at the specified
5141  * interval.
5142  *
5143  * Note that timeout functions may be delayed, due to the processing of other
5144  * event sources. Thus they should not be relied on for precise timing.
5145  * After each call to the timeout function, the time of the next
5146  * timeout is recalculated based on the current time and the given @interval
5147  *
5148  * See [memory management of sources][mainloop-memory-management] for details
5149  * on how to handle the return value and memory management of @data.
5150  *
5151  * If you want timing more precise than whole seconds, use g_timeout_add()
5152  * instead.
5153  *
5154  * The grouping of timers to fire at the same time results in a more power
5155  * and CPU efficient behavior so if your timer is in multiples of seconds
5156  * and you don't require the first timer exactly one second from now, the
5157  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
5158  *
5159  * This internally creates a main loop source using
5160  * g_timeout_source_new_seconds() and attaches it to the main loop context
5161  * using g_source_attach(). You can do these steps manually if you need
5162  * greater control.
5163  *
5164  * It is safe to call this function from any thread.
5165  *
5166  * The interval given is in terms of monotonic time, not wall clock
5167  * time.  See g_get_monotonic_time().
5168  *
5169  * Returns: the ID (greater than 0) of the event source.
5170  *
5171  * Since: 2.14
5172  **/
5173 guint
g_timeout_add_seconds_full(gint priority,guint32 interval,GSourceFunc function,gpointer data,GDestroyNotify notify)5174 g_timeout_add_seconds_full (gint           priority,
5175                             guint32        interval,
5176                             GSourceFunc    function,
5177                             gpointer       data,
5178                             GDestroyNotify notify)
5179 {
5180   GSource *source;
5181   guint id;
5182 
5183   g_return_val_if_fail (function != NULL, 0);
5184 
5185   source = g_timeout_source_new_seconds (interval);
5186 
5187   if (priority != G_PRIORITY_DEFAULT)
5188     g_source_set_priority (source, priority);
5189 
5190   g_source_set_callback (source, function, data, notify);
5191   id = g_source_attach (source, NULL);
5192   g_source_unref (source);
5193 
5194   return id;
5195 }
5196 
5197 /**
5198  * g_timeout_add_seconds:
5199  * @interval: the time between calls to the function, in seconds
5200  * @function: function to call
5201  * @data: data to pass to @function
5202  *
5203  * Sets a function to be called at regular intervals with the default
5204  * priority, %G_PRIORITY_DEFAULT.
5205  *
5206  * The function is called repeatedly until it returns %G_SOURCE_REMOVE
5207  * or %FALSE, at which point the timeout is automatically destroyed
5208  * and the function will not be called again.
5209  *
5210  * This internally creates a main loop source using
5211  * g_timeout_source_new_seconds() and attaches it to the main loop context
5212  * using g_source_attach(). You can do these steps manually if you need
5213  * greater control. Also see g_timeout_add_seconds_full().
5214  *
5215  * It is safe to call this function from any thread.
5216  *
5217  * Note that the first call of the timer may not be precise for timeouts
5218  * of one second. If you need finer precision and have such a timeout,
5219  * you may want to use g_timeout_add() instead.
5220  *
5221  * See [memory management of sources][mainloop-memory-management] for details
5222  * on how to handle the return value and memory management of @data.
5223  *
5224  * The interval given is in terms of monotonic time, not wall clock
5225  * time.  See g_get_monotonic_time().
5226  *
5227  * Returns: the ID (greater than 0) of the event source.
5228  *
5229  * Since: 2.14
5230  **/
5231 guint
g_timeout_add_seconds(guint interval,GSourceFunc function,gpointer data)5232 g_timeout_add_seconds (guint       interval,
5233                        GSourceFunc function,
5234                        gpointer    data)
5235 {
5236   g_return_val_if_fail (function != NULL, 0);
5237 
5238   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
5239 }
5240 
5241 /* Child watch functions */
5242 
5243 #ifdef G_OS_WIN32
5244 
5245 static gboolean
g_child_watch_prepare(GSource * source,gint * timeout)5246 g_child_watch_prepare (GSource *source,
5247 		       gint    *timeout)
5248 {
5249   *timeout = -1;
5250   return FALSE;
5251 }
5252 
5253 static gboolean
g_child_watch_check(GSource * source)5254 g_child_watch_check (GSource  *source)
5255 {
5256   GChildWatchSource *child_watch_source;
5257   gboolean child_exited;
5258 
5259   child_watch_source = (GChildWatchSource *) source;
5260 
5261   child_exited = child_watch_source->poll.revents & G_IO_IN;
5262 
5263   if (child_exited)
5264     {
5265       DWORD child_status;
5266 
5267       /*
5268        * Note: We do _not_ check for the special value of STILL_ACTIVE
5269        * since we know that the process has exited and doing so runs into
5270        * problems if the child process "happens to return STILL_ACTIVE(259)"
5271        * as Microsoft's Platform SDK puts it.
5272        */
5273       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
5274         {
5275 	  gchar *emsg = g_win32_error_message (GetLastError ());
5276 	  g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
5277 	  g_free (emsg);
5278 
5279 	  child_watch_source->child_status = -1;
5280 	}
5281       else
5282 	child_watch_source->child_status = child_status;
5283     }
5284 
5285   return child_exited;
5286 }
5287 
5288 static void
g_child_watch_finalize(GSource * source)5289 g_child_watch_finalize (GSource *source)
5290 {
5291 }
5292 
5293 #else /* G_OS_WIN32 */
5294 
5295 static void
wake_source(GSource * source)5296 wake_source (GSource *source)
5297 {
5298   GMainContext *context;
5299 
5300   /* This should be thread-safe:
5301    *
5302    *  - if the source is currently being added to a context, that
5303    *    context will be woken up anyway
5304    *
5305    *  - if the source is currently being destroyed, we simply need not
5306    *    to crash:
5307    *
5308    *    - the memory for the source will remain valid until after the
5309    *      source finalize function was called (which would remove the
5310    *      source from the global list which we are currently holding the
5311    *      lock for)
5312    *
5313    *    - the GMainContext will either be NULL or point to a live
5314    *      GMainContext
5315    *
5316    *    - the GMainContext will remain valid since we hold the
5317    *      main_context_list lock
5318    *
5319    *  Since we are holding a lot of locks here, don't try to enter any
5320    *  more GMainContext functions for fear of dealock -- just hit the
5321    *  GWakeup and run.  Even if that's safe now, it could easily become
5322    *  unsafe with some very minor changes in the future, and signal
5323    *  handling is not the most well-tested codepath.
5324    */
5325   G_LOCK(main_context_list);
5326   context = source->context;
5327   if (context)
5328     g_wakeup_signal (context->wakeup);
5329   G_UNLOCK(main_context_list);
5330 }
5331 
5332 static void
dispatch_unix_signals_unlocked(void)5333 dispatch_unix_signals_unlocked (void)
5334 {
5335   gboolean pending[NSIG];
5336   GSList *node;
5337   gint i;
5338 
5339   /* clear this first in case another one arrives while we're processing */
5340   g_atomic_int_set (&any_unix_signal_pending, 0);
5341 
5342   /* We atomically test/clear the bit from the global array in case
5343    * other signals arrive while we are dispatching.
5344    *
5345    * We then can safely use our own array below without worrying about
5346    * races.
5347    */
5348   for (i = 0; i < NSIG; i++)
5349     {
5350       /* Be very careful with (the volatile) unix_signal_pending.
5351        *
5352        * We must ensure that it's not possible that we clear it without
5353        * handling the signal.  We therefore must ensure that our pending
5354        * array has a field set (ie: we will do something about the
5355        * signal) before we clear the item in unix_signal_pending.
5356        *
5357        * Note specifically: we must check _our_ array.
5358        */
5359       pending[i] = g_atomic_int_compare_and_exchange (&unix_signal_pending[i], 1, 0);
5360     }
5361 
5362   /* handle GChildWatchSource instances */
5363   if (pending[SIGCHLD])
5364     {
5365       /* The only way we can do this is to scan all of the children.
5366        *
5367        * The docs promise that we will not reap children that we are not
5368        * explicitly watching, so that ties our hands from calling
5369        * waitpid(-1).  We also can't use siginfo's si_pid field since if
5370        * multiple SIGCHLD arrive at the same time, one of them can be
5371        * dropped (since a given UNIX signal can only be pending once).
5372        */
5373       for (node = unix_child_watches; node; node = node->next)
5374         {
5375           GChildWatchSource *source = node->data;
5376 
5377           if (!g_atomic_int_get (&source->child_exited))
5378             {
5379               pid_t pid;
5380               do
5381                 {
5382                   g_assert (source->pid > 0);
5383 
5384                   pid = waitpid (source->pid, &source->child_status, WNOHANG);
5385                   if (pid > 0)
5386                     {
5387                       g_atomic_int_set (&source->child_exited, TRUE);
5388                       wake_source ((GSource *) source);
5389                     }
5390                   else if (pid == -1 && errno == ECHILD)
5391                     {
5392                       g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). See the documentation of g_child_watch_source_new() for possible causes.");
5393                       source->child_status = 0;
5394                       g_atomic_int_set (&source->child_exited, TRUE);
5395                       wake_source ((GSource *) source);
5396                     }
5397                 }
5398               while (pid == -1 && errno == EINTR);
5399             }
5400         }
5401     }
5402 
5403   /* handle GUnixSignalWatchSource instances */
5404   for (node = unix_signal_watches; node; node = node->next)
5405     {
5406       GUnixSignalWatchSource *source = node->data;
5407 
5408       if (pending[source->signum] &&
5409           g_atomic_int_compare_and_exchange (&source->pending, FALSE, TRUE))
5410         {
5411           wake_source ((GSource *) source);
5412         }
5413     }
5414 
5415 }
5416 
5417 static void
dispatch_unix_signals(void)5418 dispatch_unix_signals (void)
5419 {
5420   G_LOCK(unix_signal_lock);
5421   dispatch_unix_signals_unlocked ();
5422   G_UNLOCK(unix_signal_lock);
5423 }
5424 
5425 static gboolean
g_child_watch_prepare(GSource * source,gint * timeout)5426 g_child_watch_prepare (GSource *source,
5427 		       gint    *timeout)
5428 {
5429   GChildWatchSource *child_watch_source;
5430 
5431   child_watch_source = (GChildWatchSource *) source;
5432 
5433   return g_atomic_int_get (&child_watch_source->child_exited);
5434 }
5435 
5436 static gboolean
g_child_watch_check(GSource * source)5437 g_child_watch_check (GSource *source)
5438 {
5439   GChildWatchSource *child_watch_source;
5440 
5441   child_watch_source = (GChildWatchSource *) source;
5442 
5443   return g_atomic_int_get (&child_watch_source->child_exited);
5444 }
5445 
5446 static gboolean
g_unix_signal_watch_prepare(GSource * source,gint * timeout)5447 g_unix_signal_watch_prepare (GSource *source,
5448 			     gint    *timeout)
5449 {
5450   GUnixSignalWatchSource *unix_signal_source;
5451 
5452   unix_signal_source = (GUnixSignalWatchSource *) source;
5453 
5454   return g_atomic_int_get (&unix_signal_source->pending);
5455 }
5456 
5457 static gboolean
g_unix_signal_watch_check(GSource * source)5458 g_unix_signal_watch_check (GSource  *source)
5459 {
5460   GUnixSignalWatchSource *unix_signal_source;
5461 
5462   unix_signal_source = (GUnixSignalWatchSource *) source;
5463 
5464   return g_atomic_int_get (&unix_signal_source->pending);
5465 }
5466 
5467 static gboolean
g_unix_signal_watch_dispatch(GSource * source,GSourceFunc callback,gpointer user_data)5468 g_unix_signal_watch_dispatch (GSource    *source,
5469 			      GSourceFunc callback,
5470 			      gpointer    user_data)
5471 {
5472   GUnixSignalWatchSource *unix_signal_source;
5473   gboolean again;
5474 
5475   unix_signal_source = (GUnixSignalWatchSource *) source;
5476 
5477   if (!callback)
5478     {
5479       g_warning ("Unix signal source dispatched without callback. "
5480 		 "You must call g_source_set_callback().");
5481       return FALSE;
5482     }
5483 
5484   g_atomic_int_set (&unix_signal_source->pending, FALSE);
5485 
5486   again = (callback) (user_data);
5487 
5488   return again;
5489 }
5490 
5491 static void
ref_unix_signal_handler_unlocked(int signum)5492 ref_unix_signal_handler_unlocked (int signum)
5493 {
5494   /* Ensure we have the worker context */
5495   g_get_worker_context ();
5496   unix_signal_refcount[signum]++;
5497   if (unix_signal_refcount[signum] == 1)
5498     {
5499       struct sigaction action;
5500       action.sa_handler = g_unix_signal_handler;
5501       sigemptyset (&action.sa_mask);
5502 #ifdef SA_RESTART
5503       action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
5504 #else
5505       action.sa_flags = SA_NOCLDSTOP;
5506 #endif
5507       sigaction (signum, &action, NULL);
5508     }
5509 }
5510 
5511 static void
unref_unix_signal_handler_unlocked(int signum)5512 unref_unix_signal_handler_unlocked (int signum)
5513 {
5514   unix_signal_refcount[signum]--;
5515   if (unix_signal_refcount[signum] == 0)
5516     {
5517       struct sigaction action;
5518       memset (&action, 0, sizeof (action));
5519       action.sa_handler = SIG_DFL;
5520       sigemptyset (&action.sa_mask);
5521       sigaction (signum, &action, NULL);
5522     }
5523 }
5524 
5525 /* Return a const string to avoid allocations. We lose precision in the case the
5526  * @signum is unrecognised, but that’ll do. */
5527 static const gchar *
signum_to_string(int signum)5528 signum_to_string (int signum)
5529 {
5530   /* See `man 0P signal.h` */
5531 #define SIGNAL(s) \
5532     case (s): \
5533       return ("GUnixSignalSource: " #s);
5534   switch (signum)
5535     {
5536     /* These signals are guaranteed to exist by POSIX. */
5537     SIGNAL (SIGABRT)
5538     SIGNAL (SIGFPE)
5539     SIGNAL (SIGILL)
5540     SIGNAL (SIGINT)
5541     SIGNAL (SIGSEGV)
5542     SIGNAL (SIGTERM)
5543     /* Frustratingly, these are not, and hence for brevity the list is
5544      * incomplete. */
5545 #ifdef SIGALRM
5546     SIGNAL (SIGALRM)
5547 #endif
5548 #ifdef SIGCHLD
5549     SIGNAL (SIGCHLD)
5550 #endif
5551 #ifdef SIGHUP
5552     SIGNAL (SIGHUP)
5553 #endif
5554 #ifdef SIGKILL
5555     SIGNAL (SIGKILL)
5556 #endif
5557 #ifdef SIGPIPE
5558     SIGNAL (SIGPIPE)
5559 #endif
5560 #ifdef SIGQUIT
5561     SIGNAL (SIGQUIT)
5562 #endif
5563 #ifdef SIGSTOP
5564     SIGNAL (SIGSTOP)
5565 #endif
5566 #ifdef SIGUSR1
5567     SIGNAL (SIGUSR1)
5568 #endif
5569 #ifdef SIGUSR2
5570     SIGNAL (SIGUSR2)
5571 #endif
5572 #ifdef SIGPOLL
5573     SIGNAL (SIGPOLL)
5574 #endif
5575 #ifdef SIGPROF
5576     SIGNAL (SIGPROF)
5577 #endif
5578 #ifdef SIGTRAP
5579     SIGNAL (SIGTRAP)
5580 #endif
5581     default:
5582       return "GUnixSignalSource: Unrecognized signal";
5583     }
5584 #undef SIGNAL
5585 }
5586 
5587 GSource *
_g_main_create_unix_signal_watch(int signum)5588 _g_main_create_unix_signal_watch (int signum)
5589 {
5590   GSource *source;
5591   GUnixSignalWatchSource *unix_signal_source;
5592 
5593   source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5594   unix_signal_source = (GUnixSignalWatchSource *) source;
5595 
5596   unix_signal_source->signum = signum;
5597   unix_signal_source->pending = FALSE;
5598 
5599   /* Set a default name on the source, just in case the caller does not. */
5600   g_source_set_static_name (source, signum_to_string (signum));
5601 
5602   G_LOCK (unix_signal_lock);
5603   ref_unix_signal_handler_unlocked (signum);
5604   unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5605   dispatch_unix_signals_unlocked ();
5606   G_UNLOCK (unix_signal_lock);
5607 
5608   return source;
5609 }
5610 
5611 static void
g_unix_signal_watch_finalize(GSource * source)5612 g_unix_signal_watch_finalize (GSource    *source)
5613 {
5614   GUnixSignalWatchSource *unix_signal_source;
5615 
5616   unix_signal_source = (GUnixSignalWatchSource *) source;
5617 
5618   G_LOCK (unix_signal_lock);
5619   unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5620   unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5621   G_UNLOCK (unix_signal_lock);
5622 }
5623 
5624 static void
g_child_watch_finalize(GSource * source)5625 g_child_watch_finalize (GSource *source)
5626 {
5627   G_LOCK (unix_signal_lock);
5628   unix_child_watches = g_slist_remove (unix_child_watches, source);
5629   unref_unix_signal_handler_unlocked (SIGCHLD);
5630   G_UNLOCK (unix_signal_lock);
5631 }
5632 
5633 #endif /* G_OS_WIN32 */
5634 
5635 static gboolean
g_child_watch_dispatch(GSource * source,GSourceFunc callback,gpointer user_data)5636 g_child_watch_dispatch (GSource    *source,
5637 			GSourceFunc callback,
5638 			gpointer    user_data)
5639 {
5640   GChildWatchSource *child_watch_source;
5641   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5642 
5643   child_watch_source = (GChildWatchSource *) source;
5644 
5645   if (!callback)
5646     {
5647       g_warning ("Child watch source dispatched without callback. "
5648 		 "You must call g_source_set_callback().");
5649       return FALSE;
5650     }
5651 
5652   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5653 
5654   /* We never keep a child watch source around as the child is gone */
5655   return FALSE;
5656 }
5657 
5658 #ifndef G_OS_WIN32
5659 
5660 static void
g_unix_signal_handler(int signum)5661 g_unix_signal_handler (int signum)
5662 {
5663   gint saved_errno = errno;
5664 
5665 #if defined(G_ATOMIC_LOCK_FREE) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
5666   g_atomic_int_set (&unix_signal_pending[signum], 1);
5667   g_atomic_int_set (&any_unix_signal_pending, 1);
5668 #else
5669 #warning "Can't use atomics in g_unix_signal_handler(): Unix signal handling will be racy"
5670   unix_signal_pending[signum] = 1;
5671   any_unix_signal_pending = 1;
5672 #endif
5673 
5674   g_wakeup_signal (glib_worker_context->wakeup);
5675 
5676   errno = saved_errno;
5677 }
5678 
5679 #endif /* !G_OS_WIN32 */
5680 
5681 /**
5682  * g_child_watch_source_new:
5683  * @pid: process to watch. On POSIX the positive pid of a child process. On
5684  * Windows a handle for a process (which doesn't have to be a child).
5685  *
5686  * Creates a new child_watch source.
5687  *
5688  * The source will not initially be associated with any #GMainContext
5689  * and must be added to one with g_source_attach() before it will be
5690  * executed.
5691  *
5692  * Note that child watch sources can only be used in conjunction with
5693  * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5694  *
5695  * Note that on platforms where #GPid must be explicitly closed
5696  * (see g_spawn_close_pid()) @pid must not be closed while the
5697  * source is still active. Typically, you will want to call
5698  * g_spawn_close_pid() in the callback function for the source.
5699  *
5700  * On POSIX platforms, the following restrictions apply to this API
5701  * due to limitations in POSIX process interfaces:
5702  *
5703  * * @pid must be a child of this process
5704  * * @pid must be positive
5705  * * the application must not call `waitpid` with a non-positive
5706  *   first argument, for instance in another thread
5707  * * the application must not wait for @pid to exit by any other
5708  *   mechanism, including `waitpid(pid, ...)` or a second child-watch
5709  *   source for the same @pid
5710  * * the application must not ignore `SIGCHLD`
5711  *
5712  * If any of those conditions are not met, this and related APIs will
5713  * not work correctly. This can often be diagnosed via a GLib warning
5714  * stating that `ECHILD` was received by `waitpid`.
5715  *
5716  * Calling `waitpid` for specific processes other than @pid remains a
5717  * valid thing to do.
5718  *
5719  * Returns: the newly-created child watch source
5720  *
5721  * Since: 2.4
5722  **/
5723 GSource *
g_child_watch_source_new(GPid pid)5724 g_child_watch_source_new (GPid pid)
5725 {
5726   GSource *source;
5727   GChildWatchSource *child_watch_source;
5728 
5729 #ifndef G_OS_WIN32
5730   g_return_val_if_fail (pid > 0, NULL);
5731 #endif
5732 
5733   source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5734   child_watch_source = (GChildWatchSource *)source;
5735 
5736   /* Set a default name on the source, just in case the caller does not. */
5737   g_source_set_static_name (source, "GChildWatchSource");
5738 
5739   child_watch_source->pid = pid;
5740 
5741 #ifdef G_OS_WIN32
5742   child_watch_source->poll.fd = (gintptr) pid;
5743   child_watch_source->poll.events = G_IO_IN;
5744 
5745   g_source_add_poll (source, &child_watch_source->poll);
5746 #else /* G_OS_WIN32 */
5747   G_LOCK (unix_signal_lock);
5748   ref_unix_signal_handler_unlocked (SIGCHLD);
5749   unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5750   if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5751     child_watch_source->child_exited = TRUE;
5752   G_UNLOCK (unix_signal_lock);
5753 #endif /* G_OS_WIN32 */
5754 
5755   return source;
5756 }
5757 
5758 /**
5759  * g_child_watch_add_full: (rename-to g_child_watch_add)
5760  * @priority: the priority of the idle source. Typically this will be in the
5761  *   range between %G_PRIORITY_DEFAULT_IDLE and %G_PRIORITY_HIGH_IDLE.
5762  * @pid: process to watch. On POSIX the positive pid of a child process. On
5763  * Windows a handle for a process (which doesn't have to be a child).
5764  * @function: function to call
5765  * @data: data to pass to @function
5766  * @notify: (nullable): function to call when the idle is removed, or %NULL
5767  *
5768  * Sets a function to be called when the child indicated by @pid
5769  * exits, at the priority @priority.
5770  *
5771  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5772  * you will need to pass %G_SPAWN_DO_NOT_REAP_CHILD as flag to
5773  * the spawn function for the child watching to work.
5774  *
5775  * In many programs, you will want to call g_spawn_check_wait_status()
5776  * in the callback to determine whether or not the child exited
5777  * successfully.
5778  *
5779  * Also, note that on platforms where #GPid must be explicitly closed
5780  * (see g_spawn_close_pid()) @pid must not be closed while the source
5781  * is still active.  Typically, you should invoke g_spawn_close_pid()
5782  * in the callback function for the source.
5783  *
5784  * GLib supports only a single callback per process id.
5785  * On POSIX platforms, the same restrictions mentioned for
5786  * g_child_watch_source_new() apply to this function.
5787  *
5788  * This internally creates a main loop source using
5789  * g_child_watch_source_new() and attaches it to the main loop context
5790  * using g_source_attach(). You can do these steps manually if you
5791  * need greater control.
5792  *
5793  * Returns: the ID (greater than 0) of the event source.
5794  *
5795  * Since: 2.4
5796  **/
5797 guint
g_child_watch_add_full(gint priority,GPid pid,GChildWatchFunc function,gpointer data,GDestroyNotify notify)5798 g_child_watch_add_full (gint            priority,
5799 			GPid            pid,
5800 			GChildWatchFunc function,
5801 			gpointer        data,
5802 			GDestroyNotify  notify)
5803 {
5804   GSource *source;
5805   guint id;
5806 
5807   g_return_val_if_fail (function != NULL, 0);
5808 #ifndef G_OS_WIN32
5809   g_return_val_if_fail (pid > 0, 0);
5810 #endif
5811 
5812   source = g_child_watch_source_new (pid);
5813 
5814   if (priority != G_PRIORITY_DEFAULT)
5815     g_source_set_priority (source, priority);
5816 
5817   g_source_set_callback (source, (GSourceFunc) function, data, notify);
5818   id = g_source_attach (source, NULL);
5819   g_source_unref (source);
5820 
5821   return id;
5822 }
5823 
5824 /**
5825  * g_child_watch_add:
5826  * @pid: process id to watch. On POSIX the positive pid of a child
5827  *   process. On Windows a handle for a process (which doesn't have
5828  *   to be a child).
5829  * @function: function to call
5830  * @data: data to pass to @function
5831  *
5832  * Sets a function to be called when the child indicated by @pid
5833  * exits, at a default priority, %G_PRIORITY_DEFAULT.
5834  *
5835  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5836  * you will need to pass %G_SPAWN_DO_NOT_REAP_CHILD as flag to
5837  * the spawn function for the child watching to work.
5838  *
5839  * Note that on platforms where #GPid must be explicitly closed
5840  * (see g_spawn_close_pid()) @pid must not be closed while the
5841  * source is still active. Typically, you will want to call
5842  * g_spawn_close_pid() in the callback function for the source.
5843  *
5844  * GLib supports only a single callback per process id.
5845  * On POSIX platforms, the same restrictions mentioned for
5846  * g_child_watch_source_new() apply to this function.
5847  *
5848  * This internally creates a main loop source using
5849  * g_child_watch_source_new() and attaches it to the main loop context
5850  * using g_source_attach(). You can do these steps manually if you
5851  * need greater control.
5852  *
5853  * Returns: the ID (greater than 0) of the event source.
5854  *
5855  * Since: 2.4
5856  **/
5857 guint
g_child_watch_add(GPid pid,GChildWatchFunc function,gpointer data)5858 g_child_watch_add (GPid            pid,
5859 		   GChildWatchFunc function,
5860 		   gpointer        data)
5861 {
5862   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5863 }
5864 
5865 
5866 /* Idle functions */
5867 
5868 static gboolean
g_idle_prepare(GSource * source,gint * timeout)5869 g_idle_prepare  (GSource  *source,
5870 		 gint     *timeout)
5871 {
5872   *timeout = 0;
5873 
5874   return TRUE;
5875 }
5876 
5877 static gboolean
g_idle_check(GSource * source)5878 g_idle_check    (GSource  *source)
5879 {
5880   return TRUE;
5881 }
5882 
5883 static gboolean
g_idle_dispatch(GSource * source,GSourceFunc callback,gpointer user_data)5884 g_idle_dispatch (GSource    *source,
5885 		 GSourceFunc callback,
5886 		 gpointer    user_data)
5887 {
5888   gboolean again;
5889 
5890   if (!callback)
5891     {
5892       g_warning ("Idle source dispatched without callback. "
5893 		 "You must call g_source_set_callback().");
5894       return FALSE;
5895     }
5896 
5897   again = callback (user_data);
5898 
5899   TRACE (GLIB_IDLE_DISPATCH (source, source->context, callback, user_data, again));
5900 
5901   return again;
5902 }
5903 
5904 /**
5905  * g_idle_source_new:
5906  *
5907  * Creates a new idle source.
5908  *
5909  * The source will not initially be associated with any #GMainContext
5910  * and must be added to one with g_source_attach() before it will be
5911  * executed. Note that the default priority for idle sources is
5912  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5913  * have a default priority of %G_PRIORITY_DEFAULT.
5914  *
5915  * Returns: the newly-created idle source
5916  **/
5917 GSource *
g_idle_source_new(void)5918 g_idle_source_new (void)
5919 {
5920   GSource *source;
5921 
5922   source = g_source_new (&g_idle_funcs, sizeof (GSource));
5923   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5924 
5925   /* Set a default name on the source, just in case the caller does not. */
5926   g_source_set_static_name (source, "GIdleSource");
5927 
5928   return source;
5929 }
5930 
5931 /**
5932  * g_idle_add_full: (rename-to g_idle_add)
5933  * @priority: the priority of the idle source. Typically this will be in the
5934  *   range between %G_PRIORITY_DEFAULT_IDLE and %G_PRIORITY_HIGH_IDLE.
5935  * @function: function to call
5936  * @data: data to pass to @function
5937  * @notify: (nullable): function to call when the idle is removed, or %NULL
5938  *
5939  * Adds a function to be called whenever there are no higher priority
5940  * events pending.
5941  *
5942  * If the function returns %G_SOURCE_REMOVE or %FALSE it is automatically
5943  * removed from the list of event sources and will not be called again.
5944  *
5945  * See [memory management of sources][mainloop-memory-management] for details
5946  * on how to handle the return value and memory management of @data.
5947  *
5948  * This internally creates a main loop source using g_idle_source_new()
5949  * and attaches it to the global #GMainContext using g_source_attach(), so
5950  * the callback will be invoked in whichever thread is running that main
5951  * context. You can do these steps manually if you need greater control or to
5952  * use a custom main context.
5953  *
5954  * Returns: the ID (greater than 0) of the event source.
5955  **/
5956 guint
g_idle_add_full(gint priority,GSourceFunc function,gpointer data,GDestroyNotify notify)5957 g_idle_add_full (gint           priority,
5958 		 GSourceFunc    function,
5959 		 gpointer       data,
5960 		 GDestroyNotify notify)
5961 {
5962   GSource *source;
5963   guint id;
5964 
5965   g_return_val_if_fail (function != NULL, 0);
5966 
5967   source = g_idle_source_new ();
5968 
5969   if (priority != G_PRIORITY_DEFAULT_IDLE)
5970     g_source_set_priority (source, priority);
5971 
5972   g_source_set_callback (source, function, data, notify);
5973   id = g_source_attach (source, NULL);
5974 
5975   TRACE (GLIB_IDLE_ADD (source, g_main_context_default (), id, priority, function, data));
5976 
5977   g_source_unref (source);
5978 
5979   return id;
5980 }
5981 
5982 /**
5983  * g_idle_add:
5984  * @function: function to call
5985  * @data: data to pass to @function.
5986  *
5987  * Adds a function to be called whenever there are no higher priority
5988  * events pending to the default main loop. The function is given the
5989  * default idle priority, %G_PRIORITY_DEFAULT_IDLE.  If the function
5990  * returns %FALSE it is automatically removed from the list of event
5991  * sources and will not be called again.
5992  *
5993  * See [memory management of sources][mainloop-memory-management] for details
5994  * on how to handle the return value and memory management of @data.
5995  *
5996  * This internally creates a main loop source using g_idle_source_new()
5997  * and attaches it to the global #GMainContext using g_source_attach(), so
5998  * the callback will be invoked in whichever thread is running that main
5999  * context. You can do these steps manually if you need greater control or to
6000  * use a custom main context.
6001  *
6002  * Returns: the ID (greater than 0) of the event source.
6003  **/
6004 guint
g_idle_add(GSourceFunc function,gpointer data)6005 g_idle_add (GSourceFunc    function,
6006 	    gpointer       data)
6007 {
6008   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
6009 }
6010 
6011 /**
6012  * g_idle_remove_by_data:
6013  * @data: the data for the idle source's callback.
6014  *
6015  * Removes the idle function with the given data.
6016  *
6017  * Returns: %TRUE if an idle source was found and removed.
6018  **/
6019 gboolean
g_idle_remove_by_data(gpointer data)6020 g_idle_remove_by_data (gpointer data)
6021 {
6022   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
6023 }
6024 
6025 /**
6026  * g_main_context_invoke:
6027  * @context: (nullable): a #GMainContext, or %NULL
6028  * @function: function to call
6029  * @data: data to pass to @function
6030  *
6031  * Invokes a function in such a way that @context is owned during the
6032  * invocation of @function.
6033  *
6034  * If @context is %NULL then the global default main context — as
6035  * returned by g_main_context_default() — is used.
6036  *
6037  * If @context is owned by the current thread, @function is called
6038  * directly.  Otherwise, if @context is the thread-default main context
6039  * of the current thread and g_main_context_acquire() succeeds, then
6040  * @function is called and g_main_context_release() is called
6041  * afterwards.
6042  *
6043  * In any other case, an idle source is created to call @function and
6044  * that source is attached to @context (presumably to be run in another
6045  * thread).  The idle source is attached with %G_PRIORITY_DEFAULT
6046  * priority.  If you want a different priority, use
6047  * g_main_context_invoke_full().
6048  *
6049  * Note that, as with normal idle functions, @function should probably
6050  * return %FALSE.  If it returns %TRUE, it will be continuously run in a
6051  * loop (and may prevent this call from returning).
6052  *
6053  * Since: 2.28
6054  **/
6055 void
g_main_context_invoke(GMainContext * context,GSourceFunc function,gpointer data)6056 g_main_context_invoke (GMainContext *context,
6057                        GSourceFunc   function,
6058                        gpointer      data)
6059 {
6060   g_main_context_invoke_full (context,
6061                               G_PRIORITY_DEFAULT,
6062                               function, data, NULL);
6063 }
6064 
6065 /**
6066  * g_main_context_invoke_full:
6067  * @context: (nullable): a #GMainContext, or %NULL
6068  * @priority: the priority at which to run @function
6069  * @function: function to call
6070  * @data: data to pass to @function
6071  * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
6072  *
6073  * Invokes a function in such a way that @context is owned during the
6074  * invocation of @function.
6075  *
6076  * This function is the same as g_main_context_invoke() except that it
6077  * lets you specify the priority in case @function ends up being
6078  * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
6079  *
6080  * @notify should not assume that it is called from any particular
6081  * thread or with any particular context acquired.
6082  *
6083  * Since: 2.28
6084  **/
6085 void
g_main_context_invoke_full(GMainContext * context,gint priority,GSourceFunc function,gpointer data,GDestroyNotify notify)6086 g_main_context_invoke_full (GMainContext   *context,
6087                             gint            priority,
6088                             GSourceFunc     function,
6089                             gpointer        data,
6090                             GDestroyNotify  notify)
6091 {
6092   g_return_if_fail (function != NULL);
6093 
6094   if (!context)
6095     context = g_main_context_default ();
6096 
6097   if (g_main_context_is_owner (context))
6098     {
6099       while (function (data));
6100       if (notify != NULL)
6101         notify (data);
6102     }
6103 
6104   else
6105     {
6106       GMainContext *thread_default;
6107 
6108       thread_default = g_main_context_get_thread_default ();
6109 
6110       if (!thread_default)
6111         thread_default = g_main_context_default ();
6112 
6113       if (thread_default == context && g_main_context_acquire (context))
6114         {
6115           while (function (data));
6116 
6117           g_main_context_release (context);
6118 
6119           if (notify != NULL)
6120             notify (data);
6121         }
6122       else
6123         {
6124           GSource *source;
6125 
6126           source = g_idle_source_new ();
6127           g_source_set_priority (source, priority);
6128           g_source_set_callback (source, function, data, notify);
6129           g_source_attach (source, context);
6130           g_source_unref (source);
6131         }
6132     }
6133 }
6134 
6135 static gpointer
glib_worker_main(gpointer data)6136 glib_worker_main (gpointer data)
6137 {
6138   while (TRUE)
6139     {
6140       g_main_context_iteration (glib_worker_context, TRUE);
6141 
6142 #ifdef G_OS_UNIX
6143       if (g_atomic_int_get (&any_unix_signal_pending))
6144         dispatch_unix_signals ();
6145 #endif
6146     }
6147 
6148   return NULL; /* worst GCC warning message ever... */
6149 }
6150 
6151 GMainContext *
g_get_worker_context(void)6152 g_get_worker_context (void)
6153 {
6154   static gsize initialised;
6155 
6156   if (g_once_init_enter (&initialised))
6157     {
6158       /* mask all signals in the worker thread */
6159 #ifdef G_OS_UNIX
6160       sigset_t prev_mask;
6161       sigset_t all;
6162 
6163       sigfillset (&all);
6164       pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
6165 #endif
6166       glib_worker_context = g_main_context_new ();
6167       g_thread_new ("gmain", glib_worker_main, NULL);
6168 #ifdef G_OS_UNIX
6169       pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
6170 #endif
6171       g_once_init_leave (&initialised, TRUE);
6172     }
6173 
6174   return glib_worker_context;
6175 }
6176 
6177 /**
6178  * g_steal_fd:
6179  * @fd_ptr: (not optional) (inout): A pointer to a file descriptor
6180  *
6181  * Sets @fd_ptr to `-1`, returning the value that was there before.
6182  *
6183  * Conceptually, this transfers the ownership of the file descriptor
6184  * from the referenced variable to the caller of the function (i.e.
6185  * ‘steals’ the reference). This is very similar to g_steal_pointer(),
6186  * but for file descriptors.
6187  *
6188  * On POSIX platforms, this function is async-signal safe
6189  * (see [`signal(7)`](man:signal(7)) and
6190  * [`signal-safety(7)`](man:signal-safety(7))), making it safe to call from a
6191  * signal handler or a #GSpawnChildSetupFunc.
6192  *
6193  * Returns: the value that @fd_ptr previously had
6194  * Since: 2.70
6195  */
6196