gkdbus: Fix underflow and unreachable code bug
[platform/upstream/glib.git] / gobject / gtype.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
22  */
23
24 #include "config.h"
25
26 #include "../glib/gvalgrind.h"
27 #include <string.h>
28
29 #include "gtype.h"
30 #include "gtype-private.h"
31 #include "gtypeplugin.h"
32 #include "gvaluecollector.h"
33 #include "gatomicarray.h"
34 #include "gobject_trace.h"
35
36 #include "glib-private.h"
37 #include "gconstructor.h"
38
39 #ifdef G_OS_WIN32
40 #include <windows.h>
41 #endif
42
43 #ifdef  G_ENABLE_DEBUG
44 #define IF_DEBUG(debug_type)    if (_g_type_debug_flags & G_TYPE_DEBUG_ ## debug_type)
45 #endif
46
47 /**
48  * SECTION:gtype
49  * @short_description: The GLib Runtime type identification and
50  *     management system
51  * @title:Type Information
52  *
53  * The GType API is the foundation of the GObject system. It provides the
54  * facilities for registering and managing all fundamental data types,
55  * user-defined object and interface types.
56  *
57  * For type creation and registration purposes, all types fall into one of
58  * two categories: static or dynamic.  Static types are never loaded or
59  * unloaded at run-time as dynamic types may be.  Static types are created
60  * with g_type_register_static() that gets type specific information passed
61  * in via a #GTypeInfo structure.
62  *
63  * Dynamic types are created with g_type_register_dynamic() which takes a
64  * #GTypePlugin structure instead. The remaining type information (the
65  * #GTypeInfo structure) is retrieved during runtime through #GTypePlugin
66  * and the g_type_plugin_*() API.
67  *
68  * These registration functions are usually called only once from a
69  * function whose only purpose is to return the type identifier for a
70  * specific class.  Once the type (or class or interface) is registered,
71  * it may be instantiated, inherited, or implemented depending on exactly
72  * what sort of type it is.
73  *
74  * There is also a third registration function for registering fundamental
75  * types called g_type_register_fundamental() which requires both a #GTypeInfo
76  * structure and a #GTypeFundamentalInfo structure but it is seldom used
77  * since most fundamental types are predefined rather than user-defined.
78  *
79  * Type instance and class structs are limited to a total of 64 KiB,
80  * including all parent types. Similarly, type instances' private data
81  * (as created by G_ADD_PRIVATE()) are limited to a total of
82  * 64 KiB. If a type instance needs a large static buffer, allocate it
83  * separately (typically by using #GArray or #GPtrArray) and put a pointer
84  * to the buffer in the structure.
85  *
86  * As mentioned in the [GType conventions][gtype-conventions], type names must
87  * be at least three characters long. There is no upper length limit. The first
88  * character must be a letter (a–z or A–Z) or an underscore (‘_’). Subsequent
89  * characters can be letters, numbers or any of ‘-_+’.
90  *
91  * # Runtime Debugging
92  *
93  * When `G_ENABLE_DEBUG` is defined during compilation, the GObject library
94  * supports an environment variable `GOBJECT_DEBUG` that can be set to a
95  * combination of flags to trigger debugging messages about
96  * object bookkeeping and signal emissions during runtime.
97  *
98  * The currently supported flags are:
99  *  - `objects`: Tracks all #GObject instances in a global hash table called
100  *    `debug_objects_ht`, and prints the still-alive objects on exit.
101  *  - `instance-count`: Tracks the number of instances of every #GType and makes
102  *    it available via the g_type_get_instance_count() function.
103  *  - `signals`: Currently unused.
104  */
105
106
107 /* NOTE: some functions (some internal variants and exported ones)
108  * invalidate data portions of the TypeNodes. if external functions/callbacks
109  * are called, pointers to memory maintained by TypeNodes have to be looked up
110  * again. this affects most of the struct TypeNode fields, e.g. ->children or
111  * CLASSED_NODE_IFACES_ENTRIES() respectively IFACE_NODE_PREREQUISITES() (but
112  * not ->supers[]), as all those memory portions can get realloc()ed during
113  * callback invocation.
114  *
115  * LOCKING:
116  * lock handling issues when calling static functions are indicated by
117  * uppercase letter postfixes, all static functions have to have
118  * one of the below postfixes:
119  * - _I:        [Indifferent about locking]
120  *   function doesn't care about locks at all
121  * - _U:        [Unlocked invocation]
122  *   no read or write lock has to be held across function invocation
123  *   (locks may be acquired and released during invocation though)
124  * - _L:        [Locked invocation]
125  *   a write lock or more than 0 read locks have to be held across
126  *   function invocation
127  * - _W:        [Write-locked invocation]
128  *   a write lock has to be held across function invocation
129  * - _Wm:       [Write-locked invocation, mutatable]
130  *   like _W, but the write lock might be released and reacquired
131  *   during invocation, watch your pointers
132  * - _WmREC:    [Write-locked invocation, mutatable, recursive]
133  *   like _Wm, but also acquires recursive mutex class_init_rec_mutex
134  */
135
136 #ifdef LOCK_DEBUG
137 #define G_READ_LOCK(rw_lock)    do { g_printerr (G_STRLOC ": readL++\n"); g_rw_lock_reader_lock (rw_lock); } while (0)
138 #define G_READ_UNLOCK(rw_lock)  do { g_printerr (G_STRLOC ": readL--\n"); g_rw_lock_reader_unlock (rw_lock); } while (0)
139 #define G_WRITE_LOCK(rw_lock)   do { g_printerr (G_STRLOC ": writeL++\n"); g_rw_lock_writer_lock (rw_lock); } while (0)
140 #define G_WRITE_UNLOCK(rw_lock) do { g_printerr (G_STRLOC ": writeL--\n"); g_rw_lock_writer_unlock (rw_lock); } while (0)
141 #else
142 #define G_READ_LOCK(rw_lock)    g_rw_lock_reader_lock (rw_lock)
143 #define G_READ_UNLOCK(rw_lock)  g_rw_lock_reader_unlock (rw_lock)
144 #define G_WRITE_LOCK(rw_lock)   g_rw_lock_writer_lock (rw_lock)
145 #define G_WRITE_UNLOCK(rw_lock) g_rw_lock_writer_unlock (rw_lock)
146 #endif
147 #define INVALID_RECURSION(func, arg, type_name) G_STMT_START{ \
148     static const gchar _action[] = " invalidly modified type ";  \
149     gpointer _arg = (gpointer) (arg); const gchar *_tname = (type_name), *_fname = (func); \
150     if (_arg) \
151       g_error ("%s(%p)%s'%s'", _fname, _arg, _action, _tname); \
152     else \
153       g_error ("%s()%s'%s'", _fname, _action, _tname); \
154 }G_STMT_END
155 #define g_assert_type_system_initialized() \
156   g_assert (static_quark_type_flags)
157
158 #define TYPE_FUNDAMENTAL_FLAG_MASK (G_TYPE_FLAG_CLASSED | \
159                                     G_TYPE_FLAG_INSTANTIATABLE | \
160                                     G_TYPE_FLAG_DERIVABLE | \
161                                     G_TYPE_FLAG_DEEP_DERIVABLE)
162 #define TYPE_FLAG_MASK             (G_TYPE_FLAG_ABSTRACT | G_TYPE_FLAG_VALUE_ABSTRACT | G_TYPE_FLAG_FINAL | G_TYPE_FLAG_DEPRECATED)
163
164 /* List the flags that are directly accessible via the TypeNode struct flags */
165 #define NODE_FLAG_MASK ( \
166   G_TYPE_FLAG_CLASSED | \
167   G_TYPE_FLAG_INSTANTIATABLE | \
168   G_TYPE_FLAG_FINAL)
169
170 #define SIZEOF_FUNDAMENTAL_INFO    ((gssize) MAX (MAX (sizeof (GTypeFundamentalInfo), \
171                                                        sizeof (gpointer)), \
172                                                   sizeof (glong)))
173
174 /* The 2*sizeof(size_t) alignment here is borrowed from
175  * GNU libc, so it should be good most everywhere.
176  * It is more conservative than is needed on some 64-bit
177  * platforms, but ia64 does require a 16-byte alignment.
178  * The SIMD extensions for x86 and ppc32 would want a
179  * larger alignment than this, but we don't need to
180  * do better than malloc.
181  */
182 #define STRUCT_ALIGNMENT (2 * sizeof (gsize))
183 #define ALIGN_STRUCT(offset) \
184       ((offset + (STRUCT_ALIGNMENT - 1)) & -STRUCT_ALIGNMENT)
185
186
187 /* --- typedefs --- */
188 typedef struct _TypeNode        TypeNode;
189 typedef struct _CommonData      CommonData;
190 typedef struct _BoxedData       BoxedData;
191 typedef struct _IFaceData       IFaceData;
192 typedef struct _ClassData       ClassData;
193 typedef struct _InstanceData    InstanceData;
194 typedef union  _TypeData        TypeData;
195 typedef struct _IFaceEntries    IFaceEntries;
196 typedef struct _IFaceEntry      IFaceEntry;
197 typedef struct _IFaceHolder     IFaceHolder;
198
199
200 /* --- prototypes --- */
201 static inline GTypeFundamentalInfo*     type_node_fundamental_info_I    (TypeNode               *node);
202 static        void                      type_add_flags_W                (TypeNode               *node,
203                                                                          GTypeFlags              flags);
204 static        void                      type_data_make_W                (TypeNode               *node,
205                                                                          const GTypeInfo        *info,
206                                                                          const GTypeValueTable  *value_table);
207 static inline void                      type_data_ref_Wm                (TypeNode               *node);
208 static inline void                      type_data_unref_U               (TypeNode               *node,
209                                                                          gboolean                uncached);
210 static void                             type_data_last_unref_Wm         (TypeNode *              node,
211                                                                          gboolean                uncached);
212 static inline gpointer                  type_get_qdata_L                (TypeNode               *node,
213                                                                          GQuark                  quark);
214 static inline void                      type_set_qdata_W                (TypeNode               *node,
215                                                                          GQuark                  quark,
216                                                                          gpointer                data);
217 static IFaceHolder*                     type_iface_peek_holder_L        (TypeNode               *iface,
218                                                                          GType                   instance_type);
219 static gboolean                         type_iface_vtable_base_init_Wm  (TypeNode               *iface,
220                                                                          TypeNode               *node);
221 static void                             type_iface_vtable_iface_init_Wm (TypeNode               *iface,
222                                                                          TypeNode               *node);
223 static gboolean                         type_node_is_a_L                (TypeNode               *node,
224                                                                          TypeNode               *iface_node);
225
226
227 /* --- enumeration --- */
228
229 /* The InitState enumeration is used to track the progress of initializing
230  * both classes and interface vtables. Keeping the state of initialization
231  * is necessary to handle new interfaces being added while we are initializing
232  * the class or other interfaces.
233  */
234 typedef enum
235 {
236   UNINITIALIZED,
237   BASE_CLASS_INIT,
238   BASE_IFACE_INIT,
239   CLASS_INIT,
240   IFACE_INIT,
241   INITIALIZED
242 } InitState;
243
244 /* --- structures --- */
245 struct _TypeNode
246 {
247   guint        ref_count;  /* (atomic) */
248 #ifdef G_ENABLE_DEBUG
249   guint        instance_count;  /* (atomic) */
250 #endif
251   GTypePlugin *plugin;
252   guint        n_children; /* writable with lock */
253   guint        n_supers : 8;
254   guint        n_prerequisites : 9;
255   guint        is_classed : 1;
256   guint        is_instantiatable : 1;
257   guint        is_final : 1;
258   guint        mutatable_check_cache : 1;       /* combines some common path checks */
259
260   GType       *children; /* writable with lock */
261   TypeData    *data;
262   GQuark       qname;
263   GData       *global_gdata;
264   union {
265     GAtomicArray iface_entries;         /* for !iface types */
266     GAtomicArray offsets;
267   } _prot;
268   GType       *prerequisites;
269   GType        supers[1]; /* flexible array */
270 };
271
272 #define SIZEOF_BASE_TYPE_NODE()                 (G_STRUCT_OFFSET (TypeNode, supers))
273 #define MAX_N_SUPERS                            (255)
274 #define MAX_N_CHILDREN                          (G_MAXUINT)
275 #define MAX_N_INTERFACES                        (255) /* Limited by offsets being 8 bits */
276 #define MAX_N_PREREQUISITES                     (511)
277 #define NODE_TYPE(node)                         (node->supers[0])
278 #define NODE_PARENT_TYPE(node)                  (node->supers[1])
279 #define NODE_FUNDAMENTAL_TYPE(node)             (node->supers[node->n_supers])
280 #define NODE_NAME(node)                         (g_quark_to_string (node->qname))
281 #define NODE_REFCOUNT(node)                     ((guint) g_atomic_int_get ((int *) &(node)->ref_count))
282 #define NODE_IS_BOXED(node)                     (NODE_FUNDAMENTAL_TYPE (node) == G_TYPE_BOXED)
283 #define NODE_IS_IFACE(node)                     (NODE_FUNDAMENTAL_TYPE (node) == G_TYPE_INTERFACE)
284 #define CLASSED_NODE_IFACES_ENTRIES(node)       (&(node)->_prot.iface_entries)
285 #define CLASSED_NODE_IFACES_ENTRIES_LOCKED(node)(G_ATOMIC_ARRAY_GET_LOCKED(CLASSED_NODE_IFACES_ENTRIES((node)), IFaceEntries))
286 #define IFACE_NODE_N_PREREQUISITES(node)        ((node)->n_prerequisites)
287 #define IFACE_NODE_PREREQUISITES(node)          ((node)->prerequisites)
288 #define iface_node_get_holders_L(node)          ((IFaceHolder*) type_get_qdata_L ((node), static_quark_iface_holder))
289 #define iface_node_set_holders_W(node, holders) (type_set_qdata_W ((node), static_quark_iface_holder, (holders)))
290 #define iface_node_get_dependants_array_L(n)    ((GType*) type_get_qdata_L ((n), static_quark_dependants_array))
291 #define iface_node_set_dependants_array_W(n,d)  (type_set_qdata_W ((n), static_quark_dependants_array, (d)))
292 #define TYPE_ID_MASK                            ((GType) ((1 << G_TYPE_FUNDAMENTAL_SHIFT) - 1))
293
294 #define NODE_IS_ANCESTOR(ancestor, node)                                                    \
295         ((ancestor)->n_supers <= (node)->n_supers &&                                        \
296          (node)->supers[(node)->n_supers - (ancestor)->n_supers] == NODE_TYPE (ancestor))
297
298 struct _IFaceHolder
299 {
300   GType           instance_type;
301   GInterfaceInfo *info;
302   GTypePlugin    *plugin;
303   IFaceHolder    *next;
304 };
305
306 struct _IFaceEntry
307 {
308   GType           iface_type;
309   GTypeInterface *vtable;
310   InitState       init_state;
311 };
312
313 struct _IFaceEntries {
314   gsize offset_index;
315   IFaceEntry entry[1];
316 };
317
318 #define IFACE_ENTRIES_HEADER_SIZE (sizeof(IFaceEntries) - sizeof(IFaceEntry))
319 #define IFACE_ENTRIES_N_ENTRIES(_entries) ( (G_ATOMIC_ARRAY_DATA_SIZE((_entries)) - IFACE_ENTRIES_HEADER_SIZE) / sizeof(IFaceEntry) )
320
321 struct _CommonData
322 {
323   GTypeValueTable  *value_table;
324 };
325
326 struct _BoxedData
327 {
328   CommonData         data;
329   GBoxedCopyFunc     copy_func;
330   GBoxedFreeFunc     free_func;
331 };
332
333 struct _IFaceData
334 {
335   CommonData         common;
336   guint16            vtable_size;
337   GBaseInitFunc      vtable_init_base;
338   GBaseFinalizeFunc  vtable_finalize_base;
339   GClassInitFunc     dflt_init;
340   GClassFinalizeFunc dflt_finalize;
341   gconstpointer      dflt_data;
342   gpointer           dflt_vtable;
343 };
344
345 struct _ClassData
346 {
347   CommonData         common;
348   guint16            class_size;
349   guint16            class_private_size;
350   int                init_state;  /* (atomic) - g_type_class_ref reads it unlocked */
351   GBaseInitFunc      class_init_base;
352   GBaseFinalizeFunc  class_finalize_base;
353   GClassInitFunc     class_init;
354   GClassFinalizeFunc class_finalize;
355   gconstpointer      class_data;
356   gpointer           class;
357 };
358
359 struct _InstanceData
360 {
361   CommonData         common;
362   guint16            class_size;
363   guint16            class_private_size;
364   int                init_state;  /* (atomic) - g_type_class_ref reads it unlocked */
365   GBaseInitFunc      class_init_base;
366   GBaseFinalizeFunc  class_finalize_base;
367   GClassInitFunc     class_init;
368   GClassFinalizeFunc class_finalize;
369   gconstpointer      class_data;
370   gpointer           class;
371   guint16            instance_size;
372   guint16            private_size;
373   GInstanceInitFunc  instance_init;
374 };
375
376 union _TypeData
377 {
378   CommonData         common;
379   BoxedData          boxed;
380   IFaceData          iface;
381   ClassData          class;
382   InstanceData       instance;
383 };
384
385 typedef struct {
386   gpointer            cache_data;
387   GTypeClassCacheFunc cache_func;
388 } ClassCacheFunc;
389
390 typedef struct {
391   gpointer                check_data;
392   GTypeInterfaceCheckFunc check_func;
393 } IFaceCheckFunc;
394
395
396 /* --- variables --- */
397 static GRWLock         type_rw_lock;
398 static GRecMutex       class_init_rec_mutex;
399 static guint           static_n_class_cache_funcs = 0;
400 static ClassCacheFunc *static_class_cache_funcs = NULL;
401 static guint           static_n_iface_check_funcs = 0;
402 static IFaceCheckFunc *static_iface_check_funcs = NULL;
403 static GQuark          static_quark_type_flags = 0;
404 static GQuark          static_quark_iface_holder = 0;
405 static GQuark          static_quark_dependants_array = 0;
406 static guint           type_registration_serial = 0;
407
408 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
409 GTypeDebugFlags        _g_type_debug_flags = 0;
410 G_GNUC_END_IGNORE_DEPRECATIONS
411
412 /* --- type nodes --- */
413 static GHashTable       *static_type_nodes_ht = NULL;
414 static TypeNode         *static_fundamental_type_nodes[(G_TYPE_FUNDAMENTAL_MAX >> G_TYPE_FUNDAMENTAL_SHIFT) + 1] = { NULL, };
415 static GType             static_fundamental_next = G_TYPE_RESERVED_USER_FIRST;
416
417 static inline TypeNode*
418 lookup_type_node_I (GType utype)
419 {
420   if (utype > G_TYPE_FUNDAMENTAL_MAX)
421     return (TypeNode*) (utype & ~TYPE_ID_MASK);
422   else
423     return static_fundamental_type_nodes[utype >> G_TYPE_FUNDAMENTAL_SHIFT];
424 }
425
426 /**
427  * g_type_get_type_registration_serial:
428  *
429  * Returns an opaque serial number that represents the state of the set
430  * of registered types. Any time a type is registered this serial changes,
431  * which means you can cache information based on type lookups (such as
432  * g_type_from_name()) and know if the cache is still valid at a later
433  * time by comparing the current serial with the one at the type lookup.
434  *
435  * Since: 2.36
436  *
437  * Returns: An unsigned int, representing the state of type registrations
438  */
439 guint
440 g_type_get_type_registration_serial (void)
441 {
442   return (guint)g_atomic_int_get ((gint *)&type_registration_serial);
443 }
444
445 static TypeNode*
446 type_node_any_new_W (TypeNode             *pnode,
447                      GType                 ftype,
448                      const gchar          *name,
449                      GTypePlugin          *plugin,
450                      GTypeFundamentalFlags type_flags)
451 {
452   guint n_supers;
453   GType type;
454   TypeNode *node;
455   guint i, node_size = 0;
456
457   n_supers = pnode ? pnode->n_supers + 1 : 0;
458   
459   if (!pnode)
460     node_size += SIZEOF_FUNDAMENTAL_INFO;             /* fundamental type info */
461   node_size += SIZEOF_BASE_TYPE_NODE ();              /* TypeNode structure */
462   node_size += (sizeof (GType) * (1 + n_supers + 1)); /* self + ancestors + (0) for ->supers[] */
463   node = g_malloc0 (node_size);
464   if (!pnode)                                         /* offset fundamental types */
465     {
466       node = G_STRUCT_MEMBER_P (node, SIZEOF_FUNDAMENTAL_INFO);
467       static_fundamental_type_nodes[ftype >> G_TYPE_FUNDAMENTAL_SHIFT] = node;
468       type = ftype;
469
470 #if ENABLE_VALGRIND
471       VALGRIND_MALLOCLIKE_BLOCK (node, node_size - SIZEOF_FUNDAMENTAL_INFO, FALSE, TRUE);
472 #endif
473     }
474   else
475     type = (GType) node;
476   
477   g_assert ((type & TYPE_ID_MASK) == 0);
478   
479   node->n_supers = n_supers;
480   if (!pnode)
481     {
482       node->supers[0] = type;
483       node->supers[1] = 0;
484       
485       node->is_classed = (type_flags & G_TYPE_FLAG_CLASSED) != 0;
486       node->is_instantiatable = (type_flags & G_TYPE_FLAG_INSTANTIATABLE) != 0;
487       
488       if (NODE_IS_IFACE (node))
489         {
490           IFACE_NODE_N_PREREQUISITES (node) = 0;
491           IFACE_NODE_PREREQUISITES (node) = NULL;
492         }
493       else
494         _g_atomic_array_init (CLASSED_NODE_IFACES_ENTRIES (node));
495     }
496   else
497     {
498       node->supers[0] = type;
499       memcpy (node->supers + 1, pnode->supers, sizeof (GType) * (1 + pnode->n_supers + 1));
500       
501       node->is_classed = pnode->is_classed;
502       node->is_instantiatable = pnode->is_instantiatable;
503       
504       if (NODE_IS_IFACE (node))
505         {
506           IFACE_NODE_N_PREREQUISITES (node) = 0;
507           IFACE_NODE_PREREQUISITES (node) = NULL;
508         }
509       else
510         {
511           guint j;
512           IFaceEntries *entries;
513
514           entries = _g_atomic_array_copy (CLASSED_NODE_IFACES_ENTRIES (pnode),
515                                           IFACE_ENTRIES_HEADER_SIZE,
516                                           0);
517           if (entries)
518             {
519               for (j = 0; j < IFACE_ENTRIES_N_ENTRIES (entries); j++)
520                 {
521                   entries->entry[j].vtable = NULL;
522                   entries->entry[j].init_state = UNINITIALIZED;
523                 }
524               _g_atomic_array_update (CLASSED_NODE_IFACES_ENTRIES (node),
525                                       entries);
526             }
527         }
528
529       i = pnode->n_children++;
530       pnode->children = g_renew (GType, pnode->children, pnode->n_children);
531       pnode->children[i] = type;
532     }
533
534   TRACE(GOBJECT_TYPE_NEW(name, node->supers[1], type));
535
536   node->plugin = plugin;
537   node->n_children = 0;
538   node->children = NULL;
539   node->data = NULL;
540   node->qname = g_quark_from_string (name);
541   node->global_gdata = NULL;
542   g_hash_table_insert (static_type_nodes_ht,
543                        (gpointer) g_quark_to_string (node->qname),
544                        (gpointer) type);
545
546   g_atomic_int_inc ((gint *)&type_registration_serial);
547
548   return node;
549 }
550
551 static inline GTypeFundamentalInfo*
552 type_node_fundamental_info_I (TypeNode *node)
553 {
554   GType ftype = NODE_FUNDAMENTAL_TYPE (node);
555   
556   if (ftype != NODE_TYPE (node))
557     node = lookup_type_node_I (ftype);
558   
559   return node ? G_STRUCT_MEMBER_P (node, -SIZEOF_FUNDAMENTAL_INFO) : NULL;
560 }
561
562 static TypeNode*
563 type_node_fundamental_new_W (GType                 ftype,
564                              const gchar          *name,
565                              GTypeFundamentalFlags type_flags)
566 {
567   GTypeFundamentalInfo *finfo;
568   TypeNode *node;
569   
570   g_assert ((ftype & TYPE_ID_MASK) == 0);
571   g_assert (ftype <= G_TYPE_FUNDAMENTAL_MAX);
572   
573   if (ftype >> G_TYPE_FUNDAMENTAL_SHIFT == static_fundamental_next)
574     static_fundamental_next++;
575   
576   type_flags &= TYPE_FUNDAMENTAL_FLAG_MASK;
577   
578   node = type_node_any_new_W (NULL, ftype, name, NULL, type_flags);
579   
580   finfo = type_node_fundamental_info_I (node);
581   finfo->type_flags = type_flags;
582   
583   return node;
584 }
585
586 static TypeNode*
587 type_node_new_W (TypeNode    *pnode,
588                  const gchar *name,
589                  GTypePlugin *plugin)
590      
591 {
592   g_assert (pnode);
593   g_assert (pnode->n_supers < MAX_N_SUPERS);
594   g_assert (pnode->n_children < MAX_N_CHILDREN);
595   
596   return type_node_any_new_W (pnode, NODE_FUNDAMENTAL_TYPE (pnode), name, plugin, 0);
597 }
598
599 static inline IFaceEntry*
600 lookup_iface_entry_I (IFaceEntries *entries,
601                       TypeNode     *iface_node)
602 {
603   guint8 *offsets;
604   gsize offset_index;
605   IFaceEntry *check;
606   gsize index;
607   IFaceEntry *entry;
608
609   if (entries == NULL)
610     return NULL;
611
612   G_ATOMIC_ARRAY_DO_TRANSACTION
613     (&iface_node->_prot.offsets, guint8,
614
615      entry = NULL;
616      offsets = transaction_data;
617      offset_index = entries->offset_index;
618      if (offsets != NULL &&
619          offset_index < G_ATOMIC_ARRAY_DATA_SIZE(offsets))
620        {
621          index = offsets[offset_index];
622          if (index > 0)
623            {
624              /* zero means unset, subtract one to get real index */
625              index -= 1;
626
627              if (index < IFACE_ENTRIES_N_ENTRIES (entries))
628                {
629                  check = (IFaceEntry *)&entries->entry[index];
630                  if (check->iface_type == NODE_TYPE (iface_node))
631                    entry = check;
632                }
633            }
634        }
635      );
636
637  return entry;
638 }
639
640 static inline IFaceEntry*
641 type_lookup_iface_entry_L (TypeNode *node,
642                            TypeNode *iface_node)
643 {
644   if (!NODE_IS_IFACE (iface_node))
645     return NULL;
646
647   return lookup_iface_entry_I (CLASSED_NODE_IFACES_ENTRIES_LOCKED (node),
648                                iface_node);
649 }
650
651
652 static inline gboolean
653 type_lookup_iface_vtable_I (TypeNode *node,
654                             TypeNode *iface_node,
655                             gpointer *vtable_ptr)
656 {
657   IFaceEntry *entry;
658   gboolean res;
659
660   if (!NODE_IS_IFACE (iface_node))
661     {
662       if (vtable_ptr)
663         *vtable_ptr = NULL;
664       return FALSE;
665     }
666
667   G_ATOMIC_ARRAY_DO_TRANSACTION
668     (CLASSED_NODE_IFACES_ENTRIES (node), IFaceEntries,
669
670      entry = lookup_iface_entry_I (transaction_data, iface_node);
671      res = entry != NULL;
672      if (vtable_ptr)
673        {
674          if (entry)
675            *vtable_ptr = entry->vtable;
676          else
677            *vtable_ptr = NULL;
678        }
679      );
680
681   return res;
682 }
683
684 static inline gboolean
685 type_lookup_prerequisite_L (TypeNode *iface,
686                             GType     prerequisite_type)
687 {
688   if (NODE_IS_IFACE (iface) && IFACE_NODE_N_PREREQUISITES (iface))
689     {
690       GType *prerequisites = IFACE_NODE_PREREQUISITES (iface) - 1;
691       guint n_prerequisites = IFACE_NODE_N_PREREQUISITES (iface);
692       
693       do
694         {
695           guint i;
696           GType *check;
697           
698           i = (n_prerequisites + 1) >> 1;
699           check = prerequisites + i;
700           if (prerequisite_type == *check)
701             return TRUE;
702           else if (prerequisite_type > *check)
703             {
704               n_prerequisites -= i;
705               prerequisites = check;
706             }
707           else /* if (prerequisite_type < *check) */
708             n_prerequisites = i - 1;
709         }
710       while (n_prerequisites);
711     }
712   return FALSE;
713 }
714
715 static const gchar*
716 type_descriptive_name_I (GType type)
717 {
718   if (type)
719     {
720       TypeNode *node = lookup_type_node_I (type);
721       
722       return node ? NODE_NAME (node) : "<unknown>";
723     }
724   else
725     return "<invalid>";
726 }
727
728
729 /* --- type consistency checks --- */
730 static gboolean
731 check_plugin_U (GTypePlugin *plugin,
732                 gboolean     need_complete_type_info,
733                 gboolean     need_complete_interface_info,
734                 const gchar *type_name)
735 {
736   /* G_IS_TYPE_PLUGIN() and G_TYPE_PLUGIN_GET_CLASS() are external calls: _U 
737    */
738   if (!plugin)
739     {
740       g_critical ("plugin handle for type '%s' is NULL",
741                   type_name);
742       return FALSE;
743     }
744   if (!G_IS_TYPE_PLUGIN (plugin))
745     {
746       g_critical ("plugin pointer (%p) for type '%s' is invalid",
747                   plugin, type_name);
748       return FALSE;
749     }
750   if (need_complete_type_info && !G_TYPE_PLUGIN_GET_CLASS (plugin)->complete_type_info)
751     {
752       g_critical ("plugin for type '%s' has no complete_type_info() implementation",
753                   type_name);
754       return FALSE;
755     }
756   if (need_complete_interface_info && !G_TYPE_PLUGIN_GET_CLASS (plugin)->complete_interface_info)
757     {
758       g_critical ("plugin for type '%s' has no complete_interface_info() implementation",
759                   type_name);
760       return FALSE;
761     }
762   return TRUE;
763 }
764
765 static gboolean
766 check_type_name_I (const gchar *type_name)
767 {
768   static const gchar extra_chars[] = "-_+";
769   const gchar *p = type_name;
770   gboolean name_valid;
771   
772   if (!type_name[0] || !type_name[1] || !type_name[2])
773     {
774       g_critical ("type name '%s' is too short", type_name);
775       return FALSE;
776     }
777   /* check the first letter */
778   name_valid = (p[0] >= 'A' && p[0] <= 'Z') || (p[0] >= 'a' && p[0] <= 'z') || p[0] == '_';
779   for (p = type_name + 1; *p; p++)
780     name_valid &= ((p[0] >= 'A' && p[0] <= 'Z') ||
781                    (p[0] >= 'a' && p[0] <= 'z') ||
782                    (p[0] >= '0' && p[0] <= '9') ||
783                    strchr (extra_chars, p[0]));
784   if (!name_valid)
785     {
786       g_critical ("type name '%s' contains invalid characters", type_name);
787       return FALSE;
788     }
789   if (g_type_from_name (type_name))
790     {
791       g_critical ("cannot register existing type '%s'", type_name);
792       return FALSE;
793     }
794   
795   return TRUE;
796 }
797
798 static gboolean
799 check_derivation_I (GType        parent_type,
800                     const gchar *type_name)
801 {
802   TypeNode *pnode;
803   GTypeFundamentalInfo* finfo;
804   
805   pnode = lookup_type_node_I (parent_type);
806   if (!pnode)
807     {
808       g_critical ("cannot derive type '%s' from invalid parent type '%s'",
809                   type_name,
810                   type_descriptive_name_I (parent_type));
811       return FALSE;
812     }
813   if (pnode->is_final)
814     {
815       g_critical ("cannot derive '%s' from final parent type '%s'",
816                   type_name,
817                   NODE_NAME (pnode));
818       return FALSE;
819     }
820   finfo = type_node_fundamental_info_I (pnode);
821   /* ensure flat derivability */
822   if (!(finfo->type_flags & G_TYPE_FLAG_DERIVABLE))
823     {
824       g_critical ("cannot derive '%s' from non-derivable parent type '%s'",
825                   type_name,
826                   NODE_NAME (pnode));
827       return FALSE;
828     }
829   /* ensure deep derivability */
830   if (parent_type != NODE_FUNDAMENTAL_TYPE (pnode) &&
831       !(finfo->type_flags & G_TYPE_FLAG_DEEP_DERIVABLE))
832     {
833       g_critical ("cannot derive '%s' from non-fundamental parent type '%s'",
834                   type_name,
835                   NODE_NAME (pnode));
836       return FALSE;
837     }
838   
839   return TRUE;
840 }
841
842 static gboolean
843 check_collect_format_I (const gchar *collect_format)
844 {
845   const gchar *p = collect_format;
846   gchar valid_format[] = { G_VALUE_COLLECT_INT, G_VALUE_COLLECT_LONG,
847                            G_VALUE_COLLECT_INT64, G_VALUE_COLLECT_DOUBLE,
848                            G_VALUE_COLLECT_POINTER, 0 };
849   
850   while (*p)
851     if (!strchr (valid_format, *p++))
852       return FALSE;
853   return p - collect_format <= G_VALUE_COLLECT_FORMAT_MAX_LENGTH;
854 }
855
856 static gboolean
857 check_value_table_I (const gchar           *type_name,
858                      const GTypeValueTable *value_table)
859 {
860   if (!value_table)
861     return FALSE;
862   else if (value_table->value_init == NULL)
863     {
864       if (value_table->value_free || value_table->value_copy ||
865           value_table->value_peek_pointer ||
866           value_table->collect_format || value_table->collect_value ||
867           value_table->lcopy_format || value_table->lcopy_value)
868         g_critical ("cannot handle uninitializable values of type '%s'",
869                     type_name);
870       return FALSE;
871     }
872   else /* value_table->value_init != NULL */
873     {
874       if (!value_table->value_free)
875         {
876           /* +++ optional +++
877            * g_critical ("missing 'value_free()' for type '%s'", type_name);
878            * return FALSE;
879            */
880         }
881       if (!value_table->value_copy)
882         {
883           g_critical ("missing 'value_copy()' for type '%s'", type_name);
884           return FALSE;
885         }
886       if ((value_table->collect_format || value_table->collect_value) &&
887           (!value_table->collect_format || !value_table->collect_value))
888         {
889           g_critical ("one of 'collect_format' and 'collect_value()' is unspecified for type '%s'",
890                       type_name);
891           return FALSE;
892         }
893       if (value_table->collect_format && !check_collect_format_I (value_table->collect_format))
894         {
895           g_critical ("the '%s' specification for type '%s' is too long or invalid",
896                       "collect_format",
897                       type_name);
898           return FALSE;
899         }
900       if ((value_table->lcopy_format || value_table->lcopy_value) &&
901           (!value_table->lcopy_format || !value_table->lcopy_value))
902         {
903           g_critical ("one of 'lcopy_format' and 'lcopy_value()' is unspecified for type '%s'",
904                       type_name);
905           return FALSE;
906         }
907       if (value_table->lcopy_format && !check_collect_format_I (value_table->lcopy_format))
908         {
909           g_critical ("the '%s' specification for type '%s' is too long or invalid",
910                       "lcopy_format",
911                       type_name);
912           return FALSE;
913         }
914     }
915   return TRUE;
916 }
917
918 static gboolean
919 check_type_info_I (TypeNode        *pnode,
920                    GType            ftype,
921                    const gchar     *type_name,
922                    const GTypeInfo *info)
923 {
924   GTypeFundamentalInfo *finfo = type_node_fundamental_info_I (lookup_type_node_I (ftype));
925   gboolean is_interface = ftype == G_TYPE_INTERFACE;
926   
927   g_assert (ftype <= G_TYPE_FUNDAMENTAL_MAX && !(ftype & TYPE_ID_MASK));
928   
929   /* check instance members */
930   if (!(finfo->type_flags & G_TYPE_FLAG_INSTANTIATABLE) &&
931       (info->instance_size || info->instance_init))
932     {
933       if (pnode)
934         g_critical ("cannot instantiate '%s', derived from non-instantiatable parent type '%s'",
935                     type_name,
936                     NODE_NAME (pnode));
937       else
938         g_critical ("cannot instantiate '%s' as non-instantiatable fundamental",
939                     type_name);
940       return FALSE;
941     }
942   /* check class & interface members */
943   if (!((finfo->type_flags & G_TYPE_FLAG_CLASSED) || is_interface) &&
944       (info->class_init || info->class_finalize || info->class_data ||
945        info->class_size || info->base_init || info->base_finalize))
946     {
947       if (pnode)
948         g_critical ("cannot create class for '%s', derived from non-classed parent type '%s'",
949                     type_name,
950                     NODE_NAME (pnode));
951       else
952         g_critical ("cannot create class for '%s' as non-classed fundamental",
953                     type_name);
954       return FALSE;
955     }
956   /* check interface size */
957   if (is_interface && info->class_size < sizeof (GTypeInterface))
958     {
959       g_critical ("specified interface size for type '%s' is smaller than 'GTypeInterface' size",
960                   type_name);
961       return FALSE;
962     }
963   /* check class size */
964   if (finfo->type_flags & G_TYPE_FLAG_CLASSED)
965     {
966       if (info->class_size < sizeof (GTypeClass))
967         {
968           g_critical ("specified class size for type '%s' is smaller than 'GTypeClass' size",
969                       type_name);
970           return FALSE;
971         }
972       if (pnode && info->class_size < pnode->data->class.class_size)
973         {
974           g_critical ("specified class size for type '%s' is smaller "
975                       "than the parent type's '%s' class size",
976                       type_name,
977                       NODE_NAME (pnode));
978           return FALSE;
979         }
980     }
981   /* check instance size */
982   if (finfo->type_flags & G_TYPE_FLAG_INSTANTIATABLE)
983     {
984       if (info->instance_size < sizeof (GTypeInstance))
985         {
986           g_critical ("specified instance size for type '%s' is smaller than 'GTypeInstance' size",
987                       type_name);
988           return FALSE;
989         }
990       if (pnode && info->instance_size < pnode->data->instance.instance_size)
991         {
992           g_critical ("specified instance size for type '%s' is smaller "
993                       "than the parent type's '%s' instance size",
994                       type_name,
995                       NODE_NAME (pnode));
996           return FALSE;
997         }
998     }
999   
1000   return TRUE;
1001 }
1002
1003 static TypeNode*
1004 find_conforming_child_type_L (TypeNode *pnode,
1005                               TypeNode *iface)
1006 {
1007   TypeNode *node = NULL;
1008   guint i;
1009   
1010   if (type_lookup_iface_entry_L (pnode, iface))
1011     return pnode;
1012   
1013   for (i = 0; i < pnode->n_children && !node; i++)
1014     node = find_conforming_child_type_L (lookup_type_node_I (pnode->children[i]), iface);
1015   
1016   return node;
1017 }
1018
1019 static gboolean
1020 check_add_interface_L (GType instance_type,
1021                        GType iface_type)
1022 {
1023   TypeNode *node = lookup_type_node_I (instance_type);
1024   TypeNode *iface = lookup_type_node_I (iface_type);
1025   IFaceEntry *entry;
1026   TypeNode *tnode;
1027   GType *prerequisites;
1028   guint i;
1029
1030   
1031   if (!node || !node->is_instantiatable)
1032     {
1033       g_critical ("cannot add interfaces to invalid (non-instantiatable) type '%s'",
1034                   type_descriptive_name_I (instance_type));
1035       return FALSE;
1036     }
1037   if (!iface || !NODE_IS_IFACE (iface))
1038     {
1039       g_critical ("cannot add invalid (non-interface) type '%s' to type '%s'",
1040                   type_descriptive_name_I (iface_type),
1041                   NODE_NAME (node));
1042       return FALSE;
1043     }
1044   if (node->data && node->data->class.class)
1045     {
1046       g_critical ("attempting to add an interface (%s) to class (%s) after class_init",
1047                   NODE_NAME (iface), NODE_NAME (node));
1048       return FALSE;
1049     }
1050   tnode = lookup_type_node_I (NODE_PARENT_TYPE (iface));
1051   if (NODE_PARENT_TYPE (tnode) && !type_lookup_iface_entry_L (node, tnode))
1052     {
1053       /* 2001/7/31:timj: erk, i guess this warning is junk as interface derivation is flat */
1054       g_critical ("cannot add sub-interface '%s' to type '%s' which does not conform to super-interface '%s'",
1055                   NODE_NAME (iface),
1056                   NODE_NAME (node),
1057                   NODE_NAME (tnode));
1058       return FALSE;
1059     }
1060   /* allow overriding of interface type introduced for parent type */
1061   entry = type_lookup_iface_entry_L (node, iface);
1062   if (entry && entry->vtable == NULL && !type_iface_peek_holder_L (iface, NODE_TYPE (node)))
1063     {
1064       /* ok, we do conform to this interface already, but the interface vtable was not
1065        * yet initialized, and we just conform to the interface because it got added to
1066        * one of our parents. so we allow overriding of holder info here.
1067        */
1068       return TRUE;
1069     }
1070   /* check whether one of our children already conforms (or whether the interface
1071    * got added to this node already)
1072    */
1073   tnode = find_conforming_child_type_L (node, iface);  /* tnode is_a node */
1074   if (tnode)
1075     {
1076       g_critical ("cannot add interface type '%s' to type '%s', since type '%s' already conforms to interface",
1077                   NODE_NAME (iface),
1078                   NODE_NAME (node),
1079                   NODE_NAME (tnode));
1080       return FALSE;
1081     }
1082   prerequisites = IFACE_NODE_PREREQUISITES (iface);
1083   for (i = 0; i < IFACE_NODE_N_PREREQUISITES (iface); i++)
1084     {
1085       tnode = lookup_type_node_I (prerequisites[i]);
1086       if (!type_node_is_a_L (node, tnode))
1087         {
1088           g_critical ("cannot add interface type '%s' to type '%s' which does not conform to prerequisite '%s'",
1089                       NODE_NAME (iface),
1090                       NODE_NAME (node),
1091                       NODE_NAME (tnode));
1092           return FALSE;
1093         }
1094     }
1095   return TRUE;
1096 }
1097
1098 static gboolean
1099 check_interface_info_I (TypeNode             *iface,
1100                         GType                 instance_type,
1101                         const GInterfaceInfo *info)
1102 {
1103   if ((info->interface_finalize || info->interface_data) && !info->interface_init)
1104     {
1105       g_critical ("interface type '%s' for type '%s' comes without initializer",
1106                   NODE_NAME (iface),
1107                   type_descriptive_name_I (instance_type));
1108       return FALSE;
1109     }
1110   
1111   return TRUE;
1112 }
1113
1114 /* --- type info (type node data) --- */
1115 static void
1116 type_data_make_W (TypeNode              *node,
1117                   const GTypeInfo       *info,
1118                   const GTypeValueTable *value_table)
1119 {
1120   TypeData *data;
1121   GTypeValueTable *vtable = NULL;
1122   guint vtable_size = 0;
1123   
1124   g_assert (node->data == NULL && info != NULL);
1125   
1126   if (!value_table)
1127     {
1128       TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
1129       
1130       if (pnode)
1131         vtable = pnode->data->common.value_table;
1132       else
1133         {
1134           static const GTypeValueTable zero_vtable =
1135             { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
1136           
1137           value_table = &zero_vtable;
1138         }
1139     }
1140   if (value_table)
1141     {
1142       /* need to setup vtable_size since we have to allocate it with data in one chunk */
1143       vtable_size = sizeof (GTypeValueTable);
1144       if (value_table->collect_format)
1145         vtable_size += strlen (value_table->collect_format);
1146       if (value_table->lcopy_format)
1147         vtable_size += strlen (value_table->lcopy_format);
1148       vtable_size += 2;
1149     }
1150    
1151   if (node->is_instantiatable) /* careful, is_instantiatable is also is_classed */
1152     {
1153       TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
1154
1155       data = g_malloc0 (sizeof (InstanceData) + vtable_size);
1156       if (vtable_size)
1157         vtable = G_STRUCT_MEMBER_P (data, sizeof (InstanceData));
1158       data->instance.class_size = info->class_size;
1159       data->instance.class_init_base = info->base_init;
1160       data->instance.class_finalize_base = info->base_finalize;
1161       data->instance.class_init = info->class_init;
1162       data->instance.class_finalize = info->class_finalize;
1163       data->instance.class_data = info->class_data;
1164       data->instance.class = NULL;
1165       data->instance.init_state = UNINITIALIZED;
1166       data->instance.instance_size = info->instance_size;
1167       /* We'll set the final value for data->instance.private size
1168        * after the parent class has been initialized
1169        */
1170       data->instance.private_size = 0;
1171       data->instance.class_private_size = 0;
1172       if (pnode)
1173         data->instance.class_private_size = pnode->data->instance.class_private_size;
1174       data->instance.instance_init = info->instance_init;
1175     }
1176   else if (node->is_classed) /* only classed */
1177     {
1178       TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
1179
1180       data = g_malloc0 (sizeof (ClassData) + vtable_size);
1181       if (vtable_size)
1182         vtable = G_STRUCT_MEMBER_P (data, sizeof (ClassData));
1183       data->class.class_size = info->class_size;
1184       data->class.class_init_base = info->base_init;
1185       data->class.class_finalize_base = info->base_finalize;
1186       data->class.class_init = info->class_init;
1187       data->class.class_finalize = info->class_finalize;
1188       data->class.class_data = info->class_data;
1189       data->class.class = NULL;
1190       data->class.class_private_size = 0;
1191       if (pnode)
1192         data->class.class_private_size = pnode->data->class.class_private_size;
1193       data->class.init_state = UNINITIALIZED;
1194     }
1195   else if (NODE_IS_IFACE (node))
1196     {
1197       data = g_malloc0 (sizeof (IFaceData) + vtable_size);
1198       if (vtable_size)
1199         vtable = G_STRUCT_MEMBER_P (data, sizeof (IFaceData));
1200       data->iface.vtable_size = info->class_size;
1201       data->iface.vtable_init_base = info->base_init;
1202       data->iface.vtable_finalize_base = info->base_finalize;
1203       data->iface.dflt_init = info->class_init;
1204       data->iface.dflt_finalize = info->class_finalize;
1205       data->iface.dflt_data = info->class_data;
1206       data->iface.dflt_vtable = NULL;
1207     }
1208   else if (NODE_IS_BOXED (node))
1209     {
1210       data = g_malloc0 (sizeof (BoxedData) + vtable_size);
1211       if (vtable_size)
1212         vtable = G_STRUCT_MEMBER_P (data, sizeof (BoxedData));
1213     }
1214   else
1215     {
1216       data = g_malloc0 (sizeof (CommonData) + vtable_size);
1217       if (vtable_size)
1218         vtable = G_STRUCT_MEMBER_P (data, sizeof (CommonData));
1219     }
1220   
1221   node->data = data;
1222   
1223   if (vtable_size)
1224     {
1225       gchar *p;
1226       
1227       /* we allocate the vtable and its strings together with the type data, so
1228        * children can take over their parent's vtable pointer, and we don't
1229        * need to worry freeing it or not when the child data is destroyed
1230        */
1231       *vtable = *value_table;
1232       p = G_STRUCT_MEMBER_P (vtable, sizeof (*vtable));
1233       p[0] = 0;
1234       vtable->collect_format = p;
1235       if (value_table->collect_format)
1236         {
1237           strcat (p, value_table->collect_format);
1238           p += strlen (value_table->collect_format);
1239         }
1240       p++;
1241       p[0] = 0;
1242       vtable->lcopy_format = p;
1243       if (value_table->lcopy_format)
1244         strcat  (p, value_table->lcopy_format);
1245     }
1246   node->data->common.value_table = vtable;
1247   node->mutatable_check_cache = (node->data->common.value_table->value_init != NULL &&
1248                                  !((G_TYPE_FLAG_VALUE_ABSTRACT | G_TYPE_FLAG_ABSTRACT) &
1249                                    GPOINTER_TO_UINT (type_get_qdata_L (node, static_quark_type_flags))));
1250   
1251   g_assert (node->data->common.value_table != NULL); /* paranoid */
1252
1253   g_atomic_int_set ((int *) &node->ref_count, 1);
1254 }
1255
1256 static inline void
1257 type_data_ref_Wm (TypeNode *node)
1258 {
1259   if (!node->data)
1260     {
1261       TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
1262       GTypeInfo tmp_info;
1263       GTypeValueTable tmp_value_table;
1264       
1265       g_assert (node->plugin != NULL);
1266       
1267       if (pnode)
1268         {
1269           type_data_ref_Wm (pnode);
1270           if (node->data)
1271             INVALID_RECURSION ("g_type_plugin_*", node->plugin, NODE_NAME (node));
1272         }
1273       
1274       memset (&tmp_info, 0, sizeof (tmp_info));
1275       memset (&tmp_value_table, 0, sizeof (tmp_value_table));
1276       
1277       G_WRITE_UNLOCK (&type_rw_lock);
1278       g_type_plugin_use (node->plugin);
1279       g_type_plugin_complete_type_info (node->plugin, NODE_TYPE (node), &tmp_info, &tmp_value_table);
1280       G_WRITE_LOCK (&type_rw_lock);
1281       if (node->data)
1282         INVALID_RECURSION ("g_type_plugin_*", node->plugin, NODE_NAME (node));
1283       
1284       check_type_info_I (pnode, NODE_FUNDAMENTAL_TYPE (node), NODE_NAME (node), &tmp_info);
1285       type_data_make_W (node, &tmp_info,
1286                         check_value_table_I (NODE_NAME (node),
1287                                              &tmp_value_table) ? &tmp_value_table : NULL);
1288     }
1289   else
1290     {
1291       g_assert (NODE_REFCOUNT (node) > 0);
1292       
1293       g_atomic_int_inc ((int *) &node->ref_count);
1294     }
1295 }
1296
1297 static inline gboolean
1298 type_data_ref_U (TypeNode *node)
1299 {
1300   guint current;
1301
1302   do {
1303     current = NODE_REFCOUNT (node);
1304
1305     if (current < 1)
1306       return FALSE;
1307   } while (!g_atomic_int_compare_and_exchange ((int *) &node->ref_count, current, current + 1));
1308
1309   return TRUE;
1310 }
1311
1312 static gboolean
1313 iface_node_has_available_offset_L (TypeNode *iface_node,
1314                                    gsize offset,
1315                                    int for_index)
1316 {
1317   guint8 *offsets;
1318
1319   offsets = G_ATOMIC_ARRAY_GET_LOCKED (&iface_node->_prot.offsets, guint8);
1320   if (offsets == NULL)
1321     return TRUE;
1322
1323   if (G_ATOMIC_ARRAY_DATA_SIZE (offsets) <= offset)
1324     return TRUE;
1325
1326   if (offsets[offset] == 0 ||
1327       offsets[offset] == for_index+1)
1328     return TRUE;
1329
1330   return FALSE;
1331 }
1332
1333 static gsize
1334 find_free_iface_offset_L (IFaceEntries *entries)
1335 {
1336   IFaceEntry *entry;
1337   TypeNode *iface_node;
1338   gsize offset;
1339   int i;
1340   int n_entries;
1341
1342   n_entries = IFACE_ENTRIES_N_ENTRIES (entries);
1343   offset = 0;
1344   do
1345     {
1346       for (i = 0; i < n_entries; i++)
1347         {
1348           entry = &entries->entry[i];
1349           iface_node = lookup_type_node_I (entry->iface_type);
1350
1351           if (!iface_node_has_available_offset_L (iface_node, offset, i))
1352             {
1353               offset++;
1354               break;
1355             }
1356         }
1357     }
1358   while (i != n_entries);
1359
1360   return offset;
1361 }
1362
1363 static void
1364 iface_node_set_offset_L (TypeNode *iface_node,
1365                          gsize offset,
1366                          int index)
1367 {
1368   guint8 *offsets, *old_offsets;
1369   gsize new_size, old_size;
1370   gsize i;
1371
1372   old_offsets = G_ATOMIC_ARRAY_GET_LOCKED (&iface_node->_prot.offsets, guint8);
1373   if (old_offsets == NULL)
1374     old_size = 0;
1375   else
1376     {
1377       old_size = G_ATOMIC_ARRAY_DATA_SIZE (old_offsets);
1378       if (offset < old_size &&
1379           old_offsets[offset] == index + 1)
1380         return; /* Already set to this index, return */
1381     }
1382   new_size = MAX (old_size, offset + 1);
1383
1384   offsets = _g_atomic_array_copy (&iface_node->_prot.offsets,
1385                                   0, new_size - old_size);
1386
1387   /* Mark new area as unused */
1388   for (i = old_size; i < new_size; i++)
1389     offsets[i] = 0;
1390
1391   offsets[offset] = index + 1;
1392
1393   _g_atomic_array_update (&iface_node->_prot.offsets, offsets);
1394 }
1395
1396 static void
1397 type_node_add_iface_entry_W (TypeNode   *node,
1398                              GType       iface_type,
1399                              IFaceEntry *parent_entry)
1400 {
1401   IFaceEntries *entries;
1402   IFaceEntry *entry;
1403   TypeNode *iface_node;
1404   guint i, j;
1405   guint num_entries;
1406
1407   g_assert (node->is_instantiatable);
1408
1409   entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node);
1410   if (entries != NULL)
1411     {
1412       num_entries = IFACE_ENTRIES_N_ENTRIES (entries);
1413
1414       g_assert (num_entries < MAX_N_INTERFACES);
1415
1416       for (i = 0; i < num_entries; i++)
1417         {
1418           entry = &entries->entry[i];
1419           if (entry->iface_type == iface_type)
1420             {
1421               /* this can happen in two cases:
1422                * - our parent type already conformed to iface_type and node
1423                *   got its own holder info. here, our children already have
1424                *   entries and NULL vtables, since this will only work for
1425                *   uninitialized classes.
1426                * - an interface type is added to an ancestor after it was
1427                *   added to a child type.
1428                */
1429               if (!parent_entry)
1430                 g_assert (entry->vtable == NULL && entry->init_state == UNINITIALIZED);
1431               else
1432                 {
1433                   /* sick, interface is added to ancestor *after* child type;
1434                    * nothing todo, the entry and our children were already setup correctly
1435                    */
1436                 }
1437               return;
1438             }
1439         }
1440     }
1441
1442   entries = _g_atomic_array_copy (CLASSED_NODE_IFACES_ENTRIES (node),
1443                                   IFACE_ENTRIES_HEADER_SIZE,
1444                                   sizeof (IFaceEntry));
1445   num_entries = IFACE_ENTRIES_N_ENTRIES (entries);
1446   i = num_entries - 1;
1447   if (i == 0)
1448     entries->offset_index = 0;
1449   entries->entry[i].iface_type = iface_type;
1450   entries->entry[i].vtable = NULL;
1451   entries->entry[i].init_state = UNINITIALIZED;
1452
1453   if (parent_entry)
1454     {
1455       if (node->data && g_atomic_int_get (&node->data->class.init_state) >= BASE_IFACE_INIT)
1456         {
1457           entries->entry[i].init_state = INITIALIZED;
1458           entries->entry[i].vtable = parent_entry->vtable;
1459         }
1460     }
1461
1462   /* Update offsets in iface */
1463   iface_node = lookup_type_node_I (iface_type);
1464
1465   if (iface_node_has_available_offset_L (iface_node,
1466                                          entries->offset_index,
1467                                          i))
1468     {
1469       iface_node_set_offset_L (iface_node,
1470                                entries->offset_index, i);
1471     }
1472   else
1473    {
1474       entries->offset_index =
1475         find_free_iface_offset_L (entries);
1476       for (j = 0; j < IFACE_ENTRIES_N_ENTRIES (entries); j++)
1477         {
1478           entry = &entries->entry[j];
1479           iface_node =
1480             lookup_type_node_I (entry->iface_type);
1481           iface_node_set_offset_L (iface_node,
1482                                    entries->offset_index, j);
1483         }
1484     }
1485
1486   _g_atomic_array_update (CLASSED_NODE_IFACES_ENTRIES (node), entries);
1487
1488   if (parent_entry)
1489     {
1490       for (i = 0; i < node->n_children; i++)
1491         type_node_add_iface_entry_W (lookup_type_node_I (node->children[i]), iface_type, &entries->entry[i]);
1492     }
1493 }
1494
1495 static void
1496 type_add_interface_Wm (TypeNode             *node,
1497                        TypeNode             *iface,
1498                        const GInterfaceInfo *info,
1499                        GTypePlugin          *plugin)
1500 {
1501   IFaceHolder *iholder = g_new0 (IFaceHolder, 1);
1502   IFaceEntry *entry;
1503   guint i;
1504
1505   g_assert (node->is_instantiatable && NODE_IS_IFACE (iface) && ((info && !plugin) || (!info && plugin)));
1506   
1507   iholder->next = iface_node_get_holders_L (iface);
1508   iface_node_set_holders_W (iface, iholder);
1509   iholder->instance_type = NODE_TYPE (node);
1510   iholder->info = info ? g_memdup2 (info, sizeof (*info)) : NULL;
1511   iholder->plugin = plugin;
1512
1513   /* create an iface entry for this type */
1514   type_node_add_iface_entry_W (node, NODE_TYPE (iface), NULL);
1515   
1516   /* if the class is already (partly) initialized, we may need to base
1517    * initialize and/or initialize the new interface.
1518    */
1519   if (node->data)
1520     {
1521       InitState class_state = g_atomic_int_get (&node->data->class.init_state);
1522       
1523       if (class_state >= BASE_IFACE_INIT)
1524         type_iface_vtable_base_init_Wm (iface, node);
1525       
1526       if (class_state >= IFACE_INIT)
1527         type_iface_vtable_iface_init_Wm (iface, node);
1528     }
1529   
1530   /* create iface entries for children of this type */
1531   entry = type_lookup_iface_entry_L (node, iface);
1532   for (i = 0; i < node->n_children; i++)
1533     type_node_add_iface_entry_W (lookup_type_node_I (node->children[i]), NODE_TYPE (iface), entry);
1534 }
1535
1536 static void
1537 type_iface_add_prerequisite_W (TypeNode *iface,
1538                                TypeNode *prerequisite_node)
1539 {
1540   GType prerequisite_type = NODE_TYPE (prerequisite_node);
1541   GType *prerequisites, *dependants;
1542   guint n_dependants, i;
1543   
1544   g_assert (NODE_IS_IFACE (iface) &&
1545             IFACE_NODE_N_PREREQUISITES (iface) < MAX_N_PREREQUISITES &&
1546             (prerequisite_node->is_instantiatable || NODE_IS_IFACE (prerequisite_node)));
1547   
1548   prerequisites = IFACE_NODE_PREREQUISITES (iface);
1549   for (i = 0; i < IFACE_NODE_N_PREREQUISITES (iface); i++)
1550     if (prerequisites[i] == prerequisite_type)
1551       return;                   /* we already have that prerequisiste */
1552     else if (prerequisites[i] > prerequisite_type)
1553       break;
1554   IFACE_NODE_N_PREREQUISITES (iface) += 1;
1555   IFACE_NODE_PREREQUISITES (iface) = g_renew (GType,
1556                                               IFACE_NODE_PREREQUISITES (iface),
1557                                               IFACE_NODE_N_PREREQUISITES (iface));
1558   prerequisites = IFACE_NODE_PREREQUISITES (iface);
1559   memmove (prerequisites + i + 1, prerequisites + i,
1560            sizeof (prerequisites[0]) * (IFACE_NODE_N_PREREQUISITES (iface) - i - 1));
1561   prerequisites[i] = prerequisite_type;
1562   
1563   /* we want to get notified when prerequisites get added to prerequisite_node */
1564   if (NODE_IS_IFACE (prerequisite_node))
1565     {
1566       dependants = iface_node_get_dependants_array_L (prerequisite_node);
1567       n_dependants = dependants ? dependants[0] : 0;
1568       n_dependants += 1;
1569       dependants = g_renew (GType, dependants, n_dependants + 1);
1570       dependants[n_dependants] = NODE_TYPE (iface);
1571       dependants[0] = n_dependants;
1572       iface_node_set_dependants_array_W (prerequisite_node, dependants);
1573     }
1574   
1575   /* we need to notify all dependants */
1576   dependants = iface_node_get_dependants_array_L (iface);
1577   n_dependants = dependants ? dependants[0] : 0;
1578   for (i = 1; i <= n_dependants; i++)
1579     type_iface_add_prerequisite_W (lookup_type_node_I (dependants[i]), prerequisite_node);
1580 }
1581
1582 /**
1583  * g_type_interface_add_prerequisite:
1584  * @interface_type: #GType value of an interface type
1585  * @prerequisite_type: #GType value of an interface or instantiatable type
1586  *
1587  * Adds @prerequisite_type to the list of prerequisites of @interface_type.
1588  * This means that any type implementing @interface_type must also implement
1589  * @prerequisite_type. Prerequisites can be thought of as an alternative to
1590  * interface derivation (which GType doesn't support). An interface can have
1591  * at most one instantiatable prerequisite type.
1592  */
1593 void
1594 g_type_interface_add_prerequisite (GType interface_type,
1595                                    GType prerequisite_type)
1596 {
1597   TypeNode *iface, *prerequisite_node;
1598   IFaceHolder *holders;
1599   
1600   g_return_if_fail (G_TYPE_IS_INTERFACE (interface_type));      /* G_TYPE_IS_INTERFACE() is an external call: _U */
1601   g_return_if_fail (!g_type_is_a (interface_type, prerequisite_type));
1602   g_return_if_fail (!g_type_is_a (prerequisite_type, interface_type));
1603   
1604   iface = lookup_type_node_I (interface_type);
1605   prerequisite_node = lookup_type_node_I (prerequisite_type);
1606   if (!iface || !prerequisite_node || !NODE_IS_IFACE (iface))
1607     {
1608       g_critical ("interface type '%s' or prerequisite type '%s' invalid",
1609                   type_descriptive_name_I (interface_type),
1610                   type_descriptive_name_I (prerequisite_type));
1611       return;
1612     }
1613   G_WRITE_LOCK (&type_rw_lock);
1614   holders = iface_node_get_holders_L (iface);
1615   if (holders)
1616     {
1617       G_WRITE_UNLOCK (&type_rw_lock);
1618       g_critical ("unable to add prerequisite '%s' to interface '%s' which is already in use for '%s'",
1619                   type_descriptive_name_I (prerequisite_type),
1620                   type_descriptive_name_I (interface_type),
1621                   type_descriptive_name_I (holders->instance_type));
1622       return;
1623     }
1624   if (prerequisite_node->is_instantiatable)
1625     {
1626       guint i;
1627       
1628       /* can have at most one publicly installable instantiatable prerequisite */
1629       for (i = 0; i < IFACE_NODE_N_PREREQUISITES (iface); i++)
1630         {
1631           TypeNode *prnode = lookup_type_node_I (IFACE_NODE_PREREQUISITES (iface)[i]);
1632           
1633           if (prnode->is_instantiatable)
1634             {
1635               G_WRITE_UNLOCK (&type_rw_lock);
1636               g_critical ("adding prerequisite '%s' to interface '%s' conflicts with existing prerequisite '%s'",
1637                           type_descriptive_name_I (prerequisite_type),
1638                           type_descriptive_name_I (interface_type),
1639                           type_descriptive_name_I (NODE_TYPE (prnode)));
1640               return;
1641             }
1642         }
1643       
1644       for (i = 0; i < prerequisite_node->n_supers + 1u; i++)
1645         type_iface_add_prerequisite_W (iface, lookup_type_node_I (prerequisite_node->supers[i]));
1646       G_WRITE_UNLOCK (&type_rw_lock);
1647     }
1648   else if (NODE_IS_IFACE (prerequisite_node))
1649     {
1650       GType *prerequisites;
1651       guint i;
1652       
1653       prerequisites = IFACE_NODE_PREREQUISITES (prerequisite_node);
1654       for (i = 0; i < IFACE_NODE_N_PREREQUISITES (prerequisite_node); i++)
1655         type_iface_add_prerequisite_W (iface, lookup_type_node_I (prerequisites[i]));
1656       type_iface_add_prerequisite_W (iface, prerequisite_node);
1657       G_WRITE_UNLOCK (&type_rw_lock);
1658     }
1659   else
1660     {
1661       G_WRITE_UNLOCK (&type_rw_lock);
1662       g_critical ("prerequisite '%s' for interface '%s' is neither instantiatable nor interface",
1663                   type_descriptive_name_I (prerequisite_type),
1664                   type_descriptive_name_I (interface_type));
1665     }
1666 }
1667
1668 /**
1669  * g_type_interface_prerequisites:
1670  * @interface_type: an interface type
1671  * @n_prerequisites: (out) (optional): location to return the number
1672  *     of prerequisites, or %NULL
1673  *
1674  * Returns the prerequisites of an interfaces type.
1675  *
1676  * Since: 2.2
1677  *
1678  * Returns: (array length=n_prerequisites) (transfer full): a
1679  *     newly-allocated zero-terminated array of #GType containing
1680  *     the prerequisites of @interface_type
1681  */
1682 GType*
1683 g_type_interface_prerequisites (GType  interface_type,
1684                                 guint *n_prerequisites)
1685 {
1686   TypeNode *iface;
1687   
1688   g_return_val_if_fail (G_TYPE_IS_INTERFACE (interface_type), NULL);
1689
1690   iface = lookup_type_node_I (interface_type);
1691   if (iface)
1692     {
1693       GType *types;
1694       TypeNode *inode = NULL;
1695       guint i, n = 0;
1696       
1697       G_READ_LOCK (&type_rw_lock);
1698       types = g_new0 (GType, IFACE_NODE_N_PREREQUISITES (iface) + 1);
1699       for (i = 0; i < IFACE_NODE_N_PREREQUISITES (iface); i++)
1700         {
1701           GType prerequisite = IFACE_NODE_PREREQUISITES (iface)[i];
1702           TypeNode *node = lookup_type_node_I (prerequisite);
1703           if (node->is_instantiatable)
1704             {
1705               if (!inode || type_node_is_a_L (node, inode))
1706                 inode = node;
1707             }
1708           else
1709             types[n++] = NODE_TYPE (node);
1710         }
1711       if (inode)
1712         types[n++] = NODE_TYPE (inode);
1713       
1714       if (n_prerequisites)
1715         *n_prerequisites = n;
1716       G_READ_UNLOCK (&type_rw_lock);
1717       
1718       return types;
1719     }
1720   else
1721     {
1722       if (n_prerequisites)
1723         *n_prerequisites = 0;
1724       
1725       return NULL;
1726     }
1727 }
1728
1729 /**
1730  * g_type_interface_instantiatable_prerequisite:
1731  * @interface_type: an interface type
1732  *
1733  * Returns the most specific instantiatable prerequisite of an
1734  * interface type. If the interface type has no instantiatable
1735  * prerequisite, %G_TYPE_INVALID is returned.
1736  *
1737  * See g_type_interface_add_prerequisite() for more information
1738  * about prerequisites.
1739  *
1740  * Returns: the instantiatable prerequisite type or %G_TYPE_INVALID if none
1741  *
1742  * Since: 2.68
1743  **/
1744 GType
1745 g_type_interface_instantiatable_prerequisite (GType interface_type)
1746 {
1747   TypeNode *inode = NULL;
1748   TypeNode *iface;
1749   guint i;
1750
1751   g_return_val_if_fail (G_TYPE_IS_INTERFACE (interface_type), G_TYPE_INVALID);
1752
1753   iface = lookup_type_node_I (interface_type);
1754   if (iface == NULL)
1755     return G_TYPE_INVALID;
1756
1757   G_READ_LOCK (&type_rw_lock);
1758
1759   for (i = 0; i < IFACE_NODE_N_PREREQUISITES (iface); i++)
1760     {
1761       GType prerequisite = IFACE_NODE_PREREQUISITES (iface)[i];
1762       TypeNode *node = lookup_type_node_I (prerequisite);
1763       if (node->is_instantiatable)
1764         {
1765           if (!inode || type_node_is_a_L (node, inode))
1766             inode = node;
1767         }
1768     }
1769
1770   G_READ_UNLOCK (&type_rw_lock);
1771
1772   if (inode)
1773     return NODE_TYPE (inode);
1774   else
1775     return G_TYPE_INVALID;
1776 }
1777
1778 static IFaceHolder*
1779 type_iface_peek_holder_L (TypeNode *iface,
1780                           GType     instance_type)
1781 {
1782   IFaceHolder *iholder;
1783   
1784   g_assert (NODE_IS_IFACE (iface));
1785   
1786   iholder = iface_node_get_holders_L (iface);
1787   while (iholder && iholder->instance_type != instance_type)
1788     iholder = iholder->next;
1789   return iholder;
1790 }
1791
1792 static IFaceHolder*
1793 type_iface_retrieve_holder_info_Wm (TypeNode *iface,
1794                                     GType     instance_type,
1795                                     gboolean  need_info)
1796 {
1797   IFaceHolder *iholder = type_iface_peek_holder_L (iface, instance_type);
1798   
1799   if (iholder && !iholder->info && need_info)
1800     {
1801       GInterfaceInfo tmp_info;
1802       
1803       g_assert (iholder->plugin != NULL);
1804       
1805       type_data_ref_Wm (iface);
1806       if (iholder->info)
1807         INVALID_RECURSION ("g_type_plugin_*", iface->plugin, NODE_NAME (iface));
1808       
1809       memset (&tmp_info, 0, sizeof (tmp_info));
1810       
1811       G_WRITE_UNLOCK (&type_rw_lock);
1812       g_type_plugin_use (iholder->plugin);
1813       g_type_plugin_complete_interface_info (iholder->plugin, instance_type, NODE_TYPE (iface), &tmp_info);
1814       G_WRITE_LOCK (&type_rw_lock);
1815       if (iholder->info)
1816         INVALID_RECURSION ("g_type_plugin_*", iholder->plugin, NODE_NAME (iface));
1817       
1818       check_interface_info_I (iface, instance_type, &tmp_info);
1819       iholder->info = g_memdup2 (&tmp_info, sizeof (tmp_info));
1820     }
1821   
1822   return iholder;       /* we don't modify write lock upon returning NULL */
1823 }
1824
1825 static void
1826 type_iface_blow_holder_info_Wm (TypeNode *iface,
1827                                 GType     instance_type)
1828 {
1829   IFaceHolder *iholder = iface_node_get_holders_L (iface);
1830   
1831   g_assert (NODE_IS_IFACE (iface));
1832   
1833   while (iholder->instance_type != instance_type)
1834     iholder = iholder->next;
1835   
1836   if (iholder->info && iholder->plugin)
1837     {
1838       g_free (iholder->info);
1839       iholder->info = NULL;
1840       
1841       G_WRITE_UNLOCK (&type_rw_lock);
1842       g_type_plugin_unuse (iholder->plugin);
1843       type_data_unref_U (iface, FALSE);
1844       G_WRITE_LOCK (&type_rw_lock);
1845     }
1846 }
1847
1848 static void
1849 maybe_issue_deprecation_warning (GType type)
1850 {
1851   static GHashTable *already_warned_table;
1852   static const gchar *enable_diagnostic;
1853   static GMutex already_warned_lock;
1854   gboolean already;
1855   const char *name;
1856
1857   if (g_once_init_enter (&enable_diagnostic))
1858     {
1859       const gchar *value = g_getenv ("G_ENABLE_DIAGNOSTIC");
1860
1861       if (!value)
1862         value = "0";
1863
1864       g_once_init_leave (&enable_diagnostic, value);
1865     }
1866
1867   if (enable_diagnostic[0] == '0')
1868     return;
1869
1870   g_mutex_lock (&already_warned_lock);
1871
1872   if (already_warned_table == NULL)
1873     already_warned_table = g_hash_table_new (NULL, NULL);
1874
1875   name = g_type_name (type);
1876
1877   already = g_hash_table_contains (already_warned_table, (gpointer) name);
1878   if (!already)
1879     g_hash_table_add (already_warned_table, (gpointer) name);
1880
1881   g_mutex_unlock (&already_warned_lock);
1882
1883   if (!already)
1884     g_warning ("The type %s is deprecated and shouldn’t be used "
1885                "any more. It may be removed in a future version.",
1886                name);
1887 }
1888
1889 /**
1890  * g_type_create_instance: (skip)
1891  * @type: an instantiatable type to create an instance for
1892  *
1893  * Creates and initializes an instance of @type if @type is valid and
1894  * can be instantiated. The type system only performs basic allocation
1895  * and structure setups for instances: actual instance creation should
1896  * happen through functions supplied by the type's fundamental type
1897  * implementation.  So use of g_type_create_instance() is reserved for
1898  * implementers of fundamental types only. E.g. instances of the
1899  * #GObject hierarchy should be created via g_object_new() and never
1900  * directly through g_type_create_instance() which doesn't handle things
1901  * like singleton objects or object construction.
1902  *
1903  * The extended members of the returned instance are guaranteed to be filled
1904  * with zeros.
1905  *
1906  * Note: Do not use this function, unless you're implementing a
1907  * fundamental type. Also language bindings should not use this
1908  * function, but g_object_new() instead.
1909  *
1910  * Returns: an allocated and initialized instance, subject to further
1911  *     treatment by the fundamental type implementation
1912  */
1913 GTypeInstance*
1914 g_type_create_instance (GType type)
1915 {
1916   TypeNode *node;
1917   GTypeInstance *instance;
1918   GTypeClass *class;
1919   gchar *allocated;
1920   gint private_size;
1921   gint ivar_size;
1922   guint i;
1923
1924   node = lookup_type_node_I (type);
1925   if (G_UNLIKELY (!node || !node->is_instantiatable))
1926     {
1927       g_error ("cannot create new instance of invalid (non-instantiatable) type '%s'",
1928                  type_descriptive_name_I (type));
1929     }
1930   /* G_TYPE_IS_ABSTRACT() is an external call: _U */
1931   if (G_UNLIKELY (!node->mutatable_check_cache && G_TYPE_IS_ABSTRACT (type)))
1932     {
1933       g_error ("cannot create instance of abstract (non-instantiatable) type '%s'",
1934                  type_descriptive_name_I (type));
1935     }
1936   if (G_UNLIKELY (G_TYPE_IS_DEPRECATED (type)))
1937     {
1938       maybe_issue_deprecation_warning (type);
1939     }
1940
1941   class = g_type_class_ref (type);
1942
1943   /* We allocate the 'private' areas before the normal instance data, in
1944    * reverse order.  This allows the private area of a particular class
1945    * to always be at a constant relative address to the instance data.
1946    * If we stored the private data after the instance data this would
1947    * not be the case (since a subclass that added more instance
1948    * variables would push the private data further along).
1949    *
1950    * This presents problems for valgrindability, of course, so we do a
1951    * workaround for that case.  We identify the start of the object to
1952    * valgrind as an allocated block (so that pointers to objects show up
1953    * as 'reachable' instead of 'possibly lost').  We then add an extra
1954    * pointer at the end of the object, after all instance data, back to
1955    * the start of the private area so that it is also recorded as
1956    * reachable.  We also add extra private space at the start because
1957    * valgrind doesn't seem to like us claiming to have allocated an
1958    * address that it saw allocated by malloc().
1959    */
1960   private_size = node->data->instance.private_size;
1961   ivar_size = node->data->instance.instance_size;
1962
1963 #ifdef ENABLE_VALGRIND
1964   if (G_UNLIKELY (private_size && RUNNING_ON_VALGRIND))
1965     {
1966       private_size += ALIGN_STRUCT (1);
1967
1968       /* Allocate one extra pointer size... */
1969       allocated = g_malloc0 (private_size + ivar_size + sizeof (gpointer));
1970       /* ... and point it back to the start of the private data. */
1971       *(gpointer *) (allocated + private_size + ivar_size) = allocated + ALIGN_STRUCT (1);
1972
1973       /* Tell valgrind that it should treat the object itself as such */
1974       VALGRIND_MALLOCLIKE_BLOCK (allocated + private_size, ivar_size + sizeof (gpointer), 0, TRUE);
1975       VALGRIND_MALLOCLIKE_BLOCK (allocated + ALIGN_STRUCT (1), private_size - ALIGN_STRUCT (1), 0, TRUE);
1976     }
1977   else
1978 #endif
1979     allocated = g_malloc0 (private_size + ivar_size);
1980
1981   instance = (GTypeInstance *) (allocated + private_size);
1982
1983   for (i = node->n_supers; i > 0; i--)
1984     {
1985       TypeNode *pnode;
1986       
1987       pnode = lookup_type_node_I (node->supers[i]);
1988       if (pnode->data->instance.instance_init)
1989         {
1990           instance->g_class = pnode->data->instance.class;
1991           pnode->data->instance.instance_init (instance, class);
1992         }
1993     }
1994
1995   instance->g_class = class;
1996   if (node->data->instance.instance_init)
1997     node->data->instance.instance_init (instance, class);
1998
1999 #ifdef  G_ENABLE_DEBUG
2000   IF_DEBUG (INSTANCE_COUNT)
2001     {
2002       g_atomic_int_inc ((int *) &node->instance_count);
2003     }
2004 #endif
2005
2006   TRACE(GOBJECT_OBJECT_NEW(instance, type));
2007
2008   return instance;
2009 }
2010
2011 /**
2012  * g_type_free_instance:
2013  * @instance: an instance of a type
2014  *
2015  * Frees an instance of a type, returning it to the instance pool for
2016  * the type, if there is one.
2017  *
2018  * Like g_type_create_instance(), this function is reserved for
2019  * implementors of fundamental types.
2020  */
2021 void
2022 g_type_free_instance (GTypeInstance *instance)
2023 {
2024   TypeNode *node;
2025   GTypeClass *class;
2026   gchar *allocated;
2027   gint private_size;
2028   gint ivar_size;
2029
2030   g_return_if_fail (instance != NULL && instance->g_class != NULL);
2031   
2032   class = instance->g_class;
2033   node = lookup_type_node_I (class->g_type);
2034   if (G_UNLIKELY (!node || !node->is_instantiatable || !node->data || node->data->class.class != (gpointer) class))
2035     {
2036       g_critical ("cannot free instance of invalid (non-instantiatable) type '%s'",
2037                   type_descriptive_name_I (class->g_type));
2038       return;
2039     }
2040   /* G_TYPE_IS_ABSTRACT() is an external call: _U */
2041   if (G_UNLIKELY (!node->mutatable_check_cache && G_TYPE_IS_ABSTRACT (NODE_TYPE (node))))
2042     {
2043       g_critical ("cannot free instance of abstract (non-instantiatable) type '%s'",
2044                   NODE_NAME (node));
2045       return;
2046     }
2047   
2048   instance->g_class = NULL;
2049   private_size = node->data->instance.private_size;
2050   ivar_size = node->data->instance.instance_size;
2051   allocated = ((gchar *) instance) - private_size;
2052
2053 #ifdef G_ENABLE_DEBUG
2054   memset (allocated, 0xaa, ivar_size + private_size);
2055 #endif
2056
2057 #ifdef ENABLE_VALGRIND
2058   /* See comment in g_type_create_instance() about what's going on here.
2059    * We're basically unwinding what we put into motion there.
2060    */
2061   if (G_UNLIKELY (private_size && RUNNING_ON_VALGRIND))
2062     {
2063       private_size += ALIGN_STRUCT (1);
2064       allocated -= ALIGN_STRUCT (1);
2065
2066       /* Clear out the extra pointer... */
2067       *(gpointer *) (allocated + private_size + ivar_size) = NULL;
2068       /* ... and ensure we include it in the size we free. */
2069       g_free_sized (allocated, private_size + ivar_size + sizeof (gpointer));
2070
2071       VALGRIND_FREELIKE_BLOCK (allocated + ALIGN_STRUCT (1), 0);
2072       VALGRIND_FREELIKE_BLOCK (instance, 0);
2073     }
2074   else
2075 #endif
2076     g_free_sized (allocated, private_size + ivar_size);
2077
2078 #ifdef  G_ENABLE_DEBUG
2079   IF_DEBUG (INSTANCE_COUNT)
2080     {
2081       g_atomic_int_add ((int *) &node->instance_count, -1);
2082     }
2083 #endif
2084
2085   g_type_class_unref (class);
2086 }
2087
2088 static void
2089 type_iface_ensure_dflt_vtable_Wm (TypeNode *iface)
2090 {
2091   g_assert (iface->data);
2092
2093   if (!iface->data->iface.dflt_vtable)
2094     {
2095       GTypeInterface *vtable = g_malloc0 (iface->data->iface.vtable_size);
2096       iface->data->iface.dflt_vtable = vtable;
2097       vtable->g_type = NODE_TYPE (iface);
2098       vtable->g_instance_type = 0;
2099       if (iface->data->iface.vtable_init_base ||
2100           iface->data->iface.dflt_init)
2101         {
2102           G_WRITE_UNLOCK (&type_rw_lock);
2103           if (iface->data->iface.vtable_init_base)
2104             iface->data->iface.vtable_init_base (vtable);
2105           if (iface->data->iface.dflt_init)
2106             iface->data->iface.dflt_init (vtable, (gpointer) iface->data->iface.dflt_data);
2107           G_WRITE_LOCK (&type_rw_lock);
2108         }
2109     }
2110 }
2111
2112
2113 /* This is called to allocate and do the first part of initializing
2114  * the interface vtable; type_iface_vtable_iface_init_Wm() does the remainder.
2115  *
2116  * A FALSE return indicates that we didn't find an init function for
2117  * this type/iface pair, so the vtable from the parent type should
2118  * be used. Note that the write lock is not modified upon a FALSE
2119  * return.
2120  */
2121 static gboolean
2122 type_iface_vtable_base_init_Wm (TypeNode *iface,
2123                                 TypeNode *node)
2124 {
2125   IFaceEntry *entry;
2126   IFaceHolder *iholder;
2127   GTypeInterface *vtable = NULL;
2128   TypeNode *pnode;
2129   
2130   /* type_iface_retrieve_holder_info_Wm() doesn't modify write lock for returning NULL */
2131   iholder = type_iface_retrieve_holder_info_Wm (iface, NODE_TYPE (node), TRUE);
2132   if (!iholder)
2133     return FALSE;       /* we don't modify write lock upon FALSE */
2134
2135   type_iface_ensure_dflt_vtable_Wm (iface);
2136
2137   entry = type_lookup_iface_entry_L (node, iface);
2138
2139   g_assert (iface->data && entry && entry->vtable == NULL && iholder && iholder->info);
2140   
2141   entry->init_state = IFACE_INIT;
2142
2143   pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
2144   if (pnode)    /* want to copy over parent iface contents */
2145     {
2146       IFaceEntry *pentry = type_lookup_iface_entry_L (pnode, iface);
2147       
2148       if (pentry)
2149         vtable = g_memdup2 (pentry->vtable, iface->data->iface.vtable_size);
2150     }
2151   if (!vtable)
2152     vtable = g_memdup2 (iface->data->iface.dflt_vtable, iface->data->iface.vtable_size);
2153   entry->vtable = vtable;
2154   vtable->g_type = NODE_TYPE (iface);
2155   vtable->g_instance_type = NODE_TYPE (node);
2156   
2157   if (iface->data->iface.vtable_init_base)
2158     {
2159       G_WRITE_UNLOCK (&type_rw_lock);
2160       iface->data->iface.vtable_init_base (vtable);
2161       G_WRITE_LOCK (&type_rw_lock);
2162     }
2163   return TRUE;  /* initialized the vtable */
2164 }
2165
2166 /* Finishes what type_iface_vtable_base_init_Wm started by
2167  * calling the interface init function.
2168  * this function may only be called for types with their
2169  * own interface holder info, i.e. types for which
2170  * g_type_add_interface*() was called and not children thereof.
2171  */
2172 static void
2173 type_iface_vtable_iface_init_Wm (TypeNode *iface,
2174                                  TypeNode *node)
2175 {
2176   IFaceEntry *entry = type_lookup_iface_entry_L (node, iface);
2177   IFaceHolder *iholder = type_iface_peek_holder_L (iface, NODE_TYPE (node));
2178   GTypeInterface *vtable = NULL;
2179   guint i;
2180   
2181   /* iholder->info should have been filled in by type_iface_vtable_base_init_Wm() */
2182   g_assert (iface->data && entry && iholder && iholder->info);
2183   g_assert (entry->init_state == IFACE_INIT); /* assert prior base_init() */
2184   
2185   entry->init_state = INITIALIZED;
2186       
2187   vtable = entry->vtable;
2188
2189   if (iholder->info->interface_init)
2190     {
2191       G_WRITE_UNLOCK (&type_rw_lock);
2192       if (iholder->info->interface_init)
2193         iholder->info->interface_init (vtable, iholder->info->interface_data);
2194       G_WRITE_LOCK (&type_rw_lock);
2195     }
2196   
2197   for (i = 0; i < static_n_iface_check_funcs; i++)
2198     {
2199       GTypeInterfaceCheckFunc check_func = static_iface_check_funcs[i].check_func;
2200       gpointer check_data = static_iface_check_funcs[i].check_data;
2201
2202       G_WRITE_UNLOCK (&type_rw_lock);
2203       check_func (check_data, (gpointer)vtable);
2204       G_WRITE_LOCK (&type_rw_lock);      
2205     }
2206 }
2207
2208 static gboolean
2209 type_iface_vtable_finalize_Wm (TypeNode       *iface,
2210                                TypeNode       *node,
2211                                GTypeInterface *vtable)
2212 {
2213   IFaceEntry *entry = type_lookup_iface_entry_L (node, iface);
2214   IFaceHolder *iholder;
2215   
2216   /* type_iface_retrieve_holder_info_Wm() doesn't modify write lock for returning NULL */
2217   iholder = type_iface_retrieve_holder_info_Wm (iface, NODE_TYPE (node), FALSE);
2218   if (!iholder)
2219     return FALSE;       /* we don't modify write lock upon FALSE */
2220   
2221   g_assert (entry && entry->vtable == vtable && iholder->info);
2222   
2223   entry->vtable = NULL;
2224   entry->init_state = UNINITIALIZED;
2225   if (iholder->info->interface_finalize || iface->data->iface.vtable_finalize_base)
2226     {
2227       G_WRITE_UNLOCK (&type_rw_lock);
2228       if (iholder->info->interface_finalize)
2229         iholder->info->interface_finalize (vtable, iholder->info->interface_data);
2230       if (iface->data->iface.vtable_finalize_base)
2231         iface->data->iface.vtable_finalize_base (vtable);
2232       G_WRITE_LOCK (&type_rw_lock);
2233     }
2234   vtable->g_type = 0;
2235   vtable->g_instance_type = 0;
2236   g_free (vtable);
2237   
2238   type_iface_blow_holder_info_Wm (iface, NODE_TYPE (node));
2239   
2240   return TRUE;  /* write lock modified */
2241 }
2242
2243 static void
2244 type_class_init_Wm (TypeNode   *node,
2245                     GTypeClass *pclass)
2246 {
2247   GSList *slist, *init_slist = NULL;
2248   GTypeClass *class;
2249   IFaceEntries *entries;
2250   IFaceEntry *entry;
2251   TypeNode *bnode, *pnode;
2252   guint i;
2253   
2254   /* Accessing data->class will work for instantiatable types
2255    * too because ClassData is a subset of InstanceData
2256    */
2257   g_assert (node->is_classed && node->data &&
2258             node->data->class.class_size &&
2259             !node->data->class.class &&
2260             g_atomic_int_get (&node->data->class.init_state) == UNINITIALIZED);
2261   if (node->data->class.class_private_size)
2262     class = g_malloc0 (ALIGN_STRUCT (node->data->class.class_size) + node->data->class.class_private_size);
2263   else
2264     class = g_malloc0 (node->data->class.class_size);
2265   node->data->class.class = class;
2266   g_atomic_int_set (&node->data->class.init_state, BASE_CLASS_INIT);
2267   
2268   if (pclass)
2269     {
2270       pnode = lookup_type_node_I (pclass->g_type);
2271
2272       memcpy (class, pclass, pnode->data->class.class_size);
2273       memcpy (G_STRUCT_MEMBER_P (class, ALIGN_STRUCT (node->data->class.class_size)), G_STRUCT_MEMBER_P (pclass, ALIGN_STRUCT (pnode->data->class.class_size)), pnode->data->class.class_private_size);
2274
2275       if (node->is_instantiatable)
2276         {
2277           /* We need to initialize the private_size here rather than in
2278            * type_data_make_W() since the class init for the parent
2279            * class may have changed pnode->data->instance.private_size.
2280            */
2281           node->data->instance.private_size = pnode->data->instance.private_size;
2282         }
2283     }
2284   class->g_type = NODE_TYPE (node);
2285   
2286   G_WRITE_UNLOCK (&type_rw_lock);
2287   
2288   /* stack all base class initialization functions, so we
2289    * call them in ascending order.
2290    */
2291   for (bnode = node; bnode; bnode = lookup_type_node_I (NODE_PARENT_TYPE (bnode)))
2292     if (bnode->data->class.class_init_base)
2293       init_slist = g_slist_prepend (init_slist, (gpointer) bnode->data->class.class_init_base);
2294   for (slist = init_slist; slist; slist = slist->next)
2295     {
2296       GBaseInitFunc class_init_base = (GBaseInitFunc) slist->data;
2297       
2298       class_init_base (class);
2299     }
2300   g_slist_free (init_slist);
2301   
2302   G_WRITE_LOCK (&type_rw_lock);
2303
2304   g_atomic_int_set (&node->data->class.init_state, BASE_IFACE_INIT);
2305   
2306   /* Before we initialize the class, base initialize all interfaces, either
2307    * from parent, or through our holder info
2308    */
2309   pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
2310
2311   i = 0;
2312   while ((entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node)) != NULL &&
2313           i < IFACE_ENTRIES_N_ENTRIES (entries))
2314     {
2315       entry = &entries->entry[i];
2316       while (i < IFACE_ENTRIES_N_ENTRIES (entries) &&
2317              entry->init_state == IFACE_INIT)
2318         {
2319           entry++;
2320           i++;
2321         }
2322
2323       if (i == IFACE_ENTRIES_N_ENTRIES (entries))
2324         break;
2325
2326       if (!type_iface_vtable_base_init_Wm (lookup_type_node_I (entry->iface_type), node))
2327         {
2328           guint j;
2329           IFaceEntries *pentries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (pnode);
2330           
2331           /* need to get this interface from parent, type_iface_vtable_base_init_Wm()
2332            * doesn't modify write lock upon FALSE, so entry is still valid; 
2333            */
2334           g_assert (pnode != NULL);
2335
2336           if (pentries)
2337             for (j = 0; j < IFACE_ENTRIES_N_ENTRIES (pentries); j++)
2338               {
2339                 IFaceEntry *pentry = &pentries->entry[j];
2340
2341                 if (pentry->iface_type == entry->iface_type)
2342                   {
2343                     entry->vtable = pentry->vtable;
2344                     entry->init_state = INITIALIZED;
2345                     break;
2346                   }
2347               }
2348           g_assert (entry->vtable != NULL);
2349         }
2350
2351       /* If the write lock was released, additional interface entries might
2352        * have been inserted into CLASSED_NODE_IFACES_ENTRIES (node); they'll
2353        * be base-initialized when inserted, so we don't have to worry that
2354        * we might miss them. Uninitialized entries can only be moved higher
2355        * when new ones are inserted.
2356        */
2357       i++;
2358     }
2359   
2360   g_atomic_int_set (&node->data->class.init_state, CLASS_INIT);
2361   
2362   G_WRITE_UNLOCK (&type_rw_lock);
2363
2364   if (node->data->class.class_init)
2365     node->data->class.class_init (class, (gpointer) node->data->class.class_data);
2366   
2367   G_WRITE_LOCK (&type_rw_lock);
2368   
2369   g_atomic_int_set (&node->data->class.init_state, IFACE_INIT);
2370   
2371   /* finish initializing the interfaces through our holder info.
2372    * inherited interfaces are already init_state == INITIALIZED, because
2373    * they either got setup in the above base_init loop, or during
2374    * class_init from within type_add_interface_Wm() for this or
2375    * an ancestor type.
2376    */
2377   i = 0;
2378   while ((entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node)) != NULL)
2379     {
2380       entry = &entries->entry[i];
2381       while (i < IFACE_ENTRIES_N_ENTRIES (entries) &&
2382              entry->init_state == INITIALIZED)
2383         {
2384           entry++;
2385           i++;
2386         }
2387
2388       if (i == IFACE_ENTRIES_N_ENTRIES (entries))
2389         break;
2390
2391       type_iface_vtable_iface_init_Wm (lookup_type_node_I (entry->iface_type), node);
2392       
2393       /* As in the loop above, additional initialized entries might be inserted
2394        * if the write lock is released, but that's harmless because the entries
2395        * we need to initialize only move higher in the list.
2396        */
2397       i++;
2398     }
2399   
2400   g_atomic_int_set (&node->data->class.init_state, INITIALIZED);
2401 }
2402
2403 static void
2404 type_data_finalize_class_ifaces_Wm (TypeNode *node)
2405 {
2406   guint i;
2407   IFaceEntries *entries;
2408
2409   g_assert (node->is_instantiatable && node->data && node->data->class.class && NODE_REFCOUNT (node) == 0);
2410
2411  reiterate:
2412   entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node);
2413   for (i = 0; entries != NULL && i < IFACE_ENTRIES_N_ENTRIES (entries); i++)
2414     {
2415       IFaceEntry *entry = &entries->entry[i];
2416       if (entry->vtable)
2417         {
2418           if (type_iface_vtable_finalize_Wm (lookup_type_node_I (entry->iface_type), node, entry->vtable))
2419             {
2420               /* refetch entries, IFACES_ENTRIES might be modified */
2421               goto reiterate;
2422             }
2423           else
2424             {
2425               /* type_iface_vtable_finalize_Wm() doesn't modify write lock upon FALSE,
2426                * iface vtable came from parent
2427                */
2428               entry->vtable = NULL;
2429               entry->init_state = UNINITIALIZED;
2430             }
2431         }
2432     }
2433 }
2434
2435 static void
2436 type_data_finalize_class_U (TypeNode  *node,
2437                             ClassData *cdata)
2438 {
2439   GTypeClass *class = cdata->class;
2440   TypeNode *bnode;
2441   
2442   g_assert (cdata->class && NODE_REFCOUNT (node) == 0);
2443   
2444   if (cdata->class_finalize)
2445     cdata->class_finalize (class, (gpointer) cdata->class_data);
2446   
2447   /* call all base class destruction functions in descending order
2448    */
2449   if (cdata->class_finalize_base)
2450     cdata->class_finalize_base (class);
2451   for (bnode = lookup_type_node_I (NODE_PARENT_TYPE (node)); bnode; bnode = lookup_type_node_I (NODE_PARENT_TYPE (bnode)))
2452     if (bnode->data->class.class_finalize_base)
2453       bnode->data->class.class_finalize_base (class);
2454   
2455   g_free (cdata->class);
2456 }
2457
2458 static void
2459 type_data_last_unref_Wm (TypeNode *node,
2460                          gboolean  uncached)
2461 {
2462   g_return_if_fail (node != NULL && node->plugin != NULL);
2463   
2464   if (!node->data || NODE_REFCOUNT (node) == 0)
2465     {
2466       g_critical ("cannot drop last reference to unreferenced type '%s'",
2467                   NODE_NAME (node));
2468       return;
2469     }
2470
2471   /* call class cache hooks */
2472   if (node->is_classed && node->data && node->data->class.class && static_n_class_cache_funcs && !uncached)
2473     {
2474       guint i;
2475       
2476       G_WRITE_UNLOCK (&type_rw_lock);
2477       G_READ_LOCK (&type_rw_lock);
2478       for (i = 0; i < static_n_class_cache_funcs; i++)
2479         {
2480           GTypeClassCacheFunc cache_func = static_class_cache_funcs[i].cache_func;
2481           gpointer cache_data = static_class_cache_funcs[i].cache_data;
2482           gboolean need_break;
2483           
2484           G_READ_UNLOCK (&type_rw_lock);
2485           need_break = cache_func (cache_data, node->data->class.class);
2486           G_READ_LOCK (&type_rw_lock);
2487           if (!node->data || NODE_REFCOUNT (node) == 0)
2488             INVALID_RECURSION ("GType class cache function ", cache_func, NODE_NAME (node));
2489           if (need_break)
2490             break;
2491         }
2492       G_READ_UNLOCK (&type_rw_lock);
2493       G_WRITE_LOCK (&type_rw_lock);
2494     }
2495   
2496   /* may have been re-referenced meanwhile */
2497   if (g_atomic_int_dec_and_test ((int *) &node->ref_count))
2498     {
2499       GType ptype = NODE_PARENT_TYPE (node);
2500       TypeData *tdata;
2501       
2502       if (node->is_instantiatable)
2503         {
2504           /* destroy node->data->instance.mem_chunk */
2505         }
2506       
2507       tdata = node->data;
2508       if (node->is_classed && tdata->class.class)
2509         {
2510           if (CLASSED_NODE_IFACES_ENTRIES_LOCKED (node) != NULL)
2511             type_data_finalize_class_ifaces_Wm (node);
2512           node->mutatable_check_cache = FALSE;
2513           node->data = NULL;
2514           G_WRITE_UNLOCK (&type_rw_lock);
2515           type_data_finalize_class_U (node, &tdata->class);
2516           G_WRITE_LOCK (&type_rw_lock);
2517         }
2518       else if (NODE_IS_IFACE (node) && tdata->iface.dflt_vtable)
2519         {
2520           node->mutatable_check_cache = FALSE;
2521           node->data = NULL;
2522           if (tdata->iface.dflt_finalize || tdata->iface.vtable_finalize_base)
2523             {
2524               G_WRITE_UNLOCK (&type_rw_lock);
2525               if (tdata->iface.dflt_finalize)
2526                 tdata->iface.dflt_finalize (tdata->iface.dflt_vtable, (gpointer) tdata->iface.dflt_data);
2527               if (tdata->iface.vtable_finalize_base)
2528                 tdata->iface.vtable_finalize_base (tdata->iface.dflt_vtable);
2529               G_WRITE_LOCK (&type_rw_lock);
2530             }
2531           g_free (tdata->iface.dflt_vtable);
2532         }
2533       else
2534         {
2535           node->mutatable_check_cache = FALSE;
2536           node->data = NULL;
2537         }
2538
2539       /* freeing tdata->common.value_table and its contents is taken care of
2540        * by allocating it in one chunk with tdata
2541        */
2542       g_free (tdata);
2543       
2544       G_WRITE_UNLOCK (&type_rw_lock);
2545       g_type_plugin_unuse (node->plugin);
2546       if (ptype)
2547         type_data_unref_U (lookup_type_node_I (ptype), FALSE);
2548       G_WRITE_LOCK (&type_rw_lock);
2549     }
2550 }
2551
2552 static inline void
2553 type_data_unref_U (TypeNode *node,
2554                    gboolean  uncached)
2555 {
2556   guint current;
2557
2558   do {
2559     current = NODE_REFCOUNT (node);
2560
2561     if (current <= 1)
2562     {
2563       if (!node->plugin)
2564         {
2565           g_critical ("static type '%s' unreferenced too often",
2566                       NODE_NAME (node));
2567           return;
2568         }
2569       else
2570         {
2571           /* This is the last reference of a type from a plugin.  We are
2572            * experimentally disabling support for unloading type
2573            * plugins, so don't allow the last ref to drop.
2574            */
2575           return;
2576         }
2577
2578       g_assert (current > 0);
2579
2580       g_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
2581       G_WRITE_LOCK (&type_rw_lock);
2582       type_data_last_unref_Wm (node, uncached);
2583       G_WRITE_UNLOCK (&type_rw_lock);
2584       g_rec_mutex_unlock (&class_init_rec_mutex);
2585       return;
2586     }
2587   } while (!g_atomic_int_compare_and_exchange ((int *) &node->ref_count, current, current - 1));
2588 }
2589
2590 /**
2591  * g_type_add_class_cache_func: (skip)
2592  * @cache_data: data to be passed to @cache_func
2593  * @cache_func: a #GTypeClassCacheFunc
2594  *
2595  * Adds a #GTypeClassCacheFunc to be called before the reference count of a
2596  * class goes from one to zero. This can be used to prevent premature class
2597  * destruction. All installed #GTypeClassCacheFunc functions will be chained
2598  * until one of them returns %TRUE. The functions have to check the class id
2599  * passed in to figure whether they actually want to cache the class of this
2600  * type, since all classes are routed through the same #GTypeClassCacheFunc
2601  * chain.
2602  */
2603 void
2604 g_type_add_class_cache_func (gpointer            cache_data,
2605                              GTypeClassCacheFunc cache_func)
2606 {
2607   guint i;
2608   
2609   g_return_if_fail (cache_func != NULL);
2610   
2611   G_WRITE_LOCK (&type_rw_lock);
2612   i = static_n_class_cache_funcs++;
2613   static_class_cache_funcs = g_renew (ClassCacheFunc, static_class_cache_funcs, static_n_class_cache_funcs);
2614   static_class_cache_funcs[i].cache_data = cache_data;
2615   static_class_cache_funcs[i].cache_func = cache_func;
2616   G_WRITE_UNLOCK (&type_rw_lock);
2617 }
2618
2619 /**
2620  * g_type_remove_class_cache_func: (skip)
2621  * @cache_data: data that was given when adding @cache_func
2622  * @cache_func: a #GTypeClassCacheFunc
2623  *
2624  * Removes a previously installed #GTypeClassCacheFunc. The cache
2625  * maintained by @cache_func has to be empty when calling
2626  * g_type_remove_class_cache_func() to avoid leaks.
2627  */
2628 void
2629 g_type_remove_class_cache_func (gpointer            cache_data,
2630                                 GTypeClassCacheFunc cache_func)
2631 {
2632   gboolean found_it = FALSE;
2633   guint i;
2634   
2635   g_return_if_fail (cache_func != NULL);
2636   
2637   G_WRITE_LOCK (&type_rw_lock);
2638   for (i = 0; i < static_n_class_cache_funcs; i++)
2639     if (static_class_cache_funcs[i].cache_data == cache_data &&
2640         static_class_cache_funcs[i].cache_func == cache_func)
2641       {
2642         static_n_class_cache_funcs--;
2643         memmove (static_class_cache_funcs + i,
2644                  static_class_cache_funcs + i + 1,
2645                  sizeof (static_class_cache_funcs[0]) * (static_n_class_cache_funcs - i));
2646         static_class_cache_funcs = g_renew (ClassCacheFunc, static_class_cache_funcs, static_n_class_cache_funcs);
2647         found_it = TRUE;
2648         break;
2649       }
2650   G_WRITE_UNLOCK (&type_rw_lock);
2651   
2652   if (!found_it)
2653     g_critical (G_STRLOC ": cannot remove unregistered class cache func %p with data %p",
2654                 cache_func, cache_data);
2655 }
2656
2657
2658 /**
2659  * g_type_add_interface_check: (skip)
2660  * @check_data: data to pass to @check_func
2661  * @check_func: function to be called after each interface
2662  *     is initialized
2663  *
2664  * Adds a function to be called after an interface vtable is
2665  * initialized for any class (i.e. after the @interface_init
2666  * member of #GInterfaceInfo has been called).
2667  *
2668  * This function is useful when you want to check an invariant
2669  * that depends on the interfaces of a class. For instance, the
2670  * implementation of #GObject uses this facility to check that an
2671  * object implements all of the properties that are defined on its
2672  * interfaces.
2673  *
2674  * Since: 2.4
2675  */
2676 void
2677 g_type_add_interface_check (gpointer                check_data,
2678                             GTypeInterfaceCheckFunc check_func)
2679 {
2680   guint i;
2681   
2682   g_return_if_fail (check_func != NULL);
2683   
2684   G_WRITE_LOCK (&type_rw_lock);
2685   i = static_n_iface_check_funcs++;
2686   static_iface_check_funcs = g_renew (IFaceCheckFunc, static_iface_check_funcs, static_n_iface_check_funcs);
2687   static_iface_check_funcs[i].check_data = check_data;
2688   static_iface_check_funcs[i].check_func = check_func;
2689   G_WRITE_UNLOCK (&type_rw_lock);
2690 }
2691
2692 /**
2693  * g_type_remove_interface_check: (skip)
2694  * @check_data: callback data passed to g_type_add_interface_check()
2695  * @check_func: callback function passed to g_type_add_interface_check()
2696  *
2697  * Removes an interface check function added with
2698  * g_type_add_interface_check().
2699  *
2700  * Since: 2.4
2701  */
2702 void
2703 g_type_remove_interface_check (gpointer                check_data,
2704                                GTypeInterfaceCheckFunc check_func)
2705 {
2706   gboolean found_it = FALSE;
2707   guint i;
2708   
2709   g_return_if_fail (check_func != NULL);
2710   
2711   G_WRITE_LOCK (&type_rw_lock);
2712   for (i = 0; i < static_n_iface_check_funcs; i++)
2713     if (static_iface_check_funcs[i].check_data == check_data &&
2714         static_iface_check_funcs[i].check_func == check_func)
2715       {
2716         static_n_iface_check_funcs--;
2717         memmove (static_iface_check_funcs + i,
2718                  static_iface_check_funcs + i + 1,
2719                  sizeof (static_iface_check_funcs[0]) * (static_n_iface_check_funcs - i));
2720         static_iface_check_funcs = g_renew (IFaceCheckFunc, static_iface_check_funcs, static_n_iface_check_funcs);
2721         found_it = TRUE;
2722         break;
2723       }
2724   G_WRITE_UNLOCK (&type_rw_lock);
2725   
2726   if (!found_it)
2727     g_critical (G_STRLOC ": cannot remove unregistered class check func %p with data %p",
2728                 check_func, check_data);
2729 }
2730
2731 /* --- type registration --- */
2732 /**
2733  * g_type_register_fundamental:
2734  * @type_id: a predefined type identifier
2735  * @type_name: 0-terminated string used as the name of the new type
2736  * @info: #GTypeInfo structure for this type
2737  * @finfo: #GTypeFundamentalInfo structure for this type
2738  * @flags: bitwise combination of #GTypeFlags values
2739  *
2740  * Registers @type_id as the predefined identifier and @type_name as the
2741  * name of a fundamental type. If @type_id is already registered, or a
2742  * type named @type_name is already registered, the behaviour is undefined.
2743  * The type system uses the information contained in the #GTypeInfo structure
2744  * pointed to by @info and the #GTypeFundamentalInfo structure pointed to by
2745  * @finfo to manage the type and its instances. The value of @flags determines
2746  * additional characteristics of the fundamental type.
2747  *
2748  * Returns: the predefined type identifier
2749  */
2750 GType
2751 g_type_register_fundamental (GType                       type_id,
2752                              const gchar                *type_name,
2753                              const GTypeInfo            *info,
2754                              const GTypeFundamentalInfo *finfo,
2755                              GTypeFlags                  flags)
2756 {
2757   TypeNode *node;
2758   
2759   g_assert_type_system_initialized ();
2760   g_return_val_if_fail (type_id > 0, 0);
2761   g_return_val_if_fail (type_name != NULL, 0);
2762   g_return_val_if_fail (info != NULL, 0);
2763   g_return_val_if_fail (finfo != NULL, 0);
2764   
2765   if (!check_type_name_I (type_name))
2766     return 0;
2767   if ((type_id & TYPE_ID_MASK) ||
2768       type_id > G_TYPE_FUNDAMENTAL_MAX)
2769     {
2770       g_critical ("attempt to register fundamental type '%s' with invalid type id (%" G_GSIZE_FORMAT ")",
2771                   type_name,
2772                   type_id);
2773       return 0;
2774     }
2775   if ((finfo->type_flags & G_TYPE_FLAG_INSTANTIATABLE) &&
2776       !(finfo->type_flags & G_TYPE_FLAG_CLASSED))
2777     {
2778       g_critical ("cannot register instantiatable fundamental type '%s' as non-classed",
2779                   type_name);
2780       return 0;
2781     }
2782   if (lookup_type_node_I (type_id))
2783     {
2784       g_critical ("cannot register existing fundamental type '%s' (as '%s')",
2785                   type_descriptive_name_I (type_id),
2786                   type_name);
2787       return 0;
2788     }
2789   
2790   G_WRITE_LOCK (&type_rw_lock);
2791   node = type_node_fundamental_new_W (type_id, type_name, finfo->type_flags);
2792   type_add_flags_W (node, flags);
2793   
2794   if (check_type_info_I (NULL, NODE_FUNDAMENTAL_TYPE (node), type_name, info))
2795     type_data_make_W (node, info,
2796                       check_value_table_I (type_name, info->value_table) ? info->value_table : NULL);
2797   G_WRITE_UNLOCK (&type_rw_lock);
2798   
2799   return NODE_TYPE (node);
2800 }
2801
2802 /**
2803  * g_type_register_static_simple: (skip)
2804  * @parent_type: type from which this type will be derived
2805  * @type_name: 0-terminated string used as the name of the new type
2806  * @class_size: size of the class structure (see #GTypeInfo)
2807  * @class_init: location of the class initialization function (see #GTypeInfo)
2808  * @instance_size: size of the instance structure (see #GTypeInfo)
2809  * @instance_init: location of the instance initialization function (see #GTypeInfo)
2810  * @flags: bitwise combination of #GTypeFlags values
2811  *
2812  * Registers @type_name as the name of a new static type derived from
2813  * @parent_type.  The value of @flags determines the nature (e.g.
2814  * abstract or not) of the type. It works by filling a #GTypeInfo
2815  * struct and calling g_type_register_static().
2816  *
2817  * Since: 2.12
2818  *
2819  * Returns: the new type identifier
2820  */
2821 GType
2822 g_type_register_static_simple (GType             parent_type,
2823                                const gchar      *type_name,
2824                                guint             class_size,
2825                                GClassInitFunc    class_init,
2826                                guint             instance_size,
2827                                GInstanceInitFunc instance_init,
2828                                GTypeFlags        flags)
2829 {
2830   GTypeInfo info;
2831
2832   /* Instances are not allowed to be larger than this. If you have a big
2833    * fixed-length array or something, point to it instead.
2834    */
2835   g_return_val_if_fail (class_size <= G_MAXUINT16, G_TYPE_INVALID);
2836   g_return_val_if_fail (instance_size <= G_MAXUINT16, G_TYPE_INVALID);
2837
2838   info.class_size = class_size;
2839   info.base_init = NULL;
2840   info.base_finalize = NULL;
2841   info.class_init = class_init;
2842   info.class_finalize = NULL;
2843   info.class_data = NULL;
2844   info.instance_size = instance_size;
2845   info.n_preallocs = 0;
2846   info.instance_init = instance_init;
2847   info.value_table = NULL;
2848
2849   return g_type_register_static (parent_type, type_name, &info, flags);
2850 }
2851
2852 /**
2853  * g_type_register_static:
2854  * @parent_type: type from which this type will be derived
2855  * @type_name: 0-terminated string used as the name of the new type
2856  * @info: #GTypeInfo structure for this type
2857  * @flags: bitwise combination of #GTypeFlags values
2858  *
2859  * Registers @type_name as the name of a new static type derived from
2860  * @parent_type. The type system uses the information contained in the
2861  * #GTypeInfo structure pointed to by @info to manage the type and its
2862  * instances (if not abstract). The value of @flags determines the nature
2863  * (e.g. abstract or not) of the type.
2864  *
2865  * Returns: the new type identifier
2866  */
2867 GType
2868 g_type_register_static (GType            parent_type,
2869                         const gchar     *type_name,
2870                         const GTypeInfo *info,
2871                         GTypeFlags       flags)
2872 {
2873   TypeNode *pnode, *node;
2874   GType type = 0;
2875   
2876   g_assert_type_system_initialized ();
2877   g_return_val_if_fail (parent_type > 0, 0);
2878   g_return_val_if_fail (type_name != NULL, 0);
2879   g_return_val_if_fail (info != NULL, 0);
2880   
2881   if (!check_type_name_I (type_name) ||
2882       !check_derivation_I (parent_type, type_name))
2883     return 0;
2884   if (info->class_finalize)
2885     {
2886       g_critical ("class finalizer specified for static type '%s'",
2887                   type_name);
2888       return 0;
2889     }
2890   
2891   pnode = lookup_type_node_I (parent_type);
2892   G_WRITE_LOCK (&type_rw_lock);
2893   type_data_ref_Wm (pnode);
2894   if (check_type_info_I (pnode, NODE_FUNDAMENTAL_TYPE (pnode), type_name, info))
2895     {
2896       node = type_node_new_W (pnode, type_name, NULL);
2897       type_add_flags_W (node, flags);
2898       type = NODE_TYPE (node);
2899       type_data_make_W (node, info,
2900                         check_value_table_I (type_name, info->value_table) ? info->value_table : NULL);
2901     }
2902   G_WRITE_UNLOCK (&type_rw_lock);
2903   
2904   return type;
2905 }
2906
2907 /**
2908  * g_type_register_dynamic:
2909  * @parent_type: type from which this type will be derived
2910  * @type_name: 0-terminated string used as the name of the new type
2911  * @plugin: #GTypePlugin structure to retrieve the #GTypeInfo from
2912  * @flags: bitwise combination of #GTypeFlags values
2913  *
2914  * Registers @type_name as the name of a new dynamic type derived from
2915  * @parent_type.  The type system uses the information contained in the
2916  * #GTypePlugin structure pointed to by @plugin to manage the type and its
2917  * instances (if not abstract).  The value of @flags determines the nature
2918  * (e.g. abstract or not) of the type.
2919  *
2920  * Returns: the new type identifier or %G_TYPE_INVALID if registration failed
2921  */
2922 GType
2923 g_type_register_dynamic (GType        parent_type,
2924                          const gchar *type_name,
2925                          GTypePlugin *plugin,
2926                          GTypeFlags   flags)
2927 {
2928   TypeNode *pnode, *node;
2929   GType type;
2930   
2931   g_assert_type_system_initialized ();
2932   g_return_val_if_fail (parent_type > 0, 0);
2933   g_return_val_if_fail (type_name != NULL, 0);
2934   g_return_val_if_fail (plugin != NULL, 0);
2935   
2936   if (!check_type_name_I (type_name) ||
2937       !check_derivation_I (parent_type, type_name) ||
2938       !check_plugin_U (plugin, TRUE, FALSE, type_name))
2939     return 0;
2940   
2941   G_WRITE_LOCK (&type_rw_lock);
2942   pnode = lookup_type_node_I (parent_type);
2943   node = type_node_new_W (pnode, type_name, plugin);
2944   type_add_flags_W (node, flags);
2945   type = NODE_TYPE (node);
2946   G_WRITE_UNLOCK (&type_rw_lock);
2947   
2948   return type;
2949 }
2950
2951 /**
2952  * g_type_add_interface_static:
2953  * @instance_type: #GType value of an instantiatable type
2954  * @interface_type: #GType value of an interface type
2955  * @info: #GInterfaceInfo structure for this
2956  *        (@instance_type, @interface_type) combination
2957  *
2958  * Adds @interface_type to the static @instance_type.
2959  * The information contained in the #GInterfaceInfo structure
2960  * pointed to by @info is used to manage the relationship.
2961  */
2962 void
2963 g_type_add_interface_static (GType                 instance_type,
2964                              GType                 interface_type,
2965                              const GInterfaceInfo *info)
2966 {
2967   /* G_TYPE_IS_INSTANTIATABLE() is an external call: _U */
2968   g_return_if_fail (G_TYPE_IS_INSTANTIATABLE (instance_type));
2969   g_return_if_fail (g_type_parent (interface_type) == G_TYPE_INTERFACE);
2970
2971   /* we only need to lock class_init_rec_mutex if instance_type already has its
2972    * class initialized, however this function is rarely enough called to take
2973    * the simple route and always acquire class_init_rec_mutex.
2974    */
2975   g_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
2976   G_WRITE_LOCK (&type_rw_lock);
2977   if (check_add_interface_L (instance_type, interface_type))
2978     {
2979       TypeNode *node = lookup_type_node_I (instance_type);
2980       TypeNode *iface = lookup_type_node_I (interface_type);
2981       if (check_interface_info_I (iface, NODE_TYPE (node), info))
2982         type_add_interface_Wm (node, iface, info, NULL);
2983     }
2984   G_WRITE_UNLOCK (&type_rw_lock);
2985   g_rec_mutex_unlock (&class_init_rec_mutex);
2986 }
2987
2988 /**
2989  * g_type_add_interface_dynamic:
2990  * @instance_type: #GType value of an instantiatable type
2991  * @interface_type: #GType value of an interface type
2992  * @plugin: #GTypePlugin structure to retrieve the #GInterfaceInfo from
2993  *
2994  * Adds @interface_type to the dynamic @instance_type. The information
2995  * contained in the #GTypePlugin structure pointed to by @plugin
2996  * is used to manage the relationship.
2997  */
2998 void
2999 g_type_add_interface_dynamic (GType        instance_type,
3000                               GType        interface_type,
3001                               GTypePlugin *plugin)
3002 {
3003   TypeNode *node;
3004   /* G_TYPE_IS_INSTANTIATABLE() is an external call: _U */
3005   g_return_if_fail (G_TYPE_IS_INSTANTIATABLE (instance_type));
3006   g_return_if_fail (g_type_parent (interface_type) == G_TYPE_INTERFACE);
3007
3008   node = lookup_type_node_I (instance_type);
3009   if (!check_plugin_U (plugin, FALSE, TRUE, NODE_NAME (node)))
3010     return;
3011
3012   /* see comment in g_type_add_interface_static() about class_init_rec_mutex */
3013   g_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
3014   G_WRITE_LOCK (&type_rw_lock);
3015   if (check_add_interface_L (instance_type, interface_type))
3016     {
3017       TypeNode *iface = lookup_type_node_I (interface_type);
3018       type_add_interface_Wm (node, iface, NULL, plugin);
3019     }
3020   G_WRITE_UNLOCK (&type_rw_lock);
3021   g_rec_mutex_unlock (&class_init_rec_mutex);
3022 }
3023
3024
3025 /* --- public API functions --- */
3026 /**
3027  * g_type_class_ref:
3028  * @type: type ID of a classed type
3029  *
3030  * Increments the reference count of the class structure belonging to
3031  * @type. This function will demand-create the class if it doesn't
3032  * exist already.
3033  *
3034  * Returns: (type GObject.TypeClass) (transfer none): the #GTypeClass
3035  *     structure for the given type ID
3036  */
3037 gpointer
3038 g_type_class_ref (GType type)
3039 {
3040   TypeNode *node;
3041   GType ptype;
3042   gboolean holds_ref;
3043   GTypeClass *pclass;
3044
3045   /* optimize for common code path */
3046   node = lookup_type_node_I (type);
3047   if (!node || !node->is_classed)
3048     {
3049       g_critical ("cannot retrieve class for invalid (unclassed) type '%s'",
3050                   type_descriptive_name_I (type));
3051       return NULL;
3052     }
3053
3054   if (G_LIKELY (type_data_ref_U (node)))
3055     {
3056       if (G_LIKELY (g_atomic_int_get (&node->data->class.init_state) == INITIALIZED))
3057         return node->data->class.class;
3058       holds_ref = TRUE;
3059     }
3060   else
3061     holds_ref = FALSE;
3062   
3063   /* here, we either have node->data->class.class == NULL, or a recursive
3064    * call to g_type_class_ref() with a partly initialized class, or
3065    * node->data->class.init_state == INITIALIZED, because any
3066    * concurrently running initialization was guarded by class_init_rec_mutex.
3067    */
3068   g_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
3069
3070   /* we need an initialized parent class for initializing derived classes */
3071   ptype = NODE_PARENT_TYPE (node);
3072   pclass = ptype ? g_type_class_ref (ptype) : NULL;
3073
3074   G_WRITE_LOCK (&type_rw_lock);
3075
3076   if (!holds_ref)
3077     type_data_ref_Wm (node);
3078
3079   if (!node->data->class.class) /* class uninitialized */
3080     type_class_init_Wm (node, pclass);
3081
3082   G_WRITE_UNLOCK (&type_rw_lock);
3083
3084   if (pclass)
3085     g_type_class_unref (pclass);
3086
3087   g_rec_mutex_unlock (&class_init_rec_mutex);
3088
3089   return node->data->class.class;
3090 }
3091
3092 /**
3093  * g_type_class_unref:
3094  * @g_class: (type GObject.TypeClass): a #GTypeClass structure to unref
3095  *
3096  * Decrements the reference count of the class structure being passed in.
3097  * Once the last reference count of a class has been released, classes
3098  * may be finalized by the type system, so further dereferencing of a
3099  * class pointer after g_type_class_unref() are invalid.
3100  */
3101 void
3102 g_type_class_unref (gpointer g_class)
3103 {
3104   TypeNode *node;
3105   GTypeClass *class = g_class;
3106   
3107   g_return_if_fail (g_class != NULL);
3108   
3109   node = lookup_type_node_I (class->g_type);
3110   if (node && node->is_classed && NODE_REFCOUNT (node))
3111     type_data_unref_U (node, FALSE);
3112   else
3113     g_critical ("cannot unreference class of invalid (unclassed) type '%s'",
3114                 type_descriptive_name_I (class->g_type));
3115 }
3116
3117 /**
3118  * g_type_class_unref_uncached: (skip)
3119  * @g_class: (type GObject.TypeClass): a #GTypeClass structure to unref
3120  *
3121  * A variant of g_type_class_unref() for use in #GTypeClassCacheFunc
3122  * implementations. It unreferences a class without consulting the chain
3123  * of #GTypeClassCacheFuncs, avoiding the recursion which would occur
3124  * otherwise.
3125  */
3126 void
3127 g_type_class_unref_uncached (gpointer g_class)
3128 {
3129   TypeNode *node;
3130   GTypeClass *class = g_class;
3131   
3132   g_return_if_fail (g_class != NULL);
3133   
3134   node = lookup_type_node_I (class->g_type);
3135   if (node && node->is_classed && NODE_REFCOUNT (node))
3136     type_data_unref_U (node, TRUE);
3137   else
3138     g_critical ("cannot unreference class of invalid (unclassed) type '%s'",
3139                 type_descriptive_name_I (class->g_type));
3140 }
3141
3142 /**
3143  * g_type_class_peek:
3144  * @type: type ID of a classed type
3145  *
3146  * This function is essentially the same as g_type_class_ref(),
3147  * except that the classes reference count isn't incremented.
3148  * As a consequence, this function may return %NULL if the class
3149  * of the type passed in does not currently exist (hasn't been
3150  * referenced before).
3151  *
3152  * Returns: (type GObject.TypeClass) (transfer none): the #GTypeClass
3153  *     structure for the given type ID or %NULL if the class does not
3154  *     currently exist
3155  */
3156 gpointer
3157 g_type_class_peek (GType type)
3158 {
3159   TypeNode *node;
3160   gpointer class;
3161   
3162   node = lookup_type_node_I (type);
3163   if (node && node->is_classed && NODE_REFCOUNT (node) &&
3164       g_atomic_int_get (&node->data->class.init_state) == INITIALIZED)
3165     /* ref_count _may_ be 0 */
3166     class = node->data->class.class;
3167   else
3168     class = NULL;
3169   
3170   return class;
3171 }
3172
3173 /**
3174  * g_type_class_peek_static:
3175  * @type: type ID of a classed type
3176  *
3177  * A more efficient version of g_type_class_peek() which works only for
3178  * static types.
3179  * 
3180  * Returns: (type GObject.TypeClass) (transfer none): the #GTypeClass
3181  *     structure for the given type ID or %NULL if the class does not
3182  *     currently exist or is dynamically loaded
3183  *
3184  * Since: 2.4
3185  */
3186 gpointer
3187 g_type_class_peek_static (GType type)
3188 {
3189   TypeNode *node;
3190   gpointer class;
3191   
3192   node = lookup_type_node_I (type);
3193   if (node && node->is_classed && NODE_REFCOUNT (node) &&
3194       /* peek only static types: */ node->plugin == NULL &&
3195       g_atomic_int_get (&node->data->class.init_state) == INITIALIZED)
3196     /* ref_count _may_ be 0 */
3197     class = node->data->class.class;
3198   else
3199     class = NULL;
3200   
3201   return class;
3202 }
3203
3204 /**
3205  * g_type_class_peek_parent:
3206  * @g_class: (type GObject.TypeClass): the #GTypeClass structure to
3207  *     retrieve the parent class for
3208  *
3209  * This is a convenience function often needed in class initializers.
3210  * It returns the class structure of the immediate parent type of the
3211  * class passed in.  Since derived classes hold a reference count on
3212  * their parent classes as long as they are instantiated, the returned
3213  * class will always exist.
3214  *
3215  * This function is essentially equivalent to:
3216  * g_type_class_peek (g_type_parent (G_TYPE_FROM_CLASS (g_class)))
3217  *
3218  * Returns: (type GObject.TypeClass) (transfer none): the parent class
3219  *     of @g_class
3220  */
3221 gpointer
3222 g_type_class_peek_parent (gpointer g_class)
3223 {
3224   TypeNode *node;
3225   gpointer class = NULL;
3226   
3227   g_return_val_if_fail (g_class != NULL, NULL);
3228   
3229   node = lookup_type_node_I (G_TYPE_FROM_CLASS (g_class));
3230
3231   g_return_val_if_fail (node != NULL, NULL);
3232
3233   /* We used to acquire a read lock here. That is not necessary, since 
3234    * parent->data->class.class is constant as long as the derived class
3235    * exists. 
3236    */
3237   if (node->is_classed && node->data && NODE_PARENT_TYPE (node))
3238     {
3239       node = lookup_type_node_I (NODE_PARENT_TYPE (node));
3240       class = node->data->class.class;
3241     }
3242   else if (NODE_PARENT_TYPE (node))
3243     g_critical (G_STRLOC ": invalid class pointer '%p'", g_class);
3244   
3245   return class;
3246 }
3247
3248 /**
3249  * g_type_interface_peek:
3250  * @instance_class: (type GObject.TypeClass): a #GTypeClass structure
3251  * @iface_type: an interface ID which this class conforms to
3252  *
3253  * Returns the #GTypeInterface structure of an interface to which the
3254  * passed in class conforms.
3255  *
3256  * Returns: (type GObject.TypeInterface) (transfer none): the #GTypeInterface
3257  *     structure of @iface_type if implemented by @instance_class, %NULL
3258  *     otherwise
3259  */
3260 gpointer
3261 g_type_interface_peek (gpointer instance_class,
3262                        GType    iface_type)
3263 {
3264   TypeNode *node;
3265   TypeNode *iface;
3266   gpointer vtable = NULL;
3267   GTypeClass *class = instance_class;
3268   
3269   g_return_val_if_fail (instance_class != NULL, NULL);
3270   
3271   node = lookup_type_node_I (class->g_type);
3272   iface = lookup_type_node_I (iface_type);
3273   if (node && node->is_instantiatable && iface)
3274     type_lookup_iface_vtable_I (node, iface, &vtable);
3275   else
3276     g_critical (G_STRLOC ": invalid class pointer '%p'", class);
3277   
3278   return vtable;
3279 }
3280
3281 /**
3282  * g_type_interface_peek_parent:
3283  * @g_iface: (type GObject.TypeInterface): a #GTypeInterface structure
3284  *
3285  * Returns the corresponding #GTypeInterface structure of the parent type
3286  * of the instance type to which @g_iface belongs. This is useful when
3287  * deriving the implementation of an interface from the parent type and
3288  * then possibly overriding some methods.
3289  *
3290  * Returns: (transfer none) (type GObject.TypeInterface): the
3291  *     corresponding #GTypeInterface structure of the parent type of the
3292  *     instance type to which @g_iface belongs, or %NULL if the parent
3293  *     type doesn't conform to the interface
3294  */
3295 gpointer
3296 g_type_interface_peek_parent (gpointer g_iface)
3297 {
3298   TypeNode *node;
3299   TypeNode *iface;
3300   gpointer vtable = NULL;
3301   GTypeInterface *iface_class = g_iface;
3302   
3303   g_return_val_if_fail (g_iface != NULL, NULL);
3304   
3305   iface = lookup_type_node_I (iface_class->g_type);
3306   node = lookup_type_node_I (iface_class->g_instance_type);
3307   if (node)
3308     node = lookup_type_node_I (NODE_PARENT_TYPE (node));
3309   if (node && node->is_instantiatable && iface)
3310     type_lookup_iface_vtable_I (node, iface, &vtable);
3311   else if (node)
3312     g_critical (G_STRLOC ": invalid interface pointer '%p'", g_iface);
3313   
3314   return vtable;
3315 }
3316
3317 /**
3318  * g_type_default_interface_ref:
3319  * @g_type: an interface type
3320  *
3321  * Increments the reference count for the interface type @g_type,
3322  * and returns the default interface vtable for the type.
3323  *
3324  * If the type is not currently in use, then the default vtable
3325  * for the type will be created and initialized by calling
3326  * the base interface init and default vtable init functions for
3327  * the type (the @base_init and @class_init members of #GTypeInfo).
3328  * Calling g_type_default_interface_ref() is useful when you
3329  * want to make sure that signals and properties for an interface
3330  * have been installed.
3331  *
3332  * Since: 2.4
3333  *
3334  * Returns: (type GObject.TypeInterface) (transfer none): the default
3335  *     vtable for the interface; call g_type_default_interface_unref()
3336  *     when you are done using the interface.
3337  */
3338 gpointer
3339 g_type_default_interface_ref (GType g_type)
3340 {
3341   TypeNode *node;
3342   gpointer dflt_vtable;
3343
3344   G_WRITE_LOCK (&type_rw_lock);
3345
3346   node = lookup_type_node_I (g_type);
3347   if (!node || !NODE_IS_IFACE (node) ||
3348       (node->data && NODE_REFCOUNT (node) == 0))
3349     {
3350       G_WRITE_UNLOCK (&type_rw_lock);
3351       g_critical ("cannot retrieve default vtable for invalid or non-interface type '%s'",
3352                   type_descriptive_name_I (g_type));
3353       return NULL;
3354     }
3355
3356   if (!node->data || !node->data->iface.dflt_vtable)
3357     {
3358       G_WRITE_UNLOCK (&type_rw_lock);
3359       g_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
3360       G_WRITE_LOCK (&type_rw_lock);
3361       node = lookup_type_node_I (g_type);
3362       type_data_ref_Wm (node);
3363       type_iface_ensure_dflt_vtable_Wm (node);
3364       g_rec_mutex_unlock (&class_init_rec_mutex);
3365     }
3366   else
3367     type_data_ref_Wm (node); /* ref_count >= 1 already */
3368
3369   dflt_vtable = node->data->iface.dflt_vtable;
3370   G_WRITE_UNLOCK (&type_rw_lock);
3371
3372   return dflt_vtable;
3373 }
3374
3375 /**
3376  * g_type_default_interface_peek:
3377  * @g_type: an interface type
3378  *
3379  * If the interface type @g_type is currently in use, returns its
3380  * default interface vtable.
3381  *
3382  * Since: 2.4
3383  *
3384  * Returns: (type GObject.TypeInterface) (transfer none): the default
3385  *     vtable for the interface, or %NULL if the type is not currently
3386  *     in use
3387  */
3388 gpointer
3389 g_type_default_interface_peek (GType g_type)
3390 {
3391   TypeNode *node;
3392   gpointer vtable;
3393   
3394   node = lookup_type_node_I (g_type);
3395   if (node && NODE_IS_IFACE (node) && NODE_REFCOUNT (node))
3396     vtable = node->data->iface.dflt_vtable;
3397   else
3398     vtable = NULL;
3399   
3400   return vtable;
3401 }
3402
3403 /**
3404  * g_type_default_interface_unref:
3405  * @g_iface: (type GObject.TypeInterface): the default vtable
3406  *     structure for an interface, as returned by g_type_default_interface_ref()
3407  *
3408  * Decrements the reference count for the type corresponding to the
3409  * interface default vtable @g_iface. If the type is dynamic, then
3410  * when no one is using the interface and all references have
3411  * been released, the finalize function for the interface's default
3412  * vtable (the @class_finalize member of #GTypeInfo) will be called.
3413  *
3414  * Since: 2.4
3415  */
3416 void
3417 g_type_default_interface_unref (gpointer g_iface)
3418 {
3419   TypeNode *node;
3420   GTypeInterface *vtable = g_iface;
3421   
3422   g_return_if_fail (g_iface != NULL);
3423   
3424   node = lookup_type_node_I (vtable->g_type);
3425   if (node && NODE_IS_IFACE (node))
3426     type_data_unref_U (node, FALSE);
3427   else
3428     g_critical ("cannot unreference invalid interface default vtable for '%s'",
3429                 type_descriptive_name_I (vtable->g_type));
3430 }
3431
3432 /**
3433  * g_type_name:
3434  * @type: type to return name for
3435  *
3436  * Get the unique name that is assigned to a type ID.  Note that this
3437  * function (like all other GType API) cannot cope with invalid type
3438  * IDs. %G_TYPE_INVALID may be passed to this function, as may be any
3439  * other validly registered type ID, but randomized type IDs should
3440  * not be passed in and will most likely lead to a crash.
3441  *
3442  * Returns: (nullable): static type name or %NULL
3443  */
3444 const gchar *
3445 g_type_name (GType type)
3446 {
3447   TypeNode *node;
3448   
3449   g_assert_type_system_initialized ();
3450   
3451   node = lookup_type_node_I (type);
3452   
3453   return node ? NODE_NAME (node) : NULL;
3454 }
3455
3456 /**
3457  * g_type_qname:
3458  * @type: type to return quark of type name for
3459  *
3460  * Get the corresponding quark of the type IDs name.
3461  *
3462  * Returns: the type names quark or 0
3463  */
3464 GQuark
3465 g_type_qname (GType type)
3466 {
3467   TypeNode *node;
3468   
3469   node = lookup_type_node_I (type);
3470   
3471   return node ? node->qname : 0;
3472 }
3473
3474 /**
3475  * g_type_from_name:
3476  * @name: type name to look up
3477  *
3478  * Look up the type ID from a given type name, returning 0 if no type
3479  * has been registered under this name (this is the preferred method
3480  * to find out by name whether a specific type has been registered
3481  * yet).
3482  *
3483  * Returns: corresponding type ID or 0
3484  */
3485 GType
3486 g_type_from_name (const gchar *name)
3487 {
3488   GType type = 0;
3489   
3490   g_return_val_if_fail (name != NULL, 0);
3491   
3492   G_READ_LOCK (&type_rw_lock);
3493   type = (GType) g_hash_table_lookup (static_type_nodes_ht, name);
3494   G_READ_UNLOCK (&type_rw_lock);
3495   
3496   return type;
3497 }
3498
3499 /**
3500  * g_type_parent:
3501  * @type: the derived type
3502  *
3503  * Return the direct parent type of the passed in type. If the passed
3504  * in type has no parent, i.e. is a fundamental type, 0 is returned.
3505  *
3506  * Returns: the parent type
3507  */
3508 GType
3509 g_type_parent (GType type)
3510 {
3511   TypeNode *node;
3512   
3513   node = lookup_type_node_I (type);
3514   
3515   return node ? NODE_PARENT_TYPE (node) : 0;
3516 }
3517
3518 /**
3519  * g_type_depth:
3520  * @type: a #GType
3521  *
3522  * Returns the length of the ancestry of the passed in type. This
3523  * includes the type itself, so that e.g. a fundamental type has depth 1.
3524  *
3525  * Returns: the depth of @type
3526  */
3527 guint
3528 g_type_depth (GType type)
3529 {
3530   TypeNode *node;
3531   
3532   node = lookup_type_node_I (type);
3533   
3534   return node ? node->n_supers + 1 : 0;
3535 }
3536
3537 /**
3538  * g_type_next_base:
3539  * @leaf_type: descendant of @root_type and the type to be returned
3540  * @root_type: immediate parent of the returned type
3541  *
3542  * Given a @leaf_type and a @root_type which is contained in its
3543  * ancestry, return the type that @root_type is the immediate parent
3544  * of. In other words, this function determines the type that is
3545  * derived directly from @root_type which is also a base class of
3546  * @leaf_type.  Given a root type and a leaf type, this function can
3547  * be used to determine the types and order in which the leaf type is
3548  * descended from the root type.
3549  *
3550  * Returns: immediate child of @root_type and ancestor of @leaf_type
3551  */
3552 GType
3553 g_type_next_base (GType type,
3554                   GType base_type)
3555 {
3556   GType atype = 0;
3557   TypeNode *node;
3558   
3559   node = lookup_type_node_I (type);
3560   if (node)
3561     {
3562       TypeNode *base_node = lookup_type_node_I (base_type);
3563       
3564       if (base_node && base_node->n_supers < node->n_supers)
3565         {
3566           guint n = node->n_supers - base_node->n_supers;
3567           
3568           if (node->supers[n] == base_type)
3569             atype = node->supers[n - 1];
3570         }
3571     }
3572   
3573   return atype;
3574 }
3575
3576 static inline gboolean
3577 type_node_check_conformities_UorL (TypeNode *node,
3578                                    TypeNode *iface_node,
3579                                    /*        support_inheritance */
3580                                    gboolean  support_interfaces,
3581                                    gboolean  support_prerequisites,
3582                                    gboolean  have_lock)
3583 {
3584   gboolean match;
3585
3586   if (/* support_inheritance && */
3587       NODE_IS_ANCESTOR (iface_node, node))
3588     return TRUE;
3589
3590   support_interfaces = support_interfaces && node->is_instantiatable && NODE_IS_IFACE (iface_node);
3591   support_prerequisites = support_prerequisites && NODE_IS_IFACE (node);
3592   match = FALSE;
3593   if (support_interfaces)
3594     {
3595       if (have_lock)
3596         {
3597           if (type_lookup_iface_entry_L (node, iface_node))
3598             match = TRUE;
3599         }
3600       else
3601         {
3602           if (type_lookup_iface_vtable_I (node, iface_node, NULL))
3603             match = TRUE;
3604         }
3605     }
3606   if (!match &&
3607       support_prerequisites)
3608     {
3609       if (!have_lock)
3610         G_READ_LOCK (&type_rw_lock);
3611       if (support_prerequisites && type_lookup_prerequisite_L (node, NODE_TYPE (iface_node)))
3612         match = TRUE;
3613       if (!have_lock)
3614         G_READ_UNLOCK (&type_rw_lock);
3615     }
3616   return match;
3617 }
3618
3619 static gboolean
3620 type_node_is_a_L (TypeNode *node,
3621                   TypeNode *iface_node)
3622 {
3623   return type_node_check_conformities_UorL (node, iface_node, TRUE, TRUE, TRUE);
3624 }
3625
3626 static inline gboolean
3627 type_node_conforms_to_U (TypeNode *node,
3628                          TypeNode *iface_node,
3629                          gboolean  support_interfaces,
3630                          gboolean  support_prerequisites)
3631 {
3632   return type_node_check_conformities_UorL (node, iface_node, support_interfaces, support_prerequisites, FALSE);
3633 }
3634
3635 /**
3636  * g_type_is_a:
3637  * @type: type to check ancestry for
3638  * @is_a_type: possible ancestor of @type or interface that @type
3639  *     could conform to
3640  *
3641  * If @is_a_type is a derivable type, check whether @type is a
3642  * descendant of @is_a_type. If @is_a_type is an interface, check
3643  * whether @type conforms to it.
3644  *
3645  * Returns: %TRUE if @type is a @is_a_type
3646  */
3647 gboolean
3648 (g_type_is_a) (GType type,
3649                GType iface_type)
3650 {
3651   TypeNode *node, *iface_node;
3652   gboolean is_a;
3653
3654   if (type == iface_type)
3655     return TRUE;
3656   
3657   node = lookup_type_node_I (type);
3658   iface_node = lookup_type_node_I (iface_type);
3659   is_a = node && iface_node && type_node_conforms_to_U (node, iface_node, TRUE, TRUE);
3660   
3661   return is_a;
3662 }
3663
3664 /**
3665  * g_type_children:
3666  * @type: the parent type
3667  * @n_children: (out) (optional): location to store the length of
3668  *     the returned array, or %NULL
3669  *
3670  * Return a newly allocated and 0-terminated array of type IDs, listing
3671  * the child types of @type.
3672  *
3673  * Returns: (array length=n_children) (transfer full): Newly allocated
3674  *     and 0-terminated array of child types, free with g_free()
3675  */
3676 GType*
3677 g_type_children (GType  type,
3678                  guint *n_children)
3679 {
3680   TypeNode *node;
3681   
3682   node = lookup_type_node_I (type);
3683   if (node)
3684     {
3685       GType *children;
3686       
3687       G_READ_LOCK (&type_rw_lock);      /* ->children is relocatable */
3688       children = g_new (GType, node->n_children + 1);
3689       if (node->n_children != 0)
3690         memcpy (children, node->children, sizeof (GType) * node->n_children);
3691       children[node->n_children] = 0;
3692       
3693       if (n_children)
3694         *n_children = node->n_children;
3695       G_READ_UNLOCK (&type_rw_lock);
3696       
3697       return children;
3698     }
3699   else
3700     {
3701       if (n_children)
3702         *n_children = 0;
3703       
3704       return NULL;
3705     }
3706 }
3707
3708 /**
3709  * g_type_interfaces:
3710  * @type: the type to list interface types for
3711  * @n_interfaces: (out) (optional): location to store the length of
3712  *     the returned array, or %NULL
3713  *
3714  * Return a newly allocated and 0-terminated array of type IDs, listing
3715  * the interface types that @type conforms to.
3716  *
3717  * Returns: (array length=n_interfaces) (transfer full): Newly allocated
3718  *     and 0-terminated array of interface types, free with g_free()
3719  */
3720 GType*
3721 g_type_interfaces (GType  type,
3722                    guint *n_interfaces)
3723 {
3724   TypeNode *node;
3725   
3726   node = lookup_type_node_I (type);
3727   if (node && node->is_instantiatable)
3728     {
3729       IFaceEntries *entries;
3730       GType *ifaces;
3731       guint i;
3732       
3733       G_READ_LOCK (&type_rw_lock);
3734       entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node);
3735       if (entries)
3736         {
3737           ifaces = g_new (GType, IFACE_ENTRIES_N_ENTRIES (entries) + 1);
3738           for (i = 0; i < IFACE_ENTRIES_N_ENTRIES (entries); i++)
3739             ifaces[i] = entries->entry[i].iface_type;
3740         }
3741       else
3742         {
3743           ifaces = g_new (GType, 1);
3744           i = 0;
3745         }
3746       ifaces[i] = 0;
3747       
3748       if (n_interfaces)
3749         *n_interfaces = i;
3750       G_READ_UNLOCK (&type_rw_lock);
3751       
3752       return ifaces;
3753     }
3754   else
3755     {
3756       if (n_interfaces)
3757         *n_interfaces = 0;
3758       
3759       return NULL;
3760     }
3761 }
3762
3763 typedef struct _QData QData;
3764 struct _GData
3765 {
3766   guint  n_qdatas;
3767   QData *qdatas;
3768 };
3769 struct _QData
3770 {
3771   GQuark   quark;
3772   gpointer data;
3773 };
3774
3775 static inline gpointer
3776 type_get_qdata_L (TypeNode *node,
3777                   GQuark    quark)
3778 {
3779   GData *gdata = node->global_gdata;
3780   
3781   if (quark && gdata && gdata->n_qdatas)
3782     {
3783       QData *qdatas = gdata->qdatas - 1;
3784       guint n_qdatas = gdata->n_qdatas;
3785       
3786       do
3787         {
3788           guint i;
3789           QData *check;
3790           
3791           i = (n_qdatas + 1) / 2;
3792           check = qdatas + i;
3793           if (quark == check->quark)
3794             return check->data;
3795           else if (quark > check->quark)
3796             {
3797               n_qdatas -= i;
3798               qdatas = check;
3799             }
3800           else /* if (quark < check->quark) */
3801             n_qdatas = i - 1;
3802         }
3803       while (n_qdatas);
3804     }
3805   return NULL;
3806 }
3807
3808 /**
3809  * g_type_get_qdata:
3810  * @type: a #GType
3811  * @quark: a #GQuark id to identify the data
3812  *
3813  * Obtains data which has previously been attached to @type
3814  * with g_type_set_qdata().
3815  *
3816  * Note that this does not take subtyping into account; data
3817  * attached to one type with g_type_set_qdata() cannot
3818  * be retrieved from a subtype using g_type_get_qdata().
3819  *
3820  * Returns: (transfer none): the data, or %NULL if no data was found
3821  */
3822 gpointer
3823 g_type_get_qdata (GType  type,
3824                   GQuark quark)
3825 {
3826   TypeNode *node;
3827   gpointer data;
3828   
3829   node = lookup_type_node_I (type);
3830   if (node)
3831     {
3832       G_READ_LOCK (&type_rw_lock);
3833       data = type_get_qdata_L (node, quark);
3834       G_READ_UNLOCK (&type_rw_lock);
3835     }
3836   else
3837     {
3838       g_return_val_if_fail (node != NULL, NULL);
3839       data = NULL;
3840     }
3841   return data;
3842 }
3843
3844 static inline void
3845 type_set_qdata_W (TypeNode *node,
3846                   GQuark    quark,
3847                   gpointer  data)
3848 {
3849   GData *gdata;
3850   QData *qdata;
3851   guint i;
3852   
3853   /* setup qdata list if necessary */
3854   if (!node->global_gdata)
3855     node->global_gdata = g_new0 (GData, 1);
3856   gdata = node->global_gdata;
3857   
3858   /* try resetting old data */
3859   qdata = gdata->qdatas;
3860   for (i = 0; i < gdata->n_qdatas; i++)
3861     if (qdata[i].quark == quark)
3862       {
3863         qdata[i].data = data;
3864         return;
3865       }
3866   
3867   /* add new entry */
3868   gdata->n_qdatas++;
3869   gdata->qdatas = g_renew (QData, gdata->qdatas, gdata->n_qdatas);
3870   qdata = gdata->qdatas;
3871   for (i = 0; i < gdata->n_qdatas - 1; i++)
3872     if (qdata[i].quark > quark)
3873       break;
3874   memmove (qdata + i + 1, qdata + i, sizeof (qdata[0]) * (gdata->n_qdatas - i - 1));
3875   qdata[i].quark = quark;
3876   qdata[i].data = data;
3877 }
3878
3879 /**
3880  * g_type_set_qdata:
3881  * @type: a #GType
3882  * @quark: a #GQuark id to identify the data
3883  * @data: the data
3884  *
3885  * Attaches arbitrary data to a type.
3886  */
3887 void
3888 g_type_set_qdata (GType    type,
3889                   GQuark   quark,
3890                   gpointer data)
3891 {
3892   TypeNode *node;
3893   
3894   g_return_if_fail (quark != 0);
3895   
3896   node = lookup_type_node_I (type);
3897   if (node)
3898     {
3899       G_WRITE_LOCK (&type_rw_lock);
3900       type_set_qdata_W (node, quark, data);
3901       G_WRITE_UNLOCK (&type_rw_lock);
3902     }
3903   else
3904     g_return_if_fail (node != NULL);
3905 }
3906
3907 static void
3908 type_add_flags_W (TypeNode  *node,
3909                   GTypeFlags flags)
3910 {
3911   guint dflags;
3912   
3913   g_return_if_fail ((flags & ~TYPE_FLAG_MASK) == 0);
3914   g_return_if_fail (node != NULL);
3915   
3916   if ((flags & TYPE_FLAG_MASK) && node->is_classed && node->data && node->data->class.class)
3917     g_critical ("tagging type '%s' as abstract after class initialization", NODE_NAME (node));
3918   dflags = GPOINTER_TO_UINT (type_get_qdata_L (node, static_quark_type_flags));
3919   dflags |= flags;
3920   type_set_qdata_W (node, static_quark_type_flags, GUINT_TO_POINTER (dflags));
3921
3922   node->is_final = (flags & G_TYPE_FLAG_FINAL) != 0;
3923 }
3924
3925 /**
3926  * g_type_query:
3927  * @type: #GType of a static, classed type
3928  * @query: (out caller-allocates): a user provided structure that is
3929  *     filled in with constant values upon success
3930  *
3931  * Queries the type system for information about a specific type.
3932  *
3933  * This function will fill in a user-provided structure to hold
3934  * type-specific information. If an invalid #GType is passed in, the
3935  * @type member of the #GTypeQuery is 0. All members filled into the
3936  * #GTypeQuery structure should be considered constant and have to be
3937  * left untouched.
3938  *
3939  * Since GLib 2.78, this function allows queries on dynamic types. Previously
3940  * it only supported static types.
3941  */
3942 void
3943 g_type_query (GType       type,
3944               GTypeQuery *query)
3945 {
3946   TypeNode *node;
3947   
3948   g_return_if_fail (query != NULL);
3949   
3950   /* if node is not classed, we won't allow query */
3951   query->type = 0;
3952   node = lookup_type_node_I (type);
3953   if (node && node->is_classed)
3954     {
3955       /* type is classed and probably even instantiatable */
3956       G_READ_LOCK (&type_rw_lock);
3957       if (node->data)   /* type is static or referenced */
3958         {
3959           query->type = NODE_TYPE (node);
3960           query->type_name = NODE_NAME (node);
3961           query->class_size = node->data->class.class_size;
3962           query->instance_size = node->is_instantiatable ? node->data->instance.instance_size : 0;
3963         }
3964       G_READ_UNLOCK (&type_rw_lock);
3965     }
3966 }
3967
3968 /**
3969  * g_type_get_instance_count:
3970  * @type: a #GType
3971  *
3972  * Returns the number of instances allocated of the particular type;
3973  * this is only available if GLib is built with debugging support and
3974  * the `instance-count` debug flag is set (by setting the `GOBJECT_DEBUG`
3975  * variable to include `instance-count`).
3976  *
3977  * Returns: the number of instances allocated of the given type;
3978  *   if instance counts are not available, returns 0.
3979  *
3980  * Since: 2.44
3981  */
3982 int
3983 g_type_get_instance_count (GType type)
3984 {
3985 #ifdef G_ENABLE_DEBUG
3986   TypeNode *node;
3987
3988   node = lookup_type_node_I (type);
3989   g_return_val_if_fail (node != NULL, 0);
3990
3991   return g_atomic_int_get (&node->instance_count);
3992 #else
3993   return 0;
3994 #endif
3995 }
3996
3997 /* --- implementation details --- */
3998 gboolean
3999 g_type_test_flags (GType type,
4000                    guint flags)
4001 {
4002   TypeNode *node;
4003   gboolean result = FALSE;
4004   
4005   node = lookup_type_node_I (type);
4006   if (node)
4007     {
4008       if ((flags & ~NODE_FLAG_MASK) == 0)
4009         {
4010           if (flags & G_TYPE_FLAG_CLASSED)
4011             result |= node->is_classed;
4012
4013           if (flags & G_TYPE_FLAG_INSTANTIATABLE)
4014             result |= node->is_instantiatable;
4015
4016           if (flags & G_TYPE_FLAG_FINAL)
4017             result |= node->is_final;
4018
4019           return result;
4020         }
4021
4022       guint fflags = flags & TYPE_FUNDAMENTAL_FLAG_MASK;
4023       guint tflags = flags & TYPE_FLAG_MASK;
4024       
4025       if (fflags)
4026         {
4027           GTypeFundamentalInfo *finfo = type_node_fundamental_info_I (node);
4028           
4029           fflags = (finfo->type_flags & fflags) == fflags;
4030         }
4031       else
4032         fflags = TRUE;
4033       
4034       if (tflags)
4035         {
4036           G_READ_LOCK (&type_rw_lock);
4037           tflags = (tflags & GPOINTER_TO_UINT (type_get_qdata_L (node, static_quark_type_flags))) == tflags;
4038           G_READ_UNLOCK (&type_rw_lock);
4039         }
4040       else
4041         tflags = TRUE;
4042       
4043       result = tflags && fflags;
4044     }
4045   
4046   return result;
4047 }
4048
4049 /**
4050  * g_type_get_plugin:
4051  * @type: #GType to retrieve the plugin for
4052  *
4053  * Returns the #GTypePlugin structure for @type.
4054  *
4055  * Returns: (transfer none): the corresponding plugin
4056  *     if @type is a dynamic type, %NULL otherwise
4057  */
4058 GTypePlugin*
4059 g_type_get_plugin (GType type)
4060 {
4061   TypeNode *node;
4062   
4063   node = lookup_type_node_I (type);
4064   
4065   return node ? node->plugin : NULL;
4066 }
4067
4068 /**
4069  * g_type_interface_get_plugin:
4070  * @instance_type: #GType of an instantiatable type
4071  * @interface_type: #GType of an interface type
4072  *
4073  * Returns the #GTypePlugin structure for the dynamic interface
4074  * @interface_type which has been added to @instance_type, or %NULL
4075  * if @interface_type has not been added to @instance_type or does
4076  * not have a #GTypePlugin structure. See g_type_add_interface_dynamic().
4077  *
4078  * Returns: (transfer none): the #GTypePlugin for the dynamic
4079  *     interface @interface_type of @instance_type
4080  */
4081 GTypePlugin*
4082 g_type_interface_get_plugin (GType instance_type,
4083                              GType interface_type)
4084 {
4085   TypeNode *node;
4086   TypeNode *iface;
4087   
4088   g_return_val_if_fail (G_TYPE_IS_INTERFACE (interface_type), NULL);    /* G_TYPE_IS_INTERFACE() is an external call: _U */
4089   
4090   node = lookup_type_node_I (instance_type);  
4091   iface = lookup_type_node_I (interface_type);
4092   if (node && iface)
4093     {
4094       IFaceHolder *iholder;
4095       GTypePlugin *plugin;
4096       
4097       G_READ_LOCK (&type_rw_lock);
4098       
4099       iholder = iface_node_get_holders_L (iface);
4100       while (iholder && iholder->instance_type != instance_type)
4101         iholder = iholder->next;
4102       plugin = iholder ? iholder->plugin : NULL;
4103       
4104       G_READ_UNLOCK (&type_rw_lock);
4105       
4106       return plugin;
4107     }
4108   
4109   g_return_val_if_fail (node == NULL, NULL);
4110   g_return_val_if_fail (iface == NULL, NULL);
4111   
4112   g_critical (G_STRLOC ": attempt to look up plugin for invalid instance/interface type pair.");
4113   
4114   return NULL;
4115 }
4116
4117 /**
4118  * g_type_fundamental_next:
4119  *
4120  * Returns the next free fundamental type id which can be used to
4121  * register a new fundamental type with g_type_register_fundamental().
4122  * The returned type ID represents the highest currently registered
4123  * fundamental type identifier.
4124  *
4125  * Returns: the next available fundamental type ID to be registered,
4126  *     or 0 if the type system ran out of fundamental type IDs
4127  */
4128 GType
4129 g_type_fundamental_next (void)
4130 {
4131   GType type;
4132   
4133   G_READ_LOCK (&type_rw_lock);
4134   type = static_fundamental_next;
4135   G_READ_UNLOCK (&type_rw_lock);
4136   type = G_TYPE_MAKE_FUNDAMENTAL (type);
4137   return type <= G_TYPE_FUNDAMENTAL_MAX ? type : 0;
4138 }
4139
4140 /**
4141  * g_type_fundamental:
4142  * @type_id: valid type ID
4143  * 
4144  * Internal function, used to extract the fundamental type ID portion.
4145  * Use G_TYPE_FUNDAMENTAL() instead.
4146  * 
4147  * Returns: fundamental type ID
4148  */
4149 GType
4150 g_type_fundamental (GType type_id)
4151 {
4152   TypeNode *node = lookup_type_node_I (type_id);
4153   
4154   return node ? NODE_FUNDAMENTAL_TYPE (node) : 0;
4155 }
4156
4157 gboolean
4158 g_type_check_instance_is_a (GTypeInstance *type_instance,
4159                             GType          iface_type)
4160 {
4161   TypeNode *node, *iface;
4162   gboolean check;
4163   
4164   if (!type_instance || !type_instance->g_class)
4165     return FALSE;
4166
4167   iface = lookup_type_node_I (iface_type);
4168   if (iface && iface->is_final)
4169     return type_instance->g_class->g_type == iface_type;
4170
4171   node = lookup_type_node_I (type_instance->g_class->g_type);
4172   check = node && node->is_instantiatable && iface && type_node_conforms_to_U (node, iface, TRUE, FALSE);
4173   
4174   return check;
4175 }
4176
4177 gboolean
4178 g_type_check_instance_is_fundamentally_a (GTypeInstance *type_instance,
4179                                           GType          fundamental_type)
4180 {
4181   TypeNode *node;
4182   if (!type_instance || !type_instance->g_class)
4183     return FALSE;
4184   node = lookup_type_node_I (type_instance->g_class->g_type);
4185   return node && (NODE_FUNDAMENTAL_TYPE(node) == fundamental_type);
4186 }
4187
4188 gboolean
4189 g_type_check_class_is_a (GTypeClass *type_class,
4190                          GType       is_a_type)
4191 {
4192   TypeNode *node, *iface;
4193   gboolean check;
4194   
4195   if (!type_class)
4196     return FALSE;
4197   
4198   node = lookup_type_node_I (type_class->g_type);
4199   iface = lookup_type_node_I (is_a_type);
4200   check = node && node->is_classed && iface && type_node_conforms_to_U (node, iface, FALSE, FALSE);
4201   
4202   return check;
4203 }
4204
4205 GTypeInstance*
4206 g_type_check_instance_cast (GTypeInstance *type_instance,
4207                             GType          iface_type)
4208 {
4209   if (type_instance)
4210     {
4211       if (type_instance->g_class)
4212         {
4213           TypeNode *node, *iface;
4214           gboolean is_instantiatable, check;
4215           
4216           node = lookup_type_node_I (type_instance->g_class->g_type);
4217           is_instantiatable = node && node->is_instantiatable;
4218           iface = lookup_type_node_I (iface_type);
4219           check = is_instantiatable && iface && type_node_conforms_to_U (node, iface, TRUE, FALSE);
4220           if (check)
4221             return type_instance;
4222           
4223           if (is_instantiatable)
4224             g_critical ("invalid cast from '%s' to '%s'",
4225                         type_descriptive_name_I (type_instance->g_class->g_type),
4226                         type_descriptive_name_I (iface_type));
4227           else
4228             g_critical ("invalid uninstantiatable type '%s' in cast to '%s'",
4229                         type_descriptive_name_I (type_instance->g_class->g_type),
4230                         type_descriptive_name_I (iface_type));
4231         }
4232       else
4233         g_critical ("invalid unclassed pointer in cast to '%s'",
4234                     type_descriptive_name_I (iface_type));
4235     }
4236   
4237   return type_instance;
4238 }
4239
4240 GTypeClass*
4241 g_type_check_class_cast (GTypeClass *type_class,
4242                          GType       is_a_type)
4243 {
4244   if (type_class)
4245     {
4246       TypeNode *node, *iface;
4247       gboolean is_classed, check;
4248       
4249       node = lookup_type_node_I (type_class->g_type);
4250       is_classed = node && node->is_classed;
4251       iface = lookup_type_node_I (is_a_type);
4252       check = is_classed && iface && type_node_conforms_to_U (node, iface, FALSE, FALSE);
4253       if (check)
4254         return type_class;
4255       
4256       if (is_classed)
4257         g_critical ("invalid class cast from '%s' to '%s'",
4258                     type_descriptive_name_I (type_class->g_type),
4259                     type_descriptive_name_I (is_a_type));
4260       else
4261         g_critical ("invalid unclassed type '%s' in class cast to '%s'",
4262                     type_descriptive_name_I (type_class->g_type),
4263                     type_descriptive_name_I (is_a_type));
4264     }
4265   else
4266     g_critical ("invalid class cast from (NULL) pointer to '%s'",
4267                 type_descriptive_name_I (is_a_type));
4268   return type_class;
4269 }
4270
4271 /**
4272  * g_type_check_instance:
4273  * @instance: a valid #GTypeInstance structure
4274  *
4275  * Private helper function to aid implementation of the
4276  * G_TYPE_CHECK_INSTANCE() macro.
4277  *
4278  * Returns: %TRUE if @instance is valid, %FALSE otherwise
4279  */
4280 gboolean
4281 g_type_check_instance (GTypeInstance *type_instance)
4282 {
4283   /* this function is just here to make the signal system
4284    * conveniently elaborated on instance checks
4285    */
4286   if (type_instance)
4287     {
4288       if (type_instance->g_class)
4289         {
4290           TypeNode *node = lookup_type_node_I (type_instance->g_class->g_type);
4291           
4292           if (node && node->is_instantiatable)
4293             return TRUE;
4294           
4295           g_critical ("instance of invalid non-instantiatable type '%s'",
4296                       type_descriptive_name_I (type_instance->g_class->g_type));
4297         }
4298       else
4299         g_critical ("instance with invalid (NULL) class pointer");
4300     }
4301   else
4302     g_critical ("invalid (NULL) pointer instance");
4303   
4304   return FALSE;
4305 }
4306
4307 static inline gboolean
4308 type_check_is_value_type_U (GType type)
4309 {
4310   GTypeFlags tflags = G_TYPE_FLAG_VALUE_ABSTRACT;
4311   TypeNode *node;
4312   
4313   /* common path speed up */
4314   node = lookup_type_node_I (type);
4315   if (node && node->mutatable_check_cache)
4316     return TRUE;
4317   
4318   G_READ_LOCK (&type_rw_lock);
4319  restart_check:
4320   if (node)
4321     {
4322       if (node->data && NODE_REFCOUNT (node) > 0 &&
4323           node->data->common.value_table->value_init)
4324         tflags = GPOINTER_TO_UINT (type_get_qdata_L (node, static_quark_type_flags));
4325       else if (NODE_IS_IFACE (node))
4326         {
4327           guint i;
4328           
4329           for (i = 0; i < IFACE_NODE_N_PREREQUISITES (node); i++)
4330             {
4331               GType prtype = IFACE_NODE_PREREQUISITES (node)[i];
4332               TypeNode *prnode = lookup_type_node_I (prtype);
4333               
4334               if (prnode->is_instantiatable)
4335                 {
4336                   type = prtype;
4337                   node = lookup_type_node_I (type);
4338                   goto restart_check;
4339                 }
4340             }
4341         }
4342     }
4343   G_READ_UNLOCK (&type_rw_lock);
4344   
4345   return !(tflags & G_TYPE_FLAG_VALUE_ABSTRACT);
4346 }
4347
4348 gboolean
4349 g_type_check_is_value_type (GType type)
4350 {
4351   return type_check_is_value_type_U (type);
4352 }
4353
4354 gboolean
4355 g_type_check_value (const GValue *value)
4356 {
4357   return value && type_check_is_value_type_U (value->g_type);
4358 }
4359
4360 gboolean
4361 g_type_check_value_holds (const GValue *value,
4362                           GType         type)
4363 {
4364   return value && type_check_is_value_type_U (value->g_type) && g_type_is_a (value->g_type, type);
4365 }
4366
4367 /**
4368  * g_type_value_table_peek: (skip)
4369  * @type: a #GType
4370  *
4371  * Returns the location of the #GTypeValueTable associated with @type.
4372  *
4373  * Note that this function should only be used from source code
4374  * that implements or has internal knowledge of the implementation of
4375  * @type.
4376  *
4377  * Returns: location of the #GTypeValueTable associated with @type or
4378  *     %NULL if there is no #GTypeValueTable associated with @type
4379  */
4380 GTypeValueTable*
4381 g_type_value_table_peek (GType type)
4382 {
4383   GTypeValueTable *vtable = NULL;
4384   TypeNode *node = lookup_type_node_I (type);
4385   gboolean has_refed_data, has_table;
4386
4387   if (node && NODE_REFCOUNT (node) && node->mutatable_check_cache)
4388     return node->data->common.value_table;
4389
4390   G_READ_LOCK (&type_rw_lock);
4391   
4392  restart_table_peek:
4393   has_refed_data = node && node->data && NODE_REFCOUNT (node) > 0;
4394   has_table = has_refed_data && node->data->common.value_table->value_init;
4395   if (has_refed_data)
4396     {
4397       if (has_table)
4398         vtable = node->data->common.value_table;
4399       else if (NODE_IS_IFACE (node))
4400         {
4401           guint i;
4402           
4403           for (i = 0; i < IFACE_NODE_N_PREREQUISITES (node); i++)
4404             {
4405               GType prtype = IFACE_NODE_PREREQUISITES (node)[i];
4406               TypeNode *prnode = lookup_type_node_I (prtype);
4407               
4408               if (prnode->is_instantiatable)
4409                 {
4410                   type = prtype;
4411                   node = lookup_type_node_I (type);
4412                   goto restart_table_peek;
4413                 }
4414             }
4415         }
4416     }
4417   
4418   G_READ_UNLOCK (&type_rw_lock);
4419   
4420   if (vtable)
4421     return vtable;
4422   
4423   if (!node)
4424     g_critical (G_STRLOC ": type id '%" G_GSIZE_FORMAT "' is invalid", type);
4425   if (!has_refed_data)
4426     g_critical ("can't peek value table for type '%s' which is not currently referenced",
4427                 type_descriptive_name_I (type));
4428   
4429   return NULL;
4430 }
4431
4432 const gchar *
4433 g_type_name_from_instance (GTypeInstance *instance)
4434 {
4435   if (!instance)
4436     return "<NULL-instance>";
4437   else
4438     return g_type_name_from_class (instance->g_class);
4439 }
4440
4441 const gchar *
4442 g_type_name_from_class (GTypeClass *g_class)
4443 {
4444   if (!g_class)
4445     return "<NULL-class>";
4446   else
4447     return g_type_name (g_class->g_type);
4448 }
4449
4450
4451 /* --- private api for gboxed.c --- */
4452 gpointer
4453 _g_type_boxed_copy (GType type, gpointer value)
4454 {
4455   TypeNode *node = lookup_type_node_I (type);
4456
4457   return node->data->boxed.copy_func (value);
4458 }
4459
4460 void
4461 _g_type_boxed_free (GType type, gpointer value)
4462 {
4463   TypeNode *node = lookup_type_node_I (type);
4464
4465   node->data->boxed.free_func (value);
4466 }
4467
4468 void
4469 _g_type_boxed_init (GType          type,
4470                     GBoxedCopyFunc copy_func,
4471                     GBoxedFreeFunc free_func)
4472 {
4473   TypeNode *node = lookup_type_node_I (type);
4474
4475   node->data->boxed.copy_func = copy_func;
4476   node->data->boxed.free_func = free_func;
4477 }
4478
4479 /* --- initialization --- */
4480 /**
4481  * g_type_init_with_debug_flags:
4482  * @debug_flags: bitwise combination of #GTypeDebugFlags values for
4483  *     debugging purposes
4484  *
4485  * This function used to initialise the type system with debugging
4486  * flags.  Since GLib 2.36, the type system is initialised automatically
4487  * and this function does nothing.
4488  *
4489  * If you need to enable debugging features, use the `GOBJECT_DEBUG`
4490  * environment variable.
4491  *
4492  * Deprecated: 2.36: the type system is now initialised automatically
4493  */
4494 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4495 void
4496 g_type_init_with_debug_flags (GTypeDebugFlags debug_flags)
4497 {
4498   g_assert_type_system_initialized ();
4499
4500   if (debug_flags)
4501     g_message ("g_type_init_with_debug_flags() is no longer supported.  Use the GOBJECT_DEBUG environment variable.");
4502 }
4503 G_GNUC_END_IGNORE_DEPRECATIONS
4504
4505 /**
4506  * g_type_init:
4507  *
4508  * This function used to initialise the type system.  Since GLib 2.36,
4509  * the type system is initialised automatically and this function does
4510  * nothing.
4511  *
4512  * Deprecated: 2.36: the type system is now initialised automatically
4513  */
4514 void
4515 g_type_init (void)
4516 {
4517   g_assert_type_system_initialized ();
4518 }
4519
4520 static void
4521 gobject_init (void)
4522 {
4523   const gchar *env_string;
4524   GTypeInfo info;
4525   TypeNode *node;
4526   GType type G_GNUC_UNUSED  /* when compiling with G_DISABLE_ASSERT */;
4527
4528   /* Ensure GLib is initialized first, see
4529    * https://bugzilla.gnome.org/show_bug.cgi?id=756139
4530    */
4531   GLIB_PRIVATE_CALL (glib_init) ();
4532
4533   G_WRITE_LOCK (&type_rw_lock);
4534
4535   /* setup GObject library wide debugging flags */
4536   env_string = g_getenv ("GOBJECT_DEBUG");
4537   if (env_string != NULL)
4538     {
4539       GDebugKey debug_keys[] = {
4540         { "objects", G_TYPE_DEBUG_OBJECTS },
4541         { "instance-count", G_TYPE_DEBUG_INSTANCE_COUNT },
4542         { "signals", G_TYPE_DEBUG_SIGNALS },
4543       };
4544
4545       _g_type_debug_flags = g_parse_debug_string (env_string, debug_keys, G_N_ELEMENTS (debug_keys));
4546     }
4547
4548   /* quarks */
4549   static_quark_type_flags = g_quark_from_static_string ("-g-type-private--GTypeFlags");
4550   static_quark_iface_holder = g_quark_from_static_string ("-g-type-private--IFaceHolder");
4551   static_quark_dependants_array = g_quark_from_static_string ("-g-type-private--dependants-array");
4552
4553   /* type qname hash table */
4554   static_type_nodes_ht = g_hash_table_new (g_str_hash, g_str_equal);
4555
4556   /* invalid type G_TYPE_INVALID (0)
4557    */
4558   static_fundamental_type_nodes[0] = NULL;
4559
4560   /* void type G_TYPE_NONE
4561    */
4562   node = type_node_fundamental_new_W (G_TYPE_NONE, g_intern_static_string ("void"), 0);
4563   type = NODE_TYPE (node);
4564   g_assert (type == G_TYPE_NONE);
4565
4566   /* interface fundamental type G_TYPE_INTERFACE (!classed)
4567    */
4568   memset (&info, 0, sizeof (info));
4569   node = type_node_fundamental_new_W (G_TYPE_INTERFACE, g_intern_static_string ("GInterface"), G_TYPE_FLAG_DERIVABLE);
4570   type = NODE_TYPE (node);
4571   type_data_make_W (node, &info, NULL);
4572   g_assert (type == G_TYPE_INTERFACE);
4573
4574   G_WRITE_UNLOCK (&type_rw_lock);
4575
4576   _g_value_c_init ();
4577
4578   /* G_TYPE_TYPE_PLUGIN
4579    */
4580   g_type_ensure (g_type_plugin_get_type ());
4581
4582   /* G_TYPE_* value types
4583    */
4584   _g_value_types_init ();
4585
4586   /* G_TYPE_ENUM & G_TYPE_FLAGS
4587    */
4588   _g_enum_types_init ();
4589
4590   /* G_TYPE_BOXED
4591    */
4592   _g_boxed_type_init ();
4593
4594   /* G_TYPE_PARAM
4595    */
4596   _g_param_type_init ();
4597
4598   /* G_TYPE_OBJECT
4599    */
4600   _g_object_type_init ();
4601
4602   /* G_TYPE_PARAM_* pspec types
4603    */
4604   _g_param_spec_types_init ();
4605
4606   /* Value Transformations
4607    */
4608   _g_value_transforms_init ();
4609
4610   /* Signal system
4611    */
4612   _g_signal_init ();
4613 }
4614
4615 #ifdef G_PLATFORM_WIN32
4616
4617 void gobject_win32_init (void);
4618
4619 void
4620 gobject_win32_init (void)
4621 {
4622   /* May be called more than once in static compilation mode */
4623   static gboolean win32_already_init = FALSE;
4624   if (!win32_already_init)
4625     {
4626       win32_already_init = TRUE;
4627       gobject_init ();
4628     }
4629 }
4630
4631 #ifndef GLIB_STATIC_COMPILATION
4632
4633 BOOL WINAPI DllMain (HINSTANCE hinstDLL,
4634                      DWORD     fdwReason,
4635                      LPVOID    lpvReserved);
4636
4637 BOOL WINAPI
4638 DllMain (HINSTANCE hinstDLL,
4639          DWORD     fdwReason,
4640          LPVOID    lpvReserved)
4641 {
4642   switch (fdwReason)
4643     {
4644     case DLL_PROCESS_ATTACH:
4645       gobject_win32_init ();
4646       break;
4647
4648     default:
4649       /* do nothing */
4650       ;
4651     }
4652
4653   return TRUE;
4654 }
4655
4656 #elif defined(G_HAS_CONSTRUCTORS) /* && G_PLATFORM_WIN32 && GLIB_STATIC_COMPILATION */
4657 extern void glib_win32_init (void);
4658
4659 #ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA
4660 #pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(gobject_init_ctor)
4661 #endif
4662
4663 G_DEFINE_CONSTRUCTOR(gobject_init_ctor)
4664
4665 static void
4666 gobject_init_ctor (void)
4667 {
4668   /* When built dynamically, module initialization is done through DllMain
4669    * function which is called when the dynamic library is loaded by the glib
4670    * module. So, in dynamic configuration glib is always initialized BEFORE
4671    * gobject.
4672    *
4673    * When built statically, initialization mechanism relies on hooking
4674    * functions to the CRT section directly at compilation time. As we don't
4675    * control how each compilation unit will be built and in which order, we
4676    * obtain the same kind of issue as the "static initialization order fiasco".
4677    * In this case, we must ensure explicitly that glib is always well
4678    * initialized BEFORE gobject.
4679    */
4680   glib_win32_init ();
4681   gobject_win32_init ();
4682 }
4683
4684 #else /* G_PLATFORM_WIN32 && GLIB_STATIC_COMPILATION && !G_HAS_CONSTRUCTORS */
4685 # error Your platform/compiler is missing constructor support
4686 #endif /* GLIB_STATIC_COMPILATION */
4687
4688 #elif defined(G_HAS_CONSTRUCTORS) /* && !G_PLATFORM_WIN32 */
4689
4690 #ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA
4691 #pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(gobject_init_ctor)
4692 #endif
4693
4694 G_DEFINE_CONSTRUCTOR (gobject_init_ctor)
4695
4696 static void
4697 gobject_init_ctor (void)
4698 {
4699   gobject_init ();
4700 }
4701
4702 #else /* !G_PLATFORM_WIN32 && !G_HAS_CONSTRUCTORS */
4703 #error Your platform/compiler is missing constructor support
4704 #endif /* G_PLATFORM_WIN32 */
4705
4706 /**
4707  * g_type_class_add_private:
4708  * @g_class: (type GObject.TypeClass): class structure for an instantiatable
4709  *    type
4710  * @private_size: size of private structure
4711  *
4712  * Registers a private structure for an instantiatable type.
4713  *
4714  * When an object is allocated, the private structures for
4715  * the type and all of its parent types are allocated
4716  * sequentially in the same memory block as the public
4717  * structures, and are zero-filled.
4718  *
4719  * Note that the accumulated size of the private structures of
4720  * a type and all its parent types cannot exceed 64 KiB.
4721  *
4722  * This function should be called in the type's class_init() function.
4723  * The private structure can be retrieved using the
4724  * G_TYPE_INSTANCE_GET_PRIVATE() macro.
4725  *
4726  * The following example shows attaching a private structure
4727  * MyObjectPrivate to an object MyObject defined in the standard
4728  * GObject fashion in the type's class_init() function.
4729  *
4730  * Note the use of a structure member "priv" to avoid the overhead
4731  * of repeatedly calling MY_OBJECT_GET_PRIVATE().
4732  *
4733  * |[<!-- language="C" --> 
4734  * typedef struct _MyObject        MyObject;
4735  * typedef struct _MyObjectPrivate MyObjectPrivate;
4736  *
4737  * struct _MyObject {
4738  *  GObject parent;
4739  *
4740  *  MyObjectPrivate *priv;
4741  * };
4742  *
4743  * struct _MyObjectPrivate {
4744  *   int some_field;
4745  * };
4746  *
4747  * static void
4748  * my_object_class_init (MyObjectClass *klass)
4749  * {
4750  *   g_type_class_add_private (klass, sizeof (MyObjectPrivate));
4751  * }
4752  *
4753  * static void
4754  * my_object_init (MyObject *my_object)
4755  * {
4756  *   my_object->priv = G_TYPE_INSTANCE_GET_PRIVATE (my_object,
4757  *                                                  MY_TYPE_OBJECT,
4758  *                                                  MyObjectPrivate);
4759  *   // my_object->priv->some_field will be automatically initialised to 0
4760  * }
4761  *
4762  * static int
4763  * my_object_get_some_field (MyObject *my_object)
4764  * {
4765  *   MyObjectPrivate *priv;
4766  *
4767  *   g_return_val_if_fail (MY_IS_OBJECT (my_object), 0);
4768  *
4769  *   priv = my_object->priv;
4770  *
4771  *   return priv->some_field;
4772  * }
4773  * ]|
4774  *
4775  * Since: 2.4
4776  * Deprecated: 2.58: Use the G_ADD_PRIVATE() macro with the `G_DEFINE_*`
4777  *   family of macros to add instance private data to a type
4778  */
4779 void
4780 g_type_class_add_private (gpointer g_class,
4781                           gsize    private_size)
4782 {
4783   GType instance_type = ((GTypeClass *)g_class)->g_type;
4784   TypeNode *node = lookup_type_node_I (instance_type);
4785
4786   g_return_if_fail (private_size > 0);
4787   g_return_if_fail (private_size <= 0xffff);
4788
4789   if (!node || !node->is_instantiatable || !node->data || node->data->class.class != g_class)
4790     {
4791       g_critical ("cannot add private field to invalid (non-instantiatable) type '%s'",
4792                   type_descriptive_name_I (instance_type));
4793       return;
4794     }
4795
4796   if (NODE_PARENT_TYPE (node))
4797     {
4798       TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
4799       if (node->data->instance.private_size != pnode->data->instance.private_size)
4800         {
4801           g_critical ("g_type_class_add_private() called multiple times for the same type");
4802           return;
4803         }
4804     }
4805   
4806   G_WRITE_LOCK (&type_rw_lock);
4807
4808   private_size = ALIGN_STRUCT (node->data->instance.private_size + private_size);
4809   g_assert (private_size <= 0xffff);
4810   node->data->instance.private_size = private_size;
4811   
4812   G_WRITE_UNLOCK (&type_rw_lock);
4813 }
4814
4815 /* semi-private, called only by the G_ADD_PRIVATE macro */
4816 gint
4817 g_type_add_instance_private (GType class_gtype,
4818                              gsize private_size)
4819 {
4820   TypeNode *node = lookup_type_node_I (class_gtype);
4821
4822   g_return_val_if_fail (private_size > 0, 0);
4823   g_return_val_if_fail (private_size <= 0xffff, 0);
4824
4825   if (!node || !node->is_classed || !node->is_instantiatable || !node->data)
4826     {
4827       g_critical ("cannot add private field to invalid (non-instantiatable) type '%s'",
4828                   type_descriptive_name_I (class_gtype));
4829       return 0;
4830     }
4831
4832   if (node->plugin != NULL)
4833     {
4834       g_critical ("cannot use g_type_add_instance_private() with dynamic type '%s'",
4835                   type_descriptive_name_I (class_gtype));
4836       return 0;
4837     }
4838
4839   /* in the future, we want to register the private data size of a type
4840    * directly from the get_type() implementation so that we can take full
4841    * advantage of the type definition macros that we already have.
4842    *
4843    * unfortunately, this does not behave correctly if a class in the middle
4844    * of the type hierarchy uses the "old style" of private data registration
4845    * from the class_init() implementation, as the private data offset is not
4846    * going to be known until the full class hierarchy is initialized.
4847    *
4848    * in order to transition our code to the Glorious New Future™, we proceed
4849    * with a two-step implementation: first, we provide this new function to
4850    * register the private data size in the get_type() implementation and we
4851    * hide it behind a macro. the function will return the private size, instead
4852    * of the offset, which will be stored inside a static variable defined by
4853    * the G_DEFINE_TYPE_EXTENDED() macro. the G_DEFINE_TYPE_EXTENDED() macro will
4854    * check the variable and call g_type_class_adjust_private_offset(), which
4855    * will use the data size and actually register the private data, then
4856    * return the computed offset of the private data, which will be stored
4857    * inside the static variable, so we can use it to retrieve the pointer
4858    * to the private data structure.
4859    *
4860    * once all our code has been migrated to the new idiomatic form of private
4861    * data registration, we will change the g_type_add_instance_private()
4862    * function to actually perform the registration and return the offset
4863    * of the private data; g_type_class_adjust_private_offset() already checks
4864    * if the passed argument is negative (meaning that it's an offset in the
4865    * GTypeInstance allocation) and becomes a no-op if that's the case. this
4866    * should make the migration fully transparent even if we're effectively
4867    * copying this macro into everybody's code.
4868    */
4869   return private_size;
4870 }
4871
4872 /* semi-private function, should only be used by G_DEFINE_TYPE_EXTENDED */
4873 void
4874 g_type_class_adjust_private_offset (gpointer  g_class,
4875                                     gint     *private_size_or_offset)
4876 {
4877   GType class_gtype = ((GTypeClass *) g_class)->g_type;
4878   TypeNode *node = lookup_type_node_I (class_gtype);
4879   gssize private_size;
4880
4881   g_return_if_fail (private_size_or_offset != NULL);
4882
4883   /* if we have been passed the offset instead of the private data size,
4884    * then we consider this as a no-op, and just return the value. see the
4885    * comment in g_type_add_instance_private() for the full explanation.
4886    */
4887   if (*private_size_or_offset > 0)
4888     g_return_if_fail (*private_size_or_offset <= 0xffff);
4889   else
4890     return;
4891
4892   if (!node || !node->is_classed || !node->is_instantiatable || !node->data)
4893     {
4894       g_critical ("cannot add private field to invalid (non-instantiatable) type '%s'",
4895                   type_descriptive_name_I (class_gtype));
4896       *private_size_or_offset = 0;
4897       return;
4898     }
4899
4900   if (NODE_PARENT_TYPE (node))
4901     {
4902       TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
4903       if (node->data->instance.private_size != pnode->data->instance.private_size)
4904         {
4905           g_critical ("g_type_add_instance_private() called multiple times for the same type");
4906           *private_size_or_offset = 0;
4907           return;
4908         }
4909     }
4910
4911   G_WRITE_LOCK (&type_rw_lock);
4912
4913   private_size = ALIGN_STRUCT (node->data->instance.private_size + *private_size_or_offset);
4914   g_assert (private_size <= 0xffff);
4915   node->data->instance.private_size = private_size;
4916
4917   *private_size_or_offset = -(gint) node->data->instance.private_size;
4918
4919   G_WRITE_UNLOCK (&type_rw_lock);
4920 }
4921
4922 gpointer
4923 g_type_instance_get_private (GTypeInstance *instance,
4924                              GType          private_type)
4925 {
4926   TypeNode *node;
4927
4928   g_return_val_if_fail (instance != NULL && instance->g_class != NULL, NULL);
4929
4930   node = lookup_type_node_I (private_type);
4931   if (G_UNLIKELY (!node || !node->is_instantiatable))
4932     {
4933       g_critical ("instance of invalid non-instantiatable type '%s'",
4934                   type_descriptive_name_I (instance->g_class->g_type));
4935       return NULL;
4936     }
4937
4938   return ((gchar *) instance) - node->data->instance.private_size;
4939 }
4940
4941 /**
4942  * g_type_class_get_instance_private_offset: (skip)
4943  * @g_class: (type GObject.TypeClass): a #GTypeClass
4944  *
4945  * Gets the offset of the private data for instances of @g_class.
4946  *
4947  * This is how many bytes you should add to the instance pointer of a
4948  * class in order to get the private data for the type represented by
4949  * @g_class.
4950  *
4951  * You can only call this function after you have registered a private
4952  * data area for @g_class using g_type_class_add_private().
4953  *
4954  * Returns: the offset, in bytes
4955  *
4956  * Since: 2.38
4957  **/
4958 gint
4959 g_type_class_get_instance_private_offset (gpointer g_class)
4960 {
4961   GType instance_type;
4962   guint16 parent_size;
4963   TypeNode *node;
4964
4965   g_assert (g_class != NULL);
4966
4967   instance_type = ((GTypeClass *) g_class)->g_type;
4968   node = lookup_type_node_I (instance_type);
4969
4970   g_assert (node != NULL);
4971   g_assert (node->is_instantiatable);
4972
4973   if (NODE_PARENT_TYPE (node))
4974     {
4975       TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
4976
4977       parent_size = pnode->data->instance.private_size;
4978     }
4979   else
4980     parent_size = 0;
4981
4982   if (node->data->instance.private_size == parent_size)
4983     g_error ("g_type_class_get_instance_private_offset() called on class %s but it has no private data",
4984              g_type_name (instance_type));
4985
4986   return -(gint) node->data->instance.private_size;
4987 }
4988
4989 /**
4990  * g_type_add_class_private:
4991  * @class_type: GType of a classed type
4992  * @private_size: size of private structure
4993  *
4994  * Registers a private class structure for a classed type;
4995  * when the class is allocated, the private structures for
4996  * the class and all of its parent types are allocated
4997  * sequentially in the same memory block as the public
4998  * structures, and are zero-filled.
4999  *
5000  * This function should be called in the
5001  * type's get_type() function after the type is registered.
5002  * The private structure can be retrieved using the
5003  * G_TYPE_CLASS_GET_PRIVATE() macro.
5004  *
5005  * Since: 2.24
5006  */
5007 void
5008 g_type_add_class_private (GType    class_type,
5009                           gsize    private_size)
5010 {
5011   TypeNode *node = lookup_type_node_I (class_type);
5012   gsize offset;
5013
5014   g_return_if_fail (private_size > 0);
5015
5016   if (!node || !node->is_classed || !node->data)
5017     {
5018       g_critical ("cannot add class private field to invalid type '%s'",
5019                   type_descriptive_name_I (class_type));
5020       return;
5021     }
5022
5023   if (NODE_PARENT_TYPE (node))
5024     {
5025       TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
5026       if (node->data->class.class_private_size != pnode->data->class.class_private_size)
5027         {
5028           g_critical ("g_type_add_class_private() called multiple times for the same type");
5029           return;
5030         }
5031     }
5032   
5033   G_WRITE_LOCK (&type_rw_lock);
5034
5035   offset = ALIGN_STRUCT (node->data->class.class_private_size);
5036   node->data->class.class_private_size = offset + private_size;
5037
5038   G_WRITE_UNLOCK (&type_rw_lock);
5039 }
5040
5041 gpointer
5042 g_type_class_get_private (GTypeClass *klass,
5043                           GType       private_type)
5044 {
5045   TypeNode *class_node;
5046   TypeNode *private_node;
5047   TypeNode *parent_node;
5048   gsize offset;
5049
5050   g_return_val_if_fail (klass != NULL, NULL);
5051
5052   class_node = lookup_type_node_I (klass->g_type);
5053   if (G_UNLIKELY (!class_node || !class_node->is_classed))
5054     {
5055       g_critical ("class of invalid type '%s'",
5056                   type_descriptive_name_I (klass->g_type));
5057       return NULL;
5058     }
5059
5060   private_node = lookup_type_node_I (private_type);
5061   if (G_UNLIKELY (!private_node || !NODE_IS_ANCESTOR (private_node, class_node)))
5062     {
5063       g_critical ("attempt to retrieve private data for invalid type '%s'",
5064                   type_descriptive_name_I (private_type));
5065       return NULL;
5066     }
5067
5068   offset = ALIGN_STRUCT (class_node->data->class.class_size);
5069
5070   if (NODE_PARENT_TYPE (private_node))
5071     {
5072       parent_node = lookup_type_node_I (NODE_PARENT_TYPE (private_node));
5073       g_assert (parent_node->data && NODE_REFCOUNT (parent_node) > 0);
5074
5075       if (G_UNLIKELY (private_node->data->class.class_private_size == parent_node->data->class.class_private_size))
5076         {
5077           g_critical ("g_type_instance_get_class_private() requires a prior call to g_type_add_class_private()");
5078           return NULL;
5079         }
5080
5081       offset += ALIGN_STRUCT (parent_node->data->class.class_private_size);
5082     }
5083
5084   return G_STRUCT_MEMBER_P (klass, offset);
5085 }
5086
5087 /**
5088  * g_type_ensure:
5089  * @type: a #GType
5090  *
5091  * Ensures that the indicated @type has been registered with the
5092  * type system, and its _class_init() method has been run.
5093  *
5094  * In theory, simply calling the type's _get_type() method (or using
5095  * the corresponding macro) is supposed take care of this. However,
5096  * _get_type() methods are often marked %G_GNUC_CONST for performance
5097  * reasons, even though this is technically incorrect (since
5098  * %G_GNUC_CONST requires that the function not have side effects,
5099  * which _get_type() methods do on the first call). As a result, if
5100  * you write a bare call to a _get_type() macro, it may get optimized
5101  * out by the compiler. Using g_type_ensure() guarantees that the
5102  * type's _get_type() method is called.
5103  *
5104  * Since: 2.34
5105  */
5106 void
5107 g_type_ensure (GType type)
5108 {
5109   /* In theory, @type has already been resolved and so there's nothing
5110    * to do here. But this protects us in the case where the function
5111    * gets inlined (as it might in gobject_init_ctor() above).
5112    */
5113   if (G_UNLIKELY (type == (GType)-1))
5114     g_error ("can't happen");
5115 }