Coverage Report

Created: 2025-11-16 07:45

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