Coverage Report

Created: 2025-07-12 06:25

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