Coverage Report

Created: 2025-10-10 06:40

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