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