Coverage Report

Created: 2025-07-23 08:13

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