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