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