Coverage Report

Created: 2026-02-14 07:05

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