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