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