gmain.c 168 KB
Newer Older
1
2
3
4
5
6
7
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * gmain.c: Main loop abstraction, timeouts, and idle functions
 * Copyright 1998 Owen Taylor
 *
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
12
13
14
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19
20
 */

21
/*
22
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
23
24
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
Matthias Clasen's avatar
Matthias Clasen committed
25
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
26
27
 */

Matthias Clasen's avatar
Matthias Clasen committed
28
/*
29
30
31
 * MT safe
 */

32
#include "config.h"
Matthias Clasen's avatar
Matthias Clasen committed
33
#include "glibconfig.h"
34
#include "glib_trace.h"
35

36
37
38
/* Uncomment the next line (and the corresponding line in gpoll.c) to
 * enable debugging printouts if the environment variable
 * G_MAIN_POLL_DEBUG is set to some value.
39
 */
40
41
/* #define G_MAIN_POLL_DEBUG */

42
43
44
45
46
47
48
#ifdef _WIN32
/* Always enable debugging printout on Windows, as it is more often
 * needed there...
 */
#define G_MAIN_POLL_DEBUG
#endif

49
50
#ifdef G_OS_UNIX
#include "glib-unix.h"
51
#include <pthread.h>
52
53
54
#ifdef HAVE_EVENTFD
#include <sys/eventfd.h>
#endif
55
56
#endif

57
#include <signal.h>
58
#include <sys/types.h>
59
#include <time.h>
60
#include <stdlib.h>
61
#ifdef HAVE_SYS_TIME_H
62
#include <sys/time.h>
63
#endif /* HAVE_SYS_TIME_H */
64
#ifdef G_OS_UNIX
65
#include <unistd.h>
66
#endif /* G_OS_UNIX */
67
#include <errno.h>
68
#include <string.h>
69

70
#ifdef G_OS_WIN32
71
72
#define STRICT
#include <windows.h>
73
#endif /* G_OS_WIN32 */
74

75
76
77
78
#ifdef HAVE_MACH_MACH_TIME_H
#include <mach/mach_time.h>
#endif

79
80
#include "glib_trace.h"

Matthias Clasen's avatar
Matthias Clasen committed
81
82
83
84
85
86
87
88
89
#include "gmain.h"

#include "garray.h"
#include "giochannel.h"
#include "ghash.h"
#include "ghook.h"
#include "gqueue.h"
#include "gstrfuncs.h"
#include "gtestutils.h"
90
#include "gthreadprivate.h"
91
#include "gtrace-private.h"
92

93
94
95
96
97
98
99
100
#ifdef G_OS_WIN32
#include "gwin32.h"
#endif

#ifdef  G_MAIN_POLL_DEBUG
#include "gtimer.h"
#endif

101
#include "gwakeup.h"
102
#include "gmain-internal.h"
Dan Winship's avatar
Dan Winship committed
103
#include "glib-init.h"
104
#include "glib-private.h"
105

Matthias Clasen's avatar
Matthias Clasen committed
106
107
108
109
110
111
112
113
114
115
116
117
118
/**
 * SECTION:main
 * @title: The Main Event Loop
 * @short_description: manages all available sources of events
 *
 * The main event loop manages all the available sources of events for
 * GLib and GTK+ applications. These events can come from any number of
 * different types of sources such as file descriptors (plain files,
 * pipes or sockets) and timeouts. New types of event sources can also
 * be added using g_source_attach().
 *
 * To allow multiple independent sets of sources to be handled in
 * different threads, each source is associated with a #GMainContext.
119
120
121
122
 * A #GMainContext can only be running in a single thread, but
 * sources can be added to it and removed from it from other threads. All
 * functions which operate on a #GMainContext or a built-in #GSource are
 * thread-safe.
Matthias Clasen's avatar
Matthias Clasen committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
 *
 * Each event source is assigned a priority. The default priority,
 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
 * Values greater than 0 denote lower priorities. Events from high priority
 * sources are always processed before events from lower priority sources.
 *
 * Idle functions can also be added, and assigned a priority. These will
 * be run whenever no events with a higher priority are ready to be processed.
 *
 * The #GMainLoop data type represents a main event loop. A GMainLoop is
 * created with g_main_loop_new(). After adding the initial event sources,
 * g_main_loop_run() is called. This continuously checks for new events from
 * each of the event sources and dispatches them. Finally, the processing of
 * an event from one of the sources leads to a call to g_main_loop_quit() to
 * exit the main loop, and g_main_loop_run() returns.
 *
 * It is possible to create new instances of #GMainLoop recursively.
 * This is often used in GTK+ applications when showing modal dialog
 * boxes. Note that event sources are associated with a particular
 * #GMainContext, and will be checked and dispatched for all main
 * loops associated with that GMainContext.
 *
 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
 * gtk_main_quit() and gtk_events_pending().
 *
148
149
150
 * ## Creating new source types
 *
 * One of the unusual features of the #GMainLoop functionality
Matthias Clasen's avatar
Matthias Clasen committed
151
152
153
 * is that new types of event source can be created and used in
 * addition to the builtin type of event source. A new event source
 * type is used for handling GDK events. A new source type is created
154
155
156
157
158
 * by "deriving" from the #GSource structure. The derived type of
 * source is represented by a structure that has the #GSource structure
 * as a first element, and other elements specific to the new source
 * type. To create an instance of the new source type, call
 * g_source_new() passing in the size of the derived structure and
Matthias Clasen's avatar
Matthias Clasen committed
159
 * a table of functions. These #GSourceFuncs determine the behavior of
160
161
162
 * the new source type.
 *
 * New source types basically interact with the main context
Matthias Clasen's avatar
Matthias Clasen committed
163
164
165
166
 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
 * to determine the maximum amount of time that the main loop will sleep
 * before checking the source again. In addition, or as well, the source
 * can add file descriptors to the set that the main context checks using
167
168
169
170
171
 * g_source_add_poll().
 *
 * ## Customizing the main loop iteration
 *
 * Single iterations of a #GMainContext can be run with
Matthias Clasen's avatar
Matthias Clasen committed
172
173
174
175
176
177
 * g_main_context_iteration(). In some cases, more detailed control
 * of exactly how the details of the main loop work is desired, for
 * instance, when integrating the #GMainLoop with an external main loop.
 * In such cases, you can call the component functions of
 * g_main_context_iteration() directly. These functions are
 * g_main_context_prepare(), g_main_context_query(),
178
179
 * g_main_context_check() and g_main_context_dispatch().
 *
Matthias Clasen's avatar
Matthias Clasen committed
180
181
 * ## State of a Main Context # {#mainloop-states}
 *
182
 * The operation of these functions can best be seen in terms
Matthias Clasen's avatar
Matthias Clasen committed
183
184
185
 * of a state diagram, as shown in this image.
 *
 * ![](mainloop-states.gif)
186
 *
187
 * On UNIX, the GLib mainloop is incompatible with fork(). Any program
188
189
 * using the mainloop must either exec() or exit() from the child
 * without returning to the mainloop.
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
 *
 * ## Memory management of sources # {#mainloop-memory-management}
 *
 * There are two options for memory management of the user data passed to a
 * #GSource to be passed to its callback on invocation. This data is provided
 * in calls to g_timeout_add(), g_timeout_add_full(), g_idle_add(), etc. and
 * more generally, using g_source_set_callback(). This data is typically an
 * object which ‘owns’ the timeout or idle callback, such as a widget or a
 * network protocol implementation. In many cases, it is an error for the
 * callback to be invoked after this owning object has been destroyed, as that
 * results in use of freed memory.
 *
 * The first, and preferred, option is to store the source ID returned by
 * functions such as g_timeout_add() or g_source_attach(), and explicitly
 * remove that source from the main context using g_source_remove() when the
205
 * owning object is finalized. This ensures that the callback can only be
206
207
208
209
210
211
212
213
214
215
216
217
218
 * invoked while the object is still alive.
 *
 * The second option is to hold a strong reference to the object in the
 * callback, and to release it in the callback’s #GDestroyNotify. This ensures
 * that the object is kept alive until after the source is finalized, which is
 * guaranteed to be after it is invoked for the final time. The #GDestroyNotify
 * is another callback passed to the ‘full’ variants of #GSource functions (for
 * example, g_timeout_add_full()). It is called when the source is finalized,
 * and is designed for releasing references like this.
 *
 * One important caveat of this second approach is that it will keep the object
 * alive indefinitely if the main loop is stopped before the #GSource is
 * invoked, which may be undesirable.
Matthias Clasen's avatar
Matthias Clasen committed
219
220
 */

221
222
/* Types */

223
typedef struct _GTimeoutSource GTimeoutSource;
224
typedef struct _GChildWatchSource GChildWatchSource;
225
typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
226
typedef struct _GPollRec GPollRec;
227
typedef struct _GSourceCallback GSourceCallback;
228

229
230
typedef enum
{
231
  G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
232
233
  G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
  G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
234
235
} GSourceFlags;

236
237
238
239
240
241
242
243
typedef struct _GSourceList GSourceList;

struct _GSourceList
{
  GSource *head, *tail;
  gint priority;
};

244
245
246
247
248
249
250
251
typedef struct _GMainWaiter GMainWaiter;

struct _GMainWaiter
{
  GCond *cond;
  GMutex *mutex;
};

252
253
254
255
256
typedef struct _GMainDispatch GMainDispatch;

struct _GMainDispatch
{
  gint depth;
257
  GSource *source;
258
259
};

260
#ifdef G_MAIN_POLL_DEBUG
261
gboolean _g_main_poll_debug = FALSE;
262
263
#endif

264
struct _GMainContext
265
{
266
267
268
  /* The following lock is used for both the list of sources
   * and the list of poll records
   */
269
  GMutex mutex;
270
  GCond cond;
271
272
273
  GThread *owner;
  guint owner_count;
  GSList *waiters;
274

275
  volatile gint ref_count;
276

277
278
  GHashTable *sources;              /* guint -> GSource */

279
280
281
282
  GPtrArray *pending_dispatches;
  gint timeout;			/* Timeout for current iteration */

  guint next_id;
283
  GList *source_lists;
284
  gint in_check_or_prepare;
285

286
  GPollRec *poll_records;
287
288
  guint n_poll_records;
  GPollFD *cached_poll_array;
289
  guint cached_poll_array_size;
290

291
  GWakeup *wakeup;
292
293
294
295
296
297
298
299

  GPollFD wake_up_rec;

/* Flag indicating whether the set of fd's changed during a poll */
  gboolean poll_changed;

  GPollFunc poll_func;

300
  gint64   time;
Allison Karlitskaya's avatar
Allison Karlitskaya committed
301
  gboolean time_is_fresh;
302
303
304
305
};

struct _GSourceCallback
{
306
  volatile gint ref_count;
307
308
309
  GSourceFunc func;
  gpointer    data;
  GDestroyNotify notify;
310
311
};

312
313
struct _GMainLoop
{
314
  GMainContext *context;
315
  gboolean is_running; /* (atomic) */
316
  volatile gint ref_count;
317
318
};

319
struct _GTimeoutSource
320
{
321
  GSource     source;
322
  /* Measured in seconds if 'seconds' is TRUE, or milliseconds otherwise. */
323
  guint       interval;
324
  gboolean    seconds;
325
326
};

327
328
329
330
331
struct _GChildWatchSource
{
  GSource     source;
  GPid        pid;
  gint        child_status;
332
333
334
#ifdef G_OS_WIN32
  GPollFD     poll;
#else /* G_OS_WIN32 */
335
  gboolean    child_exited; /* (atomic) */
336
#endif /* G_OS_WIN32 */
337
338
};

339
340
341
342
struct _GUnixSignalWatchSource
{
  GSource     source;
  int         signum;
343
  gboolean    pending; /* (atomic) */
344
345
};

346
347
struct _GPollRec
{
348
  GPollFD *fd;
349
  GPollRec *prev;
350
  GPollRec *next;
351
  gint priority;
352
353
};

354
355
356
357
struct _GSourcePrivate
{
  GSList *child_sources;
  GSource *parent_source;
358
359

  gint64 ready_time;
360
361
362
363
364

  /* This is currently only used on UNIX, but we always declare it (and
   * let it remain empty on Windows) to avoid #ifdef all over the place.
   */
  GSList *fds;
365
366

  GSourceDisposeFunc dispose;
367
368
};

Dan Winship's avatar
Dan Winship committed
369
370
371
372
typedef struct _GSourceIter
{
  GMainContext *context;
  gboolean may_modify;
373
  GList *current_list;
Dan Winship's avatar
Dan Winship committed
374
375
376
  GSource *source;
} GSourceIter;

377
378
#define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
#define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
379
#define G_THREAD_SELF g_thread_self ()
380
381

#define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
382
#define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
383

384
385
/* Forward declarations */

386
387
388
389
390
391
static void g_source_unref_internal             (GSource      *source,
						 GMainContext *context,
						 gboolean      have_lock);
static void g_source_destroy_internal           (GSource      *source,
						 GMainContext *context,
						 gboolean      have_lock);
392
393
394
static void g_source_set_priority_unlocked      (GSource      *source,
						 GMainContext *context,
						 gint          priority);
395
396
397
static void g_child_source_remove_internal      (GSource      *child_source,
                                                 GMainContext *context);

398
399
400
401
402
403
404
405
406
407
408
static void g_main_context_poll                 (GMainContext *context,
						 gint          timeout,
						 gint          priority,
						 GPollFD      *fds,
						 gint          n_fds);
static void g_main_context_add_poll_unlocked    (GMainContext *context,
						 gint          priority,
						 GPollFD      *fd);
static void g_main_context_remove_poll_unlocked (GMainContext *context,
						 GPollFD      *fd);

Dan Winship's avatar
Dan Winship committed
409
410
411
412
413
414
415
static void     g_source_iter_init  (GSourceIter   *iter,
				     GMainContext  *context,
				     gboolean       may_modify);
static gboolean g_source_iter_next  (GSourceIter   *iter,
				     GSource      **source);
static void     g_source_iter_clear (GSourceIter   *iter);

416
417
418
static gboolean g_timeout_dispatch (GSource     *source,
				    GSourceFunc  callback,
				    gpointer     user_data);
419
420
421
422
423
424
static gboolean g_child_watch_prepare  (GSource     *source,
				        gint        *timeout);
static gboolean g_child_watch_check    (GSource     *source);
static gboolean g_child_watch_dispatch (GSource     *source,
					GSourceFunc  callback,
					gpointer     user_data);
425
static void     g_child_watch_finalize (GSource     *source);
426
427
428
429
430
431
432
433
434
435
#ifdef G_OS_UNIX
static void g_unix_signal_handler (int signum);
static gboolean g_unix_signal_watch_prepare  (GSource     *source,
					      gint        *timeout);
static gboolean g_unix_signal_watch_check    (GSource     *source);
static gboolean g_unix_signal_watch_dispatch (GSource     *source,
					      GSourceFunc  callback,
					      gpointer     user_data);
static void     g_unix_signal_watch_finalize  (GSource     *source);
#endif
436
437
438
439
440
441
442
static gboolean g_idle_prepare     (GSource     *source,
				    gint        *timeout);
static gboolean g_idle_check       (GSource     *source);
static gboolean g_idle_dispatch    (GSource     *source,
				    GSourceFunc  callback,
				    gpointer     user_data);

443
444
static void block_source (GSource *source);

445
446
static GMainContext *glib_worker_context;

447
#ifndef G_OS_WIN32
448

449

450
451
/* UNIX signals work by marking one of these variables then waking the
 * worker context to check on them and dispatch accordingly.
452
453
454
455
 *
 * Both variables must be accessed using atomic primitives, unless those atomic
 * primitives are implemented using fallback mutexes (as those aren’t safe in
 * an interrupt context).
456
457
458
459
460
461
462
463
464
 *
 * If using atomic primitives, the variables must be of type `int` (so they’re
 * the right size for the atomic primitives). Otherwise, use `sig_atomic_t` if
 * it’s available, which is guaranteed to be async-signal-safe (but it’s *not*
 * guaranteed to be thread-safe, which is why we use atomic primitives if
 * possible).
 *
 * Typically, `sig_atomic_t` is a typedef to `int`, but that’s not the case on
 * FreeBSD, so we can’t use it unconditionally if it’s defined.
465
 */
466
#if (defined(G_ATOMIC_LOCK_FREE) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) || !defined(HAVE_SIG_ATOMIC_T)
467
468
static volatile int unix_signal_pending[NSIG];
static volatile int any_unix_signal_pending;
469
470
471
#else
static volatile sig_atomic_t unix_signal_pending[NSIG];
static volatile sig_atomic_t any_unix_signal_pending;
472
#endif
473
474
475

/* Guards all the data below */
G_LOCK_DEFINE_STATIC (unix_signal_lock);
476
static guint unix_signal_refcount[NSIG];
477
478
static GSList *unix_signal_watches;
static GSList *unix_child_watches;
479

480
GSourceFuncs g_unix_signal_funcs =
481
482
483
484
{
  g_unix_signal_watch_prepare,
  g_unix_signal_watch_check,
  g_unix_signal_watch_dispatch,
485
486
  g_unix_signal_watch_finalize,
  NULL, NULL
487
};
488
#endif /* !G_OS_WIN32 */
489
490
491
G_LOCK_DEFINE_STATIC (main_context_list);
static GSList *main_context_list = NULL;

492
GSourceFuncs g_timeout_funcs =
493
{
Allison Karlitskaya's avatar
Allison Karlitskaya committed
494
495
  NULL, /* prepare */
  NULL, /* check */
496
  g_timeout_dispatch,
497
  NULL, NULL, NULL
498
499
};

500
501
502
503
504
GSourceFuncs g_child_watch_funcs =
{
  g_child_watch_prepare,
  g_child_watch_check,
  g_child_watch_dispatch,
505
506
  g_child_watch_finalize,
  NULL, NULL
507
508
};

509
GSourceFuncs g_idle_funcs =
510
{
511
512
513
  g_idle_prepare,
  g_idle_check,
  g_idle_dispatch,
514
  NULL, NULL, NULL
515
516
};

517
518
/**
 * g_main_context_ref:
Owen Taylor's avatar
Owen Taylor committed
519
 * @context: a #GMainContext
520
521
 * 
 * Increases the reference count on a #GMainContext object by one.
522
523
 *
 * Returns: the @context that was passed in (since 2.6)
524
 **/
525
GMainContext *
526
g_main_context_ref (GMainContext *context)
527
{
528
529
  g_return_val_if_fail (context != NULL, NULL);
  g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL); 
530

531
  g_atomic_int_inc (&context->ref_count);
532
533

  return context;
534
535
}

536
static inline void
537
538
539
poll_rec_list_free (GMainContext *context,
		    GPollRec     *list)
{
540
  g_slice_free_chain (GPollRec, list, next);
541
542
}

543
544
545
546
547
548
549
550
551
/**
 * g_main_context_unref:
 * @context: a #GMainContext
 * 
 * Decreases the reference count on a #GMainContext object by one. If
 * the result is zero, free the context and free all associated memory.
 **/
void
g_main_context_unref (GMainContext *context)
552
{
Dan Winship's avatar
Dan Winship committed
553
  GSourceIter iter;
554
  GSource *source;
555
  GList *sl_iter;
556
  GSList *s_iter, *remaining_sources = NULL;
557
  GSourceList *list;
558
  guint i;
Dan Winship's avatar
Dan Winship committed
559

560
561
  g_return_if_fail (context != NULL);
  g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0); 
562

563
564
  if (!g_atomic_int_dec_and_test (&context->ref_count))
    return;
565

566
567
568
569
  G_LOCK (main_context_list);
  main_context_list = g_slist_remove (main_context_list, context);
  G_UNLOCK (main_context_list);

570
571
572
573
  /* Free pending dispatches */
  for (i = 0; i < context->pending_dispatches->len; i++)
    g_source_unref_internal (context->pending_dispatches->pdata[i], context, FALSE);

574
575
  /* g_source_iter_next() assumes the context is locked. */
  LOCK_CONTEXT (context);
576
577
578
579
580
581
582
583
584
585

  /* First collect all remaining sources from the sources lists and store a
   * new reference in a separate list. Also set the context of the sources
   * to NULL so that they can't access a partially destroyed context anymore.
   *
   * We have to do this first so that we have a strong reference to all
   * sources and destroying them below does not also free them, and so that
   * none of the sources can access the context from their finalize/dispose
   * functions. */
  g_source_iter_init (&iter, context, FALSE);
Dan Winship's avatar
Dan Winship committed
586
  while (g_source_iter_next (&iter, &source))
587
588
    {
      source->context = NULL;
589
590
591
592
593
594
595
596
597
598
599
      remaining_sources = g_slist_prepend (remaining_sources, g_source_ref (source));
    }
  g_source_iter_clear (&iter);

  /* Next destroy all sources. As we still hold a reference to all of them,
   * this won't cause any of them to be freed yet and especially prevents any
   * source that unrefs another source from its finalize function to be freed.
   */
  for (s_iter = remaining_sources; s_iter; s_iter = s_iter->next)
    {
      source = s_iter->data;
600
      g_source_destroy_internal (source, context, TRUE);
601
    }
602

603
604
605
606
607
608
  for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
    {
      list = sl_iter->data;
      g_slice_free (GSourceList, list);
    }
  g_list_free (context->source_lists);
609

610
  g_hash_table_destroy (context->sources);
611

612
  UNLOCK_CONTEXT (context);
613
  g_mutex_clear (&context->mutex);
614

615
616
  g_ptr_array_free (context->pending_dispatches, TRUE);
  g_free (context->cached_poll_array);
617
618

  poll_rec_list_free (context, context->poll_records);
619

620
  g_wakeup_free (context->wakeup);
621
  g_cond_clear (&context->cond);
622

623
  g_free (context);
624
625
626
627
628
629
630
631
632
633
634
635

  /* And now finally get rid of our references to the sources. This will cause
   * them to be freed unless something else still has a reference to them. Due
   * to setting the context pointers in the sources to NULL above, this won't
   * ever access the context or the internal linked list inside the GSource.
   * We already removed the sources completely from the context above. */
  for (s_iter = remaining_sources; s_iter; s_iter = s_iter->next)
    {
      source = s_iter->data;
      g_source_unref_internal (source, NULL, FALSE);
    }
  g_slist_free (remaining_sources);
636
637
}

638
639
640
641
642
643
644
645
646
647
648
649
/* Helper function used by mainloop/overflow test.
 */
GMainContext *
g_main_context_new_with_next_id (guint next_id)
{
  GMainContext *ret = g_main_context_new ();
  
  ret->next_id = next_id;
  
  return ret;
}

650
/**
651
 * g_main_context_new:
652
 * 
Matthias Clasen's avatar
Matthias Clasen committed
653
 * Creates a new #GMainContext structure.
654
 * 
655
 * Returns: the new #GMainContext
656
657
 **/
GMainContext *
658
g_main_context_new (void)
659
{
660
  static gsize initialised;
661
662
  GMainContext *context;

663
664
  if (g_once_init_enter (&initialised))
    {
665
#ifdef G_MAIN_POLL_DEBUG
666
      if (g_getenv ("G_MAIN_POLL_DEBUG") != NULL)
667
668
        _g_main_poll_debug = TRUE;
#endif
669

670
671
672
673
674
      g_once_init_leave (&initialised, TRUE);
    }

  context = g_new0 (GMainContext, 1);

675
676
  TRACE (GLIB_MAIN_CONTEXT_NEW (context));

677
  g_mutex_init (&context->mutex);
678
  g_cond_init (&context->cond);
Owen Taylor's avatar
Owen Taylor committed
679

680
  context->sources = g_hash_table_new (NULL, NULL);
681
682
  context->owner = NULL;
  context->waiters = NULL;
683

684
685
  context->ref_count = 1;

686
687
  context->next_id = 1;
  
688
  context->source_lists = NULL;
689
690
691
692
693
694
695
696
  
  context->poll_func = g_poll;
  
  context->cached_poll_array = NULL;
  context->cached_poll_array_size = 0;
  
  context->pending_dispatches = g_ptr_array_new ();
  
Allison Karlitskaya's avatar
Allison Karlitskaya committed
697
  context->time_is_fresh = FALSE;
698
  
699
700
701
  context->wakeup = g_wakeup_new ();
  g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
  g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
702

703
704
  G_LOCK (main_context_list);
  main_context_list = g_slist_append (main_context_list, context);
705
706

#ifdef G_MAIN_POLL_DEBUG
707
  if (_g_main_poll_debug)
708
709
710
    g_print ("created context=%p\n", context);
#endif

711
712
  G_UNLOCK (main_context_list);

713
  return context;
714
715
}

716
717
/**
 * g_main_context_default:
718
 *
719
720
721
722
 * Returns the global default main context. This is the main context
 * used for main loop functions when a main loop is not explicitly
 * specified, and corresponds to the "main" main loop. See also
 * g_main_context_get_thread_default().
723
 *
724
 * Returns: (transfer none): the global default main context.
725
726
727
 **/
GMainContext *
g_main_context_default (void)
728
{
729
  static GMainContext *default_main_context = NULL;
730

731
  if (g_once_init_enter (&default_main_context))
732
    {
733
734
735
      GMainContext *context;

      context = g_main_context_new ();
736

737
      TRACE (GLIB_MAIN_CONTEXT_DEFAULT (context));
738

739
#ifdef G_MAIN_POLL_DEBUG
740
      if (_g_main_poll_debug)
741
        g_print ("default context=%p\n", context);
742
#endif
743

744
      g_once_init_leave (&default_main_context, context);
745
    }
746

747
  return default_main_context;
748
749
}

750
static void
751
free_context (gpointer data)
752
{
753
  GMainContext *context = data;
754

755
756
  TRACE (GLIB_MAIN_CONTEXT_FREE (context));

757
758
759
760
761
762
763
764
765
  g_main_context_release (context);
  if (context)
    g_main_context_unref (context);
}

static void
free_context_stack (gpointer data)
{
  g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
766
767
}

768
769
static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);

770
771
/**
 * g_main_context_push_thread_default:
772
 * @context: (nullable): a #GMainContext, or %NULL for the global default context
773
774
775
 *
 * Acquires @context and sets it as the thread-default context for the
 * current thread. This will cause certain asynchronous operations
Matthias Clasen's avatar
Matthias Clasen committed
776
 * (such as most [gio][gio]-based I/O) which are
777
778
779
 * started in this thread to run under @context and deliver their
 * results to its main loop, rather than running under the global
 * default context in the main thread. Note that calling this function
780
781
782
 * changes the context returned by g_main_context_get_thread_default(),
 * not the one returned by g_main_context_default(), so it does not affect
 * the context used by functions like g_idle_add().
783
784
785
786
 *
 * Normally you would call this function shortly after creating a new
 * thread, passing it a #GMainContext which will be run by a
 * #GMainLoop in that thread, to set a new default context for all
787
788
789
790
791
792
793
794
795
796
797
798
 * async operations in that thread. In this case you may not need to
 * ever call g_main_context_pop_thread_default(), assuming you want the
 * new #GMainContext to be the default for the whole lifecycle of the
 * thread.
 *
 * If you don't have control over how the new thread was created (e.g.
 * in the new thread isn't newly created, or if the thread life
 * cycle is managed by a #GThreadPool), it is always suggested to wrap
 * the logic that needs to use the new #GMainContext inside a
 * g_main_context_push_thread_default() / g_main_context_pop_thread_default()
 * pair, otherwise threads that are re-used will end up never explicitly
 * releasing the #GMainContext reference they hold.
799
 *
800
 * In some cases you may want to schedule a single operation in a
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
 * non-default context, or temporarily use a non-default context in
 * the main thread. In that case, you can wrap the call to the
 * asynchronous operation inside a
 * g_main_context_push_thread_default() /
 * g_main_context_pop_thread_default() pair, but it is up to you to
 * ensure that no other asynchronous operations accidentally get
 * started while the non-default context is active.
 *
 * Beware that libraries that predate this function may not correctly
 * handle being used from a thread with a thread-default context. Eg,
 * see g_file_supports_thread_contexts().
 *
 * Since: 2.22
 **/
void
g_main_context_push_thread_default (GMainContext *context)
{
  GQueue *stack;
  gboolean acquired_context;

  acquired_context = g_main_context_acquire (context);
  g_return_if_fail (acquired_context);

  if (context == g_main_context_default ())
    context = NULL;
  else if (context)
    g_main_context_ref (context);

829
  stack = g_private_get (&thread_context_stack);
830
831
832
  if (!stack)
    {
      stack = g_queue_new ();
833
      g_private_set (&thread_context_stack, stack);
834
835
836
    }

  g_queue_push_head (stack, context);
837
838

  TRACE (GLIB_MAIN_CONTEXT_PUSH_THREAD_DEFAULT (context));
839
840
841
842
}

/**
 * g_main_context_pop_thread_default:
843
 * @context: (nullable): a #GMainContext object, or %NULL
844
845
846
847
848
849
850
851
852
853
854
855
856
857
 *
 * Pops @context off the thread-default context stack (verifying that
 * it was on the top of the stack).
 *
 * Since: 2.22
 **/
void
g_main_context_pop_thread_default (GMainContext *context)
{
  GQueue *stack;

  if (context == g_main_context_default ())
    context = NULL;

858
  stack = g_private_get (&thread_context_stack);
859
860
861
862

  g_return_if_fail (stack != NULL);
  g_return_if_fail (g_queue_peek_head (stack) == context);

863
864
  TRACE (GLIB_MAIN_CONTEXT_POP_THREAD_DEFAULT (context));

865
866
867
868
869
870
871
872
873
874
875
876
  g_queue_pop_head (stack);

  g_main_context_release (context);
  if (context)
    g_main_context_unref (context);
}

/**
 * g_main_context_get_thread_default:
 *
 * Gets the thread-default #GMainContext for this thread. Asynchronous
 * operations that want to be able to be run in contexts other than
877
878
 * the default one should call this method or
 * g_main_context_ref_thread_default() to get a #GMainContext to add
Matthias Clasen's avatar
Matthias Clasen committed
879
 * their #GSources to. (Note that even in single-threaded
880
881
 * programs applications may sometimes want to temporarily push a
 * non-default context, so it is not safe to assume that this will
882
 * always return %NULL if you are running in the default thread.)
883
 *
884
885
886
 * If you need to hold a reference on the context, use
 * g_main_context_ref_thread_default() instead.
 *
887
 * Returns: (transfer none) (nullable): the thread-default #GMainContext, or
888
 * %NULL if the thread-default context is the global default context.
889
890
891
892
893
894
895
896
 *
 * Since: 2.22
 **/
GMainContext *
g_main_context_get_thread_default (void)
{
  GQueue *stack;

897
  stack = g_private_get (&thread_context_stack);
898
899
900
901
902
903
  if (stack)
    return g_queue_peek_head (stack);
  else
    return NULL;
}

904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
/**
 * g_main_context_ref_thread_default:
 *
 * Gets the thread-default #GMainContext for this thread, as with
 * g_main_context_get_thread_default(), but also adds a reference to
 * it with g_main_context_ref(). In addition, unlike
 * g_main_context_get_thread_default(), if the thread-default context
 * is the global default context, this will return that #GMainContext
 * (with a ref added to it) rather than returning %NULL.
 *
 * Returns: (transfer full): the thread-default #GMainContext. Unref
 *     with g_main_context_unref() when you are done with it.
 *
 * Since: 2.32
 */
GMainContext *
g_main_context_ref_thread_default (void)
{
  GMainContext *context;

  context = g_main_context_get_thread_default ();
  if (!context)
    context = g_main_context_default ();
  return g_main_context_ref (context);
}

930
931
932
933
934
935
/* Hooks for adding to the main loop */

/**
 * g_source_new:
 * @source_funcs: structure containing functions that implement
 *                the sources behavior.
Matthias Clasen's avatar
Matthias Clasen committed
936
 * @struct_size: size of the #GSource structure to create.
937
 * 
Matthias Clasen's avatar
Matthias Clasen committed
938
939
 * Creates a new #GSource structure. The size is specified to
 * allow creating structures derived from #GSource that contain
940
 * additional data. The size passed in must be at least
Matthias Clasen's avatar
Matthias Clasen committed
941
 * `sizeof (GSource)`.
942
943
 * 
 * The source will not initially be associated with any #GMainContext
944
 * and must be added to one with g_source_attach() before it will be
945
946
 * executed.
 * 
947
 * Returns: the newly-created #GSource.
948
949
950
951
 **/
GSource *
g_source_new (GSourceFuncs *source_funcs,
	      guint         struct_size)
952
{
953
954
955
956
  GSource *source;

  g_return_val_if_fail (source_funcs != NULL, NULL);
  g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
957
  
958
  source = (GSource*) g_malloc0 (struct_size);
959
  source->priv = g_slice_new0 (GSourcePrivate);
960
961
  source->source_funcs = source_funcs;
  source->ref_count = 1;
962
  
963
  source->priority = G_PRIORITY_DEFAULT;
964

965
  source->flags = G_HOOK_FLAG_ACTIVE;
966

967
968
  source->priv->ready_time = -1;

969
  /* NULL/0 initialization for all other fields */
970
971
972
973
974

  TRACE (GLIB_SOURCE_NEW (source, source_funcs->prepare, source_funcs->check,
                          source_funcs->dispatch, source_funcs->finalize,
                          struct_size));

975
  return source;
976
977
}

978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
/**
 * g_source_set_dispose_function:
 * @source: A #GSource to set the dispose function on
 * @dispose: #GSourceDisposeFunc to set on the source
 *
 * Set @dispose as dispose function on @source. @dispose will be called once
 * the reference count of @source reaches 0 but before any of the state of the
 * source is freed, especially before the finalize function is called.
 *
 * This means that at this point @source is still a valid #GSource and it is
 * allow for the reference count to increase again until @dispose returns.
 *
 * The dispose function can be used to clear any "weak" references to the
 * @source in other data structures in a thread-safe way where it is possible
 * for another thread to increase the reference count of @source again while
 * it is being freed.
 *
 * The finalize function can not be used for this purpose as at that point
 * @source is already partially freed and not valid anymore.
 *
 * This should only ever be called from #GSource implementations.
 *
 * Since: 2.64
 **/
void
g_source_set_dispose_function (GSource            *source,
			       GSourceDisposeFunc  dispose)
{
  g_return_if_fail (source != NULL);
  g_return_if_fail (source->priv->dispose == NULL);
1008
  g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1009
1010
1011
  source->priv->dispose = dispose;
}

Dan Winship's avatar
Dan Winship committed
1012
1013
1014
1015
1016
1017
1018
/* Holds context's lock */
static void
g_source_iter_init (GSourceIter  *iter,
		    GMainContext *context,
		    gboolean      may_modify)
{
  iter->context = context;
1019
  iter->current_list = NULL;
Dan Winship's avatar
Dan Winship committed
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
  iter->source = NULL;
  iter->may_modify = may_modify;
}

/* Holds context's lock */
static gboolean
g_source_iter_next (GSourceIter *iter, GSource **source)
{
  GSource *next_source;

  if (iter->source)
1031
1032
1033
1034
1035
    next_source = iter->source->next;
  else
    next_source = NULL;

  if (!next_source)
Dan Winship's avatar
Dan Winship committed
1036
    {
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
      if (iter->current_list)
	iter->current_list = iter->current_list->next;
      else
	iter->current_list = iter->context->source_lists;

      if (iter->current_list)
	{
	  GSourceList *source_list = iter->current_list->data;

	  next_source = source_list->head;
	}
Dan Winship's avatar
Dan Winship committed
1048
1049
    }

1050
1051
1052
1053
  /* Note: unreffing iter->source could potentially cause its
   * GSourceList to be removed from source_lists (if iter->source is
   * the only source in its list, and it is destroyed), so we have to
   * keep it reffed until after we advance iter->current_list, above.
1054
1055
1056
1057
   *
   * Also we first have to ref the next source before unreffing the
   * previous one as unreffing the previous source can potentially
   * free the next one.
1058
   */
1059
1060
  if (next_source && iter->may_modify)
    g_source_ref (next_source);
1061
1062

  if (iter->source && iter->may_modify)
1063
    g_source_unref_internal (iter->source, iter->context, TRUE);
Dan Winship's avatar
Dan Winship committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
  iter->source = next_source;

  *source = iter->source;
  return *source != NULL;
}

/* Holds context's lock. Only necessary to call if you broke out of
 * the g_source_iter_next() loop early.
 */
static void
g_source_iter_clear (GSourceIter *iter)
{
  if (iter->source && iter->may_modify)
    {
1078
      g_source_unref_internal (iter->source, iter->context, TRUE);
Dan Winship's avatar
Dan Winship committed
1079
1080
1081
1082
      iter->source = NULL;
    }
}

1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
/* Holds context's lock
 */
static GSourceList *
find_source_list_for_priority (GMainContext *context,
			       gint          priority,
			       gboolean      create)
{
  GList *iter, *last;
  GSourceList *source_list;

  last = NULL;
  for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
    {
      source_list = iter->data;

      if (source_list->priority == priority)
	return source_list;

      if (source_list->priority > priority)
	{
	  if (!create)
	    return NULL;

	  source_list = g_slice_new0 (GSourceList);
	  source_list->priority = priority;
	  context->source_lists = g_list_insert_before (context->source_lists,
							iter,
							source_list);
	  return source_list;
	}
    }

  if (!create)
    return NULL;

  source_list = g_slice_new0 (GSourceList);
  source_list->priority = priority;

  if (!last)
    context->source_lists = g_list_append (NULL, source_list);
  else
    {
      /* This just appends source_list to the end of
       * context->source_lists without having to walk the list again.
       */
      last = g_list_append (last, source_list);
1129
      (void) last;
1130
1131
1132
1133
    }
  return source_list;
}

1134
1135
1136
/* Holds context's lock
 */
static void
1137
1138
source_add_to_context (GSource      *source,
		       GMainContext *context)
1139
{
1140
  GSourceList *source_list;
1141
  GSource *prev, *next;
1142
1143
1144

  source_list = find_source_list_for_priority (context, source->priority, TRUE);

1145
  if (source->priv->parent_source)
1146
    {
1147
1148
      g_assert (source_list->head != NULL);

1149
      /* Put the source immediately before its parent */
1150
1151
      prev = source->priv->parent_source->prev;
      next = source->priv->parent_source;
1152
1153
    }
  else
1154
    {
1155
1156
      prev = source_list->tail;
      next = NULL;
1157
    }
1158

1159
1160
1161
  source->next = next;
  if (next)
    next->prev = source;
1162
1163
  else
    source_list->tail = source;
1164
  
1165
1166
1167
  source->prev = prev;
  if (prev)
    prev->next = source;
1168
  else
1169
    source_list->head = source;
1170
1171
}

1172
1173
1174
/* Holds context's lock
 */
static void
1175
1176
source_remove_from_context (GSource      *source