Coverage Report

Created: 2026-04-01 06:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib/gobject/gobject.c
Line
Count
Source
1
/* GObject - GLib Type, Object, Parameter and Signal Library
2
 * Copyright (C) 1998-1999, 2000-2001 Tim Janik and Red Hat, Inc.
3
 *
4
 * SPDX-License-Identifier: LGPL-2.1-or-later
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General
17
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
/*
21
 * MT safe with regards to reference counting.
22
 */
23
24
#include "config.h"
25
26
#include <signal.h>
27
#include <stdint.h>
28
#include <string.h>
29
30
#include "../glib/glib-private.h"
31
32
#include "gobject.h"
33
#include "gtype-private.h"
34
#include "gvaluecollector.h"
35
#include "gsignal.h"
36
#include "gparamspecs.h"
37
#include "gvaluetypes.h"
38
#include "gobject_trace.h"
39
#include "gconstructor.h"
40
41
/**
42
 * GObject:
43
 *
44
 * The base object type.
45
 *
46
 * `GObject` is the fundamental type providing the common attributes and
47
 * methods for all object types in GTK, Pango and other libraries
48
 * based on GObject. The `GObject` class provides methods for object
49
 * construction and destruction, property access methods, and signal
50
 * support. Signals are described in detail [here](signals.html).
51
 *
52
 * For a tutorial on implementing a new `GObject` class, see [How to define and
53
 * implement a new GObject](tutorial.html#how-to-define-and-implement-a-new-gobject).
54
 * For a list of naming conventions for GObjects and their methods, see the
55
 * [GType conventions](concepts.html#conventions). For the high-level concepts
56
 * behind GObject, read
57
 * [Instantiatable classed types: Objects](concepts.html#instantiatable-classed-types-objects).
58
 *
59
 * Since GLib 2.72, all `GObject`s are guaranteed to be aligned to at least the
60
 * alignment of the largest basic GLib type (typically this is `guint64` or
61
 * `gdouble`). If you need larger alignment for an element in a `GObject`, you
62
 * should allocate it on the heap (aligned), or arrange for your `GObject` to be
63
 * appropriately padded. This guarantee applies to the `GObject` (or derived)
64
 * struct, the `GObjectClass` (or derived) struct, and any private data allocated
65
 * by `G_ADD_PRIVATE()`.
66
 */
67
68
/* --- macros --- */
69
0
#define PARAM_SPEC_PARAM_ID(pspec)    ((pspec)->param_id)
70
0
#define PARAM_SPEC_SET_PARAM_ID(pspec, id)  ((pspec)->param_id = (id))
71
72
0
#define OBJECT_HAS_TOGGLE_REF_FLAG 0x1
73
#define OBJECT_HAS_TOGGLE_REF(object) \
74
    ((g_datalist_get_flags (&(object)->qdata) & OBJECT_HAS_TOGGLE_REF_FLAG) != 0)
75
0
#define OBJECT_FLOATING_FLAG 0x2
76
77
0
#define CLASS_HAS_PROPS_FLAG 0x1
78
#define CLASS_HAS_PROPS(class) \
79
0
    ((class)->flags & CLASS_HAS_PROPS_FLAG)
80
#define CLASS_HAS_CUSTOM_CONSTRUCTOR(class) \
81
    ((class)->constructor != g_object_constructor)
82
#define CLASS_HAS_CUSTOM_CONSTRUCTED(class) \
83
0
    ((class)->constructed != g_object_constructed)
84
0
#define CLASS_HAS_NOTIFY(class) ((class)->notify != NULL)
85
#define CLASS_HAS_CUSTOM_DISPATCH(class) \
86
0
    ((class)->dispatch_properties_changed != g_object_dispatch_properties_changed)
87
#define CLASS_NEEDS_NOTIFY(class) \
88
0
    (CLASS_HAS_NOTIFY(class) || CLASS_HAS_CUSTOM_DISPATCH(class))
89
90
0
#define CLASS_HAS_DERIVED_CLASS_FLAG 0x2
91
#define CLASS_HAS_DERIVED_CLASS(class) \
92
0
    ((class)->flags & CLASS_HAS_DERIVED_CLASS_FLAG)
93
94
/* --- signals --- */
95
enum {
96
  NOTIFY,
97
  LAST_SIGNAL
98
};
99
100
101
/* --- properties --- */
102
enum {
103
  PROP_NONE
104
};
105
106
0
#define OPTIONAL_FLAG_IN_CONSTRUCTION    (1 << 0)
107
0
#define OPTIONAL_FLAG_HAS_SIGNAL_HANDLER (1 << 1) /* Set if object ever had a signal handler */
108
0
#define OPTIONAL_FLAG_HAS_NOTIFY_HANDLER (1 << 2) /* Same, specifically for "notify" */
109
0
#define OPTIONAL_FLAG_EVER_HAD_WEAK_REF  (1 << 4) /* whether on the object ever g_weak_ref_set() was called. */
110
111
#if SIZEOF_INT == 4 && GLIB_SIZEOF_VOID_P >= 8
112
#define HAVE_OPTIONAL_FLAGS_IN_GOBJECT 1
113
#else
114
#define HAVE_OPTIONAL_FLAGS_IN_GOBJECT 0
115
#endif
116
117
/* For now we only create a private struct if we don't have optional flags in
118
 * GObject. Currently we don't need it otherwise. In the future we might
119
 * always add a private struct. */
120
#define HAVE_PRIVATE (!HAVE_OPTIONAL_FLAGS_IN_GOBJECT)
121
122
#if HAVE_PRIVATE
123
typedef struct {
124
#if !HAVE_OPTIONAL_FLAGS_IN_GOBJECT
125
  guint optional_flags; /* (atomic) */
126
#endif
127
} GObjectPrivate;
128
129
static int GObject_private_offset;
130
#endif
131
132
typedef struct
133
{
134
  GTypeInstance  g_type_instance;
135
136
  /*< private >*/
137
  guint          ref_count;  /* (atomic) */
138
#if HAVE_OPTIONAL_FLAGS_IN_GOBJECT
139
  guint          optional_flags;  /* (atomic) */
140
#endif
141
  GData         *qdata;
142
} GObjectReal;
143
144
G_STATIC_ASSERT(sizeof(GObject) == sizeof(GObjectReal));
145
G_STATIC_ASSERT(G_STRUCT_OFFSET(GObject, ref_count) == G_STRUCT_OFFSET(GObjectReal, ref_count));
146
G_STATIC_ASSERT(G_STRUCT_OFFSET(GObject, qdata) == G_STRUCT_OFFSET(GObjectReal, qdata));
147
148
149
/* --- prototypes --- */
150
static void g_object_base_class_init    (GObjectClass *class);
151
static void g_object_base_class_finalize    (GObjectClass *class);
152
static void g_object_do_class_init      (GObjectClass *class);
153
static void g_object_init       (GObject  *object,
154
               GObjectClass *class);
155
static GObject* g_object_constructor      (GType                  type,
156
               guint                  n_construct_properties,
157
               GObjectConstructParam *construct_params);
158
static void     g_object_constructed                    (GObject        *object);
159
static void g_object_real_dispose     (GObject  *object);
160
static void g_object_finalize     (GObject  *object);
161
static void g_object_do_set_property    (GObject        *object,
162
               guint           property_id,
163
               const GValue   *value,
164
               GParamSpec     *pspec);
165
static void g_object_do_get_property    (GObject        *object,
166
               guint           property_id,
167
               GValue         *value,
168
               GParamSpec     *pspec);
169
static void g_value_object_init     (GValue   *value);
170
static void g_value_object_free_value   (GValue   *value);
171
static void g_value_object_copy_value   (const GValue *src_value,
172
               GValue   *dest_value);
173
static void g_value_object_transform_value    (const GValue *src_value,
174
               GValue   *dest_value);
175
static gpointer g_value_object_peek_pointer             (const GValue   *value);
176
static gchar* g_value_object_collect_value    (GValue   *value,
177
               guint           n_collect_values,
178
               GTypeCValue    *collect_values,
179
               guint           collect_flags);
180
static gchar* g_value_object_lcopy_value    (const GValue *value,
181
               guint           n_collect_values,
182
               GTypeCValue    *collect_values,
183
               guint           collect_flags);
184
static void g_object_dispatch_properties_changed  (GObject  *object,
185
               guint     n_pspecs,
186
               GParamSpec    **pspecs);
187
static void closure_array_destroy_all (GObject *object);
188
static guint               object_floating_flag_handler (GObject        *object,
189
                                                         gint            job);
190
static inline void object_set_optional_flags (GObject *object,
191
                                              guint flags);
192
static void g_object_weak_release_all (GObject *object, gboolean release_all);
193
194
static void object_interface_check_properties           (gpointer        check_data,
195
               gpointer        g_iface);
196
197
/* --- typedefs --- */
198
199
typedef struct
200
{
201
  guint16 freeze_count;
202
  guint16 len;
203
  guint16 alloc;
204
  GParamSpec *pspecs[];
205
} GObjectNotifyQueue;
206
207
/* --- variables --- */
208
static GQuark             quark_closure_array = 0;
209
static GQuark             quark_weak_notifies = 0;
210
static GQuark             quark_toggle_refs = 0;
211
static GQuark               quark_notify_queue;
212
static GParamSpecPool      *pspec_pool = NULL; /* atomic */
213
static unsigned int         gobject_signals[LAST_SIGNAL] = { 0, };
214
static guint (*floating_flag_handler) (GObject*, gint) = object_floating_flag_handler;
215
static GQuark             quark_weak_locations = 0;
216
217
static gpointer (*_local_g_datalist_id_update_atomic) (GData **datalist,
218
                                                       GQuark key_id,
219
                                                       gboolean already_locked,
220
                                                       GDataListUpdateAtomicFunc callback,
221
                                                       gpointer user_data) = NULL;
222
#undef _g_datalist_id_update_atomic_full
223
0
#define _g_datalist_id_update_atomic_full(...) ((_local_g_datalist_id_update_atomic) (__VA_ARGS__))
224
225
#if HAVE_PRIVATE
226
G_ALWAYS_INLINE static inline GObjectPrivate *
227
g_object_get_instance_private (GObject *object)
228
{
229
  return G_STRUCT_MEMBER_P (object, GObject_private_offset);
230
}
231
#endif
232
233
G_ALWAYS_INLINE static inline guint *
234
object_get_optional_flags_p (GObject *object)
235
0
{
236
0
#if HAVE_OPTIONAL_FLAGS_IN_GOBJECT
237
0
  return &(((GObjectReal *) object)->optional_flags);
238
#else
239
  return &g_object_get_instance_private (object)->optional_flags;
240
#endif
241
0
}
242
243
/*****************************************************************************/
244
245
/* For GWeakRef, we need to take a lock per-object. However, in various cases
246
 * we cannot take a strong reference on the object to keep it alive. So the
247
 * mutex cannot be in the object itself, because when we want to release the
248
 * lock, we can no longer access object.
249
 *
250
 * Instead, the mutex is on the WeakRefData, which is itself ref-counted
251
 * and has a separate lifetime from the object. */
252
typedef struct
253
{
254
  /* This is both an atomic ref-count and bit 30 (WEAK_REF_DATA_LOCK_BIT) is
255
   * used for g_bit_lock(). */
256
  gint atomic_field;
257
258
  guint16 len;
259
260
  /* Only relevant when len > 1. In that case, it's the allocated size of
261
   * "list.many" array.  */
262
  guint16 alloc;
263
264
  /* Only relevant when len > 0. In that case, either "one" or "many" union
265
   * field is in use. */
266
  union
267
  {
268
    GWeakRef *one;
269
    GWeakRef **many;
270
  } list;
271
} WeakRefData;
272
273
/* We choose bit 30, and not bit 31. Bit 31 would be the sign for gint, so it
274
 * a bit awkward to use. Note that it probably also would work fine.
275
 *
276
 * But 30 is ok, because it still leaves us space for 2^30-1 references, which
277
 * is more than we ever need. */
278
0
#define WEAK_REF_DATA_LOCK_BIT 30
279
280
static void weak_ref_data_clear_list (WeakRefData *wrdata, GObject *object);
281
282
static WeakRefData *
283
weak_ref_data_ref (WeakRefData *wrdata)
284
0
{
285
0
  gint ref;
286
287
0
#if G_ENABLE_DEBUG
288
0
  g_assert (wrdata);
289
0
#endif
290
291
0
  ref = g_atomic_int_add (&wrdata->atomic_field, 1);
292
293
0
#if G_ENABLE_DEBUG
294
  /* Overflow is almost impossible to happen, because the user would need to
295
   * spawn that many operating system threads, that all call
296
   * g_weak_ref_{set,get}() in parallel.
297
   *
298
   * Still, assert in debug mode. */
299
0
  g_assert (ref < G_MAXINT32);
300
301
  /* the real ref-count would be the following: */
302
0
  ref = (ref + 1) & ~(1 << WEAK_REF_DATA_LOCK_BIT);
303
304
  /* assert that the ref-count is still in the valid range. */
305
0
  g_assert (ref > 0 && ref < (1 << WEAK_REF_DATA_LOCK_BIT));
306
0
#endif
307
0
  (void) ref;
308
309
0
  return wrdata;
310
0
}
311
312
static void
313
weak_ref_data_unref (WeakRefData *wrdata)
314
0
{
315
0
  if (!wrdata)
316
0
    return;
317
318
  /* Note that we also use WEAK_REF_DATA_LOCK_BIT on "atomic_field" as a bit
319
   * lock. However, we will always keep the @wrdata alive (having a reference)
320
   * while holding a lock (otherwise, we couldn't unlock anymore). Thus, at the
321
   * point when we decrement the ref-count to zero, we surely also have the
322
   * @wrdata unlocked.
323
   *
324
   * This means, using "aomit_field" both as ref-count and the lock bit is
325
   * fine. */
326
327
0
  if (!g_atomic_int_dec_and_test (&wrdata->atomic_field))
328
0
    return;
329
330
0
#if G_ENABLE_DEBUG
331
  /* We expect that the list of weak locations is empty at this point.
332
   * During g_object_unref() (_object_unref_clear_weak_locations()) it
333
   * should have been cleared.
334
   *
335
   * Calling weak_ref_data_clear_list() should be unnecessary. */
336
0
  g_assert (wrdata->len == 0);
337
0
#endif
338
339
0
  g_free_sized (wrdata, sizeof (WeakRefData));
340
0
}
341
342
static void
343
weak_ref_data_lock (WeakRefData *wrdata)
344
0
{
345
  /* Note that while holding a _weak_ref_lock() on the @weak_ref, we MUST not acquire a
346
   * weak_ref_data_lock() on the @wrdata. The other way around! */
347
0
  if (wrdata)
348
0
    g_bit_lock (&wrdata->atomic_field, WEAK_REF_DATA_LOCK_BIT);
349
0
}
350
351
static void
352
weak_ref_data_unlock (WeakRefData *wrdata)
353
0
{
354
0
  if (wrdata)
355
0
    g_bit_unlock (&wrdata->atomic_field, WEAK_REF_DATA_LOCK_BIT);
356
0
}
357
358
static gpointer
359
weak_ref_data_get_or_create_cb (gpointer *data,
360
                                GDestroyNotify *destroy_notify,
361
                                gpointer user_data)
362
0
{
363
0
  WeakRefData *wrdata = *data;
364
0
  GObject *object = user_data;
365
366
0
  if (!wrdata)
367
0
    {
368
0
      wrdata = g_new (WeakRefData, 1);
369
370
      /* The initial ref-count is 1. This one is owned by the GData until the
371
       * object gets destroyed.
372
       *
373
       * The WEAK_REF_DATA_LOCK_BIT bit is of course initially unset.  */
374
0
      wrdata->atomic_field = 1;
375
0
      wrdata->len = 0;
376
      /* Other fields are left uninitialized. They are only considered with a positive @len. */
377
378
0
      *data = wrdata;
379
0
      *destroy_notify = (GDestroyNotify) weak_ref_data_unref;
380
381
      /* Mark the @object that it was ever involved with GWeakRef. This flag
382
       * will stick until @object gets destroyed, just like the WeakRefData
383
       * also won't be freed for the remainder of the life of @object. */
384
0
      object_set_optional_flags (object, OPTIONAL_FLAG_EVER_HAD_WEAK_REF);
385
0
    }
386
387
0
  return wrdata;
388
0
}
389
390
static WeakRefData *
391
weak_ref_data_get_or_create (GObject *object)
392
0
{
393
0
  if (!object)
394
0
    return NULL;
395
396
0
  return _g_datalist_id_update_atomic (&object->qdata,
397
0
                                       quark_weak_locations,
398
0
                                       weak_ref_data_get_or_create_cb,
399
0
                                       object);
400
0
}
401
402
static WeakRefData *
403
weak_ref_data_get (GObject *object)
404
0
{
405
0
  return g_datalist_id_get_data (&object->qdata, quark_weak_locations);
406
0
}
407
408
static WeakRefData *
409
weak_ref_data_get_surely (GObject *object)
410
0
{
411
0
  WeakRefData *wrdata;
412
413
  /* The "surely" part is about that we expect to have a WeakRefData.
414
   *
415
   * Note that once a GObject gets a WeakRefData (during g_weak_ref_set() and
416
   * weak_ref_data_get_or_create()), it sticks and is not freed until the
417
   * object gets destroyed.
418
   *
419
   * Maybe we could release the unused WeakRefData in g_weak_ref_set(), but
420
   * then we would always need to take a reference during weak_ref_data_get().
421
   * That is likely not worth it. */
422
423
0
  wrdata = weak_ref_data_get (object);
424
0
#if G_ENABLE_DEBUG
425
0
  g_assert (wrdata);
426
0
#endif
427
0
  return wrdata;
428
0
}
429
430
static gint32
431
weak_ref_data_list_find (WeakRefData *wrdata, GWeakRef *weak_ref)
432
0
{
433
0
  if (wrdata->len == 1u)
434
0
    {
435
0
      if (wrdata->list.one == weak_ref)
436
0
        return 0;
437
0
    }
438
0
  else
439
0
    {
440
0
      guint16 i;
441
442
0
      for (i = 0; i < wrdata->len; i++)
443
0
        {
444
0
          if (wrdata->list.many[i] == weak_ref)
445
0
            return i;
446
0
        }
447
0
    }
448
449
0
  return -1;
450
0
}
451
452
static gboolean
453
weak_ref_data_list_add (WeakRefData *wrdata, GWeakRef *weak_ref)
454
0
{
455
0
  if (wrdata->len == 0u)
456
0
    wrdata->list.one = weak_ref;
457
0
  else
458
0
    {
459
0
      if (wrdata->len == 1u)
460
0
        {
461
0
          GWeakRef *weak_ref2 = wrdata->list.one;
462
463
0
          wrdata->alloc = 4u;
464
0
          wrdata->list.many = g_new (GWeakRef *, wrdata->alloc);
465
0
          wrdata->list.many[0] = weak_ref2;
466
0
        }
467
0
      else if (wrdata->len == wrdata->alloc)
468
0
        {
469
0
          guint16 alloc;
470
471
0
          alloc = wrdata->alloc * 2u;
472
0
          if (G_UNLIKELY (alloc < wrdata->len))
473
0
            {
474
0
              if (wrdata->len == G_MAXUINT16)
475
0
                return FALSE;
476
0
              alloc = G_MAXUINT16;
477
0
            }
478
0
          wrdata->list.many = g_renew (GWeakRef *, wrdata->list.many, alloc);
479
0
          wrdata->alloc = alloc;
480
0
        }
481
482
0
      wrdata->list.many[wrdata->len] = weak_ref;
483
0
    }
484
485
0
  wrdata->len++;
486
0
  return TRUE;
487
0
}
488
489
static GWeakRef *
490
weak_ref_data_list_remove (WeakRefData *wrdata, guint16 idx, gboolean allow_shrink)
491
0
{
492
0
  GWeakRef *weak_ref;
493
494
0
#if G_ENABLE_DEBUG
495
0
  g_assert (idx < wrdata->len);
496
0
#endif
497
498
0
  wrdata->len--;
499
500
0
  if (wrdata->len == 0u)
501
0
    {
502
0
      weak_ref = wrdata->list.one;
503
0
    }
504
0
  else
505
0
    {
506
0
      weak_ref = wrdata->list.many[idx];
507
508
0
      if (wrdata->len == 1u)
509
0
        {
510
0
          GWeakRef *weak_ref2 = wrdata->list.many[idx == 0 ? 1 : 0];
511
512
0
          g_free (wrdata->list.many);
513
0
          wrdata->list.one = weak_ref2;
514
0
        }
515
0
      else
516
0
        {
517
0
          wrdata->list.many[idx] = wrdata->list.many[wrdata->len];
518
519
0
          if (allow_shrink && G_UNLIKELY (wrdata->len <= wrdata->alloc / 4u))
520
0
            {
521
              /* Shrink the buffer. When 75% are empty, shrink it to 50%. */
522
0
              if (wrdata->alloc == G_MAXUINT16)
523
0
                wrdata->alloc = ((guint32) G_MAXUINT16 + 1u) / 2u;
524
0
              else
525
0
                wrdata->alloc /= 2u;
526
0
              wrdata->list.many = g_renew (GWeakRef *, wrdata->list.many, wrdata->alloc);
527
0
            }
528
0
        }
529
0
    }
530
531
0
  return weak_ref;
532
0
}
533
534
static gboolean
535
weak_ref_data_has (GObject *object, WeakRefData *wrdata, WeakRefData **out_new_wrdata)
536
0
{
537
0
  WeakRefData *wrdata2;
538
539
  /* Check whether @object has @wrdata as WeakRefData. Note that an GObject's
540
   * WeakRefData never changes (until destruction, once it's allocated).
541
   *
542
   * If you thus hold a reference to a @wrdata, you can check that the @object
543
   * is still the same as the object where we got the @wrdata originally from.
544
   *
545
   * You couldn't do this check by using pointer equality of the GObject pointers,
546
   * when you cannot hold strong references on the objects involved. Because then
547
   * the object pointer might be dangling (and even destroyed and recreated as another
548
   * object at the same memory location).
549
   *
550
   * Basically, weak_ref_data_has() is to compare for equality of two GObject pointers,
551
   * when we cannot hold a strong reference on both. Instead, we earlier took a reference
552
   * on the @wrdata and compare that instead.
553
   */
554
555
0
  if (!object)
556
0
    {
557
      /* If @object is NULL, then it does have a NULL @wrdata, and we return
558
       * TRUE in the case.  That's a convenient special case for some callers.
559
       *
560
       * In other words, weak_ref_data_has(NULL, NULL, out_new_wrdata) is TRUE.
561
       */
562
0
#if G_ENABLE_DEBUG
563
0
      g_assert (!out_new_wrdata);
564
0
#endif
565
0
      return !wrdata;
566
0
    }
567
568
0
  if (!wrdata)
569
0
    {
570
      /* We only call this function with an @object that was previously
571
       * registered as GWeakRef.
572
       *
573
       * That means, our @object will have a wrdata, and the result of the
574
       * evaluation will be %FALSE. */
575
0
      if (out_new_wrdata)
576
0
        *out_new_wrdata = weak_ref_data_ref (weak_ref_data_get (object));
577
0
#if G_ENABLE_DEBUG
578
0
      g_assert (out_new_wrdata
579
0
                    ? *out_new_wrdata
580
0
                    : weak_ref_data_get (object));
581
0
#endif
582
0
      return FALSE;
583
0
    }
584
585
0
  wrdata2 = weak_ref_data_get_surely (object);
586
587
0
  if (wrdata == wrdata2)
588
0
    {
589
0
      if (out_new_wrdata)
590
0
        *out_new_wrdata = NULL;
591
0
      return TRUE;
592
0
    }
593
594
0
  if (out_new_wrdata)
595
0
    *out_new_wrdata = weak_ref_data_ref (wrdata2);
596
0
  return FALSE;
597
0
}
598
599
/*****************************************************************************/
600
601
/* --- functions --- */
602
603
static const GObjectNotifyQueue notify_queue_empty = {
604
  .freeze_count = 0,
605
};
606
607
G_ALWAYS_INLINE static inline gboolean
608
_is_notify_queue_empty (const GObjectNotifyQueue *nqueue)
609
0
{
610
  /* Only the notify_queue_empty instance has a zero freeze count. We check
611
   * here for that condition instead of pointer comparing to
612
   * &notify_queue_empty. That seems better because callers will afterwards
613
   * dereference "freeze_count", so the value is already loaded.
614
   *
615
   * In any case, both conditions must be equivalent.
616
   */
617
0
#ifdef G_ENABLE_DEBUG
618
0
  g_assert ((nqueue == &notify_queue_empty) == (nqueue->freeze_count == 0));
619
0
#endif
620
0
  return nqueue->freeze_count == 0;
621
0
}
622
623
G_ALWAYS_INLINE static inline gsize
624
g_object_notify_queue_alloc_size (gsize alloc)
625
0
{
626
0
  return G_STRUCT_OFFSET (GObjectNotifyQueue, pspecs) + (alloc * sizeof (GParamSpec *));
627
0
}
628
629
static GObjectNotifyQueue *
630
g_object_notify_queue_new_frozen (void)
631
0
{
632
0
  GObjectNotifyQueue *nqueue;
633
634
0
  nqueue = g_malloc (g_object_notify_queue_alloc_size (4));
635
636
0
  nqueue->freeze_count = 1;
637
0
  nqueue->alloc = 4;
638
0
  nqueue->len = 0;
639
640
0
  return nqueue;
641
0
}
642
643
static gpointer
644
g_object_notify_queue_freeze_cb (gpointer *data,
645
                                 GDestroyNotify *destroy_notify,
646
                                 gpointer user_data)
647
0
{
648
0
  GObject *object = ((gpointer *) user_data)[0];
649
0
  gboolean freeze_always = GPOINTER_TO_INT (((gpointer *) user_data)[1]);
650
0
  GObjectNotifyQueue *nqueue = *data;
651
652
0
  if (!nqueue)
653
0
    {
654
      /* The nqueue doesn't exist yet. We use the dummy object that is shared
655
       * by all instances. */
656
0
      *data = (gpointer) &notify_queue_empty;
657
0
      *destroy_notify = NULL;
658
0
    }
659
0
  else if (!freeze_always)
660
0
    {
661
      /* The caller only wants to ensure we are frozen once. If we are already frozen,
662
       * don't freeze another time.
663
       *
664
       * This is only relevant during the object initialization. */
665
0
    }
666
0
  else
667
0
    {
668
0
      if (_is_notify_queue_empty (nqueue))
669
0
        {
670
0
          nqueue = g_object_notify_queue_new_frozen ();
671
0
          *data = nqueue;
672
0
          *destroy_notify = g_free;
673
0
          nqueue->freeze_count++;
674
0
        }
675
0
      else if (G_UNLIKELY (nqueue->freeze_count == G_MAXUINT16))
676
0
        {
677
0
          g_critical ("Free queue for %s (%p) is larger than 65535,"
678
0
                      " called g_object_freeze_notify() too often."
679
0
                      " Forgot to call g_object_thaw_notify() or infinite loop",
680
0
                      G_OBJECT_TYPE_NAME (object), object);
681
0
        }
682
0
      else
683
0
        nqueue->freeze_count++;
684
0
    }
685
686
0
  return NULL;
687
0
}
688
689
static void
690
g_object_notify_queue_freeze (GObject *object, gboolean freeze_always)
691
0
{
692
0
  _g_datalist_id_update_atomic (&object->qdata,
693
0
                                quark_notify_queue,
694
0
                                g_object_notify_queue_freeze_cb,
695
0
                                ((gpointer[]){ object, GINT_TO_POINTER (!!freeze_always) }));
696
0
}
697
698
static gpointer
699
g_object_notify_queue_thaw_cb (gpointer *data,
700
                               GDestroyNotify *destroy_notify,
701
                               gpointer user_data)
702
0
{
703
0
  GObject *object = user_data;
704
0
  GObjectNotifyQueue *nqueue = *data;
705
706
0
  if (G_UNLIKELY (!nqueue))
707
0
    {
708
0
      g_critical ("%s: property-changed notification for %s(%p) is not frozen",
709
0
                  G_STRFUNC, G_OBJECT_TYPE_NAME (object), object);
710
0
      return NULL;
711
0
    }
712
713
0
  if (_is_notify_queue_empty (nqueue))
714
0
    {
715
0
      *data = NULL;
716
0
      *destroy_notify = NULL;
717
0
      return NULL;
718
0
    }
719
720
0
  nqueue->freeze_count--;
721
722
0
  if (nqueue->freeze_count > 0)
723
0
    return NULL;
724
725
0
  *data = NULL;
726
0
  *destroy_notify = NULL;
727
0
  return nqueue;
728
0
}
729
730
static void
731
g_object_notify_queue_thaw (GObject *object, gboolean take_ref)
732
0
{
733
0
  GObjectNotifyQueue *nqueue;
734
735
0
  nqueue = _g_datalist_id_update_atomic (&object->qdata,
736
0
                                         quark_notify_queue,
737
0
                                         g_object_notify_queue_thaw_cb,
738
0
                                         object);
739
740
0
  if (!nqueue)
741
0
    return;
742
743
0
  if (nqueue->len > 0)
744
0
    {
745
0
      guint16 i;
746
0
      guint16 j;
747
748
      /* Reverse the list. This is the order that we historically had. */
749
0
      for (i = 0, j = nqueue->len - 1u; i < j; i++, j--)
750
0
        {
751
0
          GParamSpec *tmp;
752
753
0
          tmp = nqueue->pspecs[i];
754
0
          nqueue->pspecs[i] = nqueue->pspecs[j];
755
0
          nqueue->pspecs[j] = tmp;
756
0
        }
757
758
0
      if (take_ref)
759
0
        g_object_ref (object);
760
761
0
      G_OBJECT_GET_CLASS (object)->dispatch_properties_changed (object, nqueue->len, nqueue->pspecs);
762
763
0
      if (take_ref)
764
0
        g_object_unref (object);
765
0
    }
766
767
0
  g_free (nqueue);
768
0
}
769
770
static gpointer
771
g_object_notify_queue_add_cb (gpointer *data,
772
                              GDestroyNotify *destroy_notify,
773
                              gpointer user_data)
774
0
{
775
0
  GParamSpec *pspec = ((gpointer *) user_data)[0];
776
0
  gboolean in_init = GPOINTER_TO_INT (((gpointer *) user_data)[1]);
777
0
  GObjectNotifyQueue *nqueue = *data;
778
0
  guint16 i;
779
780
0
  if (!nqueue)
781
0
    {
782
0
      if (!in_init)
783
0
        {
784
          /* We are not in-init and are currently not frozen. There is nothing
785
           * to do. We return FALSE to the caller, which then will dispatch
786
           * the event right away. */
787
0
          return GINT_TO_POINTER (FALSE);
788
0
        }
789
790
      /* If we are "in_init", we always want to create a queue now.
791
       *
792
       * Note in that case, the freeze will be balanced at the end of object
793
       * initialization.
794
       *
795
       * We only ensure that a nqueue exists. If it doesn't exist, we create
796
       * it (and freeze once). If it already exists (and is frozen), we don't
797
       * freeze an additional time. */
798
0
      nqueue = g_object_notify_queue_new_frozen ();
799
0
      *data = nqueue;
800
0
      *destroy_notify = g_free;
801
0
    }
802
0
  else if (_is_notify_queue_empty (nqueue))
803
0
    {
804
0
      nqueue = g_object_notify_queue_new_frozen ();
805
0
      *data = nqueue;
806
0
      *destroy_notify = g_free;
807
0
    }
808
0
  else
809
0
    {
810
0
      for (i = 0; i < nqueue->len; i++)
811
0
        {
812
0
          if (nqueue->pspecs[i] == pspec)
813
0
            goto out;
814
0
        }
815
816
0
      if (G_UNLIKELY (nqueue->len == nqueue->alloc))
817
0
        {
818
0
          guint32 alloc;
819
820
0
          alloc = ((guint32) nqueue->alloc) * 2u;
821
0
          if (alloc >= G_MAXUINT16)
822
0
            {
823
0
              if (G_UNLIKELY (nqueue->len >= G_MAXUINT16))
824
0
                g_error ("g_object_notify_queue_add_cb: cannot track more than 65535 properties for freeze notification");
825
0
              alloc = G_MAXUINT16;
826
0
            }
827
0
          nqueue = g_realloc (nqueue, g_object_notify_queue_alloc_size (alloc));
828
0
          nqueue->alloc = alloc;
829
830
0
          *data = nqueue;
831
0
        }
832
0
    }
833
834
0
  nqueue->pspecs[nqueue->len++] = pspec;
835
836
0
out:
837
0
  return GINT_TO_POINTER (TRUE);
838
0
}
839
840
static gboolean
841
g_object_notify_queue_add (GObject *object,
842
                           GParamSpec *pspec,
843
                           gboolean in_init)
844
0
{
845
0
  gpointer result;
846
847
0
  result = _g_datalist_id_update_atomic (&object->qdata,
848
0
                                         quark_notify_queue,
849
0
                                         g_object_notify_queue_add_cb,
850
0
                                         ((gpointer[]){ pspec, GINT_TO_POINTER (!!in_init) }));
851
852
0
  return GPOINTER_TO_INT (result);
853
0
}
854
855
#ifdef  G_ENABLE_DEBUG
856
G_LOCK_DEFINE_STATIC     (debug_objects);
857
static guint     debug_objects_count = 0;
858
static GHashTable *debug_objects_ht = NULL;
859
860
static void
861
debug_objects_foreach (gpointer key,
862
           gpointer value,
863
           gpointer user_data)
864
0
{
865
0
  GObject *object = value;
866
867
0
  g_message ("[%p] stale %s\tref_count=%u",
868
0
       object,
869
0
       G_OBJECT_TYPE_NAME (object),
870
0
       object->ref_count);
871
0
}
872
873
#ifdef G_HAS_CONSTRUCTORS
874
#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA
875
#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(debug_objects_atexit)
876
#endif
877
G_DEFINE_DESTRUCTOR(debug_objects_atexit)
878
#endif /* G_HAS_CONSTRUCTORS */
879
880
static void
881
debug_objects_atexit (void)
882
0
{
883
0
  GOBJECT_IF_DEBUG (OBJECTS,
884
0
    {
885
0
      G_LOCK (debug_objects);
886
0
      g_message ("stale GObjects: %u", debug_objects_count);
887
0
      g_hash_table_foreach (debug_objects_ht, debug_objects_foreach, NULL);
888
0
      G_UNLOCK (debug_objects);
889
0
    });
890
0
}
891
#endif  /* G_ENABLE_DEBUG */
892
893
void
894
_g_object_type_init (void)
895
4
{
896
4
  static gboolean initialized = FALSE;
897
4
  static const GTypeFundamentalInfo finfo = {
898
4
    G_TYPE_FLAG_CLASSED | G_TYPE_FLAG_INSTANTIATABLE | G_TYPE_FLAG_DERIVABLE | G_TYPE_FLAG_DEEP_DERIVABLE,
899
4
  };
900
4
  GTypeInfo info = {
901
4
    sizeof (GObjectClass),
902
4
    (GBaseInitFunc) g_object_base_class_init,
903
4
    (GBaseFinalizeFunc) g_object_base_class_finalize,
904
4
    (GClassInitFunc) g_object_do_class_init,
905
4
    NULL  /* class_destroy */,
906
4
    NULL  /* class_data */,
907
4
    sizeof (GObject),
908
4
    0   /* n_preallocs */,
909
4
    (GInstanceInitFunc) g_object_init,
910
4
    NULL, /* value_table */
911
4
  };
912
4
  static const GTypeValueTable value_table = {
913
4
    g_value_object_init,    /* value_init */
914
4
    g_value_object_free_value,    /* value_free */
915
4
    g_value_object_copy_value,    /* value_copy */
916
4
    g_value_object_peek_pointer,  /* value_peek_pointer */
917
4
    "p",        /* collect_format */
918
4
    g_value_object_collect_value, /* collect_value */
919
4
    "p",        /* lcopy_format */
920
4
    g_value_object_lcopy_value,   /* lcopy_value */
921
4
  };
922
4
  GType type G_GNUC_UNUSED  /* when compiling with G_DISABLE_ASSERT */;
923
  
924
4
  g_return_if_fail (initialized == FALSE);
925
4
  initialized = TRUE;
926
  
927
  /* G_TYPE_OBJECT
928
   */
929
4
  info.value_table = &value_table;
930
4
  type = g_type_register_fundamental (G_TYPE_OBJECT, g_intern_static_string ("GObject"), &info, &finfo, 0);
931
4
  g_assert (type == G_TYPE_OBJECT);
932
4
  g_value_register_transform_func (G_TYPE_OBJECT, G_TYPE_OBJECT, g_value_object_transform_value);
933
934
4
#if G_ENABLE_DEBUG
935
  /* We cannot use GOBJECT_IF_DEBUG here because of the G_HAS_CONSTRUCTORS
936
   * conditional in between, as the C spec leaves conditionals inside macro
937
   * expansions as undefined behavior. Only GCC and Clang are known to work
938
   * but compilation breaks on MSVC.
939
   *
940
   * See: https://bugzilla.gnome.org/show_bug.cgi?id=769504
941
   */
942
4
  if (_g_type_debug_flags & G_TYPE_DEBUG_OBJECTS) \
943
0
    {
944
0
      debug_objects_ht = g_hash_table_new (g_direct_hash, NULL);
945
# ifndef G_HAS_CONSTRUCTORS
946
      g_atexit (debug_objects_atexit);
947
# endif /* G_HAS_CONSTRUCTORS */
948
0
    }
949
4
#endif /* G_ENABLE_DEBUG */
950
951
#if HAVE_PRIVATE
952
  GObject_private_offset =
953
      g_type_add_instance_private (G_TYPE_OBJECT, sizeof (GObjectPrivate));
954
#endif
955
4
}
956
957
/* Initialize the global GParamSpecPool; this function needs to be
958
 * called whenever we access the GParamSpecPool and we cannot guarantee
959
 * that g_object_do_class_init() has been called: for instance, by the
960
 * interface property API.
961
 *
962
 * To avoid yet another global lock, we use atomic pointer checks: the
963
 * first caller of this function will win the race. Any other access to
964
 * the GParamSpecPool is done under its own mutex.
965
 */
966
static inline GParamSpecPool *
967
g_object_maybe_init_pspec_pool (void)
968
0
{
969
0
  GParamSpecPool *pool = g_atomic_pointer_get (&pspec_pool);
970
971
0
  if (G_UNLIKELY (pool == NULL))
972
0
    {
973
0
      GParamSpecPool *new_pool = g_param_spec_pool_new (TRUE);
974
0
      if (g_atomic_pointer_compare_and_exchange_full (&pspec_pool, NULL,
975
0
                                                      new_pool, &pool))
976
0
        pool = g_steal_pointer (&new_pool);
977
978
0
      g_clear_pointer (&new_pool, g_param_spec_pool_free);
979
0
    }
980
981
0
  return pool;
982
0
}
983
984
static void
985
g_object_base_class_init (GObjectClass *class)
986
0
{
987
0
  GObjectClass *pclass = g_type_class_peek_parent (class);
988
989
  /* Don't inherit HAS_DERIVED_CLASS flag from parent class */
990
0
  class->flags &= (unsigned) ~CLASS_HAS_DERIVED_CLASS_FLAG;
991
992
0
  if (pclass)
993
0
    pclass->flags |= CLASS_HAS_DERIVED_CLASS_FLAG;
994
995
  /* reset instance specific fields and methods that don't get inherited */
996
0
  class->construct_properties = pclass ? g_slist_copy (pclass->construct_properties) : NULL;
997
0
  class->n_construct_properties = g_slist_length (class->construct_properties);
998
0
  class->get_property = NULL;
999
0
  class->set_property = NULL;
1000
0
  class->pspecs = NULL;
1001
0
  class->n_pspecs = 0;
1002
0
}
1003
1004
static void
1005
g_object_base_class_finalize (GObjectClass *class)
1006
0
{
1007
0
  GList *list, *node;
1008
0
  GParamSpecPool *param_spec_pool;
1009
  
1010
0
  _g_signals_destroy (G_OBJECT_CLASS_TYPE (class));
1011
1012
0
  g_slist_free (class->construct_properties);
1013
0
  class->construct_properties = NULL;
1014
0
  class->n_construct_properties = 0;
1015
0
  param_spec_pool = g_atomic_pointer_get (&pspec_pool);
1016
0
  list = g_param_spec_pool_list_owned (param_spec_pool, G_OBJECT_CLASS_TYPE (class));
1017
0
  for (node = list; node; node = node->next)
1018
0
    {
1019
0
      GParamSpec *pspec = node->data;
1020
0
      g_param_spec_pool_remove (param_spec_pool, pspec);
1021
0
      PARAM_SPEC_SET_PARAM_ID (pspec, 0);
1022
0
      g_param_spec_unref (pspec);
1023
0
    }
1024
0
  g_list_free (list);
1025
0
}
1026
1027
static void
1028
g_object_do_class_init (GObjectClass *class)
1029
0
{
1030
0
  quark_closure_array = g_quark_from_static_string ("GObject-closure-array");
1031
0
  quark_weak_notifies = g_quark_from_static_string ("GObject-weak-notifies");
1032
0
  quark_weak_locations = g_quark_from_static_string ("GObject-weak-locations");
1033
0
  quark_toggle_refs = g_quark_from_static_string ("GObject-toggle-references");
1034
0
  quark_notify_queue = g_quark_from_static_string ("GObject-notify-queue");
1035
1036
0
  g_atomic_pointer_set (&_local_g_datalist_id_update_atomic, GLIB_PRIVATE_CALL (g_datalist_id_update_atomic));
1037
1038
0
  g_object_maybe_init_pspec_pool ();
1039
1040
0
  class->constructor = g_object_constructor;
1041
0
  class->constructed = g_object_constructed;
1042
0
  class->set_property = g_object_do_set_property;
1043
0
  class->get_property = g_object_do_get_property;
1044
0
  class->dispose = g_object_real_dispose;
1045
0
  class->finalize = g_object_finalize;
1046
0
  class->dispatch_properties_changed = g_object_dispatch_properties_changed;
1047
0
  class->notify = NULL;
1048
1049
  /**
1050
   * GObject::notify:
1051
   * @gobject: the object which received the signal.
1052
   * @pspec: the #GParamSpec of the property which changed.
1053
   *
1054
   * The notify signal is emitted on an object when one of its properties has
1055
   * its value set through g_object_set_property(), g_object_set(), et al.
1056
   *
1057
   * Note that getting this signal doesn’t itself guarantee that the value of
1058
   * the property has actually changed. When it is emitted is determined by the
1059
   * derived GObject class. If the implementor did not create the property with
1060
   * %G_PARAM_EXPLICIT_NOTIFY, then any call to g_object_set_property() results
1061
   * in ::notify being emitted, even if the new value is the same as the old.
1062
   * If they did pass %G_PARAM_EXPLICIT_NOTIFY, then this signal is emitted only
1063
   * when they explicitly call g_object_notify() or g_object_notify_by_pspec(),
1064
   * and common practice is to do that only when the value has actually changed.
1065
   *
1066
   * This signal is typically used to obtain change notification for a
1067
   * single property, by specifying the property name as a detail in the
1068
   * g_signal_connect() call, like this:
1069
   *
1070
   * |[<!-- language="C" --> 
1071
   * g_signal_connect (text_view->buffer, "notify::paste-target-list",
1072
   *                   G_CALLBACK (gtk_text_view_target_list_notify),
1073
   *                   text_view)
1074
   * ]|
1075
   *
1076
   * It is important to note that you must use
1077
   * [canonical parameter names][class@GObject.ParamSpec#parameter-names] as
1078
   * detail strings for the notify signal.
1079
   */
1080
0
  gobject_signals[NOTIFY] =
1081
0
    g_signal_new (g_intern_static_string ("notify"),
1082
0
      G_TYPE_FROM_CLASS (class),
1083
0
      G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS | G_SIGNAL_ACTION,
1084
0
      G_STRUCT_OFFSET (GObjectClass, notify),
1085
0
      NULL, NULL,
1086
0
      NULL,
1087
0
      G_TYPE_NONE,
1088
0
      1, G_TYPE_PARAM);
1089
1090
  /* Install a check function that we'll use to verify that classes that
1091
   * implement an interface implement all properties for that interface
1092
   */
1093
0
  g_type_add_interface_check (NULL, object_interface_check_properties);
1094
1095
#if HAVE_PRIVATE
1096
  g_type_class_adjust_private_offset (class, &GObject_private_offset);
1097
#endif
1098
0
}
1099
1100
/* Sinks @pspec if it’s a floating ref. */
1101
static inline gboolean
1102
install_property_internal (GType       g_type,
1103
         guint       property_id,
1104
         GParamSpec *pspec)
1105
0
{
1106
0
  GParamSpecPool *param_spec_pool;
1107
0
  g_param_spec_ref_sink (pspec);
1108
1109
0
  param_spec_pool = g_object_maybe_init_pspec_pool ();
1110
1111
0
  if (g_param_spec_pool_lookup (param_spec_pool, pspec->name, g_type, FALSE))
1112
0
    {
1113
0
      g_critical ("When installing property: type '%s' already has a property named '%s'",
1114
0
                  g_type_name (g_type),
1115
0
                  pspec->name);
1116
0
      g_param_spec_unref (pspec);
1117
0
      return FALSE;
1118
0
    }
1119
1120
0
  PARAM_SPEC_SET_PARAM_ID (pspec, property_id);
1121
0
  g_param_spec_pool_insert (param_spec_pool, g_steal_pointer (&pspec), g_type);
1122
0
  return TRUE;
1123
0
}
1124
1125
static gboolean
1126
validate_pspec_to_install (GParamSpec *pspec)
1127
0
{
1128
0
  g_return_val_if_fail (G_IS_PARAM_SPEC (pspec), FALSE);
1129
0
  g_return_val_if_fail (PARAM_SPEC_PARAM_ID (pspec) == 0, FALSE); /* paranoid */
1130
1131
0
  g_return_val_if_fail (pspec->flags & (G_PARAM_READABLE | G_PARAM_WRITABLE), FALSE);
1132
1133
0
#ifndef G_DISABLE_CHECKS
1134
0
  if ((pspec->flags & G_PARAM_CONSTRUCT) && (pspec->flags & G_PARAM_CONSTRUCT_ONLY))
1135
0
    {
1136
0
      g_critical ("%s: property '%s' cannot have both G_PARAM_CONSTRUCT and "
1137
0
                  "G_PARAM_CONSTRUCT_ONLY flags set simultaneously",
1138
0
                  G_STRFUNC, pspec->name);
1139
0
      return FALSE;
1140
0
    }
1141
0
#endif
1142
1143
0
  g_return_val_if_fail (!(pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY)) ||
1144
0
                        (pspec->flags & G_PARAM_WRITABLE), FALSE);
1145
1146
0
  return TRUE;
1147
0
}
1148
1149
/* Sinks @pspec if it’s a floating ref. */
1150
static gboolean
1151
validate_and_install_class_property (GObjectClass *class,
1152
                                     GType         oclass_type,
1153
                                     GType         parent_type,
1154
                                     guint         property_id,
1155
                                     GParamSpec   *pspec)
1156
0
{
1157
0
  if (!validate_pspec_to_install (pspec))
1158
0
    {
1159
0
      g_param_spec_ref_sink (pspec);
1160
0
      g_param_spec_unref (pspec);
1161
0
      return FALSE;
1162
0
    }
1163
1164
0
  g_return_val_if_fail (!(pspec->flags & G_PARAM_WRITABLE) || class->set_property != NULL, FALSE);
1165
0
  g_return_val_if_fail (!(pspec->flags & G_PARAM_READABLE) || class->get_property != NULL, FALSE);
1166
1167
0
  class->flags |= CLASS_HAS_PROPS_FLAG;
1168
0
  if (install_property_internal (oclass_type, property_id, pspec))
1169
0
    {
1170
0
      if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
1171
0
        {
1172
0
          class->construct_properties = g_slist_append (class->construct_properties, pspec);
1173
0
          class->n_construct_properties += 1;
1174
0
        }
1175
1176
      /* for property overrides of construct properties, we have to get rid
1177
       * of the overridden inherited construct property
1178
       */
1179
0
      pspec = g_param_spec_pool_lookup (g_atomic_pointer_get (&pspec_pool),
1180
0
                                        pspec->name, parent_type, TRUE);
1181
0
      if (pspec && pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
1182
0
        {
1183
0
          class->construct_properties = g_slist_remove (class->construct_properties, pspec);
1184
0
          class->n_construct_properties -= 1;
1185
0
        }
1186
1187
0
      return TRUE;
1188
0
    }
1189
0
  else
1190
0
    return FALSE;
1191
0
}
1192
1193
/**
1194
 * g_object_class_install_property:
1195
 * @oclass: a #GObjectClass
1196
 * @property_id: the id for the new property
1197
 * @pspec: the #GParamSpec for the new property
1198
 *
1199
 * Installs a new property.
1200
 *
1201
 * All properties should be installed during the class initializer.  It
1202
 * is possible to install properties after that, but doing so is not
1203
 * recommend, and specifically, is not guaranteed to be thread-safe vs.
1204
 * use of properties on the same type on other threads.
1205
 *
1206
 * Note that it is possible to redefine a property in a derived class,
1207
 * by installing a property with the same name. This can be useful at times,
1208
 * e.g. to change the range of allowed values or the default value.
1209
 */
1210
void
1211
g_object_class_install_property (GObjectClass *class,
1212
         guint         property_id,
1213
         GParamSpec   *pspec)
1214
0
{
1215
0
  GType oclass_type, parent_type;
1216
1217
0
  g_return_if_fail (G_IS_OBJECT_CLASS (class));
1218
0
  g_return_if_fail (property_id > 0);
1219
1220
0
  oclass_type = G_OBJECT_CLASS_TYPE (class);
1221
0
  parent_type = g_type_parent (oclass_type);
1222
1223
0
  if (CLASS_HAS_DERIVED_CLASS (class))
1224
0
    g_error ("Attempt to add property %s::%s to class after it was derived", G_OBJECT_CLASS_NAME (class), pspec->name);
1225
1226
0
  (void) validate_and_install_class_property (class,
1227
0
                                              oclass_type,
1228
0
                                              parent_type,
1229
0
                                              property_id,
1230
0
                                              pspec);
1231
0
}
1232
1233
typedef struct {
1234
  const char *name;
1235
  GParamSpec *pspec;
1236
} PspecEntry;
1237
1238
static int
1239
compare_pspec_entry (const void *a,
1240
                     const void *b)
1241
0
{
1242
0
  const PspecEntry *ae = a;
1243
0
  const PspecEntry *be = b;
1244
1245
0
  return ae->name < be->name ? -1 : (ae->name > be->name ? 1 : 0);
1246
0
}
1247
1248
/* This uses pointer comparisons with @property_name, so
1249
 * will only work with string literals. */
1250
static inline GParamSpec *
1251
find_pspec (GObjectClass *class,
1252
            const char   *property_name)
1253
0
{
1254
0
  const PspecEntry *pspecs = (const PspecEntry *)class->pspecs;
1255
0
  gsize n_pspecs = class->n_pspecs;
1256
1257
0
  g_assert (n_pspecs <= G_MAXSSIZE);
1258
1259
  /* The limit for choosing between linear and binary search is
1260
   * fairly arbitrary.
1261
   *
1262
   * Both searches use pointer comparisons against @property_name.
1263
   * If this function is called with a non-static @property_name,
1264
   * it will fall through to the g_param_spec_pool_lookup() case.
1265
   * That’s OK; this is an opportunistic optimisation which relies
1266
   * on the fact that *most* (but not all) property lookups use
1267
   * static property names.
1268
   */
1269
0
  if (n_pspecs < 10)
1270
0
    {
1271
0
      for (gsize i = 0; i < n_pspecs; i++)
1272
0
        {
1273
0
          if (pspecs[i].name == property_name)
1274
0
            return pspecs[i].pspec;
1275
0
        }
1276
0
    }
1277
0
  else
1278
0
    {
1279
0
      gssize lower = 0;
1280
0
      gssize upper = (int)class->n_pspecs - 1;
1281
0
      gssize mid;
1282
1283
0
      while (lower <= upper)
1284
0
        {
1285
0
          mid = (lower + upper) / 2;
1286
1287
0
          if (property_name < pspecs[mid].name)
1288
0
            upper = mid - 1;
1289
0
          else if (property_name > pspecs[mid].name)
1290
0
            lower = mid + 1;
1291
0
          else
1292
0
            return pspecs[mid].pspec;
1293
0
        }
1294
0
    }
1295
1296
0
  return g_param_spec_pool_lookup (g_atomic_pointer_get (&pspec_pool),
1297
0
                                   property_name,
1298
0
                                   ((GTypeClass *)class)->g_type,
1299
0
                                   TRUE);
1300
0
}
1301
1302
/**
1303
 * g_object_class_install_properties:
1304
 * @oclass: a #GObjectClass
1305
 * @n_pspecs: the length of the #GParamSpecs array
1306
 * @pspecs: (array length=n_pspecs): the #GParamSpecs array
1307
 *   defining the new properties
1308
 *
1309
 * Installs new properties from an array of #GParamSpecs.
1310
 *
1311
 * All properties should be installed during the class initializer.  It
1312
 * is possible to install properties after that, but doing so is not
1313
 * recommend, and specifically, is not guaranteed to be thread-safe vs.
1314
 * use of properties on the same type on other threads.
1315
 *
1316
 * The property id of each property is the index of each #GParamSpec in
1317
 * the @pspecs array.
1318
 *
1319
 * The property id of 0 is treated specially by #GObject and it should not
1320
 * be used to store a #GParamSpec.
1321
 *
1322
 * This function should be used if you plan to use a static array of
1323
 * #GParamSpecs and g_object_notify_by_pspec(). For instance, this
1324
 * class initialization:
1325
 *
1326
 * |[<!-- language="C" --> 
1327
 * typedef enum {
1328
 *   PROP_FOO = 1,
1329
 *   PROP_BAR,
1330
 *   N_PROPERTIES
1331
 * } MyObjectProperty;
1332
 *
1333
 * static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
1334
 *
1335
 * static void
1336
 * my_object_class_init (MyObjectClass *klass)
1337
 * {
1338
 *   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1339
 *
1340
 *   obj_properties[PROP_FOO] =
1341
 *     g_param_spec_int ("foo", NULL, NULL,
1342
 *                       -1, G_MAXINT,
1343
 *                       0,
1344
 *                       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1345
 *
1346
 *   obj_properties[PROP_BAR] =
1347
 *     g_param_spec_string ("bar", NULL, NULL,
1348
 *                          NULL,
1349
 *                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1350
 *
1351
 *   gobject_class->set_property = my_object_set_property;
1352
 *   gobject_class->get_property = my_object_get_property;
1353
 *   g_object_class_install_properties (gobject_class,
1354
 *                                      G_N_ELEMENTS (obj_properties),
1355
 *                                      obj_properties);
1356
 * }
1357
 * ]|
1358
 *
1359
 * allows calling g_object_notify_by_pspec() to notify of property changes:
1360
 *
1361
 * |[<!-- language="C" --> 
1362
 * void
1363
 * my_object_set_foo (MyObject *self, gint foo)
1364
 * {
1365
 *   if (self->foo != foo)
1366
 *     {
1367
 *       self->foo = foo;
1368
 *       g_object_notify_by_pspec (G_OBJECT (self), obj_properties[PROP_FOO]);
1369
 *     }
1370
 *  }
1371
 * ]|
1372
 *
1373
 * Since: 2.26
1374
 */
1375
void
1376
g_object_class_install_properties (GObjectClass  *oclass,
1377
                                   guint          n_pspecs,
1378
                                   GParamSpec   **pspecs)
1379
0
{
1380
0
  GType oclass_type, parent_type;
1381
0
  guint i;
1382
1383
0
  g_return_if_fail (G_IS_OBJECT_CLASS (oclass));
1384
0
  g_return_if_fail (n_pspecs > 1);
1385
0
  g_return_if_fail (pspecs[0] == NULL);
1386
1387
0
  if (CLASS_HAS_DERIVED_CLASS (oclass))
1388
0
    g_error ("Attempt to add properties to %s after it was derived",
1389
0
             G_OBJECT_CLASS_NAME (oclass));
1390
1391
0
  oclass_type = G_OBJECT_CLASS_TYPE (oclass);
1392
0
  parent_type = g_type_parent (oclass_type);
1393
1394
  /* we skip the first element of the array as it would have a 0 prop_id */
1395
0
  for (i = 1; i < n_pspecs; i++)
1396
0
    {
1397
0
      GParamSpec *pspec = pspecs[i];
1398
1399
0
      if (!validate_and_install_class_property (oclass,
1400
0
                                                oclass_type,
1401
0
                                                parent_type,
1402
0
                                                i,
1403
0
                                                pspec))
1404
0
        {
1405
0
          break;
1406
0
        }
1407
0
    }
1408
1409
  /* Save a copy of the pspec array inside the class struct. This
1410
   * makes it faster to look up pspecs for the class in future when
1411
   * acting on those properties.
1412
   *
1413
   * If a pspec is not in this cache array, calling code will fall
1414
   * back to using g_param_spec_pool_lookup(), so a pspec not being
1415
   * in this array is a (potential) performance problem but not a
1416
   * correctness problem. */
1417
0
  if (oclass->pspecs == NULL)
1418
0
    {
1419
0
      PspecEntry *entries;
1420
1421
0
      entries = g_new (PspecEntry, n_pspecs - 1);
1422
1423
0
      for (i = 1; i < n_pspecs; i++)
1424
0
        {
1425
0
          entries[i - 1].name = pspecs[i]->name;
1426
0
          entries[i - 1].pspec = pspecs[i];
1427
0
        }
1428
1429
0
      qsort (entries, n_pspecs - 1, sizeof (PspecEntry), compare_pspec_entry);
1430
1431
0
      oclass->pspecs = entries;
1432
0
      oclass->n_pspecs = n_pspecs - 1;
1433
0
    }
1434
0
}
1435
1436
/**
1437
 * g_object_interface_install_property:
1438
 * @g_iface: (type GObject.TypeInterface): any interface vtable for the
1439
 *    interface, or the default
1440
 *  vtable for the interface.
1441
 * @pspec: the #GParamSpec for the new property
1442
 *
1443
 * Add a property to an interface; this is only useful for interfaces
1444
 * that are added to GObject-derived types. Adding a property to an
1445
 * interface forces all objects classes with that interface to have a
1446
 * compatible property. The compatible property could be a newly
1447
 * created #GParamSpec, but normally
1448
 * g_object_class_override_property() will be used so that the object
1449
 * class only needs to provide an implementation and inherits the
1450
 * property description, default value, bounds, and so forth from the
1451
 * interface property.
1452
 *
1453
 * This function is meant to be called from the interface's default
1454
 * vtable initialization function (the @class_init member of
1455
 * #GTypeInfo.) It must not be called after after @class_init has
1456
 * been called for any object types implementing this interface.
1457
 *
1458
 * If @pspec is a floating reference, it will be consumed.
1459
 *
1460
 * Since: 2.4
1461
 */
1462
void
1463
g_object_interface_install_property (gpointer      g_iface,
1464
             GParamSpec   *pspec)
1465
0
{
1466
0
  GTypeInterface *iface_class = g_iface;
1467
  
1468
0
  g_return_if_fail (G_TYPE_IS_INTERFACE (iface_class->g_type));
1469
0
  g_return_if_fail (!G_IS_PARAM_SPEC_OVERRIDE (pspec)); /* paranoid */
1470
1471
0
  if (!validate_pspec_to_install (pspec))
1472
0
    {
1473
0
      g_param_spec_ref_sink (pspec);
1474
0
      g_param_spec_unref (pspec);
1475
0
      return;
1476
0
    }
1477
1478
0
  (void) install_property_internal (iface_class->g_type, 0, pspec);
1479
0
}
1480
1481
/* Inlined version of g_param_spec_get_redirect_target(), for speed */
1482
static inline void
1483
param_spec_follow_override (GParamSpec **pspec)
1484
0
{
1485
0
  if (((GTypeInstance *) (*pspec))->g_class->g_type == G_TYPE_PARAM_OVERRIDE)
1486
0
    *pspec = ((GParamSpecOverride *) (*pspec))->overridden;
1487
0
}
1488
1489
/**
1490
 * g_object_class_find_property:
1491
 * @oclass: a #GObjectClass
1492
 * @property_name: the name of the property to look up
1493
 *
1494
 * Looks up the #GParamSpec for a property of a class.
1495
 *
1496
 * Returns: (transfer none): the #GParamSpec for the property, or
1497
 *          %NULL if the class doesn't have a property of that name
1498
 */
1499
GParamSpec*
1500
g_object_class_find_property (GObjectClass *class,
1501
            const gchar  *property_name)
1502
0
{
1503
0
  GParamSpec *pspec;
1504
1505
0
  g_return_val_if_fail (G_IS_OBJECT_CLASS (class), NULL);
1506
0
  g_return_val_if_fail (property_name != NULL, NULL);
1507
1508
0
  pspec = find_pspec (class, property_name);
1509
1510
0
  if (pspec)
1511
0
    param_spec_follow_override (&pspec);
1512
1513
0
  return pspec;
1514
0
}
1515
1516
/**
1517
 * g_object_interface_find_property:
1518
 * @g_iface: (type GObject.TypeInterface): any interface vtable for the
1519
 *  interface, or the default vtable for the interface
1520
 * @property_name: name of a property to look up.
1521
 *
1522
 * Find the #GParamSpec with the given name for an
1523
 * interface. Generally, the interface vtable passed in as @g_iface
1524
 * will be the default vtable from g_type_default_interface_ref(), or,
1525
 * if you know the interface has already been loaded,
1526
 * g_type_default_interface_peek().
1527
 *
1528
 * Since: 2.4
1529
 *
1530
 * Returns: (transfer none): the #GParamSpec for the property of the
1531
 *          interface with the name @property_name, or %NULL if no
1532
 *          such property exists.
1533
 */
1534
GParamSpec*
1535
g_object_interface_find_property (gpointer      g_iface,
1536
          const gchar  *property_name)
1537
0
{
1538
0
  GTypeInterface *iface_class = g_iface;
1539
0
  GParamSpecPool *param_spec_pool;
1540
  
1541
0
  g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface_class->g_type), NULL);
1542
0
  g_return_val_if_fail (property_name != NULL, NULL);
1543
1544
0
  param_spec_pool = g_object_maybe_init_pspec_pool ();
1545
1546
0
  return g_param_spec_pool_lookup (param_spec_pool,
1547
0
           property_name,
1548
0
           iface_class->g_type,
1549
0
           FALSE);
1550
0
}
1551
1552
/**
1553
 * g_object_class_override_property:
1554
 * @oclass: a #GObjectClass
1555
 * @property_id: the new property ID
1556
 * @name: the name of a property registered in a parent class or
1557
 *  in an interface of this class.
1558
 *
1559
 * Registers @property_id as referring to a property with the name
1560
 * @name in a parent class or in an interface implemented by @oclass.
1561
 * This allows this class to "override" a property implementation in
1562
 * a parent class or to provide the implementation of a property from
1563
 * an interface.
1564
 *
1565
 * Internally, overriding is implemented by creating a property of type
1566
 * #GParamSpecOverride; generally operations that query the properties of
1567
 * the object class, such as g_object_class_find_property() or
1568
 * g_object_class_list_properties() will return the overridden
1569
 * property. However, in one case, the @construct_properties argument of
1570
 * the @constructor virtual function, the #GParamSpecOverride is passed
1571
 * instead, so that the @param_id field of the #GParamSpec will be
1572
 * correct.  For virtually all uses, this makes no difference. If you
1573
 * need to get the overridden property, you can call
1574
 * g_param_spec_get_redirect_target().
1575
 *
1576
 * Since: 2.4
1577
 */
1578
void
1579
g_object_class_override_property (GObjectClass *oclass,
1580
          guint         property_id,
1581
          const gchar  *name)
1582
0
{
1583
0
  GParamSpecPool *param_spec_pool;
1584
0
  GParamSpec *overridden = NULL;
1585
0
  GParamSpec *new;
1586
0
  GType parent_type;
1587
  
1588
0
  g_return_if_fail (G_IS_OBJECT_CLASS (oclass));
1589
0
  g_return_if_fail (property_id > 0);
1590
0
  g_return_if_fail (name != NULL);
1591
1592
0
  param_spec_pool = g_atomic_pointer_get (&pspec_pool);
1593
1594
  /* Find the overridden property; first check parent types
1595
   */
1596
0
  parent_type = g_type_parent (G_OBJECT_CLASS_TYPE (oclass));
1597
0
  if (parent_type != G_TYPE_NONE)
1598
0
    overridden = g_param_spec_pool_lookup (param_spec_pool,
1599
0
             name,
1600
0
             parent_type,
1601
0
             TRUE);
1602
0
  if (!overridden)
1603
0
    {
1604
0
      GType *ifaces;
1605
0
      guint n_ifaces;
1606
      
1607
      /* Now check interfaces
1608
       */
1609
0
      ifaces = g_type_interfaces (G_OBJECT_CLASS_TYPE (oclass), &n_ifaces);
1610
0
      while (n_ifaces-- && !overridden)
1611
0
  {
1612
0
    overridden = g_param_spec_pool_lookup (param_spec_pool,
1613
0
             name,
1614
0
             ifaces[n_ifaces],
1615
0
             FALSE);
1616
0
  }
1617
      
1618
0
      g_free (ifaces);
1619
0
    }
1620
1621
0
  if (!overridden)
1622
0
    {
1623
0
      g_critical ("%s: Can't find property to override for '%s::%s'",
1624
0
      G_STRFUNC, G_OBJECT_CLASS_NAME (oclass), name);
1625
0
      return;
1626
0
    }
1627
1628
0
  new = g_param_spec_override (name, overridden);
1629
0
  g_object_class_install_property (oclass, property_id, new);
1630
0
}
1631
1632
/**
1633
 * g_object_class_list_properties:
1634
 * @oclass: a #GObjectClass
1635
 * @n_properties: (out): return location for the length of the returned array
1636
 *
1637
 * Get an array of #GParamSpec* for all properties of a class.
1638
 *
1639
 * Returns: (array length=n_properties) (transfer container): an array of
1640
 *          #GParamSpec* which should be freed after use
1641
 */
1642
GParamSpec** /* free result */
1643
g_object_class_list_properties (GObjectClass *class,
1644
        guint        *n_properties_p)
1645
0
{
1646
0
  GParamSpec **pspecs;
1647
0
  guint n;
1648
1649
0
  g_return_val_if_fail (G_IS_OBJECT_CLASS (class), NULL);
1650
1651
0
  pspecs = g_param_spec_pool_list (g_atomic_pointer_get (&pspec_pool),
1652
0
           G_OBJECT_CLASS_TYPE (class),
1653
0
           &n);
1654
0
  if (n_properties_p)
1655
0
    *n_properties_p = n;
1656
1657
0
  return pspecs;
1658
0
}
1659
1660
/**
1661
 * g_object_interface_list_properties:
1662
 * @g_iface: (type GObject.TypeInterface): any interface vtable for the
1663
 *  interface, or the default vtable for the interface
1664
 * @n_properties_p: (out): location to store number of properties returned.
1665
 *
1666
 * Lists the properties of an interface.Generally, the interface
1667
 * vtable passed in as @g_iface will be the default vtable from
1668
 * g_type_default_interface_ref(), or, if you know the interface has
1669
 * already been loaded, g_type_default_interface_peek().
1670
 *
1671
 * Since: 2.4
1672
 *
1673
 * Returns: (array length=n_properties_p) (transfer container): a
1674
 *   pointer to an array of pointers to #GParamSpec
1675
 *   structures. The paramspecs are owned by GLib, but the
1676
 *   array should be freed with g_free() when you are done with
1677
 *   it.
1678
 */
1679
GParamSpec**
1680
g_object_interface_list_properties (gpointer      g_iface,
1681
            guint        *n_properties_p)
1682
0
{
1683
0
  GTypeInterface *iface_class = g_iface;
1684
0
  GParamSpecPool *param_spec_pool;
1685
0
  GParamSpec **pspecs;
1686
0
  guint n;
1687
1688
0
  g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface_class->g_type), NULL);
1689
1690
0
  param_spec_pool = g_object_maybe_init_pspec_pool ();
1691
1692
0
  pspecs = g_param_spec_pool_list (param_spec_pool,
1693
0
           iface_class->g_type,
1694
0
           &n);
1695
0
  if (n_properties_p)
1696
0
    *n_properties_p = n;
1697
1698
0
  return pspecs;
1699
0
}
1700
1701
static inline guint
1702
object_get_optional_flags (GObject *object)
1703
0
{
1704
0
  return (guint) g_atomic_int_get ((gint *) object_get_optional_flags_p (object));
1705
0
}
1706
1707
static inline void
1708
object_set_optional_flags (GObject *object,
1709
                          guint flags)
1710
0
{
1711
0
  g_atomic_int_or ((gint *) object_get_optional_flags_p (object), (int) flags);
1712
0
}
1713
1714
static inline void
1715
object_unset_optional_flags (GObject *object,
1716
                               guint flags)
1717
0
{
1718
0
  g_atomic_int_and ((gint *) object_get_optional_flags_p (object), (int) ~flags);
1719
0
}
1720
1721
gboolean
1722
_g_object_has_signal_handler (GObject *object)
1723
0
{
1724
0
  return (object_get_optional_flags (object) & OPTIONAL_FLAG_HAS_SIGNAL_HANDLER) != 0;
1725
0
}
1726
1727
static inline gboolean
1728
_g_object_has_notify_handler (GObject *object)
1729
0
{
1730
0
  return CLASS_NEEDS_NOTIFY (G_OBJECT_GET_CLASS (object)) ||
1731
0
         (object_get_optional_flags (object) & OPTIONAL_FLAG_HAS_NOTIFY_HANDLER) != 0;
1732
0
}
1733
1734
void
1735
_g_object_set_has_signal_handler (GObject *object,
1736
                                  guint    signal_id)
1737
0
{
1738
0
  guint flags = OPTIONAL_FLAG_HAS_SIGNAL_HANDLER;
1739
0
  if (signal_id == gobject_signals[NOTIFY])
1740
0
    flags |= OPTIONAL_FLAG_HAS_NOTIFY_HANDLER;
1741
0
  object_set_optional_flags (object, flags);
1742
0
}
1743
1744
static inline gboolean
1745
object_in_construction (GObject *object)
1746
0
{
1747
0
  return (object_get_optional_flags (object) & OPTIONAL_FLAG_IN_CONSTRUCTION) != 0;
1748
0
}
1749
1750
static inline void
1751
set_object_in_construction (GObject *object)
1752
0
{
1753
0
  object_set_optional_flags (object, OPTIONAL_FLAG_IN_CONSTRUCTION);
1754
0
}
1755
1756
static inline void
1757
unset_object_in_construction (GObject *object)
1758
0
{
1759
0
  object_unset_optional_flags (object, OPTIONAL_FLAG_IN_CONSTRUCTION);
1760
0
}
1761
1762
static void
1763
g_object_init (GObject    *object,
1764
         GObjectClass *class)
1765
0
{
1766
0
  object->ref_count = 1;
1767
0
  object->qdata = NULL;
1768
1769
0
  if (CLASS_HAS_PROPS (class) && CLASS_NEEDS_NOTIFY (class))
1770
0
    {
1771
      /* freeze object's notification queue, g_object_new_internal() preserves pairedness */
1772
0
      g_object_notify_queue_freeze (object, TRUE);
1773
0
    }
1774
1775
  /* mark object in-construction for notify_queue_thaw() and to allow construct-only properties */
1776
0
  set_object_in_construction (object);
1777
1778
0
  GOBJECT_IF_DEBUG (OBJECTS,
1779
0
    {
1780
0
      G_LOCK (debug_objects);
1781
0
      debug_objects_count++;
1782
0
      g_hash_table_add (debug_objects_ht, object);
1783
0
      G_UNLOCK (debug_objects);
1784
0
    });
1785
0
}
1786
1787
static void
1788
g_object_do_set_property (GObject      *object,
1789
        guint         property_id,
1790
        const GValue *value,
1791
        GParamSpec   *pspec)
1792
0
{
1793
0
  switch (property_id)
1794
0
    {
1795
0
    default:
1796
0
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1797
0
      break;
1798
0
    }
1799
0
}
1800
1801
static void
1802
g_object_do_get_property (GObject     *object,
1803
        guint        property_id,
1804
        GValue      *value,
1805
        GParamSpec  *pspec)
1806
0
{
1807
0
  switch (property_id)
1808
0
    {
1809
0
    default:
1810
0
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1811
0
      break;
1812
0
    }
1813
0
}
1814
1815
static void
1816
g_object_real_dispose (GObject *object)
1817
0
{
1818
0
  g_signal_handlers_destroy (object);
1819
1820
  /* GWeakNotify and GClosure can call into user code */
1821
0
  g_object_weak_release_all (object, FALSE);
1822
0
  closure_array_destroy_all (object);
1823
0
}
1824
1825
static gboolean
1826
g_diagnostic_is_enabled (void)
1827
0
{
1828
0
  static const char *g_enable_diagnostic = NULL;
1829
1830
0
  if (g_once_init_enter_pointer (&g_enable_diagnostic))
1831
0
    {
1832
0
      const gchar *value = g_getenv ("G_ENABLE_DIAGNOSTIC");
1833
1834
0
      if (value == NULL)
1835
0
        value = "0";
1836
1837
0
      g_once_init_leave_pointer (&g_enable_diagnostic, value);
1838
0
    }
1839
1840
0
  return g_enable_diagnostic[0] == '1';
1841
0
}
1842
1843
#ifdef G_ENABLE_DEBUG
1844
static gboolean
1845
floating_check (GObject *object)
1846
0
{
1847
0
  if (g_diagnostic_is_enabled ())
1848
0
    return g_object_is_floating (object);
1849
1850
0
  return FALSE;
1851
0
}
1852
#endif
1853
1854
static void
1855
g_object_finalize (GObject *object)
1856
0
{
1857
0
#ifdef G_ENABLE_DEBUG
1858
0
  if (object_in_construction (object))
1859
0
    {
1860
0
      g_critical ("object %s %p finalized while still in-construction",
1861
0
                  G_OBJECT_TYPE_NAME (object), object);
1862
0
    }
1863
1864
0
 if (floating_check (object))
1865
0
   {
1866
0
      g_critical ("A floating object %s %p was finalized. This means that someone\n"
1867
0
                  "called g_object_unref() on an object that had only a floating\n"
1868
0
                  "reference; the initial floating reference is not owned by anyone\n"
1869
0
                  "and must be removed with g_object_ref_sink().",
1870
0
                  G_OBJECT_TYPE_NAME (object), object);
1871
0
   }
1872
0
#endif
1873
1874
0
  g_datalist_clear (&object->qdata);
1875
  
1876
0
  GOBJECT_IF_DEBUG (OBJECTS,
1877
0
    {
1878
0
      G_LOCK (debug_objects);
1879
0
      g_assert (g_hash_table_contains (debug_objects_ht, object));
1880
0
      g_hash_table_remove (debug_objects_ht, object);
1881
0
      debug_objects_count--;
1882
0
      G_UNLOCK (debug_objects);
1883
0
    });
1884
0
}
1885
1886
static void
1887
g_object_dispatch_properties_changed (GObject     *object,
1888
              guint        n_pspecs,
1889
              GParamSpec **pspecs)
1890
0
{
1891
0
  guint i;
1892
1893
0
  for (i = 0; i < n_pspecs; i++)
1894
0
    g_signal_emit (object, gobject_signals[NOTIFY], g_param_spec_get_name_quark (pspecs[i]), pspecs[i]);
1895
0
}
1896
1897
/**
1898
 * g_object_run_dispose:
1899
 * @object: a #GObject
1900
 *
1901
 * Releases all references to other objects. This can be used to break
1902
 * reference cycles.
1903
 *
1904
 * This function should only be called from object system implementations.
1905
 */
1906
void
1907
g_object_run_dispose (GObject *object)
1908
0
{
1909
0
  WeakRefData *wrdata;
1910
1911
0
  g_return_if_fail (G_IS_OBJECT (object));
1912
0
  g_return_if_fail (g_atomic_int_get (&object->ref_count) > 0);
1913
1914
0
  g_object_ref (object);
1915
1916
0
  TRACE (GOBJECT_OBJECT_DISPOSE(object,G_TYPE_FROM_INSTANCE(object), 0));
1917
0
  G_OBJECT_GET_CLASS (object)->dispose (object);
1918
0
  TRACE (GOBJECT_OBJECT_DISPOSE_END(object,G_TYPE_FROM_INSTANCE(object), 0));
1919
1920
0
  if ((object_get_optional_flags (object) & OPTIONAL_FLAG_EVER_HAD_WEAK_REF))
1921
0
    {
1922
0
      wrdata = weak_ref_data_get_surely (object);
1923
0
      weak_ref_data_lock (wrdata);
1924
0
      weak_ref_data_clear_list (wrdata, object);
1925
0
      weak_ref_data_unlock (wrdata);
1926
0
    }
1927
1928
0
  g_object_unref (object);
1929
0
}
1930
1931
/**
1932
 * g_object_freeze_notify:
1933
 * @object: a #GObject
1934
 *
1935
 * Increases the freeze count on @object. If the freeze count is
1936
 * non-zero, the emission of "notify" signals on @object is
1937
 * stopped. The signals are queued until the freeze count is decreased
1938
 * to zero. Duplicate notifications are squashed so that at most one
1939
 * #GObject::notify signal is emitted for each property modified while the
1940
 * object is frozen.
1941
 *
1942
 * This is necessary for accessors that modify multiple properties to prevent
1943
 * premature notification while the object is still being modified.
1944
 */
1945
void
1946
g_object_freeze_notify (GObject *object)
1947
0
{
1948
0
  g_return_if_fail (G_IS_OBJECT (object));
1949
1950
0
#ifndef G_DISABLE_CHECKS
1951
0
  if (G_UNLIKELY (g_atomic_int_get (&object->ref_count) <= 0))
1952
0
    {
1953
0
      g_critical ("Attempting to freeze the notification queue for object %s[%p]; "
1954
0
                  "Property notification does not work during instance finalization.",
1955
0
                  G_OBJECT_TYPE_NAME (object),
1956
0
                  object);
1957
0
      return;
1958
0
    }
1959
0
#endif
1960
1961
0
  g_object_notify_queue_freeze (object, TRUE);
1962
0
}
1963
1964
static inline void
1965
g_object_notify_by_spec_internal (GObject    *object,
1966
                                  GParamSpec *pspec)
1967
0
{
1968
0
  guint object_flags;
1969
0
  gboolean needs_notify;
1970
0
  gboolean in_init;
1971
1972
0
  if (G_UNLIKELY (~pspec->flags & G_PARAM_READABLE))
1973
0
    return;
1974
1975
0
  param_spec_follow_override (&pspec);
1976
1977
  /* get all flags we need with a single atomic read */
1978
0
  object_flags = object_get_optional_flags (object);
1979
0
  needs_notify = ((object_flags & OPTIONAL_FLAG_HAS_NOTIFY_HANDLER) != 0) ||
1980
0
                  CLASS_NEEDS_NOTIFY (G_OBJECT_GET_CLASS (object));
1981
0
  in_init = (object_flags & OPTIONAL_FLAG_IN_CONSTRUCTION) != 0;
1982
1983
0
  if (pspec != NULL && needs_notify)
1984
0
    {
1985
0
      if (!g_object_notify_queue_add (object, pspec, in_init))
1986
0
        {
1987
          /*
1988
           * Coverity doesn’t understand the paired ref/unref here and seems to
1989
           * ignore the ref, thus reports every call to g_object_notify() as
1990
           * causing a double-free. That’s incorrect, but I can’t get a model
1991
           * file to work for avoiding the false positives, so instead comment
1992
           * out the ref/unref when doing static analysis.
1993
           */
1994
0
#ifndef __COVERITY__
1995
0
          g_object_ref (object);
1996
0
#endif
1997
1998
          /* not frozen, so just dispatch the notification directly */
1999
0
          G_OBJECT_GET_CLASS (object)
2000
0
              ->dispatch_properties_changed (object, 1, &pspec);
2001
2002
0
#ifndef __COVERITY__
2003
0
          g_object_unref (object);
2004
0
#endif
2005
0
        }
2006
0
    }
2007
0
}
2008
2009
/**
2010
 * g_object_notify:
2011
 * @object: a #GObject
2012
 * @property_name: the name of a property installed on the class of @object.
2013
 *
2014
 * Emits a "notify" signal for the property @property_name on @object.
2015
 *
2016
 * When possible, eg. when signaling a property change from within the class
2017
 * that registered the property, you should use g_object_notify_by_pspec()
2018
 * instead.
2019
 *
2020
 * Note that emission of the notify signal may be blocked with
2021
 * g_object_freeze_notify(). In this case, the signal emissions are queued
2022
 * and will be emitted (in reverse order) when g_object_thaw_notify() is
2023
 * called.
2024
 */
2025
void
2026
g_object_notify (GObject     *object,
2027
     const gchar *property_name)
2028
0
{
2029
0
  GParamSpec *pspec;
2030
  
2031
0
  g_return_if_fail (G_IS_OBJECT (object));
2032
0
  g_return_if_fail (property_name != NULL);
2033
  
2034
  /* We don't need to get the redirect target
2035
   * (by, e.g. calling g_object_class_find_property())
2036
   * because g_object_notify_queue_add() does that
2037
   */
2038
0
  pspec = g_param_spec_pool_lookup (g_atomic_pointer_get (&pspec_pool),
2039
0
            property_name,
2040
0
            G_OBJECT_TYPE (object),
2041
0
            TRUE);
2042
2043
0
  if (!pspec)
2044
0
    g_critical ("%s: object class '%s' has no property named '%s'",
2045
0
          G_STRFUNC,
2046
0
          G_OBJECT_TYPE_NAME (object),
2047
0
          property_name);
2048
0
  else
2049
0
    g_object_notify_by_spec_internal (object, pspec);
2050
0
}
2051
2052
/**
2053
 * g_object_notify_by_pspec:
2054
 * @object: a #GObject
2055
 * @pspec: the #GParamSpec of a property installed on the class of @object.
2056
 *
2057
 * Emits a "notify" signal for the property specified by @pspec on @object.
2058
 *
2059
 * This function omits the property name lookup, hence it is faster than
2060
 * g_object_notify().
2061
 *
2062
 * One way to avoid using g_object_notify() from within the
2063
 * class that registered the properties, and using g_object_notify_by_pspec()
2064
 * instead, is to store the GParamSpec used with
2065
 * g_object_class_install_property() inside a static array, e.g.:
2066
 *
2067
 *|[<!-- language="C" --> 
2068
 *   typedef enum
2069
 *   {
2070
 *     PROP_FOO = 1,
2071
 *     PROP_LAST
2072
 *   } MyObjectProperty;
2073
 *
2074
 *   static GParamSpec *properties[PROP_LAST];
2075
 *
2076
 *   static void
2077
 *   my_object_class_init (MyObjectClass *klass)
2078
 *   {
2079
 *     properties[PROP_FOO] = g_param_spec_int ("foo", NULL, NULL,
2080
 *                                              0, 100,
2081
 *                                              50,
2082
 *                                              G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
2083
 *     g_object_class_install_property (gobject_class,
2084
 *                                      PROP_FOO,
2085
 *                                      properties[PROP_FOO]);
2086
 *   }
2087
 * ]|
2088
 *
2089
 * and then notify a change on the "foo" property with:
2090
 *
2091
 * |[<!-- language="C" --> 
2092
 *   g_object_notify_by_pspec (self, properties[PROP_FOO]);
2093
 * ]|
2094
 *
2095
 * Since: 2.26
2096
 */
2097
void
2098
g_object_notify_by_pspec (GObject    *object,
2099
        GParamSpec *pspec)
2100
0
{
2101
2102
0
  g_return_if_fail (G_IS_OBJECT (object));
2103
0
  g_return_if_fail (G_IS_PARAM_SPEC (pspec));
2104
2105
0
  g_object_notify_by_spec_internal (object, pspec);
2106
0
}
2107
2108
/**
2109
 * g_object_thaw_notify:
2110
 * @object: a #GObject
2111
 *
2112
 * Reverts the effect of a previous call to
2113
 * g_object_freeze_notify(). The freeze count is decreased on @object
2114
 * and when it reaches zero, queued "notify" signals are emitted.
2115
 *
2116
 * Duplicate notifications for each property are squashed so that at most one
2117
 * #GObject::notify signal is emitted for each property, in the reverse order
2118
 * in which they have been queued.
2119
 *
2120
 * It is an error to call this function when the freeze count is zero.
2121
 */
2122
void
2123
g_object_thaw_notify (GObject *object)
2124
0
{
2125
0
  g_return_if_fail (G_IS_OBJECT (object));
2126
2127
0
#ifndef G_DISABLE_CHECKS
2128
0
  if (G_UNLIKELY (g_atomic_int_get (&object->ref_count) <= 0))
2129
0
    {
2130
0
      g_critical ("Attempting to thaw the notification queue for object %s[%p]; "
2131
0
                  "Property notification does not work during instance finalization.",
2132
0
                  G_OBJECT_TYPE_NAME (object),
2133
0
                  object);
2134
0
      return;
2135
0
    }
2136
0
#endif
2137
2138
0
  g_object_notify_queue_thaw (object, TRUE);
2139
0
}
2140
2141
static void
2142
maybe_issue_property_deprecation_warning (const GParamSpec *pspec)
2143
0
{
2144
0
  static GHashTable *already_warned_table;
2145
0
  static GMutex already_warned_lock;
2146
0
  gboolean already;
2147
2148
0
  if (!g_diagnostic_is_enabled ())
2149
0
    return;
2150
2151
  /* We hash only on property names: this means that we could end up in
2152
   * a situation where we fail to emit a warning about a pair of
2153
   * same-named deprecated properties used on two separate types.
2154
   * That's pretty unlikely to occur, and even if it does, you'll still
2155
   * have seen the warning for the first one...
2156
   *
2157
   * Doing it this way lets us hash directly on the (interned) property
2158
   * name pointers.
2159
   */
2160
0
  g_mutex_lock (&already_warned_lock);
2161
2162
0
  if (already_warned_table == NULL)
2163
0
    already_warned_table = g_hash_table_new (NULL, NULL);
2164
2165
0
  already = g_hash_table_contains (already_warned_table, (gpointer) pspec->name);
2166
0
  if (!already)
2167
0
    g_hash_table_add (already_warned_table, (gpointer) pspec->name);
2168
2169
0
  g_mutex_unlock (&already_warned_lock);
2170
2171
0
  if (!already)
2172
0
    g_warning ("The property %s:%s is deprecated and shouldn't be used "
2173
0
               "anymore. It will be removed in a future version.",
2174
0
               g_type_name (pspec->owner_type), pspec->name);
2175
0
}
2176
2177
static inline void
2178
consider_issuing_property_deprecation_warning (const GParamSpec *pspec)
2179
0
{
2180
0
  if (G_UNLIKELY (pspec->flags & G_PARAM_DEPRECATED))
2181
0
    maybe_issue_property_deprecation_warning (pspec);
2182
0
}
2183
2184
static inline void
2185
object_get_property (GObject     *object,
2186
         GParamSpec  *pspec,
2187
         GValue      *value)
2188
0
{
2189
0
  GTypeInstance *inst = (GTypeInstance *) object;
2190
0
  GObjectClass *class;
2191
0
  guint param_id = PARAM_SPEC_PARAM_ID (pspec);
2192
2193
0
  if (G_LIKELY (inst->g_class->g_type == pspec->owner_type))
2194
0
    class = (GObjectClass *) inst->g_class;
2195
0
  else
2196
0
    class = g_type_class_peek (pspec->owner_type);
2197
2198
0
  g_assert (class != NULL);
2199
2200
0
  param_spec_follow_override (&pspec);
2201
2202
0
  consider_issuing_property_deprecation_warning (pspec);
2203
2204
0
  class->get_property (object, param_id, value, pspec);
2205
0
}
2206
2207
static inline void
2208
object_set_property (GObject             *object,
2209
         GParamSpec          *pspec,
2210
         const GValue        *value,
2211
         gboolean             nqueue_is_frozen,
2212
         gboolean             user_specified)
2213
0
{
2214
0
  GTypeInstance *inst = (GTypeInstance *) object;
2215
0
  GObjectClass *class;
2216
0
  GParamSpecClass *pclass;
2217
0
  guint param_id = PARAM_SPEC_PARAM_ID (pspec);
2218
2219
0
  if (G_LIKELY (inst->g_class->g_type == pspec->owner_type))
2220
0
    class = (GObjectClass *) inst->g_class;
2221
0
  else
2222
0
    class = g_type_class_peek (pspec->owner_type);
2223
2224
0
  g_assert (class != NULL);
2225
2226
0
  param_spec_follow_override (&pspec);
2227
2228
0
  if (user_specified)
2229
0
    consider_issuing_property_deprecation_warning (pspec);
2230
2231
0
  pclass = G_PARAM_SPEC_GET_CLASS (pspec);
2232
0
  if (g_value_type_compatible (G_VALUE_TYPE (value), pspec->value_type) &&
2233
0
      (pclass->value_validate == NULL ||
2234
0
       (pclass->value_is_valid != NULL && pclass->value_is_valid (pspec, value))))
2235
0
    {
2236
0
      class->set_property (object, param_id, value, pspec);
2237
0
    }
2238
0
  else
2239
0
    {
2240
      /* provide a copy to work from, convert (if necessary) and validate */
2241
0
      GValue tmp_value = G_VALUE_INIT;
2242
2243
0
      g_value_init (&tmp_value, pspec->value_type);
2244
2245
0
      if (!g_value_transform (value, &tmp_value))
2246
0
        g_critical ("unable to set property '%s' of type '%s' from value of type '%s'",
2247
0
                    pspec->name,
2248
0
                    g_type_name (pspec->value_type),
2249
0
                    G_VALUE_TYPE_NAME (value));
2250
0
      else if (g_param_value_validate (pspec, &tmp_value) && !(pspec->flags & G_PARAM_LAX_VALIDATION))
2251
0
        {
2252
0
          gchar *contents = g_strdup_value_contents (value);
2253
2254
0
          g_critical ("value \"%s\" of type '%s' is invalid or out of range for property '%s' of type '%s'",
2255
0
                      contents,
2256
0
                      G_VALUE_TYPE_NAME (value),
2257
0
                      pspec->name,
2258
0
                      g_type_name (pspec->value_type));
2259
0
          g_free (contents);
2260
0
        }
2261
0
      else
2262
0
        {
2263
0
          class->set_property (object, param_id, &tmp_value, pspec);
2264
0
        }
2265
2266
0
      g_value_unset (&tmp_value);
2267
0
    }
2268
2269
0
  if ((pspec->flags & (G_PARAM_EXPLICIT_NOTIFY | G_PARAM_READABLE)) == G_PARAM_READABLE &&
2270
0
      nqueue_is_frozen)
2271
0
    g_object_notify_queue_add (object, pspec, FALSE);
2272
0
}
2273
2274
static void
2275
object_interface_check_properties (gpointer check_data,
2276
           gpointer g_iface)
2277
0
{
2278
0
  GTypeInterface *iface_class = g_iface;
2279
0
  GObjectClass *class;
2280
0
  GParamSpecPool *param_spec_pool;
2281
0
  GType iface_type = iface_class->g_type;
2282
0
  GParamSpec **pspecs;
2283
0
  guint n;
2284
2285
0
  class = g_type_class_ref (iface_class->g_instance_type);
2286
2287
0
  if (class == NULL)
2288
0
    return;
2289
2290
0
  if (!G_IS_OBJECT_CLASS (class))
2291
0
    goto out;
2292
2293
0
  param_spec_pool = g_atomic_pointer_get (&pspec_pool);
2294
0
  pspecs = g_param_spec_pool_list (param_spec_pool, iface_type, &n);
2295
2296
0
  while (n--)
2297
0
    {
2298
0
      GParamSpec *class_pspec = g_param_spec_pool_lookup (param_spec_pool,
2299
0
                pspecs[n]->name,
2300
0
                G_OBJECT_CLASS_TYPE (class),
2301
0
                TRUE);
2302
2303
0
      if (!class_pspec)
2304
0
  {
2305
0
    g_critical ("Object class %s doesn't implement property "
2306
0
          "'%s' from interface '%s'",
2307
0
          g_type_name (G_OBJECT_CLASS_TYPE (class)),
2308
0
          pspecs[n]->name,
2309
0
          g_type_name (iface_type));
2310
2311
0
    continue;
2312
0
  }
2313
2314
      /* We do a number of checks on the properties of an interface to
2315
       * make sure that all classes implementing the interface are
2316
       * overriding the properties correctly.
2317
       *
2318
       * We do the checks in order of importance so that we can give
2319
       * more useful error messages first.
2320
       *
2321
       * First, we check that the implementation doesn't remove the
2322
       * basic functionality (readability, writability) advertised by
2323
       * the interface.  Next, we check that it doesn't introduce
2324
       * additional restrictions (such as construct-only).  Finally, we
2325
       * make sure the types are compatible.
2326
       */
2327
2328
0
#define SUBSET(a,b,mask) (((a) & ~(b) & (mask)) == 0)
2329
      /* If the property on the interface is readable then the
2330
       * implementation must be readable.  If the interface is writable
2331
       * then the implementation must be writable.
2332
       */
2333
0
      if (!SUBSET (pspecs[n]->flags, class_pspec->flags, G_PARAM_READABLE | G_PARAM_WRITABLE))
2334
0
        {
2335
0
          g_critical ("Flags for property '%s' on class '%s' remove functionality compared with the "
2336
0
                      "property on interface '%s'\n", pspecs[n]->name,
2337
0
                      g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (iface_type));
2338
0
          continue;
2339
0
        }
2340
2341
      /* If the property on the interface is writable then we need to
2342
       * make sure the implementation doesn't introduce new restrictions
2343
       * on that writability (ie: construct-only).
2344
       *
2345
       * If the interface was not writable to begin with then we don't
2346
       * really have any problems here because "writable at construct
2347
       * time only" is still more permissive than "read only".
2348
       */
2349
0
      if (pspecs[n]->flags & G_PARAM_WRITABLE)
2350
0
        {
2351
0
          if (!SUBSET (class_pspec->flags, pspecs[n]->flags, G_PARAM_CONSTRUCT_ONLY))
2352
0
            {
2353
0
              g_critical ("Flags for property '%s' on class '%s' introduce additional restrictions on "
2354
0
                          "writability compared with the property on interface '%s'\n", pspecs[n]->name,
2355
0
                          g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (iface_type));
2356
0
              continue;
2357
0
            }
2358
0
        }
2359
0
#undef SUBSET
2360
2361
      /* If the property on the interface is readable then we are
2362
       * effectively advertising that reading the property will return a
2363
       * value of a specific type.  All implementations of the interface
2364
       * need to return items of this type -- but may be more
2365
       * restrictive.  For example, it is legal to have:
2366
       *
2367
       *   GtkWidget *get_item();
2368
       *
2369
       * that is implemented by a function that always returns a
2370
       * GtkEntry.  In short: readability implies that the
2371
       * implementation  value type must be equal or more restrictive.
2372
       *
2373
       * Similarly, if the property on the interface is writable then
2374
       * must be able to accept the property being set to any value of
2375
       * that type, including subclasses.  In this case, we may also be
2376
       * less restrictive.  For example, it is legal to have:
2377
       *
2378
       *   set_item (GtkEntry *);
2379
       *
2380
       * that is implemented by a function that will actually work with
2381
       * any GtkWidget.  In short: writability implies that the
2382
       * implementation value type must be equal or less restrictive.
2383
       *
2384
       * In the case that the property is both readable and writable
2385
       * then the only way that both of the above can be satisfied is
2386
       * with a type that is exactly equal.
2387
       */
2388
0
      switch (pspecs[n]->flags & (G_PARAM_READABLE | G_PARAM_WRITABLE))
2389
0
        {
2390
0
        case G_PARAM_READABLE | G_PARAM_WRITABLE:
2391
          /* class pspec value type must have exact equality with interface */
2392
0
          if (pspecs[n]->value_type != class_pspec->value_type)
2393
0
            g_critical ("Read/writable property '%s' on class '%s' has type '%s' which is not exactly equal to the "
2394
0
                        "type '%s' of the property on the interface '%s'\n", pspecs[n]->name,
2395
0
                        g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
2396
0
                        g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])), g_type_name (iface_type));
2397
0
          break;
2398
2399
0
        case G_PARAM_READABLE:
2400
          /* class pspec value type equal or more restrictive than interface */
2401
0
          if (!g_type_is_a (class_pspec->value_type, pspecs[n]->value_type))
2402
0
            g_critical ("Read-only property '%s' on class '%s' has type '%s' which is not equal to or more "
2403
0
                        "restrictive than the type '%s' of the property on the interface '%s'\n", pspecs[n]->name,
2404
0
                        g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
2405
0
                        g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])), g_type_name (iface_type));
2406
0
          break;
2407
2408
0
        case G_PARAM_WRITABLE:
2409
          /* class pspec value type equal or less restrictive than interface */
2410
0
          if (!g_type_is_a (pspecs[n]->value_type, class_pspec->value_type))
2411
0
            g_critical ("Write-only property '%s' on class '%s' has type '%s' which is not equal to or less "
2412
0
                        "restrictive than the type '%s' of the property on the interface '%s' \n", pspecs[n]->name,
2413
0
                        g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
2414
0
                        g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])), g_type_name (iface_type));
2415
0
          break;
2416
2417
0
        default:
2418
0
          g_assert_not_reached ();
2419
0
        }
2420
0
    }
2421
2422
0
  g_free (pspecs);
2423
2424
0
 out:
2425
0
  g_type_class_unref (class);
2426
0
}
2427
2428
GType
2429
g_object_get_type (void)
2430
0
{
2431
0
    return G_TYPE_OBJECT;
2432
0
}
2433
2434
/**
2435
 * g_object_new: (skip)
2436
 * @object_type: the type id of the #GObject subtype to instantiate
2437
 * @first_property_name: the name of the first property
2438
 * @...: the value of the first property, followed optionally by more
2439
 *   name/value pairs, followed by %NULL
2440
 *
2441
 * Creates a new instance of a #GObject subtype and sets its properties.
2442
 *
2443
 * Construction parameters (see %G_PARAM_CONSTRUCT, %G_PARAM_CONSTRUCT_ONLY)
2444
 * which are not explicitly specified are set to their default values. Any
2445
 * private data for the object is guaranteed to be initialized with zeros, as
2446
 * per g_type_create_instance().
2447
 *
2448
 * Note that in C, small integer types in variable argument lists are promoted
2449
 * up to `gint` or `guint` as appropriate, and read back accordingly. `gint` is
2450
 * 32 bits on every platform on which GLib is currently supported. This means that
2451
 * you can use C expressions of type `gint` with g_object_new() and properties of
2452
 * type `gint` or `guint` or smaller. Specifically, you can use integer literals
2453
 * with these property types.
2454
 *
2455
 * When using property types of `gint64` or `guint64`, you must ensure that the
2456
 * value that you provide is 64 bit. This means that you should use a cast or
2457
 * make use of the %G_GINT64_CONSTANT or %G_GUINT64_CONSTANT macros.
2458
 *
2459
 * Similarly, `gfloat` is promoted to `gdouble`, so you must ensure that the value
2460
 * you provide is a `gdouble`, even for a property of type `gfloat`.
2461
 *
2462
 * Since GLib 2.72, all #GObjects are guaranteed to be aligned to at least the
2463
 * alignment of the largest basic GLib type (typically this is `guint64` or
2464
 * `gdouble`). If you need larger alignment for an element in a #GObject, you
2465
 * should allocate it on the heap (aligned), or arrange for your #GObject to be
2466
 * appropriately padded.
2467
 *
2468
 * Returns: (transfer full) (type GObject.Object): a new instance of
2469
 *   @object_type
2470
 */
2471
gpointer
2472
g_object_new (GType    object_type,
2473
        const gchar *first_property_name,
2474
        ...)
2475
0
{
2476
0
  GObject *object;
2477
0
  va_list var_args;
2478
  
2479
  /* short circuit for calls supplying no properties */
2480
0
  if (!first_property_name)
2481
0
    return g_object_new_with_properties (object_type, 0, NULL, NULL);
2482
2483
0
  va_start (var_args, first_property_name);
2484
0
  object = g_object_new_valist (object_type, first_property_name, var_args);
2485
0
  va_end (var_args);
2486
  
2487
0
  return object;
2488
0
}
2489
2490
/* Check alignment. (See https://gitlab.gnome.org/GNOME/glib/-/issues/1231.)
2491
 * This should never fail, since g_type_create_instance() uses g_slice_alloc0().
2492
 * The GSlice allocator always aligns to the next power of 2 greater than the
2493
 * allocation size. The allocation size for a GObject is
2494
 *   sizeof(GTypeInstance) + sizeof(guint) + sizeof(GData*)
2495
 * which is 12B on 32-bit platforms, and larger on 64-bit systems. In both
2496
 * cases, that’s larger than the 8B needed for a guint64 or gdouble.
2497
 *
2498
 * If GSlice falls back to malloc(), it’s documented to return something
2499
 * suitably aligned for any basic type. */
2500
static inline gboolean
2501
g_object_is_aligned (GObject *object)
2502
0
{
2503
0
  return ((((guintptr) (void *) object) %
2504
0
             MAX (G_ALIGNOF (gdouble),
2505
0
                  MAX (G_ALIGNOF (guint64),
2506
0
                       MAX (G_ALIGNOF (gint),
2507
0
                            G_ALIGNOF (glong))))) == 0);
2508
0
}
2509
2510
static gpointer
2511
g_object_new_with_custom_constructor (GObjectClass          *class,
2512
                                      GObjectConstructParam *params,
2513
                                      guint                  n_params)
2514
0
{
2515
0
  gboolean nqueue_is_frozen = FALSE;
2516
0
  gboolean newly_constructed;
2517
0
  GObjectConstructParam *cparams;
2518
0
  gboolean free_cparams = FALSE;
2519
0
  GObject *object;
2520
0
  GValue *cvalues;
2521
0
  gint cvals_used;
2522
0
  GSList *node;
2523
0
  guint i;
2524
2525
  /* If we have ->constructed() then we have to do a lot more work.
2526
   * It's possible that this is a singleton and it's also possible
2527
   * that the user's constructor() will attempt to modify the values
2528
   * that we pass in, so we'll need to allocate copies of them.
2529
   * It's also possible that the user may attempt to call
2530
   * g_object_set() from inside of their constructor, so we need to
2531
   * add ourselves to a list of objects for which that is allowed
2532
   * while their constructor() is running.
2533
   */
2534
2535
  /* Create the array of GObjectConstructParams for constructor(),
2536
   * The 1024 here is an arbitrary, high limit that no sane code
2537
   * will ever hit, just to avoid the possibility of stack overflow.
2538
   */
2539
0
  if (G_LIKELY (class->n_construct_properties < 1024))
2540
0
    {
2541
0
      cparams = g_newa0 (GObjectConstructParam, class->n_construct_properties);
2542
0
      cvalues = g_newa0 (GValue, class->n_construct_properties);
2543
0
    }
2544
0
  else
2545
0
    {
2546
0
      cparams = g_new0 (GObjectConstructParam, class->n_construct_properties);
2547
0
      cvalues = g_new0 (GValue, class->n_construct_properties);
2548
0
      free_cparams = TRUE;
2549
0
    }
2550
0
  cvals_used = 0;
2551
0
  i = 0;
2552
2553
  /* As above, we may find the value in the passed-in params list.
2554
   *
2555
   * If we have the value passed in then we can use the GValue from
2556
   * it directly because it is safe to modify.  If we use the
2557
   * default value from the class, we had better not pass that in
2558
   * and risk it being modified, so we create a new one.
2559
   * */
2560
0
  for (node = class->construct_properties; node; node = node->next)
2561
0
    {
2562
0
      GParamSpec *pspec;
2563
0
      GValue *value;
2564
0
      guint j;
2565
2566
0
      pspec = node->data;
2567
0
      value = NULL; /* to silence gcc... */
2568
2569
0
      for (j = 0; j < n_params; j++)
2570
0
        if (params[j].pspec == pspec)
2571
0
          {
2572
0
            consider_issuing_property_deprecation_warning (pspec);
2573
0
            value = params[j].value;
2574
0
            break;
2575
0
          }
2576
2577
0
      if (value == NULL)
2578
0
        {
2579
0
          value = &cvalues[cvals_used++];
2580
0
          g_value_init (value, pspec->value_type);
2581
0
          g_param_value_set_default (pspec, value);
2582
0
        }
2583
2584
0
      cparams[i].pspec = pspec;
2585
0
      cparams[i].value = value;
2586
0
      i++;
2587
0
    }
2588
2589
  /* construct object from construction parameters */
2590
0
  g_assert (class->n_construct_properties <= UINT_MAX);
2591
0
  object = class->constructor (class->g_type_class.g_type, (unsigned int) class->n_construct_properties, cparams);
2592
  /* free construction values */
2593
0
  while (cvals_used--)
2594
0
    g_value_unset (&cvalues[cvals_used]);
2595
2596
0
  if (free_cparams)
2597
0
    {
2598
0
      g_free (cparams);
2599
0
      g_free (cvalues);
2600
0
    }
2601
2602
  /* There is code in the wild that relies on being able to return NULL
2603
   * from its custom constructor.  This was never a supported operation,
2604
   * but since the code is already out there...
2605
   */
2606
0
  if (object == NULL)
2607
0
    {
2608
0
      g_critical ("Custom constructor for class %s returned NULL (which is invalid). "
2609
0
                  "Please use GInitable instead.", G_OBJECT_CLASS_NAME (class));
2610
0
      return NULL;
2611
0
    }
2612
2613
0
  if (!g_object_is_aligned (object))
2614
0
    {
2615
0
      g_critical ("Custom constructor for class %s returned a non-aligned "
2616
0
                  "GObject (which is invalid since GLib 2.72). Assuming any "
2617
0
                  "code using this object doesn’t require it to be aligned. "
2618
0
                  "Please fix your constructor to align to the largest GLib "
2619
0
                  "basic type (typically gdouble or guint64).",
2620
0
                  G_OBJECT_CLASS_NAME (class));
2621
0
    }
2622
2623
  /* g_object_init() will have marked the object as being in-construction.
2624
   * Check if the returned object still is so marked, or if this is an
2625
   * already-existing singleton (in which case we should not do 'constructed').
2626
   */
2627
0
  newly_constructed = object_in_construction (object);
2628
0
  if (newly_constructed)
2629
0
    unset_object_in_construction (object);
2630
2631
0
  if (CLASS_HAS_PROPS (class))
2632
0
    {
2633
0
      if ((newly_constructed && _g_object_has_notify_handler (object)) ||
2634
0
          _g_object_has_notify_handler (object))
2635
0
        {
2636
          /* This may or may not have been setup in g_object_init().
2637
           * If it hasn't, we do it now.
2638
           */
2639
0
          g_object_notify_queue_freeze (object, FALSE);
2640
0
          nqueue_is_frozen = TRUE;
2641
0
        }
2642
0
    }
2643
2644
  /* run 'constructed' handler if there is a custom one */
2645
0
  if (newly_constructed && CLASS_HAS_CUSTOM_CONSTRUCTED (class))
2646
0
    class->constructed (object);
2647
2648
  /* set remaining properties */
2649
0
  for (i = 0; i < n_params; i++)
2650
0
    if (!(params[i].pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY)))
2651
0
      object_set_property (object, params[i].pspec, params[i].value, nqueue_is_frozen, TRUE);
2652
2653
0
  if (nqueue_is_frozen)
2654
0
    g_object_notify_queue_thaw (object, FALSE);
2655
2656
0
  return object;
2657
0
}
2658
2659
static gpointer
2660
g_object_new_internal (GObjectClass          *class,
2661
                       GObjectConstructParam *params,
2662
                       guint                  n_params)
2663
0
{
2664
0
  gboolean nqueue_is_frozen = FALSE;
2665
0
  GObject *object;
2666
0
  guint i;
2667
2668
0
  if G_UNLIKELY (CLASS_HAS_CUSTOM_CONSTRUCTOR (class))
2669
0
    return g_object_new_with_custom_constructor (class, params, n_params);
2670
2671
0
  object = (GObject *) g_type_create_instance (class->g_type_class.g_type);
2672
2673
0
  g_assert (g_object_is_aligned (object));
2674
2675
0
  unset_object_in_construction (object);
2676
2677
0
  if (CLASS_HAS_PROPS (class))
2678
0
    {
2679
0
      GSList *node;
2680
2681
0
      if (_g_object_has_notify_handler (object))
2682
0
        {
2683
          /* This may or may not have been setup in g_object_init().
2684
           * If it hasn't, we do it now.
2685
           */
2686
0
          g_object_notify_queue_freeze (object, FALSE);
2687
0
          nqueue_is_frozen = TRUE;
2688
0
        }
2689
2690
      /* We will set exactly n_construct_properties construct
2691
       * properties, but they may come from either the class default
2692
       * values or the passed-in parameter list.
2693
       */
2694
0
      for (node = class->construct_properties; node; node = node->next)
2695
0
        {
2696
0
          const GValue *value;
2697
0
          GParamSpec *pspec;
2698
0
          guint j;
2699
0
          gboolean user_specified = FALSE;
2700
2701
0
          pspec = node->data;
2702
0
          value = NULL; /* to silence gcc... */
2703
2704
0
          for (j = 0; j < n_params; j++)
2705
0
            if (params[j].pspec == pspec)
2706
0
              {
2707
0
                value = params[j].value;
2708
0
                user_specified = TRUE;
2709
0
                break;
2710
0
              }
2711
2712
0
          if (value == NULL)
2713
0
            value = g_param_spec_get_default_value (pspec);
2714
2715
0
          object_set_property (object, pspec, value, nqueue_is_frozen, user_specified);
2716
0
        }
2717
0
    }
2718
2719
  /* run 'constructed' handler if there is a custom one */
2720
0
  if (CLASS_HAS_CUSTOM_CONSTRUCTED (class))
2721
0
    class->constructed (object);
2722
2723
  /* Set remaining properties.  The construct properties will
2724
   * already have been taken, so set only the non-construct ones.
2725
   */
2726
0
  for (i = 0; i < n_params; i++)
2727
0
    if (!(params[i].pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY)))
2728
0
      object_set_property (object, params[i].pspec, params[i].value, nqueue_is_frozen, TRUE);
2729
2730
0
  if (nqueue_is_frozen)
2731
0
    g_object_notify_queue_thaw (object, FALSE);
2732
2733
0
  return object;
2734
0
}
2735
2736
2737
static inline gboolean
2738
g_object_new_is_valid_property (GType                  object_type,
2739
                                GParamSpec            *pspec,
2740
                                const char            *name,
2741
                                GObjectConstructParam *params,
2742
                                guint                  n_params)
2743
0
{
2744
0
  guint i;
2745
2746
0
  if (G_UNLIKELY (pspec == NULL))
2747
0
    {
2748
0
      g_critical ("%s: object class '%s' has no property named '%s'",
2749
0
                  G_STRFUNC, g_type_name (object_type), name);
2750
0
      return FALSE;
2751
0
    }
2752
2753
0
  if (G_UNLIKELY (~pspec->flags & G_PARAM_WRITABLE))
2754
0
    {
2755
0
      g_critical ("%s: property '%s' of object class '%s' is not writable",
2756
0
                  G_STRFUNC, pspec->name, g_type_name (object_type));
2757
0
      return FALSE;
2758
0
    }
2759
2760
0
  if (G_UNLIKELY (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY)))
2761
0
    {
2762
0
      for (i = 0; i < n_params; i++)
2763
0
        if (params[i].pspec == pspec)
2764
0
          break;
2765
0
      if (G_UNLIKELY (i != n_params))
2766
0
        {
2767
0
          g_critical ("%s: property '%s' for type '%s' cannot be set twice",
2768
0
                      G_STRFUNC, name, g_type_name (object_type));
2769
0
          return FALSE;
2770
0
        }
2771
0
    }
2772
0
  return TRUE;
2773
0
}
2774
2775
2776
/**
2777
 * g_object_new_with_properties: (skip)
2778
 * @object_type: the object type to instantiate
2779
 * @n_properties: the number of properties
2780
 * @names: (array length=n_properties): the names of each property to be set
2781
 * @values: (array length=n_properties): the values of each property to be set
2782
 *
2783
 * Creates a new instance of a #GObject subtype and sets its properties using
2784
 * the provided arrays. Both arrays must have exactly @n_properties elements,
2785
 * and the names and values correspond by index.
2786
 *
2787
 * Construction parameters (see %G_PARAM_CONSTRUCT, %G_PARAM_CONSTRUCT_ONLY)
2788
 * which are not explicitly specified are set to their default values.
2789
 *
2790
 * Returns: (type GObject.Object) (transfer full): a new instance of
2791
 * @object_type
2792
 *
2793
 * Since: 2.54
2794
 */
2795
GObject *
2796
g_object_new_with_properties (GType          object_type,
2797
                              guint          n_properties,
2798
                              const char    *names[],
2799
                              const GValue   values[])
2800
0
{
2801
0
  GObjectClass *class, *unref_class = NULL;
2802
0
  GObject *object;
2803
2804
0
  g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
2805
2806
  /* Try to avoid thrashing the ref_count if we don't need to (since
2807
   * it's a locked operation).
2808
   */
2809
0
  class = g_type_class_peek_static (object_type);
2810
2811
0
  if (class == NULL)
2812
0
    class = unref_class = g_type_class_ref (object_type);
2813
2814
0
  if (n_properties > 0)
2815
0
    {
2816
0
      guint i, count = 0;
2817
0
      GObjectConstructParam *params;
2818
2819
0
      params = g_newa (GObjectConstructParam, n_properties);
2820
0
      for (i = 0; i < n_properties; i++)
2821
0
        {
2822
0
          GParamSpec *pspec = find_pspec (class, names[i]);
2823
2824
0
          if (!g_object_new_is_valid_property (object_type, pspec, names[i], params, count))
2825
0
            continue;
2826
0
          params[count].pspec = pspec;
2827
0
          params[count].value = (GValue *) &values[i];
2828
0
          count++;
2829
0
        }
2830
0
      object = g_object_new_internal (class, params, count);
2831
0
    }
2832
0
  else
2833
0
    object = g_object_new_internal (class, NULL, 0);
2834
2835
0
  if (unref_class != NULL)
2836
0
    g_type_class_unref (unref_class);
2837
2838
0
  return object;
2839
0
}
2840
2841
/**
2842
 * g_object_newv:
2843
 * @object_type: the type id of the #GObject subtype to instantiate
2844
 * @n_parameters: the length of the @parameters array
2845
 * @parameters: (array length=n_parameters): an array of #GParameter
2846
 *
2847
 * Creates a new instance of a #GObject subtype and sets its properties.
2848
 *
2849
 * Construction parameters (see %G_PARAM_CONSTRUCT, %G_PARAM_CONSTRUCT_ONLY)
2850
 * which are not explicitly specified are set to their default values.
2851
 *
2852
 * Returns: (type GObject.Object) (transfer full): a new instance of
2853
 * @object_type
2854
 *
2855
 * Deprecated: 2.54: Use g_object_new_with_properties() instead.
2856
 * deprecated. See #GParameter for more information.
2857
 */
2858
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
2859
gpointer
2860
g_object_newv (GType       object_type,
2861
               guint       n_parameters,
2862
               GParameter *parameters)
2863
0
{
2864
0
  GObjectClass *class, *unref_class = NULL;
2865
0
  GObject *object;
2866
2867
0
  g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
2868
0
  g_return_val_if_fail (n_parameters == 0 || parameters != NULL, NULL);
2869
2870
  /* Try to avoid thrashing the ref_count if we don't need to (since
2871
   * it's a locked operation).
2872
   */
2873
0
  class = g_type_class_peek_static (object_type);
2874
2875
0
  if (!class)
2876
0
    class = unref_class = g_type_class_ref (object_type);
2877
2878
0
  if (n_parameters)
2879
0
    {
2880
0
      GObjectConstructParam *cparams;
2881
0
      guint i, j;
2882
2883
0
      cparams = g_newa (GObjectConstructParam, n_parameters);
2884
0
      j = 0;
2885
2886
0
      for (i = 0; i < n_parameters; i++)
2887
0
        {
2888
0
          GParamSpec *pspec = find_pspec (class, parameters[i].name);
2889
2890
0
          if (!g_object_new_is_valid_property (object_type, pspec, parameters[i].name, cparams, j))
2891
0
            continue;
2892
2893
0
          cparams[j].pspec = pspec;
2894
0
          cparams[j].value = &parameters[i].value;
2895
0
          j++;
2896
0
        }
2897
2898
0
      object = g_object_new_internal (class, cparams, j);
2899
0
    }
2900
0
  else
2901
    /* Fast case: no properties passed in. */
2902
0
    object = g_object_new_internal (class, NULL, 0);
2903
2904
0
  if (unref_class)
2905
0
    g_type_class_unref (unref_class);
2906
2907
0
  return object;
2908
0
}
2909
G_GNUC_END_IGNORE_DEPRECATIONS
2910
2911
/**
2912
 * g_object_new_valist: (skip)
2913
 * @object_type: the type id of the #GObject subtype to instantiate
2914
 * @first_property_name: the name of the first property
2915
 * @var_args: the value of the first property, followed optionally by more
2916
 *  name/value pairs, followed by %NULL
2917
 *
2918
 * Creates a new instance of a #GObject subtype and sets its properties.
2919
 *
2920
 * Construction parameters (see %G_PARAM_CONSTRUCT, %G_PARAM_CONSTRUCT_ONLY)
2921
 * which are not explicitly specified are set to their default values.
2922
 *
2923
 * Returns: a new instance of @object_type
2924
 */
2925
GObject*
2926
g_object_new_valist (GType        object_type,
2927
                     const gchar *first_property_name,
2928
                     va_list      var_args)
2929
0
{
2930
0
  GObjectClass *class, *unref_class = NULL;
2931
0
  GObject *object;
2932
2933
0
  g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
2934
2935
  /* Try to avoid thrashing the ref_count if we don't need to (since
2936
   * it's a locked operation).
2937
   */
2938
0
  class = g_type_class_peek_static (object_type);
2939
2940
0
  if (!class)
2941
0
    class = unref_class = g_type_class_ref (object_type);
2942
2943
0
  if (first_property_name)
2944
0
    {
2945
0
      GObjectConstructParam params_stack[16];
2946
0
      GValue values_stack[G_N_ELEMENTS (params_stack)];
2947
0
      GTypeValueTable *vtabs_stack[G_N_ELEMENTS (params_stack)];
2948
0
      const gchar *name;
2949
0
      GObjectConstructParam *params = params_stack;
2950
0
      GValue *values = values_stack;
2951
0
      GTypeValueTable **vtabs = vtabs_stack;
2952
0
      guint n_params = 0;
2953
0
      guint n_params_alloc = G_N_ELEMENTS (params_stack);
2954
2955
0
      name = first_property_name;
2956
2957
0
      do
2958
0
        {
2959
0
          gchar *error = NULL;
2960
0
          GParamSpec *pspec = find_pspec (class, name);
2961
2962
0
          if (!g_object_new_is_valid_property (object_type, pspec, name, params, n_params))
2963
0
            break;
2964
2965
0
          if (G_UNLIKELY (n_params == n_params_alloc))
2966
0
            {
2967
0
              guint i;
2968
2969
0
              if (n_params_alloc == G_N_ELEMENTS (params_stack))
2970
0
                {
2971
0
                  n_params_alloc = G_N_ELEMENTS (params_stack) * 2u;
2972
0
                  params = g_new (GObjectConstructParam, n_params_alloc);
2973
0
                  values = g_new (GValue, n_params_alloc);
2974
0
                  vtabs = g_new (GTypeValueTable *, n_params_alloc);
2975
0
                  memcpy (params, params_stack, sizeof (GObjectConstructParam) * n_params);
2976
0
                  memcpy (values, values_stack, sizeof (GValue) * n_params);
2977
0
                  memcpy (vtabs, vtabs_stack, sizeof (GTypeValueTable *) * n_params);
2978
0
                }
2979
0
              else
2980
0
                {
2981
0
                  n_params_alloc *= 2u;
2982
0
                  params = g_realloc (params, sizeof (GObjectConstructParam) * n_params_alloc);
2983
0
                  values = g_realloc (values, sizeof (GValue) * n_params_alloc);
2984
0
                  vtabs = g_realloc (vtabs, sizeof (GTypeValueTable *) * n_params_alloc);
2985
0
                }
2986
2987
0
              for (i = 0; i < n_params; i++)
2988
0
                params[i].value = &values[i];
2989
0
            }
2990
2991
0
          params[n_params].pspec = pspec;
2992
0
          params[n_params].value = &values[n_params];
2993
0
          memset (&values[n_params], 0, sizeof (GValue));
2994
2995
0
          G_VALUE_COLLECT_INIT2 (&values[n_params], vtabs[n_params], pspec->value_type, var_args, G_VALUE_NOCOPY_CONTENTS, &error);
2996
2997
0
          if (error)
2998
0
            {
2999
0
              g_critical ("%s: %s", G_STRFUNC, error);
3000
0
              g_value_unset (&values[n_params]);
3001
0
              g_free (error);
3002
0
              break;
3003
0
            }
3004
3005
0
          n_params++;
3006
0
        }
3007
0
      while ((name = va_arg (var_args, const gchar *)));
3008
3009
0
      object = g_object_new_internal (class, params, n_params);
3010
3011
0
      while (n_params--)
3012
0
        {
3013
          /* We open-code g_value_unset() here to avoid the
3014
           * cost of looking up the GTypeValueTable again.
3015
           */
3016
0
          if (vtabs[n_params]->value_free)
3017
0
            vtabs[n_params]->value_free (params[n_params].value);
3018
0
        }
3019
3020
0
      if (G_UNLIKELY (n_params_alloc != G_N_ELEMENTS (params_stack)))
3021
0
        {
3022
0
          g_free (params);
3023
0
          g_free (values);
3024
0
          g_free (vtabs);
3025
0
        }
3026
0
    }
3027
0
  else
3028
    /* Fast case: no properties passed in. */
3029
0
    object = g_object_new_internal (class, NULL, 0);
3030
3031
0
  if (unref_class)
3032
0
    g_type_class_unref (unref_class);
3033
3034
0
  return object;
3035
0
}
3036
3037
static GObject*
3038
g_object_constructor (GType                  type,
3039
          guint                  n_construct_properties,
3040
          GObjectConstructParam *construct_params)
3041
0
{
3042
0
  GObject *object;
3043
3044
  /* create object */
3045
0
  object = (GObject*) g_type_create_instance (type);
3046
  
3047
  /* set construction parameters */
3048
0
  if (n_construct_properties)
3049
0
    {
3050
0
      g_object_notify_queue_freeze (object, TRUE);
3051
      
3052
      /* set construct properties */
3053
0
      while (n_construct_properties--)
3054
0
  {
3055
0
    GValue *value = construct_params->value;
3056
0
    GParamSpec *pspec = construct_params->pspec;
3057
3058
0
    construct_params++;
3059
0
    object_set_property (object, pspec, value, TRUE, FALSE);
3060
0
  }
3061
3062
0
      g_object_notify_queue_thaw (object, FALSE);
3063
      /* the notification queue is still frozen from g_object_init(), so
3064
       * we don't need to handle it here, g_object_newv() takes
3065
       * care of that
3066
       */
3067
0
    }
3068
3069
0
  return object;
3070
0
}
3071
3072
static void
3073
g_object_constructed (GObject *object)
3074
0
{
3075
  /* empty default impl to allow unconditional upchaining */
3076
0
}
3077
3078
static inline gboolean
3079
g_object_set_is_valid_property (GObject         *object,
3080
                                GParamSpec      *pspec,
3081
                                const char      *property_name)
3082
0
{
3083
0
  if (G_UNLIKELY (pspec == NULL))
3084
0
    {
3085
0
      g_critical ("%s: object class '%s' has no property named '%s'",
3086
0
                  G_STRFUNC, G_OBJECT_TYPE_NAME (object), property_name);
3087
0
      return FALSE;
3088
0
    }
3089
0
  if (G_UNLIKELY (!(pspec->flags & G_PARAM_WRITABLE)))
3090
0
    {
3091
0
      g_critical ("%s: property '%s' of object class '%s' is not writable",
3092
0
                  G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
3093
0
      return FALSE;
3094
0
    }
3095
0
  if (G_UNLIKELY (((pspec->flags & G_PARAM_CONSTRUCT_ONLY) && !object_in_construction (object))))
3096
0
    {
3097
0
      g_critical ("%s: construct property \"%s\" for object '%s' can't be set after construction",
3098
0
                  G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
3099
0
      return FALSE;
3100
0
    }
3101
0
  return TRUE;
3102
0
}
3103
3104
/**
3105
 * g_object_setv: (skip)
3106
 * @object: a #GObject
3107
 * @n_properties: the number of properties
3108
 * @names: (array length=n_properties): the names of each property to be set
3109
 * @values: (array length=n_properties): the values of each property to be set
3110
 *
3111
 * Sets @n_properties properties for an @object.
3112
 * Properties to be set will be taken from @values. All properties must be
3113
 * valid. Warnings will be emitted and undefined behaviour may result if invalid
3114
 * properties are passed in.
3115
 *
3116
 * Since: 2.54
3117
 */
3118
void
3119
g_object_setv (GObject       *object,
3120
               guint          n_properties,
3121
               const gchar   *names[],
3122
               const GValue   values[])
3123
0
{
3124
0
  guint i;
3125
0
  gboolean nqueue_is_frozen = FALSE;
3126
0
  GParamSpec *pspec;
3127
0
  GObjectClass *class;
3128
3129
0
  g_return_if_fail (G_IS_OBJECT (object));
3130
3131
0
  if (n_properties == 0)
3132
0
    return;
3133
3134
0
  g_object_ref (object);
3135
3136
0
  class = G_OBJECT_GET_CLASS (object);
3137
3138
0
  if (_g_object_has_notify_handler (object))
3139
0
    {
3140
0
      g_object_notify_queue_freeze (object, TRUE);
3141
0
      nqueue_is_frozen = TRUE;
3142
0
    }
3143
3144
0
  for (i = 0; i < n_properties; i++)
3145
0
    {
3146
0
      pspec = find_pspec (class, names[i]);
3147
3148
0
      if (!g_object_set_is_valid_property (object, pspec, names[i]))
3149
0
        break;
3150
3151
0
      object_set_property (object, pspec, &values[i], nqueue_is_frozen, TRUE);
3152
0
    }
3153
3154
0
  if (nqueue_is_frozen)
3155
0
    g_object_notify_queue_thaw (object, FALSE);
3156
3157
0
  g_object_unref (object);
3158
0
}
3159
3160
/**
3161
 * g_object_set_valist: (skip)
3162
 * @object: a #GObject
3163
 * @first_property_name: name of the first property to set
3164
 * @var_args: value for the first property, followed optionally by more
3165
 *  name/value pairs, followed by %NULL
3166
 *
3167
 * Sets properties on an object.
3168
 */
3169
void
3170
g_object_set_valist (GObject   *object,
3171
         const gchar *first_property_name,
3172
         va_list    var_args)
3173
0
{
3174
0
  gboolean nqueue_is_frozen = FALSE;
3175
0
  const gchar *name;
3176
0
  GObjectClass *class;
3177
  
3178
0
  g_return_if_fail (G_IS_OBJECT (object));
3179
3180
0
  g_object_ref (object);
3181
3182
0
  if (_g_object_has_notify_handler (object))
3183
0
    {
3184
0
      g_object_notify_queue_freeze (object, TRUE);
3185
0
      nqueue_is_frozen = TRUE;
3186
0
    }
3187
3188
0
  class = G_OBJECT_GET_CLASS (object);
3189
3190
0
  name = first_property_name;
3191
0
  while (name)
3192
0
    {
3193
0
      GValue value = G_VALUE_INIT;
3194
0
      GParamSpec *pspec;
3195
0
      gchar *error = NULL;
3196
0
      GTypeValueTable *vtab;
3197
      
3198
0
      pspec = find_pspec (class, name);
3199
3200
0
      if (!g_object_set_is_valid_property (object, pspec, name))
3201
0
        break;
3202
3203
0
      G_VALUE_COLLECT_INIT2 (&value, vtab, pspec->value_type, var_args, G_VALUE_NOCOPY_CONTENTS, &error);
3204
0
      if (error)
3205
0
  {
3206
0
    g_critical ("%s: %s", G_STRFUNC, error);
3207
0
    g_free (error);
3208
0
          g_value_unset (&value);
3209
0
    break;
3210
0
  }
3211
3212
0
      object_set_property (object, pspec, &value, nqueue_is_frozen, TRUE);
3213
3214
      /* We open-code g_value_unset() here to avoid the
3215
       * cost of looking up the GTypeValueTable again.
3216
       */
3217
0
      if (vtab->value_free)
3218
0
        vtab->value_free (&value);
3219
3220
0
      name = va_arg (var_args, gchar*);
3221
0
    }
3222
3223
0
  if (nqueue_is_frozen)
3224
0
    g_object_notify_queue_thaw (object, FALSE);
3225
3226
0
  g_object_unref (object);
3227
0
}
3228
3229
static inline gboolean
3230
g_object_get_is_valid_property (GObject          *object,
3231
                                GParamSpec       *pspec,
3232
                                const char       *property_name)
3233
0
{
3234
0
  if (G_UNLIKELY (pspec == NULL))
3235
0
    {
3236
0
      g_critical ("%s: object class '%s' has no property named '%s'",
3237
0
                  G_STRFUNC, G_OBJECT_TYPE_NAME (object), property_name);
3238
0
      return FALSE;
3239
0
    }
3240
0
  if (G_UNLIKELY (!(pspec->flags & G_PARAM_READABLE)))
3241
0
    {
3242
0
      g_critical ("%s: property '%s' of object class '%s' is not readable",
3243
0
                  G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
3244
0
      return FALSE;
3245
0
    }
3246
0
  return TRUE;
3247
0
}
3248
3249
/**
3250
 * g_object_getv:
3251
 * @object: a #GObject
3252
 * @n_properties: the number of properties
3253
 * @names: (array length=n_properties): the names of each property to get
3254
 * @values: (array length=n_properties): the values of each property to get
3255
 *
3256
 * Gets @n_properties properties for an @object.
3257
 * Obtained properties will be set to @values. All properties must be valid.
3258
 * Warnings will be emitted and undefined behaviour may result if invalid
3259
 * properties are passed in.
3260
 *
3261
 * Since: 2.54
3262
 */
3263
void
3264
g_object_getv (GObject      *object,
3265
               guint         n_properties,
3266
               const gchar  *names[],
3267
               GValue        values[])
3268
0
{
3269
0
  guint i;
3270
0
  GParamSpec *pspec;
3271
0
  GObjectClass *class;
3272
3273
0
  g_return_if_fail (G_IS_OBJECT (object));
3274
3275
0
  if (n_properties == 0)
3276
0
    return;
3277
3278
0
  g_object_ref (object);
3279
3280
0
  class = G_OBJECT_GET_CLASS (object);
3281
3282
0
  memset (values, 0, n_properties * sizeof (GValue));
3283
3284
0
  for (i = 0; i < n_properties; i++)
3285
0
    {
3286
0
      pspec = find_pspec (class, names[i]);
3287
3288
0
      if (!g_object_get_is_valid_property (object, pspec, names[i]))
3289
0
        break;
3290
0
      g_value_init (&values[i], pspec->value_type);
3291
0
      object_get_property (object, pspec, &values[i]);
3292
0
    }
3293
0
  g_object_unref (object);
3294
0
}
3295
3296
/**
3297
 * g_object_get_valist: (skip)
3298
 * @object: a #GObject
3299
 * @first_property_name: name of the first property to get
3300
 * @var_args: return location for the first property, followed optionally by more
3301
 *  name/return location pairs, followed by %NULL
3302
 *
3303
 * Gets properties of an object.
3304
 *
3305
 * In general, a copy is made of the property contents and the caller
3306
 * is responsible for freeing the memory in the appropriate manner for
3307
 * the type, for instance by calling g_free() or g_object_unref().
3308
 *
3309
 * See g_object_get().
3310
 */
3311
void
3312
g_object_get_valist (GObject   *object,
3313
         const gchar *first_property_name,
3314
         va_list    var_args)
3315
0
{
3316
0
  const gchar *name;
3317
0
  GObjectClass *class;
3318
  
3319
0
  g_return_if_fail (G_IS_OBJECT (object));
3320
  
3321
0
  g_object_ref (object);
3322
3323
0
  class = G_OBJECT_GET_CLASS (object);
3324
3325
0
  name = first_property_name;
3326
3327
0
  while (name)
3328
0
    {
3329
0
      GValue value = G_VALUE_INIT;
3330
0
      GParamSpec *pspec;
3331
0
      gchar *error;
3332
3333
0
      pspec = find_pspec (class, name);
3334
3335
0
      if (!g_object_get_is_valid_property (object, pspec, name))
3336
0
        break;
3337
      
3338
0
      g_value_init (&value, pspec->value_type);
3339
      
3340
0
      object_get_property (object, pspec, &value);
3341
      
3342
0
      G_VALUE_LCOPY (&value, var_args, 0, &error);
3343
0
      if (error)
3344
0
  {
3345
0
    g_critical ("%s: %s", G_STRFUNC, error);
3346
0
    g_free (error);
3347
0
    g_value_unset (&value);
3348
0
    break;
3349
0
  }
3350
      
3351
0
      g_value_unset (&value);
3352
      
3353
0
      name = va_arg (var_args, gchar*);
3354
0
    }
3355
  
3356
0
  g_object_unref (object);
3357
0
}
3358
3359
/**
3360
 * g_object_set: (skip)
3361
 * @object: (type GObject.Object): a #GObject
3362
 * @first_property_name: name of the first property to set
3363
 * @...: value for the first property, followed optionally by more
3364
 *  name/value pairs, followed by %NULL
3365
 *
3366
 * Sets properties on an object.
3367
 *
3368
 * The same caveats about passing integer literals as varargs apply as with
3369
 * g_object_new(). In particular, any integer literals set as the values for
3370
 * properties of type #gint64 or #guint64 must be 64 bits wide, using the
3371
 * %G_GINT64_CONSTANT or %G_GUINT64_CONSTANT macros.
3372
 *
3373
 * Note that the "notify" signals are queued and only emitted (in
3374
 * reverse order) after all properties have been set. See
3375
 * g_object_freeze_notify().
3376
 */
3377
void
3378
g_object_set (gpointer     _object,
3379
        const gchar *first_property_name,
3380
        ...)
3381
0
{
3382
0
  GObject *object = _object;
3383
0
  va_list var_args;
3384
  
3385
0
  g_return_if_fail (G_IS_OBJECT (object));
3386
  
3387
0
  va_start (var_args, first_property_name);
3388
0
  g_object_set_valist (object, first_property_name, var_args);
3389
0
  va_end (var_args);
3390
0
}
3391
3392
/**
3393
 * g_object_get: (skip)
3394
 * @object: (type GObject.Object): a #GObject
3395
 * @first_property_name: name of the first property to get
3396
 * @...: return location for the first property, followed optionally by more
3397
 *  name/return location pairs, followed by %NULL
3398
 *
3399
 * Gets properties of an object.
3400
 *
3401
 * In general, a copy is made of the property contents and the caller
3402
 * is responsible for freeing the memory in the appropriate manner for
3403
 * the type, for instance by calling g_free() or g_object_unref().
3404
 *
3405
 * Here is an example of using g_object_get() to get the contents
3406
 * of three properties: an integer, a string and an object:
3407
 * |[<!-- language="C" --> 
3408
 *  gint intval;
3409
 *  guint64 uint64val;
3410
 *  gchar *strval;
3411
 *  GObject *objval;
3412
 *
3413
 *  g_object_get (my_object,
3414
 *                "int-property", &intval,
3415
 *                "uint64-property", &uint64val,
3416
 *                "str-property", &strval,
3417
 *                "obj-property", &objval,
3418
 *                NULL);
3419
 *
3420
 *  // Do something with intval, uint64val, strval, objval
3421
 *
3422
 *  g_free (strval);
3423
 *  g_object_unref (objval);
3424
 * ]|
3425
 */
3426
void
3427
g_object_get (gpointer     _object,
3428
        const gchar *first_property_name,
3429
        ...)
3430
0
{
3431
0
  GObject *object = _object;
3432
0
  va_list var_args;
3433
  
3434
0
  g_return_if_fail (G_IS_OBJECT (object));
3435
  
3436
0
  va_start (var_args, first_property_name);
3437
0
  g_object_get_valist (object, first_property_name, var_args);
3438
0
  va_end (var_args);
3439
0
}
3440
3441
/**
3442
 * g_object_set_property:
3443
 * @object: a #GObject
3444
 * @property_name: the name of the property to set
3445
 * @value: the value
3446
 *
3447
 * Sets a property on an object.
3448
 */
3449
void
3450
g_object_set_property (GObject      *object,
3451
           const gchar  *property_name,
3452
           const GValue *value)
3453
0
{
3454
0
  g_object_setv (object, 1, &property_name, value);
3455
0
}
3456
3457
/**
3458
 * g_object_get_property:
3459
 * @object: a #GObject
3460
 * @property_name: the name of the property to get
3461
 * @value: return location for the property value
3462
 *
3463
 * Gets a property of an object.
3464
 *
3465
 * The @value can be:
3466
 *
3467
 *  - an empty #GValue initialized by %G_VALUE_INIT, which will be
3468
 *    automatically initialized with the expected type of the property
3469
 *    (since GLib 2.60)
3470
 *  - a #GValue initialized with the expected type of the property
3471
 *  - a #GValue initialized with a type to which the expected type
3472
 *    of the property can be transformed
3473
 *
3474
 * In general, a copy is made of the property contents and the caller is
3475
 * responsible for freeing the memory by calling g_value_unset().
3476
 *
3477
 * Note that g_object_get_property() is really intended for language
3478
 * bindings, g_object_get() is much more convenient for C programming.
3479
 */
3480
void
3481
g_object_get_property (GObject     *object,
3482
           const gchar *property_name,
3483
           GValue    *value)
3484
0
{
3485
0
  GParamSpec *pspec;
3486
  
3487
0
  g_return_if_fail (G_IS_OBJECT (object));
3488
0
  g_return_if_fail (property_name != NULL);
3489
0
  g_return_if_fail (value != NULL);
3490
  
3491
0
  g_object_ref (object);
3492
  
3493
0
  pspec = find_pspec (G_OBJECT_GET_CLASS (object), property_name);
3494
3495
0
  if (g_object_get_is_valid_property (object, pspec, property_name))
3496
0
    {
3497
0
      GValue *prop_value, tmp_value = G_VALUE_INIT;
3498
      
3499
0
      if (G_VALUE_TYPE (value) == G_TYPE_INVALID)
3500
0
        {
3501
          /* zero-initialized value */
3502
0
          g_value_init (value, pspec->value_type);
3503
0
          prop_value = value;
3504
0
        }
3505
0
      else if (G_VALUE_TYPE (value) == pspec->value_type)
3506
0
        {
3507
          /* auto-conversion of the callers value type */
3508
0
          g_value_reset (value);
3509
0
          prop_value = value;
3510
0
        }
3511
0
      else if (!g_value_type_transformable (pspec->value_type, G_VALUE_TYPE (value)))
3512
0
        {
3513
0
          g_critical ("%s: can't retrieve property '%s' of type '%s' as value of type '%s'",
3514
0
                      G_STRFUNC, pspec->name,
3515
0
                      g_type_name (pspec->value_type),
3516
0
                      G_VALUE_TYPE_NAME (value));
3517
0
          g_object_unref (object);
3518
0
          return;
3519
0
        }
3520
0
      else
3521
0
        {
3522
0
          g_value_init (&tmp_value, pspec->value_type);
3523
0
          prop_value = &tmp_value;
3524
0
        }
3525
0
      object_get_property (object, pspec, prop_value);
3526
0
      if (prop_value != value)
3527
0
        {
3528
0
          g_value_transform (prop_value, value);
3529
0
          g_value_unset (&tmp_value);
3530
0
        }
3531
0
    }
3532
  
3533
0
  g_object_unref (object);
3534
0
}
3535
3536
/**
3537
 * g_object_connect: (skip)
3538
 * @object: (type GObject.Object): a #GObject
3539
 * @signal_spec: the spec for the first signal
3540
 * @...: [type@GObject.Callback] for the first signal, followed by data for the
3541
 *   first signal, followed optionally by more signal
3542
 *   spec/callback/data triples, followed by `NULL`
3543
 *
3544
 * A convenience function to connect multiple signals at once.
3545
 *
3546
 * The signal specs expected by this function have the form
3547
 * `modifier::signal_name`, where `modifier` can be one of the
3548
 * following:
3549
 *
3550
 * - `signal`: equivalent to `g_signal_connect_data (..., NULL, G_CONNECT_DEFAULT)`
3551
 * - `object-signal`, `object_signal`: equivalent to `g_signal_connect_object (..., G_CONNECT_DEFAULT)`
3552
 * - `swapped-signal`, `swapped_signal`: equivalent to `g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED)`
3553
 * - `swapped_object_signal`, `swapped-object-signal`: equivalent to `g_signal_connect_object (..., G_CONNECT_SWAPPED)`
3554
 * - `signal_after`, `signal-after`: equivalent to `g_signal_connect_data (..., NULL, G_CONNECT_AFTER)`
3555
 * - `object_signal_after`, `object-signal-after`: equivalent to `g_signal_connect_object (..., G_CONNECT_AFTER)`
3556
 * - `swapped_signal_after`, `swapped-signal-after`: equivalent to `g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED | G_CONNECT_AFTER)`
3557
 * - `swapped_object_signal_after`, `swapped-object-signal-after`: equivalent to `g_signal_connect_object (..., G_CONNECT_SWAPPED | G_CONNECT_AFTER)`
3558
 *
3559
 * ```c
3560
 * menu->toplevel = g_object_connect (g_object_new (GTK_TYPE_WINDOW,
3561
 *                                                  "type", GTK_WINDOW_POPUP,
3562
 *                                                  "child", menu,
3563
 *                                                  NULL),
3564
 *                                    "signal::event", gtk_menu_window_event, menu,
3565
 *                                    "signal::size_request", gtk_menu_window_size_request, menu,
3566
 *                                    "signal::destroy", gtk_widget_destroyed, &menu->toplevel,
3567
 *                                    NULL);
3568
 * ```
3569
 *
3570
 * Returns: (transfer none) (type GObject.Object): the object
3571
 */
3572
gpointer
3573
g_object_connect (gpointer     _object,
3574
      const gchar *signal_spec,
3575
      ...)
3576
0
{
3577
0
  GObject *object = _object;
3578
0
  va_list var_args;
3579
3580
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3581
0
  g_return_val_if_fail (object->ref_count > 0, object);
3582
3583
0
  va_start (var_args, signal_spec);
3584
0
  while (signal_spec)
3585
0
    {
3586
0
      GCallback callback = va_arg (var_args, GCallback);
3587
0
      gpointer data = va_arg (var_args, gpointer);
3588
3589
0
      if (strncmp (signal_spec, "signal::", 8) == 0)
3590
0
  g_signal_connect_data (object, signal_spec + 8,
3591
0
             callback, data, NULL,
3592
0
             G_CONNECT_DEFAULT);
3593
0
      else if (strncmp (signal_spec, "object_signal::", 15) == 0 ||
3594
0
               strncmp (signal_spec, "object-signal::", 15) == 0)
3595
0
  g_signal_connect_object (object, signal_spec + 15,
3596
0
         callback, data,
3597
0
         G_CONNECT_DEFAULT);
3598
0
      else if (strncmp (signal_spec, "swapped_signal::", 16) == 0 ||
3599
0
               strncmp (signal_spec, "swapped-signal::", 16) == 0)
3600
0
  g_signal_connect_data (object, signal_spec + 16,
3601
0
             callback, data, NULL,
3602
0
             G_CONNECT_SWAPPED);
3603
0
      else if (strncmp (signal_spec, "swapped_object_signal::", 23) == 0 ||
3604
0
               strncmp (signal_spec, "swapped-object-signal::", 23) == 0)
3605
0
  g_signal_connect_object (object, signal_spec + 23,
3606
0
         callback, data,
3607
0
         G_CONNECT_SWAPPED);
3608
0
      else if (strncmp (signal_spec, "signal_after::", 14) == 0 ||
3609
0
               strncmp (signal_spec, "signal-after::", 14) == 0)
3610
0
  g_signal_connect_data (object, signal_spec + 14,
3611
0
             callback, data, NULL,
3612
0
             G_CONNECT_AFTER);
3613
0
      else if (strncmp (signal_spec, "object_signal_after::", 21) == 0 ||
3614
0
               strncmp (signal_spec, "object-signal-after::", 21) == 0)
3615
0
  g_signal_connect_object (object, signal_spec + 21,
3616
0
         callback, data,
3617
0
         G_CONNECT_AFTER);
3618
0
      else if (strncmp (signal_spec, "swapped_signal_after::", 22) == 0 ||
3619
0
               strncmp (signal_spec, "swapped-signal-after::", 22) == 0)
3620
0
  g_signal_connect_data (object, signal_spec + 22,
3621
0
             callback, data, NULL,
3622
0
             G_CONNECT_SWAPPED | G_CONNECT_AFTER);
3623
0
      else if (strncmp (signal_spec, "swapped_object_signal_after::", 29) == 0 ||
3624
0
               strncmp (signal_spec, "swapped-object-signal-after::", 29) == 0)
3625
0
  g_signal_connect_object (object, signal_spec + 29,
3626
0
         callback, data,
3627
0
         G_CONNECT_SWAPPED | G_CONNECT_AFTER);
3628
0
      else
3629
0
  {
3630
0
    g_critical ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
3631
0
    break;
3632
0
  }
3633
0
      signal_spec = va_arg (var_args, gchar*);
3634
0
    }
3635
0
  va_end (var_args);
3636
3637
0
  return object;
3638
0
}
3639
3640
/**
3641
 * g_object_disconnect: (skip)
3642
 * @object: (type GObject.Object): a #GObject
3643
 * @signal_spec: the spec for the first signal
3644
 * @...: #GCallback for the first signal, followed by data for the first signal,
3645
 *  followed optionally by more signal spec/callback/data triples,
3646
 *  followed by %NULL
3647
 *
3648
 * A convenience function to disconnect multiple signals at once.
3649
 *
3650
 * The signal specs expected by this function have the form
3651
 * "any_signal", which means to disconnect any signal with matching
3652
 * callback and data, or "any_signal::signal_name", which only
3653
 * disconnects the signal named "signal_name".
3654
 */
3655
void
3656
g_object_disconnect (gpointer     _object,
3657
         const gchar *signal_spec,
3658
         ...)
3659
0
{
3660
0
  GObject *object = _object;
3661
0
  va_list var_args;
3662
3663
0
  g_return_if_fail (G_IS_OBJECT (object));
3664
0
  g_return_if_fail (object->ref_count > 0);
3665
3666
0
  va_start (var_args, signal_spec);
3667
0
  while (signal_spec)
3668
0
    {
3669
0
      GCallback callback = va_arg (var_args, GCallback);
3670
0
      gpointer data = va_arg (var_args, gpointer);
3671
0
      guint sid = 0, detail = 0, mask = 0;
3672
3673
0
      if (strncmp (signal_spec, "any_signal::", 12) == 0 ||
3674
0
          strncmp (signal_spec, "any-signal::", 12) == 0)
3675
0
  {
3676
0
    signal_spec += 12;
3677
0
    mask = G_SIGNAL_MATCH_ID | G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
3678
0
  }
3679
0
      else if (strcmp (signal_spec, "any_signal") == 0 ||
3680
0
               strcmp (signal_spec, "any-signal") == 0)
3681
0
  {
3682
0
    signal_spec += 10;
3683
0
    mask = G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
3684
0
  }
3685
0
      else
3686
0
  {
3687
0
    g_critical ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
3688
0
    break;
3689
0
  }
3690
3691
0
      if ((mask & G_SIGNAL_MATCH_ID) &&
3692
0
    !g_signal_parse_name (signal_spec, G_OBJECT_TYPE (object), &sid, &detail, FALSE))
3693
0
  g_critical ("%s: invalid signal name \"%s\"", G_STRFUNC, signal_spec);
3694
0
      else if (!g_signal_handlers_disconnect_matched (object, mask | (detail ? G_SIGNAL_MATCH_DETAIL : 0),
3695
0
                  sid, detail,
3696
0
                  NULL, (gpointer)callback, data))
3697
0
  g_critical ("%s: signal handler %p(%p) is not connected", G_STRFUNC, callback, data);
3698
0
      signal_spec = va_arg (var_args, gchar*);
3699
0
    }
3700
0
  va_end (var_args);
3701
0
}
3702
3703
typedef struct
3704
{
3705
  GWeakNotify notify;
3706
  gpointer data;
3707
} WeakRefTuple;
3708
3709
struct _WeakRefReleaseAllState;
3710
3711
typedef struct _WeakRefReleaseAllState
3712
{
3713
  guint remaining_to_notify;
3714
  struct _WeakRefReleaseAllState *release_all_next;
3715
} WeakRefReleaseAllState;
3716
3717
typedef struct
3718
{
3719
  guint n_weak_refs;
3720
  guint alloc_size;
3721
  WeakRefReleaseAllState *release_all_states;
3722
  WeakRefTuple weak_refs[1]; /* flexible array */
3723
} WeakRefStack;
3724
3725
0
#define WEAK_REF_STACK_ALLOC_SIZE(alloc_size) (G_STRUCT_OFFSET (WeakRefStack, weak_refs) + sizeof (WeakRefTuple) * (alloc_size))
3726
3727
G_GNUC_UNUSED G_ALWAYS_INLINE static inline gboolean
3728
_weak_ref_release_all_state_contains (WeakRefReleaseAllState *release_all_state, WeakRefReleaseAllState *needle)
3729
0
{
3730
0
  for (; release_all_state; release_all_state = release_all_state->release_all_next)
3731
0
    {
3732
0
      if (release_all_state == needle)
3733
0
        return TRUE;
3734
0
    }
3735
0
  return FALSE;
3736
0
}
3737
3738
G_ALWAYS_INLINE static inline void
3739
_weak_ref_stack_free (WeakRefStack *wstack)
3740
0
{
3741
0
#ifdef G_ENABLE_DEBUG
3742
0
  g_assert (!wstack->release_all_states);
3743
0
#endif
3744
0
  g_free (wstack);
3745
0
}
3746
3747
G_ALWAYS_INLINE static inline void
3748
_weak_ref_stack_update_release_all_state (WeakRefStack *wstack, guint idx)
3749
0
{
3750
0
  WeakRefReleaseAllState **previous_ptr;
3751
0
  WeakRefReleaseAllState *release_all_state;
3752
3753
0
#ifdef G_ENABLE_DEBUG
3754
0
  g_assert (idx < wstack->n_weak_refs);
3755
0
#endif
3756
3757
0
  previous_ptr = &wstack->release_all_states;
3758
3759
0
  while (G_UNLIKELY ((release_all_state = *previous_ptr)))
3760
0
    {
3761
0
      if (idx >= release_all_state->remaining_to_notify)
3762
0
        {
3763
0
#ifdef G_ENABLE_DEBUG
3764
0
          g_assert (release_all_state->remaining_to_notify <= wstack->n_weak_refs);
3765
0
#endif
3766
          /* We removed an index higher than the "remaining_to_notify" count. */
3767
0
          goto next;
3768
0
        }
3769
3770
      /* Lower the "remaining_to_notify" bar of the entries we consider, as we
3771
       * just removed an entry at index @idx (below that bar). */
3772
0
      release_all_state->remaining_to_notify--;
3773
3774
0
      if (release_all_state->remaining_to_notify > 0)
3775
0
        goto next;
3776
3777
      /* Remove the entry from the linked list. No need to reset
3778
       * release_all_state->release_all_next pointer to NULL as it has no
3779
       * purpose when not being linked. */
3780
0
      *previous_ptr = release_all_state->release_all_next;
3781
0
      continue;
3782
3783
0
    next:
3784
0
      previous_ptr = &release_all_state->release_all_next;
3785
0
    }
3786
0
}
3787
3788
static gpointer
3789
g_object_weak_ref_cb (gpointer *data,
3790
                      GDestroyNotify *destroy_notify,
3791
                      gpointer user_data)
3792
0
{
3793
0
  WeakRefTuple *tuple = user_data;
3794
0
  WeakRefStack *wstack = *data;
3795
0
  guint i;
3796
3797
0
  if (!wstack)
3798
0
    {
3799
0
      wstack = g_malloc (WEAK_REF_STACK_ALLOC_SIZE (1));
3800
0
      wstack->alloc_size = 1;
3801
0
      wstack->n_weak_refs = 1;
3802
0
      wstack->release_all_states = NULL;
3803
0
      i = 0;
3804
3805
0
      *data = wstack;
3806
      /* We don't set a @destroy_notify. Shortly before finalize(), we call
3807
       * g_object_weak_release_all(), which frees the WeakRefStack. At that
3808
       * point the ref-count is already at zero and g_object_weak_ref() will
3809
       * assert against being called. This means, we expect that there is
3810
       * never anything to destroy. */
3811
0
#ifdef G_ENABLE_DEBUG
3812
0
      *destroy_notify = g_destroy_notify_assert_not_reached;
3813
0
#endif
3814
0
    }
3815
0
  else
3816
0
    {
3817
0
      i = wstack->n_weak_refs++;
3818
3819
0
      if (G_UNLIKELY (wstack->n_weak_refs > wstack->alloc_size))
3820
0
        {
3821
0
          if (G_UNLIKELY (wstack->alloc_size >= (G_MAXUINT / 2u + 1u)))
3822
0
            g_error ("g_object_weak_ref(): cannot register more than 2^31 references");
3823
0
          wstack->alloc_size = wstack->alloc_size * 2u;
3824
3825
0
          wstack = g_realloc (wstack, WEAK_REF_STACK_ALLOC_SIZE (wstack->alloc_size));
3826
0
          *data = wstack;
3827
0
        }
3828
0
    }
3829
3830
0
  wstack->weak_refs[i] = *tuple;
3831
3832
0
  return NULL;
3833
0
}
3834
3835
/**
3836
 * g_object_weak_ref: (skip)
3837
 * @object: #GObject to reference weakly
3838
 * @notify: callback to invoke before the object is freed
3839
 * @data: extra data to pass to notify
3840
 *
3841
 * Adds a weak reference callback to an object. Weak references are
3842
 * used for notification when an object is disposed. They are called
3843
 * "weak references" because they allow you to safely hold a pointer
3844
 * to an object without calling g_object_ref() (g_object_ref() adds a
3845
 * strong reference, that is, forces the object to stay alive).
3846
 *
3847
 * Note that the weak references created by this method are not
3848
 * thread-safe: they cannot safely be used in one thread if the
3849
 * object's last g_object_unref() might happen in another thread.
3850
 * Use #GWeakRef if thread-safety is required.
3851
 */
3852
void
3853
g_object_weak_ref (GObject    *object,
3854
       GWeakNotify notify,
3855
       gpointer    data)
3856
0
{
3857
0
  g_return_if_fail (G_IS_OBJECT (object));
3858
0
  g_return_if_fail (notify != NULL);
3859
0
  g_return_if_fail (g_atomic_int_get (&object->ref_count) >= 1);
3860
3861
0
  _g_datalist_id_update_atomic (&object->qdata,
3862
0
                                quark_weak_notifies,
3863
0
                                g_object_weak_ref_cb,
3864
0
                                &((WeakRefTuple){
3865
0
                                    .notify = notify,
3866
0
                                    .data = data,
3867
0
                                }));
3868
0
}
3869
3870
static gpointer
3871
g_object_weak_unref_cb (gpointer *data,
3872
                        GDestroyNotify *destroy_notify,
3873
                        gpointer user_data)
3874
0
{
3875
0
  WeakRefTuple *tuple = user_data;
3876
0
  WeakRefStack *wstack = *data;
3877
0
  gboolean found_one = FALSE;
3878
0
  guint i;
3879
3880
0
  if (wstack)
3881
0
    {
3882
0
      for (i = 0; i < wstack->n_weak_refs; i++)
3883
0
        {
3884
0
          if (wstack->weak_refs[i].notify != tuple->notify ||
3885
0
              wstack->weak_refs[i].data != tuple->data)
3886
0
            continue;
3887
3888
0
          _weak_ref_stack_update_release_all_state (wstack, i);
3889
3890
0
          wstack->n_weak_refs -= 1;
3891
0
          if (wstack->n_weak_refs == 0)
3892
0
            {
3893
0
              _weak_ref_stack_free (wstack);
3894
0
              *data = NULL;
3895
0
            }
3896
0
          else
3897
0
            {
3898
0
              if (i != wstack->n_weak_refs)
3899
0
                {
3900
0
                  memmove (&wstack->weak_refs[i],
3901
0
                           &wstack->weak_refs[i + 1],
3902
0
                           sizeof (wstack->weak_refs[i]) * (wstack->n_weak_refs - i));
3903
0
                }
3904
3905
0
              if (G_UNLIKELY (wstack->n_weak_refs <= wstack->alloc_size / 4u))
3906
0
                {
3907
0
                  wstack->alloc_size = wstack->alloc_size / 2u;
3908
0
                  wstack = g_realloc (wstack, WEAK_REF_STACK_ALLOC_SIZE (wstack->alloc_size));
3909
0
                  *data = wstack;
3910
0
                }
3911
0
            }
3912
3913
0
          found_one = TRUE;
3914
0
          break;
3915
0
        }
3916
0
    }
3917
3918
0
  if (!found_one)
3919
0
    g_critical ("%s: couldn't find weak ref %p(%p)", G_STRFUNC, tuple->notify, tuple->data);
3920
3921
0
  return NULL;
3922
0
}
3923
3924
/**
3925
 * g_object_weak_unref: (skip)
3926
 * @object: #GObject to remove a weak reference from
3927
 * @notify: callback to search for
3928
 * @data: data to search for
3929
 *
3930
 * Removes a weak reference callback to an object.
3931
 */
3932
void
3933
g_object_weak_unref (GObject    *object,
3934
         GWeakNotify notify,
3935
         gpointer    data)
3936
0
{
3937
0
  g_return_if_fail (G_IS_OBJECT (object));
3938
0
  g_return_if_fail (notify != NULL);
3939
3940
0
  _g_datalist_id_update_atomic (&object->qdata,
3941
0
                                quark_weak_notifies,
3942
0
                                g_object_weak_unref_cb,
3943
0
                                &((WeakRefTuple){
3944
0
                                    .notify = notify,
3945
0
                                    .data = data,
3946
0
                                }));
3947
0
}
3948
3949
typedef struct
3950
{
3951
  WeakRefReleaseAllState *const release_all_state;
3952
  WeakRefTuple tuple;
3953
  gboolean release_all_done;
3954
} WeakRefReleaseAllData;
3955
3956
static gpointer
3957
g_object_weak_release_all_cb (gpointer *data,
3958
                              GDestroyNotify *destroy_notify,
3959
                              gpointer user_data)
3960
0
{
3961
0
  WeakRefStack *wstack = *data;
3962
0
  WeakRefReleaseAllData *wdata = user_data;
3963
0
  WeakRefReleaseAllState *release_all_state = wdata->release_all_state;
3964
3965
0
  if (!wstack)
3966
0
    return NULL;
3967
3968
0
#ifdef G_ENABLE_DEBUG
3969
0
  g_assert (wstack->n_weak_refs > 0);
3970
0
#endif
3971
3972
0
  if (release_all_state)
3973
0
    {
3974
0
      if (release_all_state->remaining_to_notify == G_MAXUINT)
3975
0
        {
3976
0
          if (wstack->n_weak_refs == 1u)
3977
0
            {
3978
              /* We only pop the single entry. */
3979
0
              wdata->release_all_done = TRUE;
3980
0
              release_all_state = NULL;
3981
0
            }
3982
0
          else
3983
0
            {
3984
0
              release_all_state->remaining_to_notify = wstack->n_weak_refs;
3985
3986
              /* Prepend to linked list. */
3987
0
              release_all_state->release_all_next = wstack->release_all_states;
3988
0
              wstack->release_all_states = release_all_state;
3989
0
            }
3990
0
        }
3991
0
      else
3992
0
        {
3993
0
          if (release_all_state->remaining_to_notify == 0u)
3994
0
            {
3995
0
#ifdef G_ENABLE_DEBUG
3996
0
              g_assert (!_weak_ref_release_all_state_contains (wstack->release_all_states, release_all_state));
3997
0
#endif
3998
0
              return NULL;
3999
0
            }
4000
0
#ifdef G_ENABLE_DEBUG
4001
0
          g_assert (release_all_state->remaining_to_notify <= wstack->n_weak_refs);
4002
0
          g_assert (_weak_ref_release_all_state_contains (wstack->release_all_states, release_all_state));
4003
0
#endif
4004
0
        }
4005
0
    }
4006
4007
0
  _weak_ref_stack_update_release_all_state (wstack, 0);
4008
4009
0
  if (release_all_state && release_all_state->remaining_to_notify == 0)
4010
0
    wdata->release_all_done = TRUE;
4011
4012
0
  wstack->n_weak_refs--;
4013
4014
  /* Emit the notifications in FIFO order. */
4015
0
  wdata->tuple = wstack->weak_refs[0];
4016
4017
0
  if (wstack->n_weak_refs == 0)
4018
0
    {
4019
0
      _weak_ref_stack_free (wstack);
4020
0
      *data = NULL;
4021
4022
      /* Also set release_all_done.
4023
       *
4024
       * If g_object_weak_release_all() was called during dispose (with
4025
       * release_all FALSE), we anyway have an upper limit of how many
4026
       * notifications we want to pop. We only pop the notifications that were
4027
       * registered when the loop initially starts. In that case, we surely
4028
       * don't want the caller to call back.
4029
       *
4030
       * g_object_weak_release_all() is also being called before finalize. At
4031
       * that point, the ref count is already at zero, and g_object_weak_ref()
4032
       * asserts against being called. So nobody can register a new weak ref
4033
       * anymore.
4034
       *
4035
       * In both cases, we don't require the calling loop to call back. This
4036
       * saves an additional GData lookup. */
4037
0
      wdata->release_all_done = TRUE;
4038
0
    }
4039
0
  else
4040
0
    {
4041
0
      memmove (&wstack->weak_refs[0],
4042
0
               &wstack->weak_refs[1],
4043
0
               sizeof (wstack->weak_refs[0]) * wstack->n_weak_refs);
4044
4045
      /* Don't bother to shrink the buffer. Most likely the object gets
4046
       * destroyed soon after. */
4047
0
    }
4048
4049
0
  return wdata;
4050
0
}
4051
4052
static void
4053
g_object_weak_release_all (GObject *object, gboolean release_all)
4054
0
{
4055
0
  WeakRefReleaseAllState release_all_state = {
4056
0
    .remaining_to_notify = G_MAXUINT,
4057
0
  };
4058
0
  WeakRefReleaseAllData wdata = {
4059
0
    .release_all_state = release_all ? NULL : &release_all_state,
4060
0
    .release_all_done = FALSE,
4061
0
  };
4062
4063
0
  while (TRUE)
4064
0
    {
4065
0
      if (!_g_datalist_id_update_atomic (&object->qdata,
4066
0
                                         quark_weak_notifies,
4067
0
                                         g_object_weak_release_all_cb,
4068
0
                                         &wdata))
4069
0
        break;
4070
4071
0
      wdata.tuple.notify (wdata.tuple.data, object);
4072
4073
0
      if (wdata.release_all_done)
4074
0
        break;
4075
0
    }
4076
0
}
4077
4078
/**
4079
 * g_object_add_weak_pointer: (skip)
4080
 * @object: The object that should be weak referenced.
4081
 * @weak_pointer_location: (inout) (not optional): The memory address
4082
 *    of a pointer.
4083
 *
4084
 * Adds a weak reference from weak_pointer to @object to indicate that
4085
 * the pointer located at @weak_pointer_location is only valid during
4086
 * the lifetime of @object. When the @object is finalized,
4087
 * @weak_pointer will be set to %NULL.
4088
 *
4089
 * Note that as with g_object_weak_ref(), the weak references created by
4090
 * this method are not thread-safe: they cannot safely be used in one
4091
 * thread if the object's last g_object_unref() might happen in another
4092
 * thread. Use #GWeakRef if thread-safety is required.
4093
 */
4094
void
4095
g_object_add_weak_pointer (GObject  *object, 
4096
                           gpointer *weak_pointer_location)
4097
0
{
4098
0
  g_return_if_fail (G_IS_OBJECT (object));
4099
0
  g_return_if_fail (weak_pointer_location != NULL);
4100
4101
0
  g_object_weak_ref (object, 
4102
0
                     (GWeakNotify) g_nullify_pointer, 
4103
0
                     weak_pointer_location);
4104
0
}
4105
4106
/**
4107
 * g_object_remove_weak_pointer: (skip)
4108
 * @object: The object that is weak referenced.
4109
 * @weak_pointer_location: (inout) (not optional): The memory address
4110
 *    of a pointer.
4111
 *
4112
 * Removes a weak reference from @object that was previously added
4113
 * using g_object_add_weak_pointer(). The @weak_pointer_location has
4114
 * to match the one used with g_object_add_weak_pointer().
4115
 */
4116
void
4117
g_object_remove_weak_pointer (GObject  *object, 
4118
                              gpointer *weak_pointer_location)
4119
0
{
4120
0
  g_return_if_fail (G_IS_OBJECT (object));
4121
0
  g_return_if_fail (weak_pointer_location != NULL);
4122
4123
0
  g_object_weak_unref (object, 
4124
0
                       (GWeakNotify) g_nullify_pointer, 
4125
0
                       weak_pointer_location);
4126
0
}
4127
4128
static guint
4129
object_floating_flag_handler (GObject        *object,
4130
                              gint            job)
4131
0
{
4132
0
  switch (job)
4133
0
    {
4134
0
      gpointer oldvalue;
4135
0
    case +1:    /* force floating if possible */
4136
0
      oldvalue = g_atomic_pointer_get (&object->qdata);
4137
0
      while (!g_atomic_pointer_compare_and_exchange_full (
4138
0
        (void**) &object->qdata, oldvalue,
4139
0
        (void *) ((guintptr) oldvalue | OBJECT_FLOATING_FLAG),
4140
0
        &oldvalue))
4141
0
        ;
4142
0
      return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
4143
0
    case -1:    /* sink if possible */
4144
0
      oldvalue = g_atomic_pointer_get (&object->qdata);
4145
0
      while (!g_atomic_pointer_compare_and_exchange_full (
4146
0
        (void**) &object->qdata, oldvalue,
4147
0
        (void *) ((guintptr) oldvalue & ~(gsize) OBJECT_FLOATING_FLAG),
4148
0
        &oldvalue))
4149
0
        ;
4150
0
      return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
4151
0
    default:    /* check floating */
4152
0
      return 0 != ((gsize) g_atomic_pointer_get (&object->qdata) & OBJECT_FLOATING_FLAG);
4153
0
    }
4154
0
}
4155
4156
/**
4157
 * g_object_is_floating:
4158
 * @object: (type GObject.Object): a #GObject
4159
 *
4160
 * Checks whether @object has a [floating](floating-refs.html) reference.
4161
 *
4162
 * Since: 2.10
4163
 *
4164
 * Returns: %TRUE if @object has a floating reference
4165
 */
4166
gboolean
4167
g_object_is_floating (gpointer _object)
4168
0
{
4169
0
  GObject *object = _object;
4170
0
  g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
4171
0
  return (floating_flag_handler (object, 0) != 0);
4172
0
}
4173
4174
/**
4175
 * g_object_ref_sink:
4176
 * @object: (type GObject.Object): a #GObject
4177
 *
4178
 * Increase the reference count of @object, and possibly remove the
4179
 * [floating](floating-refs.html) reference, if @object has a floating reference.
4180
 *
4181
 * In other words, if the object is floating, then this call "assumes
4182
 * ownership" of the floating reference, converting it to a normal
4183
 * reference by clearing the floating flag while leaving the reference
4184
 * count unchanged.  If the object is not floating, then this call
4185
 * adds a new normal reference increasing the reference count by one.
4186
 *
4187
 * Since GLib 2.56, the type of @object will be propagated to the return type
4188
 * under the same conditions as for g_object_ref().
4189
 *
4190
 * Since: 2.10
4191
 *
4192
 * Returns: (type GObject.Object) (transfer none): @object
4193
 */
4194
gpointer
4195
(g_object_ref_sink) (gpointer _object)
4196
0
{
4197
0
  GObject *object = _object;
4198
0
  gboolean was_floating;
4199
0
  g_return_val_if_fail (G_IS_OBJECT (object), object);
4200
0
  g_return_val_if_fail (g_atomic_int_get (&object->ref_count) >= 1, object);
4201
0
  g_object_ref (object);
4202
0
  was_floating = (floating_flag_handler (object, -1) != 0);
4203
0
  if (was_floating)
4204
0
    g_object_unref (object);
4205
0
  return object;
4206
0
}
4207
4208
/**
4209
 * g_object_take_ref: (skip)
4210
 * @object: (type GObject.Object): a #GObject
4211
 *
4212
 * If @object is floating, sink it.  Otherwise, do nothing.
4213
 *
4214
 * In other words, this function will convert a floating reference (if
4215
 * present) into a full reference.
4216
 *
4217
 * Typically you want to use g_object_ref_sink() in order to
4218
 * automatically do the correct thing with respect to floating or
4219
 * non-floating references, but there is one specific scenario where
4220
 * this function is helpful.
4221
 *
4222
 * The situation where this function is helpful is when creating an API
4223
 * that allows the user to provide a callback function that returns a
4224
 * GObject. We certainly want to allow the user the flexibility to
4225
 * return a non-floating reference from this callback (for the case
4226
 * where the object that is being returned already exists).
4227
 *
4228
 * At the same time, the API style of some popular GObject-based
4229
 * libraries (such as Gtk) make it likely that for newly-created GObject
4230
 * instances, the user can be saved some typing if they are allowed to
4231
 * return a floating reference.
4232
 *
4233
 * Using this function on the return value of the user's callback allows
4234
 * the user to do whichever is more convenient for them. The caller will
4235
 * always receives exactly one full reference to the value: either the
4236
 * one that was returned in the first place, or a floating reference
4237
 * that has been converted to a full reference.
4238
 *
4239
 * This function has an odd interaction when combined with
4240
 * g_object_ref_sink() running at the same time in another thread on
4241
 * the same #GObject instance. If g_object_ref_sink() runs first then
4242
 * the result will be that the floating reference is converted to a hard
4243
 * reference. If g_object_take_ref() runs first then the result will be
4244
 * that the floating reference is converted to a hard reference and an
4245
 * additional reference on top of that one is added. It is best to avoid
4246
 * this situation.
4247
 *
4248
 * Since: 2.70
4249
 *
4250
 * Returns: (type GObject.Object) (transfer full): @object
4251
 */
4252
gpointer
4253
g_object_take_ref (gpointer _object)
4254
0
{
4255
0
  GObject *object = _object;
4256
0
  g_return_val_if_fail (G_IS_OBJECT (object), object);
4257
0
  g_return_val_if_fail (g_atomic_int_get (&object->ref_count) >= 1, object);
4258
4259
0
  floating_flag_handler (object, -1);
4260
4261
0
  return object;
4262
0
}
4263
4264
/**
4265
 * g_object_force_floating:
4266
 * @object: a #GObject
4267
 *
4268
 * This function is intended for #GObject implementations to re-enforce
4269
 * a [floating](floating-refs.html) object reference. Doing this is seldom
4270
 * required: all #GInitiallyUnowneds are created with a floating reference
4271
 * which usually just needs to be sunken by calling g_object_ref_sink().
4272
 *
4273
 * Since: 2.10
4274
 */
4275
void
4276
g_object_force_floating (GObject *object)
4277
0
{
4278
0
  g_return_if_fail (G_IS_OBJECT (object));
4279
0
  g_return_if_fail (g_atomic_int_get (&object->ref_count) >= 1);
4280
4281
0
  floating_flag_handler (object, +1);
4282
0
}
4283
4284
typedef struct
4285
{
4286
  GToggleNotify notify;
4287
  gpointer data;
4288
} ToggleRefTuple;
4289
4290
typedef struct
4291
{
4292
  GObject *object;
4293
  ToggleRefTuple tuple;
4294
} ToggleRefCallbackData;
4295
4296
typedef struct
4297
{
4298
  guint n_toggle_refs;
4299
  ToggleRefTuple toggle_refs[1]; /* flexible array */
4300
} ToggleRefStack;
4301
4302
static gpointer
4303
toggle_refs_check_and_ref_cb (gpointer *data,
4304
                              GDestroyNotify *destroy_notify,
4305
                              gpointer user_data)
4306
0
{
4307
0
  GToggleNotify *toggle_notify = ((gpointer *) user_data)[0];
4308
0
  gpointer *toggle_data = ((gpointer *) user_data)[1];
4309
0
  ToggleRefStack *tstack = *data;
4310
4311
0
  if (G_UNLIKELY (tstack->n_toggle_refs != 1))
4312
0
    {
4313
      /* We only reach this line after we checked that the ref-count was 1
4314
       * and that OBJECT_HAS_TOGGLE_REF(). We expect that there is exactly
4315
       * one toggle reference registered. */
4316
0
      g_critical ("Unexpected number of toggle-refs. g_object_add_toggle_ref() must be paired with g_object_remove_toggle_ref()");
4317
0
      *toggle_notify = NULL;
4318
0
      return NULL;
4319
0
    }
4320
4321
0
  *toggle_notify = tstack->toggle_refs[0].notify;
4322
0
  *toggle_data = tstack->toggle_refs[0].data;
4323
0
  return NULL;
4324
0
}
4325
4326
G_ALWAYS_INLINE static inline gboolean
4327
toggle_refs_check_and_ref_or_deref (GObject *object,
4328
                                    gboolean is_ref,
4329
                                    gint *old_ref,
4330
                                    GToggleNotify *toggle_notify,
4331
                                    gpointer *toggle_data)
4332
0
{
4333
0
  const gint ref_curr = is_ref ? 1 : 2;
4334
0
  const gint ref_next = is_ref ? 2 : 1;
4335
0
  gboolean success;
4336
4337
0
#if G_ENABLE_DEBUG
4338
0
  g_assert (ref_curr == *old_ref);
4339
0
#endif
4340
4341
0
  *toggle_notify = NULL;
4342
0
  *toggle_data = NULL;
4343
4344
  /* This is called from g_object_ref()/g_object_unref() and a hot path.
4345
   *
4346
   * We hack the GData open and take the g_datalist_lock() outside. Then we
4347
   * perform checks, that most likely will tell us that there is not toggle
4348
   * notifications. Only if we have a toggle notification, we call
4349
   * _g_datalist_id_update_atomic_full(). */
4350
4351
0
  g_datalist_lock (&object->qdata);
4352
4353
  /* @old_ref is mainly an (out) parameter. On failure to compare-and-exchange,
4354
   * we MUST return the new value which the caller will use for retry.*/
4355
4356
0
  success = g_atomic_int_compare_and_exchange_full ((int *) &object->ref_count,
4357
0
                                                    ref_curr,
4358
0
                                                    ref_next,
4359
0
                                                    old_ref);
4360
4361
  /* Note that if we are called during g_object_unref (@is_ref set to FALSE),
4362
   * then we drop the ref count from 2 to 1 and give up our reference. We thus
4363
   * no longer hold a strong reference and another thread may race against
4364
   * destroying the object.
4365
   *
4366
   * After this point with is_ref=FALSE and success=TRUE, @object must no
4367
   * longer be accessed.
4368
   *
4369
   * The exception is here. While we still hold the lock, we know that @object
4370
   * could not be destroyed, because g_object_unref() also needs to acquire the
4371
   * same lock before finalizing @object. Thus, we know object cannot yet be
4372
   * destroyed and we can access it until the unlock below. */
4373
4374
0
  if (G_UNLIKELY (!success))
4375
0
    {
4376
0
      g_datalist_unlock (&object->qdata);
4377
0
      return FALSE;
4378
0
    }
4379
4380
0
  if (G_LIKELY (!OBJECT_HAS_TOGGLE_REF (object)))
4381
0
    {
4382
0
      g_datalist_unlock (&object->qdata);
4383
0
      return TRUE;
4384
0
    }
4385
4386
  /* slow-path. We have a toggle reference. Call into g_datalist_id_update_atomic().
4387
   *
4388
   * Note that _g_datalist_id_update_atomic_full() will release the lock! */
4389
0
  _g_datalist_id_update_atomic_full (&object->qdata,
4390
0
                                     quark_toggle_refs,
4391
0
                                     TRUE,
4392
0
                                     toggle_refs_check_and_ref_cb,
4393
0
                                     (gpointer[2]){ toggle_notify, toggle_data });
4394
4395
0
  return TRUE;
4396
0
}
4397
4398
static gpointer
4399
toggle_refs_ref_cb (gpointer *data,
4400
                    GDestroyNotify *destroy_notify,
4401
                    gpointer user_data)
4402
0
{
4403
0
  ToggleRefCallbackData *trdata = user_data;
4404
0
  ToggleRefStack *tstack = *data;
4405
0
  guint i;
4406
4407
0
  if (!tstack)
4408
0
    {
4409
0
      tstack = g_new (ToggleRefStack, 1);
4410
0
      tstack->n_toggle_refs = 1;
4411
0
      i = 0;
4412
4413
0
      g_datalist_set_flags (&trdata->object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
4414
4415
0
      *destroy_notify = g_free;
4416
0
    }
4417
0
  else
4418
0
    {
4419
0
      i = tstack->n_toggle_refs++;
4420
0
      tstack = g_realloc (tstack, sizeof (*tstack) + sizeof (tstack->toggle_refs[0]) * i);
4421
0
    }
4422
4423
0
  *data = tstack;
4424
4425
0
  tstack->toggle_refs[i] = trdata->tuple;
4426
4427
0
  return NULL;
4428
0
}
4429
4430
/**
4431
 * g_object_add_toggle_ref: (skip)
4432
 * @object: a #GObject
4433
 * @notify: a function to call when this reference is the
4434
 *  last reference to the object, or is no longer
4435
 *  the last reference.
4436
 * @data: data to pass to @notify
4437
 *
4438
 * Increases the reference count of the object by one and sets a
4439
 * callback to be called when all other references to the object are
4440
 * dropped, or when this is already the last reference to the object
4441
 * and another reference is established.
4442
 *
4443
 * This functionality is intended for binding @object to a proxy
4444
 * object managed by another memory manager. This is done with two
4445
 * paired references: the strong reference added by
4446
 * g_object_add_toggle_ref() and a reverse reference to the proxy
4447
 * object which is either a strong reference or weak reference.
4448
 *
4449
 * The setup is that when there are no other references to @object,
4450
 * only a weak reference is held in the reverse direction from @object
4451
 * to the proxy object, but when there are other references held to
4452
 * @object, a strong reference is held. The @notify callback is called
4453
 * when the reference from @object to the proxy object should be
4454
 * "toggled" from strong to weak (@is_last_ref true) or weak to strong
4455
 * (@is_last_ref false).
4456
 *
4457
 * Since a (normal) reference must be held to the object before
4458
 * calling g_object_add_toggle_ref(), the initial state of the reverse
4459
 * link is always strong.
4460
 *
4461
 * Multiple toggle references may be added to the same gobject,
4462
 * however if there are multiple toggle references to an object, none
4463
 * of them will ever be notified until all but one are removed.  For
4464
 * this reason, you should only ever use a toggle reference if there
4465
 * is important state in the proxy object.
4466
 *
4467
 * Note that if you unref the object on another thread, then @notify might
4468
 * still be invoked after g_object_remove_toggle_ref(), and the object argument
4469
 * might be a dangling pointer. If the object is destroyed on other threads,
4470
 * you must take care of that yourself.
4471
 *
4472
 * A g_object_add_toggle_ref() must be released with g_object_remove_toggle_ref().
4473
 *
4474
 * Since: 2.8
4475
 */
4476
void
4477
g_object_add_toggle_ref (GObject       *object,
4478
       GToggleNotify  notify,
4479
       gpointer       data)
4480
0
{
4481
0
  g_return_if_fail (G_IS_OBJECT (object));
4482
0
  g_return_if_fail (notify != NULL);
4483
0
  g_return_if_fail (g_atomic_int_get (&object->ref_count) >= 1);
4484
4485
0
  g_object_ref (object);
4486
4487
0
  _g_datalist_id_update_atomic (&object->qdata,
4488
0
                                quark_toggle_refs,
4489
0
                                toggle_refs_ref_cb,
4490
0
                                &((ToggleRefCallbackData){
4491
0
                                    .object = object,
4492
0
                                    .tuple = {
4493
0
                                        .notify = notify,
4494
0
                                        .data = data,
4495
0
                                    },
4496
0
                                }));
4497
0
}
4498
4499
static gpointer
4500
toggle_refs_unref_cb (gpointer *data,
4501
                      GDestroyNotify *destroy_notify,
4502
                      gpointer user_data)
4503
0
{
4504
0
  ToggleRefCallbackData *trdata = user_data;
4505
0
  ToggleRefStack *tstack = *data;
4506
0
  gboolean found_one = FALSE;
4507
0
  guint i;
4508
4509
0
  if (tstack)
4510
0
    {
4511
0
      for (i = 0; i < tstack->n_toggle_refs; i++)
4512
0
        {
4513
0
          if (tstack->toggle_refs[i].notify == trdata->tuple.notify &&
4514
0
              (tstack->toggle_refs[i].data == trdata->tuple.data || trdata->tuple.data == NULL))
4515
0
            {
4516
0
              found_one = TRUE;
4517
0
              break;
4518
0
            }
4519
0
        }
4520
0
    }
4521
4522
0
  if (G_LIKELY (found_one))
4523
0
    {
4524
4525
0
      tstack->n_toggle_refs -= 1;
4526
0
      if (tstack->n_toggle_refs == 0)
4527
0
        {
4528
0
          g_datalist_unset_flags (&trdata->object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
4529
0
          g_free (tstack);
4530
0
          *data = NULL;
4531
0
          *destroy_notify = NULL;
4532
0
        }
4533
0
      else if (i != tstack->n_toggle_refs)
4534
0
        tstack->toggle_refs[i] = tstack->toggle_refs[tstack->n_toggle_refs];
4535
0
    }
4536
4537
0
  return GINT_TO_POINTER (found_one);
4538
0
}
4539
4540
/**
4541
 * g_object_remove_toggle_ref: (skip)
4542
 * @object: a #GObject
4543
 * @notify: a function to call when this reference is the
4544
 *  last reference to the object, or is no longer
4545
 *  the last reference.
4546
 * @data: (nullable): data to pass to @notify, or %NULL to
4547
 *  match any toggle refs with the @notify argument.
4548
 *
4549
 * Removes a reference added with g_object_add_toggle_ref(). The
4550
 * reference count of the object is decreased by one.
4551
 *
4552
 * Note that if you unref the object on another thread, then @notify might
4553
 * still be invoked after g_object_remove_toggle_ref(), and the object argument
4554
 * might be a dangling pointer. If the object is destroyed on other threads,
4555
 * you must take care of that yourself.
4556
 *
4557
 * Since: 2.8
4558
 */
4559
void
4560
g_object_remove_toggle_ref (GObject       *object,
4561
          GToggleNotify  notify,
4562
          gpointer       data)
4563
0
{
4564
0
  gboolean found_one;
4565
0
  gpointer result;
4566
4567
0
  g_return_if_fail (G_IS_OBJECT (object));
4568
0
  g_return_if_fail (notify != NULL);
4569
4570
0
  result = _g_datalist_id_update_atomic (&object->qdata,
4571
0
                                         quark_toggle_refs,
4572
0
                                         toggle_refs_unref_cb,
4573
0
                                         &((ToggleRefCallbackData){
4574
0
                                             .object = object,
4575
0
                                             .tuple = {
4576
0
                                                 .notify = notify,
4577
0
                                                 .data = data,
4578
0
                                             },
4579
0
                                         }));
4580
4581
0
  found_one = GPOINTER_TO_INT (result);
4582
4583
0
  if (!found_one)
4584
0
    {
4585
0
      g_critical ("%s: couldn't find toggle ref %p(%p)", G_STRFUNC, notify, data);
4586
0
      return;
4587
0
    }
4588
4589
0
  g_object_unref (object);
4590
0
}
4591
4592
/* Internal implementation of g_object_ref() which doesn't call out to user code.
4593
 * @out_toggle_notify and @out_toggle_data *must* be provided, and if non-`NULL`
4594
 * values are returned, then the caller *must* call that toggle notify function
4595
 * as soon as it is safe to do so. It may call (or be) user-provided code so should
4596
 * only be called once all locks are released. */
4597
static gpointer
4598
object_ref (GObject *object,
4599
            GToggleNotify *out_toggle_notify,
4600
            gpointer *out_toggle_data)
4601
0
{
4602
0
  GToggleNotify toggle_notify;
4603
0
  gpointer toggle_data;
4604
0
  gint old_ref;
4605
4606
0
  old_ref = g_atomic_int_get (&object->ref_count);
4607
4608
0
retry:
4609
0
  toggle_notify = NULL;
4610
0
  toggle_data = NULL;
4611
0
  if (old_ref > 1 && old_ref < G_MAXINT)
4612
0
    {
4613
      /* Fast-path. We have apparently more than 1 references already. No
4614
       * special handling for toggle references, just increment the ref count. */
4615
0
      if (!g_atomic_int_compare_and_exchange_full ((int *) &object->ref_count,
4616
0
                                                   old_ref, old_ref + 1, &old_ref))
4617
0
        goto retry;
4618
0
    }
4619
0
  else if (old_ref == 1)
4620
0
    {
4621
      /* With ref count 1, check whether we need to emit a toggle notification. */
4622
0
      if (!toggle_refs_check_and_ref_or_deref (object, TRUE, &old_ref, &toggle_notify, &toggle_data))
4623
0
        goto retry;
4624
0
    }
4625
0
  else
4626
0
    {
4627
0
      gboolean object_already_finalized = TRUE;
4628
4629
0
      *out_toggle_notify = NULL;
4630
0
      *out_toggle_data = NULL;
4631
0
      g_return_val_if_fail (!object_already_finalized, NULL);
4632
0
      return NULL;
4633
0
    }
4634
4635
0
  TRACE (GOBJECT_OBJECT_REF (object, (uintmax_t) G_TYPE_FROM_INSTANCE (object), old_ref));
4636
4637
0
  *out_toggle_notify = toggle_notify;
4638
0
  *out_toggle_data = toggle_data;
4639
0
  return object;
4640
0
}
4641
4642
/**
4643
 * g_object_ref:
4644
 * @object: (type GObject.Object): a #GObject
4645
 *
4646
 * Increases the reference count of @object.
4647
 *
4648
 * Since GLib 2.56, if `GLIB_VERSION_MAX_ALLOWED` is 2.56 or greater, the type
4649
 * of @object will be propagated to the return type (using the GCC typeof()
4650
 * extension), so any casting the caller needs to do on the return type must be
4651
 * explicit.
4652
 *
4653
 * Returns: (type GObject.Object) (transfer full): the same @object
4654
 */
4655
gpointer
4656
(g_object_ref) (gpointer _object)
4657
0
{
4658
0
  GObject *object = _object;
4659
0
  GToggleNotify toggle_notify;
4660
0
  gpointer toggle_data;
4661
4662
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4663
4664
0
  object = object_ref (object, &toggle_notify, &toggle_data);
4665
4666
0
  if (toggle_notify)
4667
0
    toggle_notify (toggle_data, object, FALSE);
4668
4669
0
  return object;
4670
0
}
4671
4672
static gboolean
4673
_object_unref_clear_weak_locations (GObject *object, gint *p_old_ref, gboolean do_unref)
4674
0
{
4675
0
  WeakRefData *wrdata;
4676
0
  gboolean success;
4677
4678
  /* Fast path, for objects that never had a GWeakRef registered. */
4679
0
  if (!(object_get_optional_flags (object) & OPTIONAL_FLAG_EVER_HAD_WEAK_REF))
4680
0
    {
4681
      /* The caller previously just checked atomically that the ref-count was
4682
       * one.
4683
       *
4684
       * At this point still, @object never ever had a GWeakRef registered.
4685
       * That means, nobody else holds a strong reference and also nobody else
4686
       * can hold a weak reference, to race against obtaining another
4687
       * reference. We are good to proceed. */
4688
0
      if (do_unref)
4689
0
        {
4690
0
          if (!g_atomic_int_compare_and_exchange ((gint *) &object->ref_count, 1, 0))
4691
0
            {
4692
0
#if G_ENABLE_DEBUG
4693
0
              g_assert_not_reached ();
4694
0
#endif
4695
0
            }
4696
0
        }
4697
0
      return TRUE;
4698
0
    }
4699
4700
  /* Slow path. We must obtain a lock on the @wrdata, to atomically release
4701
   * weak references and check that the ref count is as expected. */
4702
4703
0
  wrdata = weak_ref_data_get_surely (object);
4704
4705
0
  weak_ref_data_lock (wrdata);
4706
4707
0
  if (do_unref)
4708
0
    {
4709
0
      success = g_atomic_int_compare_and_exchange_full ((gint *) &object->ref_count,
4710
0
                                                        1, 0,
4711
0
                                                        p_old_ref);
4712
0
    }
4713
0
  else
4714
0
    {
4715
0
      *p_old_ref = g_atomic_int_get ((gint *) &object->ref_count);
4716
0
      success = (*p_old_ref == 1);
4717
0
    }
4718
4719
0
  if (success)
4720
0
    weak_ref_data_clear_list (wrdata, object);
4721
4722
0
  weak_ref_data_unlock (wrdata);
4723
4724
0
  return success;
4725
0
}
4726
4727
/**
4728
 * g_object_unref:
4729
 * @object: (type GObject.Object) (transfer full):: a #GObject
4730
 *
4731
 * Decreases the reference count of @object. When its reference count
4732
 * drops to 0, the object is finalized (i.e. its memory is freed).
4733
 *
4734
 * If the pointer to the #GObject may be reused in future (for example, if it is
4735
 * an instance variable of another object), it is recommended to clear the
4736
 * pointer to %NULL rather than retain a dangling pointer to a potentially
4737
 * invalid #GObject instance. Use g_clear_object() for this.
4738
 */
4739
void
4740
g_object_unref (gpointer _object)
4741
0
{
4742
0
  GObject *object = _object;
4743
0
  gint old_ref;
4744
0
  GToggleNotify toggle_notify;
4745
0
  gpointer toggle_data;
4746
0
  gboolean nqueue_is_frozen;
4747
0
  GType obj_gtype;
4748
4749
0
  g_return_if_fail (G_IS_OBJECT (object));
4750
4751
  /* obj_gtype will be needed for TRACE(GOBJECT_OBJECT_UNREF()) later. Note
4752
   * that we issue the TRACE() after decrementing the ref-counter. If at that
4753
   * point the reference counter does not reach zero, somebody else can race
4754
   * and destroy the object.
4755
   *
4756
   * This means, TRACE() can be called with a dangling object pointer. This
4757
   * could only be avoided, by emitting the TRACE before doing the actual
4758
   * unref, but at that point we wouldn't know the correct "old_ref" value.
4759
   * Maybe this should change.
4760
   *
4761
   * Anyway. At that later point we can also no longer safely get the GType for
4762
   * the TRACE(). Do it now.
4763
   */
4764
0
  obj_gtype = G_TYPE_FROM_INSTANCE (object);
4765
0
  (void) obj_gtype;
4766
4767
0
  old_ref = g_atomic_int_get (&object->ref_count);
4768
4769
0
retry_beginning:
4770
4771
0
  if (old_ref > 2)
4772
0
    {
4773
      /* We have many references. If we can decrement the ref counter, we are done. */
4774
0
      if (!g_atomic_int_compare_and_exchange_full ((int *) &object->ref_count,
4775
0
                                                   old_ref, old_ref - 1, &old_ref))
4776
0
        goto retry_beginning;
4777
4778
      /* Beware: object might be a dangling pointer. */
4779
0
      TRACE (GOBJECT_OBJECT_UNREF (object, (uintmax_t) obj_gtype, old_ref));
4780
0
      return;
4781
0
    }
4782
4783
0
  if (old_ref == 2)
4784
0
    {
4785
      /* We are about to return the second-to-last reference. In that case we
4786
       * might need to notify a toggle reference.
4787
       *
4788
       * Note that a g_object_add_toggle_ref() MUST always be released
4789
       * via g_object_remove_toggle_ref(). Thus, if we are here with
4790
       * an old_ref of 2, then at most one of the references can be
4791
       * a toggle reference.
4792
       *
4793
       * We need to take a lock, to avoid races. */
4794
4795
0
      if (!toggle_refs_check_and_ref_or_deref (object, FALSE, &old_ref, &toggle_notify, &toggle_data))
4796
0
        goto retry_beginning;
4797
4798
      /* Beware: object might be a dangling pointer. */
4799
0
      TRACE (GOBJECT_OBJECT_UNREF (object, obj_gtype, old_ref));
4800
0
      if (toggle_notify)
4801
0
        toggle_notify (toggle_data, object, TRUE);
4802
0
      return;
4803
0
    }
4804
4805
0
  if (G_UNLIKELY (old_ref != 1))
4806
0
    {
4807
0
      gboolean object_already_finalized = TRUE;
4808
4809
0
      g_return_if_fail (!object_already_finalized);
4810
0
      return;
4811
0
    }
4812
4813
  /* We only have one reference left. Proceed to (maybe) clear weak locations. */
4814
0
  if (!_object_unref_clear_weak_locations (object, &old_ref, FALSE))
4815
0
    goto retry_beginning;
4816
4817
  /* At this point, we checked with an atomic read that we only hold only one
4818
   * reference. Weak locations are cleared (and toggle references are not to
4819
   * be considered in this case). Proceed with dispose().
4820
   *
4821
   * First, freeze the notification queue, so we don't accidentally emit
4822
   * notifications during dispose() and finalize().
4823
   *
4824
   * The notification queue stays frozen unless the instance acquires a
4825
   * reference during dispose(), in which case we thaw it and dispatch all the
4826
   * notifications. If the instance gets through to finalize(), the
4827
   * notification queue gets automatically drained when g_object_finalize() is
4828
   * reached and the qdata is cleared.
4829
   *
4830
   * Important: Note that g_object_notify_queue_freeze() takes an object lock.
4831
   * That happens to be the same lock that is also taken by
4832
   * toggle_refs_check_and_ref_or_deref(), that is very important. See also the
4833
   * code comment in toggle_refs_check_and_ref_or_deref().
4834
   */
4835
0
  g_object_notify_queue_freeze (object, TRUE);
4836
0
  nqueue_is_frozen = TRUE;
4837
4838
0
  TRACE (GOBJECT_OBJECT_DISPOSE (object, (uintmax_t) G_TYPE_FROM_INSTANCE (object), 1));
4839
0
  G_OBJECT_GET_CLASS (object)->dispose (object);
4840
0
  TRACE (GOBJECT_OBJECT_DISPOSE_END (object, (uintmax_t) G_TYPE_FROM_INSTANCE (object), 1));
4841
4842
  /* Must re-fetch old-ref. _object_unref_clear_weak_locations() relies on
4843
   * that.  */
4844
0
  old_ref = g_atomic_int_get (&object->ref_count);
4845
4846
0
retry_decrement:
4847
  /* Here, old_ref is 1 if we just come from dispose(). If the object was resurrected,
4848
   * we can hit `goto retry_decrement` and be here with a larger old_ref. */
4849
4850
0
  if (old_ref > 1 && nqueue_is_frozen)
4851
0
    {
4852
      /* If the object was resurrected, we need to unfreeze the notify
4853
       * queue. */
4854
0
      g_object_notify_queue_thaw (object, FALSE);
4855
0
      nqueue_is_frozen = FALSE;
4856
4857
      /* Note at this point, @old_ref might be wrong.
4858
       *
4859
       * Also note that _object_unref_clear_weak_locations() requires that we
4860
       * atomically checked that @old_ref is 1. However, as @old_ref is larger
4861
       * than 1, that will not be called. Instead, all other code paths below,
4862
       * handle the possibility of a bogus @old_ref.
4863
       *
4864
       * No need to re-fetch. */
4865
0
    }
4866
4867
0
  if (old_ref > 2)
4868
0
    {
4869
0
      if (!g_atomic_int_compare_and_exchange_full ((int *) &object->ref_count,
4870
0
                                                   old_ref, old_ref - 1,
4871
0
                                                   &old_ref))
4872
0
        goto retry_decrement;
4873
4874
      /* Beware: object might be a dangling pointer. */
4875
0
      TRACE (GOBJECT_OBJECT_UNREF (object, obj_gtype, old_ref));
4876
0
      return;
4877
0
    }
4878
4879
0
  if (old_ref == 2)
4880
0
    {
4881
      /* If the object was resurrected and the current ref-count is 2, then we
4882
       * are about to drop the ref-count to 1. We may need to emit a toggle
4883
       * notification. Take a lock and check for that.
4884
       *
4885
       * In that case, we need a lock to get the toggle notification. */
4886
0
      if (!toggle_refs_check_and_ref_or_deref (object, FALSE, &old_ref, &toggle_notify, &toggle_data))
4887
0
        goto retry_decrement;
4888
4889
      /* Beware: object might be a dangling pointer. */
4890
0
      TRACE (GOBJECT_OBJECT_UNREF (object, obj_gtype, old_ref));
4891
0
      if (toggle_notify)
4892
0
        toggle_notify (toggle_data, object, TRUE);
4893
0
      return;
4894
0
    }
4895
4896
  /* old_ref is (atomically!) checked to be 1, we are about to drop the
4897
   * reference count to zero in _object_unref_clear_weak_locations(). */
4898
0
  if (!_object_unref_clear_weak_locations (object, &old_ref, TRUE))
4899
0
    goto retry_decrement;
4900
4901
0
  TRACE (GOBJECT_OBJECT_UNREF (object, obj_gtype, old_ref));
4902
4903
  /* The object is almost gone. Finalize. */
4904
4905
0
  closure_array_destroy_all (object);
4906
0
  g_signal_handlers_destroy (object);
4907
0
  g_object_weak_release_all (object, TRUE);
4908
4909
0
  TRACE (GOBJECT_OBJECT_FINALIZE (object, (uintmax_t) G_TYPE_FROM_INSTANCE (object)));
4910
0
  G_OBJECT_GET_CLASS (object)->finalize (object);
4911
0
  TRACE (GOBJECT_OBJECT_FINALIZE_END (object, (uintmax_t) G_TYPE_FROM_INSTANCE (object)));
4912
4913
0
  GOBJECT_IF_DEBUG (OBJECTS,
4914
0
                    {
4915
0
                      gboolean was_present;
4916
4917
                      /* catch objects not chaining finalize handlers */
4918
0
                      G_LOCK (debug_objects);
4919
0
                      was_present = g_hash_table_remove (debug_objects_ht, object);
4920
0
                      G_UNLOCK (debug_objects);
4921
4922
0
                      if (was_present)
4923
0
                        g_critical ("Object %p of type %s not finalized correctly.",
4924
0
                                    object, G_OBJECT_TYPE_NAME (object));
4925
0
                    });
4926
0
  g_type_free_instance ((GTypeInstance *) object);
4927
0
}
4928
4929
/**
4930
 * g_clear_object: (skip)
4931
 * @object_ptr: a pointer to a #GObject reference
4932
 *
4933
 * Clears a reference to a #GObject.
4934
 *
4935
 * @object_ptr must not be %NULL.
4936
 *
4937
 * If the reference is %NULL then this function does nothing.
4938
 * Otherwise, the reference count of the object is decreased and the
4939
 * pointer is set to %NULL.
4940
 *
4941
 * A macro is also included that allows this function to be used without
4942
 * pointer casts.
4943
 *
4944
 * Since: 2.28
4945
 **/
4946
#undef g_clear_object
4947
void
4948
g_clear_object (GObject **object_ptr)
4949
0
{
4950
0
  g_clear_pointer (object_ptr, g_object_unref);
4951
0
}
4952
4953
/**
4954
 * g_object_get_qdata:
4955
 * @object: The GObject to get a stored user data pointer from
4956
 * @quark: A #GQuark, naming the user data pointer
4957
 * 
4958
 * This function gets back user data pointers stored via
4959
 * g_object_set_qdata().
4960
 * 
4961
 * Returns: (transfer none) (nullable): The user data pointer set, or %NULL
4962
 */
4963
gpointer
4964
g_object_get_qdata (GObject *object,
4965
        GQuark   quark)
4966
0
{
4967
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4968
  
4969
0
  return quark ? g_datalist_id_get_data (&object->qdata, quark) : NULL;
4970
0
}
4971
4972
/**
4973
 * g_object_set_qdata: (skip)
4974
 * @object: The GObject to set store a user data pointer
4975
 * @quark: A #GQuark, naming the user data pointer
4976
 * @data: (nullable): An opaque user data pointer
4977
 *
4978
 * This sets an opaque, named pointer on an object.
4979
 * The name is specified through a #GQuark (retrieved e.g. via
4980
 * g_quark_from_static_string()), and the pointer
4981
 * can be gotten back from the @object with g_object_get_qdata()
4982
 * until the @object is finalized.
4983
 * Setting a previously set user data pointer, overrides (frees)
4984
 * the old pointer set, using #NULL as pointer essentially
4985
 * removes the data stored.
4986
 */
4987
void
4988
g_object_set_qdata (GObject *object,
4989
        GQuark   quark,
4990
        gpointer data)
4991
0
{
4992
0
  g_return_if_fail (G_IS_OBJECT (object));
4993
0
  g_return_if_fail (quark > 0);
4994
4995
0
  g_datalist_id_set_data (&object->qdata, quark, data);
4996
0
}
4997
4998
/**
4999
 * g_object_dup_qdata: (skip)
5000
 * @object: the #GObject to store user data on
5001
 * @quark: a #GQuark, naming the user data pointer
5002
 * @dup_func: (nullable): function to dup the value
5003
 * @user_data: (nullable): passed as user_data to @dup_func
5004
 *
5005
 * This is a variant of g_object_get_qdata() which returns
5006
 * a 'duplicate' of the value. @dup_func defines the
5007
 * meaning of 'duplicate' in this context, it could e.g.
5008
 * take a reference on a ref-counted object.
5009
 *
5010
 * If the @quark is not set on the object then @dup_func
5011
 * will be called with a %NULL argument.
5012
 *
5013
 * Note that @dup_func is called while user data of @object
5014
 * is locked.
5015
 *
5016
 * This function can be useful to avoid races when multiple
5017
 * threads are using object data on the same key on the same
5018
 * object.
5019
 *
5020
 * Returns: the result of calling @dup_func on the value
5021
 *     associated with @quark on @object, or %NULL if not set.
5022
 *     If @dup_func is %NULL, the value is returned
5023
 *     unmodified.
5024
 *
5025
 * Since: 2.34
5026
 */
5027
gpointer
5028
g_object_dup_qdata (GObject        *object,
5029
                    GQuark          quark,
5030
                    GDuplicateFunc   dup_func,
5031
                    gpointer         user_data)
5032
0
{
5033
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
5034
0
  g_return_val_if_fail (quark > 0, NULL);
5035
5036
0
  return g_datalist_id_dup_data (&object->qdata, quark, dup_func, user_data);
5037
0
}
5038
5039
/**
5040
 * g_object_replace_qdata: (skip)
5041
 * @object: the #GObject to store user data on
5042
 * @quark: a #GQuark, naming the user data pointer
5043
 * @oldval: (nullable): the old value to compare against
5044
 * @newval: (nullable): the new value
5045
 * @destroy: (nullable): a destroy notify for the new value
5046
 * @old_destroy: (out) (optional): destroy notify for the existing value
5047
 *
5048
 * Compares the user data for the key @quark on @object with
5049
 * @oldval, and if they are the same, replaces @oldval with
5050
 * @newval.
5051
 *
5052
 * This is like a typical atomic compare-and-exchange
5053
 * operation, for user data on an object.
5054
 *
5055
 * If the previous value was replaced then ownership of the
5056
 * old value (@oldval) is passed to the caller, including
5057
 * the registered destroy notify for it (passed out in @old_destroy).
5058
 * It’s up to the caller to free this as needed, which may
5059
 * or may not include using @old_destroy as sometimes replacement
5060
 * should not destroy the object in the normal way.
5061
 *
5062
 * Returns: %TRUE if the existing value for @quark was replaced
5063
 *  by @newval, %FALSE otherwise.
5064
 *
5065
 * Since: 2.34
5066
 */
5067
gboolean
5068
g_object_replace_qdata (GObject        *object,
5069
                        GQuark          quark,
5070
                        gpointer        oldval,
5071
                        gpointer        newval,
5072
                        GDestroyNotify  destroy,
5073
                        GDestroyNotify *old_destroy)
5074
0
{
5075
0
  g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
5076
0
  g_return_val_if_fail (quark > 0, FALSE);
5077
5078
0
  return g_datalist_id_replace_data (&object->qdata, quark,
5079
0
                                     oldval, newval, destroy,
5080
0
                                     old_destroy);
5081
0
}
5082
5083
/**
5084
 * g_object_set_qdata_full: (skip)
5085
 * @object: The GObject to set store a user data pointer
5086
 * @quark: A #GQuark, naming the user data pointer
5087
 * @data: (nullable): An opaque user data pointer
5088
 * @destroy: (nullable): Function to invoke with @data as argument, when @data
5089
 *           needs to be freed
5090
 *
5091
 * This function works like g_object_set_qdata(), but in addition,
5092
 * a void (*destroy) (gpointer) function may be specified which is
5093
 * called with @data as argument when the @object is finalized, or
5094
 * the data is being overwritten by a call to g_object_set_qdata()
5095
 * with the same @quark.
5096
 */
5097
void
5098
g_object_set_qdata_full (GObject       *object,
5099
       GQuark   quark,
5100
       gpointer data,
5101
       GDestroyNotify destroy)
5102
0
{
5103
0
  g_return_if_fail (G_IS_OBJECT (object));
5104
0
  g_return_if_fail (quark > 0);
5105
  
5106
0
  g_datalist_id_set_data_full (&object->qdata, quark, data,
5107
0
             data ? destroy : (GDestroyNotify) NULL);
5108
0
}
5109
5110
/**
5111
 * g_object_steal_qdata:
5112
 * @object: The GObject to get a stored user data pointer from
5113
 * @quark: A #GQuark, naming the user data pointer
5114
 *
5115
 * This function gets back user data pointers stored via
5116
 * g_object_set_qdata() and removes the @data from object
5117
 * without invoking its destroy() function (if any was
5118
 * set).
5119
 * Usually, calling this function is only required to update
5120
 * user data pointers with a destroy notifier, for example:
5121
 * |[<!-- language="C" --> 
5122
 * void
5123
 * object_add_to_user_list (GObject     *object,
5124
 *                          const gchar *new_string)
5125
 * {
5126
 *   // the quark, naming the object data
5127
 *   GQuark quark_string_list = g_quark_from_static_string ("my-string-list");
5128
 *   // retrieve the old string list
5129
 *   GList *list = g_object_steal_qdata (object, quark_string_list);
5130
 *
5131
 *   // prepend new string
5132
 *   list = g_list_prepend (list, g_strdup (new_string));
5133
 *   // this changed 'list', so we need to set it again
5134
 *   g_object_set_qdata_full (object, quark_string_list, list, free_string_list);
5135
 * }
5136
 * static void
5137
 * free_string_list (gpointer data)
5138
 * {
5139
 *   GList *node, *list = data;
5140
 *
5141
 *   for (node = list; node; node = node->next)
5142
 *     g_free (node->data);
5143
 *   g_list_free (list);
5144
 * }
5145
 * ]|
5146
 * Using g_object_get_qdata() in the above example, instead of
5147
 * g_object_steal_qdata() would have left the destroy function set,
5148
 * and thus the partial string list would have been freed upon
5149
 * g_object_set_qdata_full().
5150
 *
5151
 * Returns: (transfer full) (nullable): The user data pointer set, or %NULL
5152
 */
5153
gpointer
5154
g_object_steal_qdata (GObject *object,
5155
          GQuark   quark)
5156
0
{
5157
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
5158
0
  g_return_val_if_fail (quark > 0, NULL);
5159
  
5160
0
  return g_datalist_id_remove_no_notify (&object->qdata, quark);
5161
0
}
5162
5163
/**
5164
 * g_object_get_data:
5165
 * @object: #GObject containing the associations
5166
 * @key: name of the key for that association
5167
 * 
5168
 * Gets a named field from the objects table of associations (see g_object_set_data()).
5169
 * 
5170
 * Returns: (transfer none) (nullable): the data if found,
5171
 *          or %NULL if no such data exists.
5172
 */
5173
gpointer
5174
g_object_get_data (GObject     *object,
5175
                   const gchar *key)
5176
0
{
5177
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
5178
0
  g_return_val_if_fail (key != NULL, NULL);
5179
5180
0
  return g_datalist_get_data (&object->qdata, key);
5181
0
}
5182
5183
/**
5184
 * g_object_set_data:
5185
 * @object: #GObject containing the associations.
5186
 * @key: name of the key
5187
 * @data: (nullable): data to associate with that key
5188
 *
5189
 * Each object carries around a table of associations from
5190
 * strings to pointers.  This function lets you set an association.
5191
 *
5192
 * If the object already had an association with that name,
5193
 * the old association will be destroyed.
5194
 *
5195
 * Internally, the @key is converted to a #GQuark using g_quark_from_string().
5196
 * This means a copy of @key is kept permanently (even after @object has been
5197
 * finalized) — so it is recommended to only use a small, bounded set of values
5198
 * for @key in your program, to avoid the #GQuark storage growing unbounded.
5199
 */
5200
void
5201
g_object_set_data (GObject     *object,
5202
                   const gchar *key,
5203
                   gpointer     data)
5204
0
{
5205
0
  g_return_if_fail (G_IS_OBJECT (object));
5206
0
  g_return_if_fail (key != NULL);
5207
5208
0
  g_datalist_id_set_data (&object->qdata, g_quark_from_string (key), data);
5209
0
}
5210
5211
/**
5212
 * g_object_dup_data: (skip)
5213
 * @object: the #GObject to store user data on
5214
 * @key: a string, naming the user data pointer
5215
 * @dup_func: (nullable): function to dup the value
5216
 * @user_data: (nullable): passed as user_data to @dup_func
5217
 *
5218
 * This is a variant of g_object_get_data() which returns
5219
 * a 'duplicate' of the value. @dup_func defines the
5220
 * meaning of 'duplicate' in this context, it could e.g.
5221
 * take a reference on a ref-counted object.
5222
 *
5223
 * If the @key is not set on the object then @dup_func
5224
 * will be called with a %NULL argument.
5225
 *
5226
 * Note that @dup_func is called while user data of @object
5227
 * is locked.
5228
 *
5229
 * This function can be useful to avoid races when multiple
5230
 * threads are using object data on the same key on the same
5231
 * object.
5232
 *
5233
 * Returns: the result of calling @dup_func on the value
5234
 *     associated with @key on @object, or %NULL if not set.
5235
 *     If @dup_func is %NULL, the value is returned
5236
 *     unmodified.
5237
 *
5238
 * Since: 2.34
5239
 */
5240
gpointer
5241
g_object_dup_data (GObject        *object,
5242
                   const gchar    *key,
5243
                   GDuplicateFunc   dup_func,
5244
                   gpointer         user_data)
5245
0
{
5246
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
5247
0
  g_return_val_if_fail (key != NULL, NULL);
5248
5249
0
  return g_datalist_id_dup_data (&object->qdata,
5250
0
                                 g_quark_from_string (key),
5251
0
                                 dup_func, user_data);
5252
0
}
5253
5254
/**
5255
 * g_object_replace_data: (skip)
5256
 * @object: the #GObject to store user data on
5257
 * @key: a string, naming the user data pointer
5258
 * @oldval: (nullable): the old value to compare against
5259
 * @newval: (nullable): the new value
5260
 * @destroy: (nullable): a destroy notify for the new value
5261
 * @old_destroy: (out) (optional): destroy notify for the existing value
5262
 *
5263
 * Compares the user data for the key @key on @object with
5264
 * @oldval, and if they are the same, replaces @oldval with
5265
 * @newval.
5266
 *
5267
 * This is like a typical atomic compare-and-exchange
5268
 * operation, for user data on an object.
5269
 *
5270
 * If the previous value was replaced then ownership of the
5271
 * old value (@oldval) is passed to the caller, including
5272
 * the registered destroy notify for it (passed out in @old_destroy).
5273
 * It’s up to the caller to free this as needed, which may
5274
 * or may not include using @old_destroy as sometimes replacement
5275
 * should not destroy the object in the normal way.
5276
 *
5277
 * See g_object_set_data() for guidance on using a small, bounded set of values
5278
 * for @key.
5279
 *
5280
 * Returns: %TRUE if the existing value for @key was replaced
5281
 *  by @newval, %FALSE otherwise.
5282
 *
5283
 * Since: 2.34
5284
 */
5285
gboolean
5286
g_object_replace_data (GObject        *object,
5287
                       const gchar    *key,
5288
                       gpointer        oldval,
5289
                       gpointer        newval,
5290
                       GDestroyNotify  destroy,
5291
                       GDestroyNotify *old_destroy)
5292
0
{
5293
0
  g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
5294
0
  g_return_val_if_fail (key != NULL, FALSE);
5295
5296
0
  return g_datalist_id_replace_data (&object->qdata,
5297
0
                                     g_quark_from_string (key),
5298
0
                                     oldval, newval, destroy,
5299
0
                                     old_destroy);
5300
0
}
5301
5302
/**
5303
 * g_object_set_data_full: (skip)
5304
 * @object: #GObject containing the associations
5305
 * @key: name of the key
5306
 * @data: (nullable): data to associate with that key
5307
 * @destroy: (nullable): function to call when the association is destroyed
5308
 *
5309
 * Like g_object_set_data() except it adds notification
5310
 * for when the association is destroyed, either by setting it
5311
 * to a different value or when the object is destroyed.
5312
 *
5313
 * Note that the @destroy callback is not called if @data is %NULL.
5314
 */
5315
void
5316
g_object_set_data_full (GObject       *object,
5317
                        const gchar   *key,
5318
                        gpointer       data,
5319
                        GDestroyNotify destroy)
5320
0
{
5321
0
  g_return_if_fail (G_IS_OBJECT (object));
5322
0
  g_return_if_fail (key != NULL);
5323
5324
0
  g_datalist_id_set_data_full (&object->qdata, g_quark_from_string (key), data,
5325
0
             data ? destroy : (GDestroyNotify) NULL);
5326
0
}
5327
5328
/**
5329
 * g_object_steal_data:
5330
 * @object: #GObject containing the associations
5331
 * @key: name of the key
5332
 *
5333
 * Remove a specified datum from the object's data associations,
5334
 * without invoking the association's destroy handler.
5335
 *
5336
 * Returns: (transfer full) (nullable): the data if found, or %NULL
5337
 *          if no such data exists.
5338
 */
5339
gpointer
5340
g_object_steal_data (GObject     *object,
5341
                     const gchar *key)
5342
0
{
5343
0
  GQuark quark;
5344
5345
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
5346
0
  g_return_val_if_fail (key != NULL, NULL);
5347
5348
0
  quark = g_quark_try_string (key);
5349
5350
0
  return quark ? g_datalist_id_remove_no_notify (&object->qdata, quark) : NULL;
5351
0
}
5352
5353
static void
5354
g_value_object_init (GValue *value)
5355
0
{
5356
0
  value->data[0].v_pointer = NULL;
5357
0
}
5358
5359
static void
5360
g_value_object_free_value (GValue *value)
5361
0
{
5362
0
  g_clear_object ((GObject**) &value->data[0].v_pointer);
5363
0
}
5364
5365
static void
5366
g_value_object_copy_value (const GValue *src_value,
5367
         GValue *dest_value)
5368
0
{
5369
0
  g_set_object ((GObject**) &dest_value->data[0].v_pointer,
5370
0
                src_value->data[0].v_pointer);
5371
0
}
5372
5373
static void
5374
g_value_object_transform_value (const GValue *src_value,
5375
        GValue       *dest_value)
5376
0
{
5377
0
  if (src_value->data[0].v_pointer && g_type_is_a (G_OBJECT_TYPE (src_value->data[0].v_pointer), G_VALUE_TYPE (dest_value)))
5378
0
    dest_value->data[0].v_pointer = g_object_ref (src_value->data[0].v_pointer);
5379
0
  else
5380
0
    dest_value->data[0].v_pointer = NULL;
5381
0
}
5382
5383
static gpointer
5384
g_value_object_peek_pointer (const GValue *value)
5385
0
{
5386
0
  return value->data[0].v_pointer;
5387
0
}
5388
5389
static gchar*
5390
g_value_object_collect_value (GValue    *value,
5391
            guint        n_collect_values,
5392
            GTypeCValue *collect_values,
5393
            guint        collect_flags)
5394
0
{
5395
0
  if (collect_values[0].v_pointer)
5396
0
    {
5397
0
      GObject *object = collect_values[0].v_pointer;
5398
      
5399
0
      if (object->g_type_instance.g_class == NULL)
5400
0
  return g_strconcat ("invalid unclassed object pointer for value type '",
5401
0
          G_VALUE_TYPE_NAME (value),
5402
0
          "'",
5403
0
          NULL);
5404
0
      else if (!g_value_type_compatible (G_OBJECT_TYPE (object), G_VALUE_TYPE (value)))
5405
0
  return g_strconcat ("invalid object type '",
5406
0
          G_OBJECT_TYPE_NAME (object),
5407
0
          "' for value type '",
5408
0
          G_VALUE_TYPE_NAME (value),
5409
0
          "'",
5410
0
          NULL);
5411
      /* never honour G_VALUE_NOCOPY_CONTENTS for ref-counted types */
5412
0
      value->data[0].v_pointer = g_object_ref (object);
5413
0
    }
5414
0
  else
5415
0
    value->data[0].v_pointer = NULL;
5416
  
5417
0
  return NULL;
5418
0
}
5419
5420
static gchar*
5421
g_value_object_lcopy_value (const GValue *value,
5422
          guint        n_collect_values,
5423
          GTypeCValue *collect_values,
5424
          guint        collect_flags)
5425
0
{
5426
0
  GObject **object_p = collect_values[0].v_pointer;
5427
5428
0
  g_return_val_if_fail (object_p != NULL, g_strdup_printf ("value location for '%s' passed as NULL", G_VALUE_TYPE_NAME (value)));
5429
5430
0
  if (!value->data[0].v_pointer)
5431
0
    *object_p = NULL;
5432
0
  else if (collect_flags & G_VALUE_NOCOPY_CONTENTS)
5433
0
    *object_p = value->data[0].v_pointer;
5434
0
  else
5435
0
    *object_p = g_object_ref (value->data[0].v_pointer);
5436
  
5437
0
  return NULL;
5438
0
}
5439
5440
/**
5441
 * g_value_set_object:
5442
 * @value: a valid #GValue of %G_TYPE_OBJECT derived type
5443
 * @v_object: (type GObject.Object) (nullable): object value to be set
5444
 *
5445
 * Set the contents of a %G_TYPE_OBJECT derived #GValue to @v_object.
5446
 *
5447
 * g_value_set_object() increases the reference count of @v_object
5448
 * (the #GValue holds a reference to @v_object).  If you do not wish
5449
 * to increase the reference count of the object (i.e. you wish to
5450
 * pass your current reference to the #GValue because you no longer
5451
 * need it), use g_value_take_object() instead.
5452
 *
5453
 * It is important that your #GValue holds a reference to @v_object (either its
5454
 * own, or one it has taken) to ensure that the object won't be destroyed while
5455
 * the #GValue still exists).
5456
 */
5457
void
5458
g_value_set_object (GValue   *value,
5459
        gpointer  v_object)
5460
0
{
5461
0
  GObject *old;
5462
5463
0
  g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
5464
5465
0
  if G_UNLIKELY (value->data[0].v_pointer == v_object)
5466
0
    return;
5467
5468
0
  old = g_steal_pointer (&value->data[0].v_pointer);
5469
5470
0
  if (v_object)
5471
0
    {
5472
0
      g_return_if_fail (G_IS_OBJECT (v_object));
5473
0
      g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
5474
5475
0
      value->data[0].v_pointer = g_object_ref (v_object);
5476
0
    }
5477
5478
0
  g_clear_object (&old);
5479
0
}
5480
5481
/**
5482
 * g_value_set_object_take_ownership: (skip)
5483
 * @value: a valid #GValue of %G_TYPE_OBJECT derived type
5484
 * @v_object: (nullable): object value to be set
5485
 *
5486
 * This is an internal function introduced mainly for C marshallers.
5487
 *
5488
 * Deprecated: 2.4: Use g_value_take_object() instead.
5489
 */
5490
void
5491
g_value_set_object_take_ownership (GValue  *value,
5492
           gpointer v_object)
5493
0
{
5494
0
  g_value_take_object (value, v_object);
5495
0
}
5496
5497
/**
5498
 * g_value_take_object: (skip)
5499
 * @value: a valid #GValue of %G_TYPE_OBJECT derived type
5500
 * @v_object: (nullable): object value to be set
5501
 *
5502
 * Sets the contents of a %G_TYPE_OBJECT derived #GValue to @v_object
5503
 * and takes over the ownership of the caller’s reference to @v_object;
5504
 * the caller doesn’t have to unref it any more (i.e. the reference
5505
 * count of the object is not increased).
5506
 *
5507
 * If you want the #GValue to hold its own reference to @v_object, use
5508
 * g_value_set_object() instead.
5509
 *
5510
 * Since: 2.4
5511
 */
5512
void
5513
g_value_take_object (GValue  *value,
5514
         gpointer v_object)
5515
0
{
5516
0
  g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
5517
5518
0
  g_clear_object ((GObject **) &value->data[0].v_pointer);
5519
5520
0
  if (v_object)
5521
0
    {
5522
0
      g_return_if_fail (G_IS_OBJECT (v_object));
5523
0
      g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
5524
5525
0
      value->data[0].v_pointer = g_steal_pointer (&v_object);
5526
0
    }
5527
0
}
5528
5529
/**
5530
 * g_value_get_object:
5531
 * @value: a valid #GValue of %G_TYPE_OBJECT derived type
5532
 * 
5533
 * Get the contents of a %G_TYPE_OBJECT derived #GValue.
5534
 * 
5535
 * Returns: (type GObject.Object) (transfer none) (nullable): object contents of @value
5536
 */
5537
gpointer
5538
g_value_get_object (const GValue *value)
5539
0
{
5540
0
  g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
5541
  
5542
0
  return value->data[0].v_pointer;
5543
0
}
5544
5545
/**
5546
 * g_value_dup_object:
5547
 * @value: a valid #GValue whose type is derived from %G_TYPE_OBJECT
5548
 *
5549
 * Get the contents of a %G_TYPE_OBJECT derived #GValue, increasing
5550
 * its reference count. If the contents of the #GValue are %NULL, then
5551
 * %NULL will be returned.
5552
 *
5553
 * Returns: (type GObject.Object) (transfer full) (nullable): object content of @value,
5554
 *          should be unreferenced when no longer needed.
5555
 */
5556
gpointer
5557
g_value_dup_object (const GValue *value)
5558
0
{
5559
0
  g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
5560
  
5561
0
  return value->data[0].v_pointer ? g_object_ref (value->data[0].v_pointer) : NULL;
5562
0
}
5563
5564
/**
5565
 * g_signal_connect_object: (skip)
5566
 * @instance: (type GObject.TypeInstance): the instance to connect to.
5567
 * @detailed_signal: a string of the form "signal-name::detail".
5568
 * @c_handler: the #GCallback to connect.
5569
 * @gobject: (type GObject.Object) (nullable): the object to pass as data
5570
 *    to @c_handler.
5571
 * @connect_flags: a combination of #GConnectFlags.
5572
 *
5573
 * This is similar to g_signal_connect_data(), but uses a closure which
5574
 * ensures that the @gobject stays alive during the call to @c_handler
5575
 * by temporarily adding a reference count to @gobject.
5576
 *
5577
 * When the @gobject is destroyed the signal handler will be automatically
5578
 * disconnected.  Note that this is not currently threadsafe (ie:
5579
 * emitting a signal while @gobject is being destroyed in another thread
5580
 * is not safe).
5581
 *
5582
 * This function cannot fail. If the given signal name doesn’t exist,
5583
 * a critical warning is emitted. No validation is performed on the
5584
 * "detail" string when specified in @detailed_signal, other than a
5585
 * non-empty check.
5586
 *
5587
 * Refer to the [signals documentation](signals.html) for more
5588
 * details.
5589
 *
5590
 * Returns: the handler id.
5591
 */
5592
gulong
5593
g_signal_connect_object (gpointer      instance,
5594
       const gchar  *detailed_signal,
5595
       GCallback     c_handler,
5596
       gpointer      gobject,
5597
       GConnectFlags connect_flags)
5598
0
{
5599
0
  g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (instance), 0);
5600
0
  g_return_val_if_fail (detailed_signal != NULL, 0);
5601
0
  g_return_val_if_fail (c_handler != NULL, 0);
5602
5603
0
  if (gobject)
5604
0
    {
5605
0
      GClosure *closure;
5606
5607
0
      g_return_val_if_fail (G_IS_OBJECT (gobject), 0);
5608
5609
0
      closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, gobject);
5610
5611
0
      return g_signal_connect_closure (instance, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
5612
0
    }
5613
0
  else
5614
0
    return g_signal_connect_data (instance, detailed_signal, c_handler, NULL, NULL, connect_flags);
5615
0
}
5616
5617
typedef struct {
5618
  GObject  *object;
5619
  guint     n_closures;
5620
  GClosure *closures[1]; /* flexible array */
5621
} CArray;
5622
5623
static gpointer
5624
object_remove_closure_cb (gpointer *data,
5625
                          GDestroyNotify *destroy_notify,
5626
                          gpointer user_data)
5627
0
{
5628
0
  GClosure *closure = user_data;
5629
0
  CArray *carray = *data;
5630
0
  guint i;
5631
5632
0
  for (i = 0; i < carray->n_closures; i++)
5633
0
    {
5634
0
      if (carray->closures[i] == closure)
5635
0
        {
5636
0
          carray->n_closures--;
5637
0
          if (carray->n_closures == 0)
5638
0
            {
5639
0
              g_free (carray);
5640
0
              *data = NULL;
5641
0
            }
5642
0
          else if (i < carray->n_closures)
5643
0
            carray->closures[i] = carray->closures[carray->n_closures];
5644
0
          return NULL;
5645
0
        }
5646
0
    }
5647
5648
0
  g_return_val_if_reached (NULL);
5649
0
}
5650
5651
static void
5652
object_remove_closure (gpointer data,
5653
                       GClosure *closure)
5654
0
{
5655
0
  GObject *object = data;
5656
5657
0
  _g_datalist_id_update_atomic (&object->qdata,
5658
0
                                quark_closure_array,
5659
0
                                object_remove_closure_cb,
5660
0
                                closure);
5661
0
}
5662
5663
static gpointer
5664
closure_array_destroy_all_cb (gpointer *data,
5665
                              GDestroyNotify *destroy_notify,
5666
                              gpointer user_data)
5667
0
{
5668
0
  CArray *carray = *data;
5669
0
  GClosure *closure;
5670
5671
0
  if (!carray)
5672
0
    return NULL;
5673
5674
0
  closure = carray->closures[--carray->n_closures];
5675
5676
0
  if (carray->n_closures == 0)
5677
0
    {
5678
0
      g_free (carray);
5679
0
      *data = NULL;
5680
0
    }
5681
5682
0
  return closure;
5683
0
}
5684
5685
static void
5686
closure_array_destroy_all (GObject *object)
5687
0
{
5688
0
  GClosure *closure;
5689
5690
  /* We invalidate closures in a loop. As this emits external callbacks, a callee
5691
   * could register another closure, which the loop would invalidate too.
5692
   *
5693
   * This is an intentional choice. Maybe it would be instead better to only
5694
   * only release the closures that were registered when the loop started. That
5695
   * would be possible, but is not done that way. */
5696
0
  while ((closure = _g_datalist_id_update_atomic (&object->qdata,
5697
0
                                                  quark_closure_array,
5698
0
                                                  closure_array_destroy_all_cb,
5699
0
                                                  NULL)))
5700
0
    {
5701
0
      g_closure_remove_invalidate_notifier (closure, object, object_remove_closure);
5702
0
      g_closure_invalidate (closure);
5703
0
    }
5704
0
}
5705
5706
static gpointer
5707
g_object_watch_closure_cb (gpointer *data,
5708
                           GDestroyNotify *destroy_notify,
5709
                           gpointer user_data)
5710
0
{
5711
0
  GObject *object = ((gpointer *) user_data)[0];
5712
0
  GClosure *closure = ((gpointer *) user_data)[1];
5713
0
  CArray *carray = *data;
5714
0
  guint i;
5715
5716
0
  if (!carray)
5717
0
    {
5718
0
      carray = g_new (CArray, 1);
5719
0
      carray->object = object;
5720
0
      carray->n_closures = 1;
5721
0
      i = 0;
5722
5723
0
#if G_ENABLE_DEBUG
5724
      /* We never expect there is anything to destroy. We require
5725
       * these entries to be released via closure_array_destroy_all(). */
5726
0
      *destroy_notify = g_destroy_notify_assert_not_reached;
5727
0
#endif
5728
0
    }
5729
0
  else
5730
0
    {
5731
0
      i = carray->n_closures++;
5732
0
      carray = g_realloc (carray, sizeof (*carray) + sizeof (carray->closures[0]) * i);
5733
0
    }
5734
5735
0
  *data = carray;
5736
5737
0
  carray->closures[i] = closure;
5738
5739
0
  return NULL;
5740
0
}
5741
5742
/**
5743
 * g_object_watch_closure:
5744
 * @object: #GObject restricting lifetime of @closure
5745
 * @closure: #GClosure to watch
5746
 *
5747
 * This function essentially limits the life time of the @closure to
5748
 * the life time of the object. That is, when the object is finalized,
5749
 * the @closure is invalidated by calling g_closure_invalidate() on
5750
 * it, in order to prevent invocations of the closure with a finalized
5751
 * (nonexisting) object. Also, g_object_ref() and g_object_unref() are
5752
 * added as marshal guards to the @closure, to ensure that an extra
5753
 * reference count is held on @object during invocation of the
5754
 * @closure.  Usually, this function will be called on closures that
5755
 * use this @object as closure data.
5756
 */
5757
void
5758
g_object_watch_closure (GObject  *object,
5759
      GClosure *closure)
5760
0
{
5761
0
  g_return_if_fail (G_IS_OBJECT (object));
5762
0
  g_return_if_fail (closure != NULL);
5763
0
  g_return_if_fail (closure->is_invalid == FALSE);
5764
0
  g_return_if_fail (closure->in_marshal == FALSE);
5765
0
  g_return_if_fail (g_atomic_int_get (&object->ref_count) > 0); /* this doesn't work on finalizing objects */
5766
5767
0
  g_closure_add_invalidate_notifier (closure, object, object_remove_closure);
5768
0
  g_closure_add_marshal_guards (closure,
5769
0
                                object, (GClosureNotify) g_object_ref,
5770
0
                                object, (GClosureNotify) g_object_unref);
5771
5772
0
  _g_datalist_id_update_atomic (&object->qdata,
5773
0
                                quark_closure_array,
5774
0
                                g_object_watch_closure_cb,
5775
0
                                ((gpointer[]){ object, closure }));
5776
0
}
5777
5778
/**
5779
 * g_closure_new_object:
5780
 * @sizeof_closure: the size of the structure to allocate, must be at least
5781
 *  `sizeof (GClosure)`
5782
 * @object: a #GObject pointer to store in the @data field of the newly
5783
 *  allocated #GClosure
5784
 *
5785
 * A variant of g_closure_new_simple() which stores @object in the
5786
 * @data field of the closure and calls g_object_watch_closure() on
5787
 * @object and the created closure. This function is mainly useful
5788
 * when implementing new types of closures.
5789
 *
5790
 * Returns: (transfer floating): a newly allocated #GClosure
5791
 */
5792
GClosure *
5793
g_closure_new_object (guint    sizeof_closure,
5794
          GObject *object)
5795
0
{
5796
0
  GClosure *closure;
5797
5798
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
5799
0
  g_return_val_if_fail (g_atomic_int_get (&object->ref_count) > 0, NULL);     /* this doesn't work on finalizing objects */
5800
5801
0
  closure = g_closure_new_simple (sizeof_closure, object);
5802
0
  g_object_watch_closure (object, closure);
5803
5804
0
  return closure;
5805
0
}
5806
5807
/**
5808
 * g_cclosure_new_object: (skip)
5809
 * @callback_func: the function to invoke
5810
 * @object: a #GObject pointer to pass to @callback_func
5811
 *
5812
 * A variant of g_cclosure_new() which uses @object as @user_data and
5813
 * calls g_object_watch_closure() on @object and the created
5814
 * closure. This function is useful when you have a callback closely
5815
 * associated with a #GObject, and want the callback to no longer run
5816
 * after the object is is freed.
5817
 *
5818
 * Returns: (transfer floating): a new #GCClosure
5819
 */
5820
GClosure *
5821
g_cclosure_new_object (GCallback callback_func,
5822
           GObject  *object)
5823
0
{
5824
0
  GClosure *closure;
5825
5826
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
5827
0
  g_return_val_if_fail (g_atomic_int_get (&object->ref_count) > 0, NULL);     /* this doesn't work on finalizing objects */
5828
0
  g_return_val_if_fail (callback_func != NULL, NULL);
5829
5830
0
  closure = g_cclosure_new (callback_func, object, NULL);
5831
0
  g_object_watch_closure (object, closure);
5832
5833
0
  return closure;
5834
0
}
5835
5836
/**
5837
 * g_cclosure_new_object_swap: (skip)
5838
 * @callback_func: the function to invoke
5839
 * @object: a #GObject pointer to pass to @callback_func
5840
 *
5841
 * A variant of g_cclosure_new_swap() which uses @object as @user_data
5842
 * and calls g_object_watch_closure() on @object and the created
5843
 * closure. This function is useful when you have a callback closely
5844
 * associated with a #GObject, and want the callback to no longer run
5845
 * after the object is is freed.
5846
 *
5847
 * Returns: (transfer floating): a new #GCClosure
5848
 */
5849
GClosure *
5850
g_cclosure_new_object_swap (GCallback callback_func,
5851
          GObject  *object)
5852
0
{
5853
0
  GClosure *closure;
5854
5855
0
  g_return_val_if_fail (G_IS_OBJECT (object), NULL);
5856
0
  g_return_val_if_fail (g_atomic_int_get (&object->ref_count) > 0, NULL);     /* this doesn't work on finalizing objects */
5857
0
  g_return_val_if_fail (callback_func != NULL, NULL);
5858
5859
0
  closure = g_cclosure_new_swap (callback_func, object, NULL);
5860
0
  g_object_watch_closure (object, closure);
5861
5862
0
  return closure;
5863
0
}
5864
5865
gsize
5866
g_object_compat_control (gsize           what,
5867
                         gpointer        data)
5868
0
{
5869
0
  switch (what)
5870
0
    {
5871
0
      gpointer *pp;
5872
0
    case 1:     /* floating base type */
5873
0
      return (gsize) G_TYPE_INITIALLY_UNOWNED;
5874
0
    case 2:     /* FIXME: remove this once GLib/Gtk+ break ABI again */
5875
0
      floating_flag_handler = (guint(*)(GObject*,gint)) data;
5876
0
      return 1;
5877
0
    case 3:     /* FIXME: remove this once GLib/Gtk+ break ABI again */
5878
0
      pp = data;
5879
0
      *pp = floating_flag_handler;
5880
0
      return 1;
5881
0
    default:
5882
0
      return 0;
5883
0
    }
5884
0
}
5885
5886
0
G_DEFINE_TYPE (GInitiallyUnowned, g_initially_unowned, G_TYPE_OBJECT)
5887
0
5888
0
static void
5889
0
g_initially_unowned_init (GInitiallyUnowned *object)
5890
0
{
5891
0
  g_object_force_floating (object);
5892
0
}
5893
5894
static void
5895
g_initially_unowned_class_init (GInitiallyUnownedClass *klass)
5896
0
{
5897
0
}
5898
5899
/**
5900
 * GWeakRef:
5901
 *
5902
 * A structure containing a weak reference to a #GObject.
5903
 *
5904
 * A `GWeakRef` can either be empty (i.e. point to %NULL), or point to an
5905
 * object for as long as at least one "strong" reference to that object
5906
 * exists. Before the object's #GObjectClass.dispose method is called,
5907
 * every #GWeakRef associated with becomes empty (i.e. points to %NULL).
5908
 *
5909
 * Like #GValue, #GWeakRef can be statically allocated, stack- or
5910
 * heap-allocated, or embedded in larger structures.
5911
 *
5912
 * Unlike g_object_weak_ref() and g_object_add_weak_pointer(), this weak
5913
 * reference is thread-safe: converting a weak pointer to a reference is
5914
 * atomic with respect to invalidation of weak pointers to destroyed
5915
 * objects.
5916
 *
5917
 * If the object's #GObjectClass.dispose method results in additional
5918
 * references to the object being held (‘re-referencing’), any #GWeakRefs taken
5919
 * before it was disposed will continue to point to %NULL.  Any #GWeakRefs taken
5920
 * during disposal and after re-referencing, or after disposal has returned due
5921
 * to the re-referencing, will continue to point to the object until its refcount
5922
 * goes back to zero, at which point they too will be invalidated.
5923
 *
5924
 * It is invalid to take a #GWeakRef on an object during #GObjectClass.dispose
5925
 * without first having or creating a strong reference to the object.
5926
 */
5927
5928
0
#define WEAK_REF_LOCK_BIT 0
5929
5930
static GObject *
5931
_weak_ref_clean_pointer (gpointer ptr)
5932
0
{
5933
  /* Drop the lockbit WEAK_REF_LOCK_BIT from @ptr (if set). */
5934
0
  return g_pointer_bit_lock_mask_ptr (ptr, WEAK_REF_LOCK_BIT, FALSE, 0, NULL);
5935
0
}
5936
5937
static void
5938
_weak_ref_lock (GWeakRef *weak_ref, GObject **out_object)
5939
0
{
5940
  /* Note that while holding a _weak_ref_lock() on the @weak_ref, we MUST not acquire a
5941
   * weak_ref_data_lock() on the @wrdata. The other way around! */
5942
5943
0
  if (out_object)
5944
0
    {
5945
0
      guintptr ptr;
5946
5947
0
      g_pointer_bit_lock_and_get (&weak_ref->priv.p, WEAK_REF_LOCK_BIT, &ptr);
5948
0
      *out_object = _weak_ref_clean_pointer ((gpointer) ptr);
5949
0
    }
5950
0
  else
5951
0
    g_pointer_bit_lock (&weak_ref->priv.p, WEAK_REF_LOCK_BIT);
5952
0
}
5953
5954
static void
5955
_weak_ref_unlock (GWeakRef *weak_ref)
5956
0
{
5957
0
  g_pointer_bit_unlock (&weak_ref->priv.p, WEAK_REF_LOCK_BIT);
5958
0
}
5959
5960
static void
5961
_weak_ref_unlock_and_set (GWeakRef *weak_ref, GObject *object)
5962
0
{
5963
0
  g_pointer_bit_unlock_and_set (&weak_ref->priv.p, WEAK_REF_LOCK_BIT, object, 0);
5964
0
}
5965
5966
static void
5967
weak_ref_data_clear_list (WeakRefData *wrdata, GObject *object)
5968
0
{
5969
0
  while (wrdata->len > 0u)
5970
0
    {
5971
0
      GWeakRef *weak_ref;
5972
0
      gpointer ptr;
5973
5974
      /* pass "allow_shrink=FALSE", so we don't reallocate needlessly. We
5975
       * anyway are about to clear the entire list. */
5976
0
      weak_ref = weak_ref_data_list_remove (wrdata, wrdata->len - 1u, FALSE);
5977
5978
      /* Fast-path. Most likely @weak_ref is currently not locked, so we can
5979
       * just atomically set the pointer to NULL. */
5980
0
      ptr = g_atomic_pointer_get (&weak_ref->priv.p);
5981
0
#if G_ENABLE_DEBUG
5982
0
      g_assert (G_IS_OBJECT (_weak_ref_clean_pointer (ptr)));
5983
0
      g_assert (!object || object == _weak_ref_clean_pointer (ptr));
5984
0
#endif
5985
0
      if (G_LIKELY (ptr == _weak_ref_clean_pointer (ptr)))
5986
0
        {
5987
          /* The pointer is unlocked. Try an atomic compare-and-exchange... */
5988
0
          if (g_atomic_pointer_compare_and_exchange (&weak_ref->priv.p, ptr, NULL))
5989
0
            {
5990
              /* Done. Go to the next. */
5991
0
              continue;
5992
0
            }
5993
0
        }
5994
5995
      /* The @weak_ref is locked. Acquire the lock to set the pointer to NULL. */
5996
0
      _weak_ref_lock (weak_ref, NULL);
5997
0
      _weak_ref_unlock_and_set (weak_ref, NULL);
5998
0
    }
5999
0
}
6000
6001
static void
6002
_weak_ref_set (GWeakRef *weak_ref,
6003
               GObject *new_object,
6004
               gboolean called_by_init)
6005
0
{
6006
0
  WeakRefData *old_wrdata;
6007
0
  WeakRefData *new_wrdata;
6008
0
  GObject *old_object;
6009
6010
0
  new_wrdata = weak_ref_data_get_or_create (new_object);
6011
6012
0
#if G_ENABLE_DEBUG
6013
0
  g_assert (!new_object || object_get_optional_flags (new_object) & OPTIONAL_FLAG_EVER_HAD_WEAK_REF);
6014
0
#endif
6015
6016
0
  if (called_by_init)
6017
0
    {
6018
      /* The caller is g_weak_ref_init(). We know that the weak_ref should be
6019
       * NULL. We thus set @old_wrdata to NULL without checking.
6020
       *
6021
       * Also important, the caller ensured that @new_object is not NULL. So we
6022
       * are expected to set @weak_ref from NULL to a non-NULL @new_object. */
6023
0
      old_wrdata = NULL;
6024
0
#if G_ENABLE_DEBUG
6025
0
      g_assert (new_object);
6026
0
#endif
6027
0
    }
6028
0
  else
6029
0
    {
6030
      /* We must get a wrdata object @old_wrdata for the current @old_object. */
6031
0
      _weak_ref_lock (weak_ref, &old_object);
6032
6033
0
      if (old_object == new_object)
6034
0
        {
6035
          /* Already set. We are done. */
6036
0
          _weak_ref_unlock (weak_ref);
6037
0
          return;
6038
0
        }
6039
6040
0
      old_wrdata = old_object
6041
0
                       ? weak_ref_data_ref (weak_ref_data_get (old_object))
6042
0
                       : NULL;
6043
0
      _weak_ref_unlock (weak_ref);
6044
0
    }
6045
6046
  /* We need a lock on @old_wrdata, @new_wrdata and @weak_ref. We need to take
6047
   * these locks in a certain order to avoid deadlock. We sort them by pointer
6048
   * value.
6049
   *
6050
   * Note that @old_wrdata or @new_wrdata may be NULL, which is handled
6051
   * correctly.
6052
   *
6053
   * Note that @old_wrdata and @new_wrdata are never identical at this point.
6054
   */
6055
0
  if (new_wrdata && old_wrdata && (((guintptr) (gpointer) old_wrdata) < ((guintptr) ((gpointer) new_wrdata))))
6056
0
    {
6057
0
      weak_ref_data_lock (old_wrdata);
6058
0
      weak_ref_data_lock (new_wrdata);
6059
0
    }
6060
0
  else
6061
0
    {
6062
0
      weak_ref_data_lock (new_wrdata);
6063
0
      weak_ref_data_lock (old_wrdata);
6064
0
    }
6065
0
  _weak_ref_lock (weak_ref, &old_object);
6066
6067
0
  if (!weak_ref_data_has (old_object, old_wrdata, NULL))
6068
0
    {
6069
      /* A race. @old_object no longer has the expected @old_wrdata after
6070
       * getting all the locks. */
6071
0
      if (old_object)
6072
0
        {
6073
          /* We lost the race and find a different object set. It's fine, our
6074
           * action was lost in the race and we are done. No need to retry. */
6075
0
          weak_ref_data_unlock (old_wrdata);
6076
0
          weak_ref_data_unlock (new_wrdata);
6077
0
          _weak_ref_unlock (weak_ref);
6078
0
          weak_ref_data_unref (old_wrdata);
6079
0
          return;
6080
0
        }
6081
6082
      /* @old_object is NULL after a race. We didn't expect that, but it's
6083
       * fine. Proceed to set @new_object... */
6084
0
    }
6085
6086
0
  if (old_object)
6087
0
    {
6088
0
      gint32 idx;
6089
6090
0
      idx = weak_ref_data_list_find (old_wrdata, weak_ref);
6091
0
      if (idx < 0)
6092
0
        g_critical ("unexpected missing GWeakRef data");
6093
0
      else
6094
0
        weak_ref_data_list_remove (old_wrdata, idx, TRUE);
6095
0
    }
6096
6097
0
  weak_ref_data_unlock (old_wrdata);
6098
6099
0
  if (new_object)
6100
0
    {
6101
0
#if G_ENABLE_DEBUG
6102
0
      g_assert (new_wrdata != NULL);
6103
0
      g_assert (weak_ref_data_list_find (new_wrdata, weak_ref) < 0);
6104
0
#endif
6105
0
      if (g_atomic_int_get (&new_object->ref_count) < 1)
6106
0
        {
6107
0
          g_critical ("calling g_weak_ref_set() with already destroyed object");
6108
0
          new_object = NULL;
6109
0
        }
6110
0
      else
6111
0
        {
6112
0
          if (!weak_ref_data_list_add (new_wrdata, weak_ref))
6113
0
            {
6114
0
              g_critical ("Too many GWeakRef registered");
6115
0
              new_object = NULL;
6116
0
            }
6117
0
        }
6118
0
    }
6119
6120
0
  _weak_ref_unlock_and_set (weak_ref, new_object);
6121
0
  weak_ref_data_unlock (new_wrdata);
6122
6123
0
  weak_ref_data_unref (old_wrdata);
6124
0
}
6125
6126
/**
6127
 * g_weak_ref_init: (skip)
6128
 * @weak_ref: uninitialized or empty location for a weak reference
6129
 * @object: (type GObject.Object) (nullable): a #GObject or %NULL
6130
 *
6131
 * Initialise a non-statically-allocated #GWeakRef.
6132
 *
6133
 * This function also calls g_weak_ref_set() with @object on the
6134
 * freshly-initialised weak reference.
6135
 *
6136
 * This function should always be matched with a call to
6137
 * g_weak_ref_clear().  It is not necessary to use this function for a
6138
 * #GWeakRef in static storage because it will already be
6139
 * properly initialised.  Just use g_weak_ref_set() directly.
6140
 *
6141
 * Since: 2.32
6142
 */
6143
void
6144
g_weak_ref_init (GWeakRef *weak_ref,
6145
                 gpointer object)
6146
0
{
6147
0
  g_return_if_fail (weak_ref);
6148
0
  g_return_if_fail (object == NULL || G_IS_OBJECT (object));
6149
6150
0
  g_atomic_pointer_set (&weak_ref->priv.p, NULL);
6151
0
  if (object)
6152
0
    {
6153
      /* We give a hint that the weak_ref is currently NULL. Unlike
6154
       * g_weak_ref_set(), we then don't need the extra lock just to
6155
       * find out that we have no object. */
6156
0
      _weak_ref_set (weak_ref, object, TRUE);
6157
0
    }
6158
0
}
6159
6160
/**
6161
 * g_weak_ref_clear: (skip)
6162
 * @weak_ref: location of a weak reference, which
6163
 *  may be empty
6164
 *
6165
 * Frees resources associated with a non-statically-allocated #GWeakRef.
6166
 * After this call, the #GWeakRef is left in an undefined state.
6167
 *
6168
 * You should only call this on a #GWeakRef that previously had
6169
 * g_weak_ref_init() called on it.
6170
 *
6171
 * Since: 2.32
6172
 */
6173
void
6174
g_weak_ref_clear (GWeakRef *weak_ref)
6175
0
{
6176
0
  g_weak_ref_set (weak_ref, NULL);
6177
6178
  /* be unkind */
6179
0
  weak_ref->priv.p = (void *) 0xccccccccu;
6180
0
}
6181
6182
/**
6183
 * g_weak_ref_get: (skip)
6184
 * @weak_ref: location of a weak reference to a #GObject
6185
 *
6186
 * If @weak_ref is not empty, atomically acquire a strong
6187
 * reference to the object it points to, and return that reference.
6188
 *
6189
 * This function is needed because of the potential race between taking
6190
 * the pointer value and g_object_ref() on it, if the object was losing
6191
 * its last reference at the same time in a different thread.
6192
 *
6193
 * The caller should release the resulting reference in the usual way,
6194
 * by using g_object_unref().
6195
 *
6196
 * Returns: (transfer full) (type GObject.Object) (nullable): the object pointed to
6197
 *     by @weak_ref, or %NULL if it was empty
6198
 *
6199
 * Since: 2.32
6200
 */
6201
gpointer
6202
g_weak_ref_get (GWeakRef *weak_ref)
6203
0
{
6204
0
  WeakRefData *wrdata;
6205
0
  WeakRefData *new_wrdata;
6206
0
  GToggleNotify toggle_notify = NULL;
6207
0
  gpointer toggle_data = NULL;
6208
0
  GObject *object;
6209
6210
0
  g_return_val_if_fail (weak_ref, NULL);
6211
6212
  /* We cannot take the strong reference on @object yet. Otherwise,
6213
   * _object_unref_clear_weak_locations() might have just taken the lock on
6214
   * @wrdata, see that the ref-count is 1 and plan to proceed clearing weak
6215
   * locations. If we then take a strong reference here, the object becomes
6216
   * alive and well, but _object_unref_clear_weak_locations() would proceed and
6217
   * clear the @weak_ref.
6218
   *
6219
   * We avoid that, by can only taking the strong reference when having a lock
6220
   * on @wrdata, so we are in sync with _object_unref_clear_weak_locations().
6221
   *
6222
   * But first we must get a reference to the @wrdata.
6223
   */
6224
0
  _weak_ref_lock (weak_ref, &object);
6225
0
  wrdata = object
6226
0
               ? weak_ref_data_ref (weak_ref_data_get (object))
6227
0
               : NULL;
6228
0
  _weak_ref_unlock (weak_ref);
6229
6230
0
  if (!wrdata)
6231
0
    {
6232
      /* There is no @wrdata and no object. We are done. */
6233
0
      return NULL;
6234
0
    }
6235
6236
0
retry:
6237
6238
  /* Now proceed to get the strong reference. This time with acquiring a lock
6239
   * on the per-object @wrdata and on @weak_ref.
6240
   *
6241
   * As the order in which locks are taken is important, we previously had to
6242
   * get a _weak_ref_lock(), to obtain the @wrdata. Now we have to lock on the
6243
   * @wrdata first, and the @weak_ref again. */
6244
0
  weak_ref_data_lock (wrdata);
6245
0
  _weak_ref_lock (weak_ref, &object);
6246
6247
0
  if (!object)
6248
0
    {
6249
      /* Object is gone in the meantime. That is fine. */
6250
0
      new_wrdata = NULL;
6251
0
    }
6252
0
  else
6253
0
    {
6254
      /* Check that @object still refers to the same object as before. We do
6255
       * that by comparing the @wrdata object. A GObject keeps its (unique!)
6256
       * wrdata instance until the end, and since @wrdata is still alive,
6257
       * @object is the same as before, if-and-only-if its @wrdata is the same.
6258
       */
6259
0
      if (weak_ref_data_has (object, wrdata, &new_wrdata))
6260
0
        {
6261
          /* We are (still) good. Take a strong ref while holding the necessary locks. */
6262
0
          object = object_ref (object, &toggle_notify, &toggle_data);
6263
0
        }
6264
0
      else
6265
0
        {
6266
          /* The @object changed and has no longer the same @wrdata. In this
6267
           * case, we need to start over.
6268
           *
6269
           * Note that @new_wrdata references the wrdata of the now current
6270
           * @object. We will use that during the retry. */
6271
0
        }
6272
0
    }
6273
6274
0
  _weak_ref_unlock (weak_ref);
6275
0
  weak_ref_data_unlock (wrdata);
6276
0
  weak_ref_data_unref (wrdata);
6277
6278
0
  if (new_wrdata)
6279
0
    {
6280
      /* There was a race. The object changed. Retry, with @new_wrdata. */
6281
0
      wrdata = new_wrdata;
6282
0
      goto retry;
6283
0
    }
6284
6285
0
  if (toggle_notify)
6286
0
    toggle_notify (toggle_data, object, FALSE);
6287
6288
0
  return object;
6289
0
}
6290
6291
/**
6292
 * g_weak_ref_set: (skip)
6293
 * @weak_ref: location for a weak reference
6294
 * @object: (type GObject.Object) (nullable): a #GObject or %NULL
6295
 *
6296
 * Change the object to which @weak_ref points, or set it to
6297
 * %NULL.
6298
 *
6299
 * You must own a strong reference on @object while calling this
6300
 * function.
6301
 *
6302
 * Since: 2.32
6303
 */
6304
void
6305
g_weak_ref_set (GWeakRef *weak_ref,
6306
                gpointer object)
6307
0
{
6308
0
  g_return_if_fail (weak_ref != NULL);
6309
0
  g_return_if_fail (object == NULL || G_IS_OBJECT (object));
6310
6311
0
  _weak_ref_set (weak_ref, object, FALSE);
6312
0
}