Coverage Report

Created: 2026-03-31 06:14

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