Coverage Report

Created: 2025-08-28 06:24

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