Coverage Report

Created: 2025-10-10 07:05

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