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