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