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