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