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