Make all accesses of Node->ref_count atomic
[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   guint              init_state : 4;
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   guint              init_state : 4;
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 gboolean
1207 iface_node_has_available_offset_L (TypeNode *iface_node,
1208                                    int offset,
1209                                    int for_index)
1210 {
1211   guint8 *offsets;
1212
1213   offsets = G_ATOMIC_ARRAY_GET_LOCKED (&iface_node->data->iface.offsets, guint8);
1214   if (offsets == NULL)
1215     return TRUE;
1216
1217   if (G_ATOMIC_ARRAY_DATA_SIZE (offsets) <= offset)
1218     return TRUE;
1219
1220   if (offsets[offset] == 0 ||
1221       offsets[offset] == for_index+1)
1222     return TRUE;
1223
1224   return FALSE;
1225 }
1226
1227 static int
1228 find_free_iface_offset_L (IFaceEntries *entries)
1229 {
1230   IFaceEntry *entry;
1231   TypeNode *iface_node;
1232   int offset;
1233   int i;
1234   int n_entries;
1235
1236   n_entries = IFACE_ENTRIES_N_ENTRIES (entries);
1237   offset = -1;
1238   do
1239     {
1240       offset++;
1241       for (i = 0; i < n_entries; i++)
1242         {
1243           entry = &entries->entry[i];
1244           iface_node = lookup_type_node_I (entry->iface_type);
1245
1246           if (!iface_node_has_available_offset_L (iface_node, offset, i))
1247             break;
1248         }
1249     }
1250   while (i != n_entries);
1251
1252   return offset;
1253 }
1254
1255 static void
1256 iface_node_set_offset_L (TypeNode *iface_node,
1257                          int offset,
1258                          int index)
1259 {
1260   guint8 *offsets, *old_offsets;
1261   int new_size, old_size;
1262   int i;
1263
1264   old_offsets = G_ATOMIC_ARRAY_GET_LOCKED (&iface_node->data->iface.offsets, guint8);
1265   if (old_offsets == NULL)
1266     old_size = 0;
1267   else
1268     {
1269       old_size = G_ATOMIC_ARRAY_DATA_SIZE (old_offsets);
1270       if (offset < old_size &&
1271           old_offsets[offset] == index + 1)
1272         return; /* Already set to this index, return */
1273     }
1274   new_size = MAX (old_size, offset + 1);
1275
1276   offsets = _g_atomic_array_copy (&iface_node->data->iface.offsets,
1277                                   0, new_size - old_size);
1278
1279   /* Mark new area as unused */
1280   for (i = old_size; i < new_size; i++)
1281     offsets[i] = 0;
1282
1283   offsets[offset] = index + 1;
1284
1285   _g_atomic_array_update (&iface_node->data->iface.offsets, offsets);
1286 }
1287
1288 static void
1289 type_node_add_iface_entry_W (TypeNode   *node,
1290                              GType       iface_type,
1291                              IFaceEntry *parent_entry)
1292 {
1293   IFaceEntries *entries;
1294   IFaceEntry *entry;
1295   TypeNode *iface_node;
1296   guint i, j;
1297   int num_entries;
1298
1299   g_assert (node->is_instantiatable);
1300
1301   entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node);
1302   if (entries != NULL)
1303     {
1304       num_entries = IFACE_ENTRIES_N_ENTRIES (entries);
1305
1306       g_assert (num_entries < MAX_N_INTERFACES);
1307
1308       for (i = 0; i < num_entries; i++)
1309         {
1310           entry = &entries->entry[i];
1311           if (entry->iface_type == iface_type)
1312             {
1313               /* this can happen in two cases:
1314                * - our parent type already conformed to iface_type and node
1315                *   got its own holder info. here, our children already have
1316                *   entries and NULL vtables, since this will only work for
1317                *   uninitialized classes.
1318                * - an interface type is added to an ancestor after it was
1319                *   added to a child type.
1320                */
1321               if (!parent_entry)
1322                 g_assert (entry->vtable == NULL && entry->init_state == UNINITIALIZED);
1323               else
1324                 {
1325                   /* sick, interface is added to ancestor *after* child type;
1326                    * nothing todo, the entry and our children were already setup correctly
1327                    */
1328                 }
1329               return;
1330             }
1331         }
1332     }
1333
1334   entries = _g_atomic_array_copy (CLASSED_NODE_IFACES_ENTRIES (node),
1335                                   IFACE_ENTRIES_HEADER_SIZE,
1336                                   sizeof (IFaceEntry));
1337   num_entries = IFACE_ENTRIES_N_ENTRIES (entries);
1338   i = num_entries - 1;
1339   if (i == 0)
1340     entries->offset_index = 0;
1341   entries->entry[i].iface_type = iface_type;
1342   entries->entry[i].vtable = NULL;
1343   entries->entry[i].init_state = UNINITIALIZED;
1344
1345   if (parent_entry)
1346     {
1347       if (node->data && node->data->class.init_state >= BASE_IFACE_INIT)
1348         {
1349           entries->entry[i].init_state = INITIALIZED;
1350           entries->entry[i].vtable = parent_entry->vtable;
1351         }
1352     }
1353
1354   /* Update offsets in iface */
1355   iface_node = lookup_type_node_I (iface_type);
1356
1357   if (iface_node_has_available_offset_L (iface_node,
1358                                          entries->offset_index,
1359                                          i))
1360     {
1361       iface_node_set_offset_L (iface_node,
1362                                entries->offset_index, i);
1363     }
1364   else
1365    {
1366       entries->offset_index =
1367         find_free_iface_offset_L (entries);
1368       for (j = 0; j < IFACE_ENTRIES_N_ENTRIES (entries); j++)
1369         {
1370           entry = &entries->entry[j];
1371           iface_node =
1372             lookup_type_node_I (entry->iface_type);
1373           iface_node_set_offset_L (iface_node,
1374                                    entries->offset_index, j);
1375         }
1376     }
1377
1378   _g_atomic_array_update (CLASSED_NODE_IFACES_ENTRIES (node), entries);
1379
1380   if (parent_entry)
1381     {
1382       for (i = 0; i < node->n_children; i++)
1383         type_node_add_iface_entry_W (lookup_type_node_I (node->children[i]), iface_type, &entries->entry[i]);
1384     }
1385 }
1386
1387 static void
1388 type_add_interface_Wm (TypeNode             *node,
1389                        TypeNode             *iface,
1390                        const GInterfaceInfo *info,
1391                        GTypePlugin          *plugin)
1392 {
1393   IFaceHolder *iholder = g_new0 (IFaceHolder, 1);
1394   IFaceEntry *entry;
1395   guint i;
1396
1397   g_assert (node->is_instantiatable && NODE_IS_IFACE (iface) && ((info && !plugin) || (!info && plugin)));
1398   
1399   iholder->next = iface_node_get_holders_L (iface);
1400   iface_node_set_holders_W (iface, iholder);
1401   iholder->instance_type = NODE_TYPE (node);
1402   iholder->info = info ? g_memdup (info, sizeof (*info)) : NULL;
1403   iholder->plugin = plugin;
1404
1405   /* create an iface entry for this type */
1406   type_node_add_iface_entry_W (node, NODE_TYPE (iface), NULL);
1407   
1408   /* if the class is already (partly) initialized, we may need to base
1409    * initalize and/or initialize the new interface.
1410    */
1411   if (node->data)
1412     {
1413       InitState class_state = node->data->class.init_state;
1414       
1415       if (class_state >= BASE_IFACE_INIT)
1416         type_iface_vtable_base_init_Wm (iface, node);
1417       
1418       if (class_state >= IFACE_INIT)
1419         type_iface_vtable_iface_init_Wm (iface, node);
1420     }
1421   
1422   /* create iface entries for children of this type */
1423   entry = type_lookup_iface_entry_L (node, iface);
1424   for (i = 0; i < node->n_children; i++)
1425     type_node_add_iface_entry_W (lookup_type_node_I (node->children[i]), NODE_TYPE (iface), entry);
1426 }
1427
1428 static void
1429 type_iface_add_prerequisite_W (TypeNode *iface,
1430                                TypeNode *prerequisite_node)
1431 {
1432   GType prerequisite_type = NODE_TYPE (prerequisite_node);
1433   GType *prerequisites, *dependants;
1434   guint n_dependants, i;
1435   
1436   g_assert (NODE_IS_IFACE (iface) &&
1437             IFACE_NODE_N_PREREQUISITES (iface) < MAX_N_PREREQUISITES &&
1438             (prerequisite_node->is_instantiatable || NODE_IS_IFACE (prerequisite_node)));
1439   
1440   prerequisites = IFACE_NODE_PREREQUISITES (iface);
1441   for (i = 0; i < IFACE_NODE_N_PREREQUISITES (iface); i++)
1442     if (prerequisites[i] == prerequisite_type)
1443       return;                   /* we already have that prerequisiste */
1444     else if (prerequisites[i] > prerequisite_type)
1445       break;
1446   IFACE_NODE_N_PREREQUISITES (iface) += 1;
1447   IFACE_NODE_PREREQUISITES (iface) = g_renew (GType,
1448                                               IFACE_NODE_PREREQUISITES (iface),
1449                                               IFACE_NODE_N_PREREQUISITES (iface));
1450   prerequisites = IFACE_NODE_PREREQUISITES (iface);
1451   g_memmove (prerequisites + i + 1, prerequisites + i,
1452              sizeof (prerequisites[0]) * (IFACE_NODE_N_PREREQUISITES (iface) - i - 1));
1453   prerequisites[i] = prerequisite_type;
1454   
1455   /* we want to get notified when prerequisites get added to prerequisite_node */
1456   if (NODE_IS_IFACE (prerequisite_node))
1457     {
1458       dependants = iface_node_get_dependants_array_L (prerequisite_node);
1459       n_dependants = dependants ? dependants[0] : 0;
1460       n_dependants += 1;
1461       dependants = g_renew (GType, dependants, n_dependants + 1);
1462       dependants[n_dependants] = NODE_TYPE (iface);
1463       dependants[0] = n_dependants;
1464       iface_node_set_dependants_array_W (prerequisite_node, dependants);
1465     }
1466   
1467   /* we need to notify all dependants */
1468   dependants = iface_node_get_dependants_array_L (iface);
1469   n_dependants = dependants ? dependants[0] : 0;
1470   for (i = 1; i <= n_dependants; i++)
1471     type_iface_add_prerequisite_W (lookup_type_node_I (dependants[i]), prerequisite_node);
1472 }
1473
1474 /**
1475  * g_type_interface_add_prerequisite:
1476  * @interface_type: #GType value of an interface type.
1477  * @prerequisite_type: #GType value of an interface or instantiatable type.
1478  *
1479  * Adds @prerequisite_type to the list of prerequisites of @interface_type.
1480  * This means that any type implementing @interface_type must also implement
1481  * @prerequisite_type. Prerequisites can be thought of as an alternative to
1482  * interface derivation (which GType doesn't support). An interface can have
1483  * at most one instantiatable prerequisite type.
1484  */
1485 void
1486 g_type_interface_add_prerequisite (GType interface_type,
1487                                    GType prerequisite_type)
1488 {
1489   TypeNode *iface, *prerequisite_node;
1490   IFaceHolder *holders;
1491   
1492   g_return_if_fail (G_TYPE_IS_INTERFACE (interface_type));      /* G_TYPE_IS_INTERFACE() is an external call: _U */
1493   g_return_if_fail (!g_type_is_a (interface_type, prerequisite_type));
1494   g_return_if_fail (!g_type_is_a (prerequisite_type, interface_type));
1495   
1496   iface = lookup_type_node_I (interface_type);
1497   prerequisite_node = lookup_type_node_I (prerequisite_type);
1498   if (!iface || !prerequisite_node || !NODE_IS_IFACE (iface))
1499     {
1500       g_warning ("interface type `%s' or prerequisite type `%s' invalid",
1501                  type_descriptive_name_I (interface_type),
1502                  type_descriptive_name_I (prerequisite_type));
1503       return;
1504     }
1505   G_WRITE_LOCK (&type_rw_lock);
1506   holders = iface_node_get_holders_L (iface);
1507   if (holders)
1508     {
1509       G_WRITE_UNLOCK (&type_rw_lock);
1510       g_warning ("unable to add prerequisite `%s' to interface `%s' which is already in use for `%s'",
1511                  type_descriptive_name_I (prerequisite_type),
1512                  type_descriptive_name_I (interface_type),
1513                  type_descriptive_name_I (holders->instance_type));
1514       return;
1515     }
1516   if (prerequisite_node->is_instantiatable)
1517     {
1518       guint i;
1519       
1520       /* can have at most one publically installable instantiatable prerequisite */
1521       for (i = 0; i < IFACE_NODE_N_PREREQUISITES (iface); i++)
1522         {
1523           TypeNode *prnode = lookup_type_node_I (IFACE_NODE_PREREQUISITES (iface)[i]);
1524           
1525           if (prnode->is_instantiatable)
1526             {
1527               G_WRITE_UNLOCK (&type_rw_lock);
1528               g_warning ("adding prerequisite `%s' to interface `%s' conflicts with existing prerequisite `%s'",
1529                          type_descriptive_name_I (prerequisite_type),
1530                          type_descriptive_name_I (interface_type),
1531                          type_descriptive_name_I (NODE_TYPE (prnode)));
1532               return;
1533             }
1534         }
1535       
1536       for (i = 0; i < prerequisite_node->n_supers + 1; i++)
1537         type_iface_add_prerequisite_W (iface, lookup_type_node_I (prerequisite_node->supers[i]));
1538       G_WRITE_UNLOCK (&type_rw_lock);
1539     }
1540   else if (NODE_IS_IFACE (prerequisite_node))
1541     {
1542       GType *prerequisites;
1543       guint i;
1544       
1545       prerequisites = IFACE_NODE_PREREQUISITES (prerequisite_node);
1546       for (i = 0; i < IFACE_NODE_N_PREREQUISITES (prerequisite_node); i++)
1547         type_iface_add_prerequisite_W (iface, lookup_type_node_I (prerequisites[i]));
1548       type_iface_add_prerequisite_W (iface, prerequisite_node);
1549       G_WRITE_UNLOCK (&type_rw_lock);
1550     }
1551   else
1552     {
1553       G_WRITE_UNLOCK (&type_rw_lock);
1554       g_warning ("prerequisite `%s' for interface `%s' is neither instantiatable nor interface",
1555                  type_descriptive_name_I (prerequisite_type),
1556                  type_descriptive_name_I (interface_type));
1557     }
1558 }
1559
1560 /**
1561  * g_type_interface_prerequisites:
1562  * @interface_type: an interface type
1563  * @n_prerequisites: location to return the number of prerequisites, or %NULL
1564  *
1565  * Returns the prerequisites of an interfaces type.
1566  *
1567  * Since: 2.2
1568  *
1569  * Returns: a newly-allocated zero-terminated array of #GType containing
1570  *  the prerequisites of @interface_type
1571  */
1572 GType*
1573 g_type_interface_prerequisites (GType  interface_type,
1574                                 guint *n_prerequisites)
1575 {
1576   TypeNode *iface;
1577   
1578   g_return_val_if_fail (G_TYPE_IS_INTERFACE (interface_type), NULL);
1579
1580   iface = lookup_type_node_I (interface_type);
1581   if (iface)
1582     {
1583       GType *types;
1584       TypeNode *inode = NULL;
1585       guint i, n = 0;
1586       
1587       G_READ_LOCK (&type_rw_lock);
1588       types = g_new0 (GType, IFACE_NODE_N_PREREQUISITES (iface) + 1);
1589       for (i = 0; i < IFACE_NODE_N_PREREQUISITES (iface); i++)
1590         {
1591           GType prerequisite = IFACE_NODE_PREREQUISITES (iface)[i];
1592           TypeNode *node = lookup_type_node_I (prerequisite);
1593           if (node->is_instantiatable &&
1594               (!inode || type_node_is_a_L (node, inode)))
1595             inode = node;
1596           else
1597             types[n++] = NODE_TYPE (node);
1598         }
1599       if (inode)
1600         types[n++] = NODE_TYPE (inode);
1601       
1602       if (n_prerequisites)
1603         *n_prerequisites = n;
1604       G_READ_UNLOCK (&type_rw_lock);
1605       
1606       return types;
1607     }
1608   else
1609     {
1610       if (n_prerequisites)
1611         *n_prerequisites = 0;
1612       
1613       return NULL;
1614     }
1615 }
1616
1617
1618 static IFaceHolder*
1619 type_iface_peek_holder_L (TypeNode *iface,
1620                           GType     instance_type)
1621 {
1622   IFaceHolder *iholder;
1623   
1624   g_assert (NODE_IS_IFACE (iface));
1625   
1626   iholder = iface_node_get_holders_L (iface);
1627   while (iholder && iholder->instance_type != instance_type)
1628     iholder = iholder->next;
1629   return iholder;
1630 }
1631
1632 static IFaceHolder*
1633 type_iface_retrieve_holder_info_Wm (TypeNode *iface,
1634                                     GType     instance_type,
1635                                     gboolean  need_info)
1636 {
1637   IFaceHolder *iholder = type_iface_peek_holder_L (iface, instance_type);
1638   
1639   if (iholder && !iholder->info && need_info)
1640     {
1641       GInterfaceInfo tmp_info;
1642       
1643       g_assert (iholder->plugin != NULL);
1644       
1645       type_data_ref_Wm (iface);
1646       if (iholder->info)
1647         INVALID_RECURSION ("g_type_plugin_*", iface->plugin, NODE_NAME (iface));
1648       
1649       memset (&tmp_info, 0, sizeof (tmp_info));
1650       
1651       G_WRITE_UNLOCK (&type_rw_lock);
1652       g_type_plugin_use (iholder->plugin);
1653       g_type_plugin_complete_interface_info (iholder->plugin, instance_type, NODE_TYPE (iface), &tmp_info);
1654       G_WRITE_LOCK (&type_rw_lock);
1655       if (iholder->info)
1656         INVALID_RECURSION ("g_type_plugin_*", iholder->plugin, NODE_NAME (iface));
1657       
1658       check_interface_info_I (iface, instance_type, &tmp_info);
1659       iholder->info = g_memdup (&tmp_info, sizeof (tmp_info));
1660     }
1661   
1662   return iholder;       /* we don't modify write lock upon returning NULL */
1663 }
1664
1665 static void
1666 type_iface_blow_holder_info_Wm (TypeNode *iface,
1667                                 GType     instance_type)
1668 {
1669   IFaceHolder *iholder = iface_node_get_holders_L (iface);
1670   
1671   g_assert (NODE_IS_IFACE (iface));
1672   
1673   while (iholder->instance_type != instance_type)
1674     iholder = iholder->next;
1675   
1676   if (iholder->info && iholder->plugin)
1677     {
1678       g_free (iholder->info);
1679       iholder->info = NULL;
1680       
1681       G_WRITE_UNLOCK (&type_rw_lock);
1682       g_type_plugin_unuse (iholder->plugin);
1683       type_data_unref_U (iface, FALSE);
1684       G_WRITE_LOCK (&type_rw_lock);
1685     }
1686 }
1687
1688 /* Assumes type's class already exists
1689  */
1690 static inline size_t
1691 type_total_instance_size_I (TypeNode *node)
1692 {
1693   gsize total_instance_size;
1694
1695   total_instance_size = node->data->instance.instance_size;
1696   if (node->data->instance.private_size != 0)
1697     total_instance_size = ALIGN_STRUCT (total_instance_size) + node->data->instance.private_size;
1698
1699   return total_instance_size;
1700 }
1701
1702 /* --- type structure creation/destruction --- */
1703 typedef struct {
1704   gpointer instance;
1705   gpointer class;
1706 } InstanceRealClass;
1707
1708 static gint
1709 instance_real_class_cmp (gconstpointer p1,
1710                          gconstpointer p2)
1711 {
1712   const InstanceRealClass *irc1 = p1;
1713   const InstanceRealClass *irc2 = p2;
1714   guint8 *i1 = irc1->instance;
1715   guint8 *i2 = irc2->instance;
1716   return G_BSEARCH_ARRAY_CMP (i1, i2);
1717 }
1718
1719 G_LOCK_DEFINE_STATIC (instance_real_class);
1720 static GBSearchArray *instance_real_class_bsa = NULL;
1721 static GBSearchConfig instance_real_class_bconfig = {
1722   sizeof (InstanceRealClass),
1723   instance_real_class_cmp,
1724   0,
1725 };
1726
1727 static inline void
1728 instance_real_class_set (gpointer    instance,
1729                          GTypeClass *class)
1730 {
1731   InstanceRealClass key;
1732   key.instance = instance;
1733   key.class = class;
1734   G_LOCK (instance_real_class);
1735   if (!instance_real_class_bsa)
1736     instance_real_class_bsa = g_bsearch_array_create (&instance_real_class_bconfig);
1737   instance_real_class_bsa = g_bsearch_array_replace (instance_real_class_bsa, &instance_real_class_bconfig, &key);
1738   G_UNLOCK (instance_real_class);
1739 }
1740
1741 static inline void
1742 instance_real_class_remove (gpointer instance)
1743 {
1744   InstanceRealClass key, *node;
1745   guint index;
1746   key.instance = instance;
1747   G_LOCK (instance_real_class);
1748   node = g_bsearch_array_lookup (instance_real_class_bsa, &instance_real_class_bconfig, &key);
1749   index = g_bsearch_array_get_index (instance_real_class_bsa, &instance_real_class_bconfig, node);
1750   instance_real_class_bsa = g_bsearch_array_remove (instance_real_class_bsa, &instance_real_class_bconfig, index);
1751   if (!g_bsearch_array_get_n_nodes (instance_real_class_bsa))
1752     {
1753       g_bsearch_array_free (instance_real_class_bsa, &instance_real_class_bconfig);
1754       instance_real_class_bsa = NULL;
1755     }
1756   G_UNLOCK (instance_real_class);
1757 }
1758
1759 static inline GTypeClass*
1760 instance_real_class_get (gpointer instance)
1761 {
1762   InstanceRealClass key, *node;
1763   GTypeClass *class;
1764   key.instance = instance;
1765   G_LOCK (instance_real_class);
1766   node = instance_real_class_bsa ? g_bsearch_array_lookup (instance_real_class_bsa, &instance_real_class_bconfig, &key) : NULL;
1767   class = node ? node->class : NULL;
1768   G_UNLOCK (instance_real_class);
1769   return class;
1770 }
1771
1772 /**
1773  * g_type_create_instance:
1774  * @type: An instantiatable type to create an instance for.
1775  *
1776  * Creates and initializes an instance of @type if @type is valid and
1777  * can be instantiated. The type system only performs basic allocation
1778  * and structure setups for instances: actual instance creation should
1779  * happen through functions supplied by the type's fundamental type
1780  * implementation.  So use of g_type_create_instance() is reserved for
1781  * implementators of fundamental types only. E.g. instances of the
1782  * #GObject hierarchy should be created via g_object_new() and
1783  * <emphasis>never</emphasis> directly through
1784  * g_type_create_instance() which doesn't handle things like singleton
1785  * objects or object construction.  Note: Do <emphasis>not</emphasis>
1786  * use this function, unless you're implementing a fundamental
1787  * type. Also language bindings should <emphasis>not</emphasis> use
1788  * this function but g_object_new() instead.
1789  *
1790  * Returns: An allocated and initialized instance, subject to further
1791  *  treatment by the fundamental type implementation.
1792  */
1793 GTypeInstance*
1794 g_type_create_instance (GType type)
1795 {
1796   TypeNode *node;
1797   GTypeInstance *instance;
1798   GTypeClass *class;
1799   guint i, total_size;
1800   
1801   node = lookup_type_node_I (type);
1802   if (!node || !node->is_instantiatable)
1803     {
1804       g_warning ("cannot create new instance of invalid (non-instantiatable) type `%s'",
1805                  type_descriptive_name_I (type));
1806       return NULL;
1807     }
1808   /* G_TYPE_IS_ABSTRACT() is an external call: _U */
1809   if (!node->mutatable_check_cache && G_TYPE_IS_ABSTRACT (type))
1810     {
1811       g_warning ("cannot create instance of abstract (non-instantiatable) type `%s'",
1812                  type_descriptive_name_I (type));
1813       return NULL;
1814     }
1815   
1816   class = g_type_class_ref (type);
1817   total_size = type_total_instance_size_I (node);
1818
1819   instance = g_slice_alloc0 (total_size);
1820
1821   if (node->data->instance.private_size)
1822     instance_real_class_set (instance, class);
1823   for (i = node->n_supers; i > 0; i--)
1824     {
1825       TypeNode *pnode;
1826       
1827       pnode = lookup_type_node_I (node->supers[i]);
1828       if (pnode->data->instance.instance_init)
1829         {
1830           instance->g_class = pnode->data->instance.class;
1831           pnode->data->instance.instance_init (instance, class);
1832         }
1833     }
1834   if (node->data->instance.private_size)
1835     instance_real_class_remove (instance);
1836
1837   instance->g_class = class;
1838   if (node->data->instance.instance_init)
1839     node->data->instance.instance_init (instance, class);
1840   
1841   return instance;
1842 }
1843
1844 /**
1845  * g_type_free_instance:
1846  * @instance: an instance of a type.
1847  *
1848  * Frees an instance of a type, returning it to the instance pool for
1849  * the type, if there is one.
1850  *
1851  * Like g_type_create_instance(), this function is reserved for
1852  * implementors of fundamental types.
1853  */
1854 void
1855 g_type_free_instance (GTypeInstance *instance)
1856 {
1857   TypeNode *node;
1858   GTypeClass *class;
1859   
1860   g_return_if_fail (instance != NULL && instance->g_class != NULL);
1861   
1862   class = instance->g_class;
1863   node = lookup_type_node_I (class->g_type);
1864   if (!node || !node->is_instantiatable || !node->data || node->data->class.class != (gpointer) class)
1865     {
1866       g_warning ("cannot free instance of invalid (non-instantiatable) type `%s'",
1867                  type_descriptive_name_I (class->g_type));
1868       return;
1869     }
1870   /* G_TYPE_IS_ABSTRACT() is an external call: _U */
1871   if (!node->mutatable_check_cache && G_TYPE_IS_ABSTRACT (NODE_TYPE (node)))
1872     {
1873       g_warning ("cannot free instance of abstract (non-instantiatable) type `%s'",
1874                  NODE_NAME (node));
1875       return;
1876     }
1877   
1878   instance->g_class = NULL;
1879 #ifdef G_ENABLE_DEBUG  
1880   memset (instance, 0xaa, type_total_instance_size_I (node));
1881 #endif
1882   g_slice_free1 (type_total_instance_size_I (node), instance);
1883
1884   g_type_class_unref (class);
1885 }
1886
1887 static void
1888 type_iface_ensure_dflt_vtable_Wm (TypeNode *iface)
1889 {
1890   g_assert (iface->data);
1891
1892   if (!iface->data->iface.dflt_vtable)
1893     {
1894       GTypeInterface *vtable = g_malloc0 (iface->data->iface.vtable_size);
1895       iface->data->iface.dflt_vtable = vtable;
1896       vtable->g_type = NODE_TYPE (iface);
1897       vtable->g_instance_type = 0;
1898       if (iface->data->iface.vtable_init_base ||
1899           iface->data->iface.dflt_init)
1900         {
1901           G_WRITE_UNLOCK (&type_rw_lock);
1902           if (iface->data->iface.vtable_init_base)
1903             iface->data->iface.vtable_init_base (vtable);
1904           if (iface->data->iface.dflt_init)
1905             iface->data->iface.dflt_init (vtable, (gpointer) iface->data->iface.dflt_data);
1906           G_WRITE_LOCK (&type_rw_lock);
1907         }
1908     }
1909 }
1910
1911
1912 /* This is called to allocate and do the first part of initializing
1913  * the interface vtable; type_iface_vtable_iface_init_Wm() does the remainder.
1914  *
1915  * A FALSE return indicates that we didn't find an init function for
1916  * this type/iface pair, so the vtable from the parent type should
1917  * be used. Note that the write lock is not modified upon a FALSE
1918  * return.
1919  */
1920 static gboolean
1921 type_iface_vtable_base_init_Wm (TypeNode *iface,
1922                                 TypeNode *node)
1923 {
1924   IFaceEntry *entry;
1925   IFaceHolder *iholder;
1926   GTypeInterface *vtable = NULL;
1927   TypeNode *pnode;
1928   
1929   /* type_iface_retrieve_holder_info_Wm() doesn't modify write lock for returning NULL */
1930   iholder = type_iface_retrieve_holder_info_Wm (iface, NODE_TYPE (node), TRUE);
1931   if (!iholder)
1932     return FALSE;       /* we don't modify write lock upon FALSE */
1933
1934   type_iface_ensure_dflt_vtable_Wm (iface);
1935
1936   entry = type_lookup_iface_entry_L (node, iface);
1937
1938   g_assert (iface->data && entry && entry->vtable == NULL && iholder && iholder->info);
1939   
1940   entry->init_state = IFACE_INIT;
1941
1942   pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
1943   if (pnode)    /* want to copy over parent iface contents */
1944     {
1945       IFaceEntry *pentry = type_lookup_iface_entry_L (pnode, iface);
1946       
1947       if (pentry)
1948         vtable = g_memdup (pentry->vtable, iface->data->iface.vtable_size);
1949     }
1950   if (!vtable)
1951     vtable = g_memdup (iface->data->iface.dflt_vtable, iface->data->iface.vtable_size);
1952   entry->vtable = vtable;
1953   vtable->g_type = NODE_TYPE (iface);
1954   vtable->g_instance_type = NODE_TYPE (node);
1955   
1956   if (iface->data->iface.vtable_init_base)
1957     {
1958       G_WRITE_UNLOCK (&type_rw_lock);
1959       iface->data->iface.vtable_init_base (vtable);
1960       G_WRITE_LOCK (&type_rw_lock);
1961     }
1962   return TRUE;  /* initialized the vtable */
1963 }
1964
1965 /* Finishes what type_iface_vtable_base_init_Wm started by
1966  * calling the interface init function.
1967  * this function may only be called for types with their
1968  * own interface holder info, i.e. types for which
1969  * g_type_add_interface*() was called and not children thereof.
1970  */
1971 static void
1972 type_iface_vtable_iface_init_Wm (TypeNode *iface,
1973                                  TypeNode *node)
1974 {
1975   IFaceEntry *entry = type_lookup_iface_entry_L (node, iface);
1976   IFaceHolder *iholder = type_iface_peek_holder_L (iface, NODE_TYPE (node));
1977   GTypeInterface *vtable = NULL;
1978   guint i;
1979   
1980   /* iholder->info should have been filled in by type_iface_vtable_base_init_Wm() */
1981   g_assert (iface->data && entry && iholder && iholder->info);
1982   g_assert (entry->init_state == IFACE_INIT); /* assert prior base_init() */
1983   
1984   entry->init_state = INITIALIZED;
1985       
1986   vtable = entry->vtable;
1987
1988   if (iholder->info->interface_init)
1989     {
1990       G_WRITE_UNLOCK (&type_rw_lock);
1991       if (iholder->info->interface_init)
1992         iholder->info->interface_init (vtable, iholder->info->interface_data);
1993       G_WRITE_LOCK (&type_rw_lock);
1994     }
1995   
1996   for (i = 0; i < static_n_iface_check_funcs; i++)
1997     {
1998       GTypeInterfaceCheckFunc check_func = static_iface_check_funcs[i].check_func;
1999       gpointer check_data = static_iface_check_funcs[i].check_data;
2000
2001       G_WRITE_UNLOCK (&type_rw_lock);
2002       check_func (check_data, (gpointer)vtable);
2003       G_WRITE_LOCK (&type_rw_lock);      
2004     }
2005 }
2006
2007 static gboolean
2008 type_iface_vtable_finalize_Wm (TypeNode       *iface,
2009                                TypeNode       *node,
2010                                GTypeInterface *vtable)
2011 {
2012   IFaceEntry *entry = type_lookup_iface_entry_L (node, iface);
2013   IFaceHolder *iholder;
2014   
2015   /* type_iface_retrieve_holder_info_Wm() doesn't modify write lock for returning NULL */
2016   iholder = type_iface_retrieve_holder_info_Wm (iface, NODE_TYPE (node), FALSE);
2017   if (!iholder)
2018     return FALSE;       /* we don't modify write lock upon FALSE */
2019   
2020   g_assert (entry && entry->vtable == vtable && iholder->info);
2021   
2022   entry->vtable = NULL;
2023   entry->init_state = UNINITIALIZED;
2024   if (iholder->info->interface_finalize || iface->data->iface.vtable_finalize_base)
2025     {
2026       G_WRITE_UNLOCK (&type_rw_lock);
2027       if (iholder->info->interface_finalize)
2028         iholder->info->interface_finalize (vtable, iholder->info->interface_data);
2029       if (iface->data->iface.vtable_finalize_base)
2030         iface->data->iface.vtable_finalize_base (vtable);
2031       G_WRITE_LOCK (&type_rw_lock);
2032     }
2033   vtable->g_type = 0;
2034   vtable->g_instance_type = 0;
2035   g_free (vtable);
2036   
2037   type_iface_blow_holder_info_Wm (iface, NODE_TYPE (node));
2038   
2039   return TRUE;  /* write lock modified */
2040 }
2041
2042 static void
2043 type_class_init_Wm (TypeNode   *node,
2044                     GTypeClass *pclass)
2045 {
2046   GSList *slist, *init_slist = NULL;
2047   GTypeClass *class;
2048   IFaceEntries *entries;
2049   IFaceEntry *entry;
2050   TypeNode *bnode, *pnode;
2051   guint i;
2052   
2053   g_assert (node->is_classed && node->data &&
2054             node->data->class.class_size &&
2055             !node->data->class.class &&
2056             node->data->class.init_state == UNINITIALIZED);
2057
2058   class = g_malloc0 (node->data->class.class_size);
2059   node->data->class.class = class;
2060   node->data->class.init_state = BASE_CLASS_INIT;
2061   
2062   if (pclass)
2063     {
2064       TypeNode *pnode = lookup_type_node_I (pclass->g_type);
2065       
2066       memcpy (class, pclass, pnode->data->class.class_size);
2067
2068       if (node->is_instantiatable)
2069         {
2070           /* We need to initialize the private_size here rather than in
2071            * type_data_make_W() since the class init for the parent
2072            * class may have changed pnode->data->instance.private_size.
2073            */
2074           node->data->instance.private_size = pnode->data->instance.private_size;
2075         }
2076     }
2077   class->g_type = NODE_TYPE (node);
2078   
2079   G_WRITE_UNLOCK (&type_rw_lock);
2080   
2081   /* stack all base class initialization functions, so we
2082    * call them in ascending order.
2083    */
2084   for (bnode = node; bnode; bnode = lookup_type_node_I (NODE_PARENT_TYPE (bnode)))
2085     if (bnode->data->class.class_init_base)
2086       init_slist = g_slist_prepend (init_slist, (gpointer) bnode->data->class.class_init_base);
2087   for (slist = init_slist; slist; slist = slist->next)
2088     {
2089       GBaseInitFunc class_init_base = (GBaseInitFunc) slist->data;
2090       
2091       class_init_base (class);
2092     }
2093   g_slist_free (init_slist);
2094   
2095   G_WRITE_LOCK (&type_rw_lock);
2096
2097   node->data->class.init_state = BASE_IFACE_INIT;
2098   
2099   /* Before we initialize the class, base initialize all interfaces, either
2100    * from parent, or through our holder info
2101    */
2102   pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
2103
2104   i = 0;
2105   while ((entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node)) != NULL &&
2106           i < IFACE_ENTRIES_N_ENTRIES (entries))
2107     {
2108       entry = &entries->entry[i];
2109       while (i < IFACE_ENTRIES_N_ENTRIES (entries) &&
2110              entry->init_state == IFACE_INIT)
2111         {
2112           entry++;
2113           i++;
2114         }
2115
2116       if (i == IFACE_ENTRIES_N_ENTRIES (entries))
2117         break;
2118
2119       if (!type_iface_vtable_base_init_Wm (lookup_type_node_I (entry->iface_type), node))
2120         {
2121           guint j;
2122           IFaceEntries *pentries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (pnode);
2123           
2124           /* need to get this interface from parent, type_iface_vtable_base_init_Wm()
2125            * doesn't modify write lock upon FALSE, so entry is still valid; 
2126            */
2127           g_assert (pnode != NULL);
2128
2129           if (pentries)
2130             for (j = 0; j < IFACE_ENTRIES_N_ENTRIES (pentries); j++)
2131               {
2132                 IFaceEntry *pentry = &pentries->entry[j];
2133
2134                 if (pentry->iface_type == entry->iface_type)
2135                   {
2136                     entry->vtable = pentry->vtable;
2137                     entry->init_state = INITIALIZED;
2138                     break;
2139                   }
2140               }
2141           g_assert (entry->vtable != NULL);
2142         }
2143
2144       /* If the write lock was released, additional interface entries might
2145        * have been inserted into CLASSED_NODE_IFACES_ENTRIES (node); they'll
2146        * be base-initialized when inserted, so we don't have to worry that
2147        * we might miss them. Uninitialized entries can only be moved higher
2148        * when new ones are inserted.
2149        */
2150       i++;
2151     }
2152   
2153   node->data->class.init_state = CLASS_INIT;
2154   
2155   G_WRITE_UNLOCK (&type_rw_lock);
2156
2157   if (node->data->class.class_init)
2158     node->data->class.class_init (class, (gpointer) node->data->class.class_data);
2159   
2160   G_WRITE_LOCK (&type_rw_lock);
2161   
2162   node->data->class.init_state = IFACE_INIT;
2163   
2164   /* finish initializing the interfaces through our holder info.
2165    * inherited interfaces are already init_state == INITIALIZED, because
2166    * they either got setup in the above base_init loop, or during
2167    * class_init from within type_add_interface_Wm() for this or
2168    * an anchestor type.
2169    */
2170   i = 0;
2171   while ((entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node)) != NULL)
2172     {
2173       entry = &entries->entry[i];
2174       while (i < IFACE_ENTRIES_N_ENTRIES (entries) &&
2175              entry->init_state == INITIALIZED)
2176         {
2177           entry++;
2178           i++;
2179         }
2180
2181       if (i == IFACE_ENTRIES_N_ENTRIES (entries))
2182         break;
2183
2184       type_iface_vtable_iface_init_Wm (lookup_type_node_I (entry->iface_type), node);
2185       
2186       /* As in the loop above, additional initialized entries might be inserted
2187        * if the write lock is released, but that's harmless because the entries
2188        * we need to initialize only move higher in the list.
2189        */
2190       i++;
2191     }
2192   
2193   node->data->class.init_state = INITIALIZED;
2194 }
2195
2196 static void
2197 type_data_finalize_class_ifaces_Wm (TypeNode *node)
2198 {
2199   guint i;
2200   IFaceEntries *entries;
2201
2202   g_assert (node->is_instantiatable && node->data && node->data->class.class && NODE_REFCOUNT (node) == 0);
2203
2204  reiterate:
2205   entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node);
2206   for (i = 0; entries != NULL && i < IFACE_ENTRIES_N_ENTRIES (entries); i++)
2207     {
2208       IFaceEntry *entry = &entries->entry[i];
2209       if (entry->vtable)
2210         {
2211           if (type_iface_vtable_finalize_Wm (lookup_type_node_I (entry->iface_type), node, entry->vtable))
2212             {
2213               /* refetch entries, IFACES_ENTRIES might be modified */
2214               goto reiterate;
2215             }
2216           else
2217             {
2218               /* type_iface_vtable_finalize_Wm() doesn't modify write lock upon FALSE,
2219                * iface vtable came from parent
2220                */
2221               entry->vtable = NULL;
2222               entry->init_state = UNINITIALIZED;
2223             }
2224         }
2225     }
2226 }
2227
2228 static void
2229 type_data_finalize_class_U (TypeNode  *node,
2230                             ClassData *cdata)
2231 {
2232   GTypeClass *class = cdata->class;
2233   TypeNode *bnode;
2234   
2235   g_assert (cdata->class && NODE_REFCOUNT (node) == 0);
2236   
2237   if (cdata->class_finalize)
2238     cdata->class_finalize (class, (gpointer) cdata->class_data);
2239   
2240   /* call all base class destruction functions in descending order
2241    */
2242   if (cdata->class_finalize_base)
2243     cdata->class_finalize_base (class);
2244   for (bnode = lookup_type_node_I (NODE_PARENT_TYPE (node)); bnode; bnode = lookup_type_node_I (NODE_PARENT_TYPE (bnode)))
2245     if (bnode->data->class.class_finalize_base)
2246       bnode->data->class.class_finalize_base (class);
2247   
2248   g_free (cdata->class);
2249 }
2250
2251 static void
2252 type_data_last_unref_Wm (TypeNode *node,
2253                          gboolean  uncached)
2254 {
2255   g_return_if_fail (node != NULL && node->plugin != NULL);
2256   
2257   if (!node->data || NODE_REFCOUNT (node) == 0)
2258     {
2259       g_warning ("cannot drop last reference to unreferenced type `%s'",
2260                  NODE_NAME (node));
2261       return;
2262     }
2263
2264   /* call class cache hooks */
2265   if (node->is_classed && node->data && node->data->class.class && static_n_class_cache_funcs && !uncached)
2266     {
2267       guint i;
2268       
2269       G_WRITE_UNLOCK (&type_rw_lock);
2270       G_READ_LOCK (&type_rw_lock);
2271       for (i = 0; i < static_n_class_cache_funcs; i++)
2272         {
2273           GTypeClassCacheFunc cache_func = static_class_cache_funcs[i].cache_func;
2274           gpointer cache_data = static_class_cache_funcs[i].cache_data;
2275           gboolean need_break;
2276           
2277           G_READ_UNLOCK (&type_rw_lock);
2278           need_break = cache_func (cache_data, node->data->class.class);
2279           G_READ_LOCK (&type_rw_lock);
2280           if (!node->data || NODE_REFCOUNT (node) == 0)
2281             INVALID_RECURSION ("GType class cache function ", cache_func, NODE_NAME (node));
2282           if (need_break)
2283             break;
2284         }
2285       G_READ_UNLOCK (&type_rw_lock);
2286       G_WRITE_LOCK (&type_rw_lock);
2287     }
2288   
2289   /* may have been re-referenced meanwhile */
2290   if (g_atomic_int_dec_and_test ((int *) &node->ref_count))
2291     {
2292       GType ptype = NODE_PARENT_TYPE (node);
2293       TypeData *tdata;
2294       
2295       if (node->is_instantiatable)
2296         {
2297           /* destroy node->data->instance.mem_chunk */
2298         }
2299       
2300       tdata = node->data;
2301       if (node->is_classed && tdata->class.class)
2302         {
2303           if (CLASSED_NODE_IFACES_ENTRIES_LOCKED (node) != NULL)
2304             type_data_finalize_class_ifaces_Wm (node);
2305           node->mutatable_check_cache = FALSE;
2306           node->data = NULL;
2307           G_WRITE_UNLOCK (&type_rw_lock);
2308           type_data_finalize_class_U (node, &tdata->class);
2309           G_WRITE_LOCK (&type_rw_lock);
2310         }
2311       else if (NODE_IS_IFACE (node) && tdata->iface.dflt_vtable)
2312         {
2313           node->mutatable_check_cache = FALSE;
2314           node->data = NULL;
2315           if (tdata->iface.dflt_finalize || tdata->iface.vtable_finalize_base)
2316             {
2317               G_WRITE_UNLOCK (&type_rw_lock);
2318               if (tdata->iface.dflt_finalize)
2319                 tdata->iface.dflt_finalize (tdata->iface.dflt_vtable, (gpointer) tdata->iface.dflt_data);
2320               if (tdata->iface.vtable_finalize_base)
2321                 tdata->iface.vtable_finalize_base (tdata->iface.dflt_vtable);
2322               G_WRITE_LOCK (&type_rw_lock);
2323             }
2324           g_free (tdata->iface.dflt_vtable);
2325         }
2326       else
2327         {
2328           node->mutatable_check_cache = FALSE;
2329           node->data = NULL;
2330         }
2331
2332       /* freeing tdata->common.value_table and its contents is taken care of
2333        * by allocating it in one chunk with tdata
2334        */
2335       g_free (tdata);
2336       
2337       G_WRITE_UNLOCK (&type_rw_lock);
2338       g_type_plugin_unuse (node->plugin);
2339       if (ptype)
2340         type_data_unref_U (lookup_type_node_I (ptype), FALSE);
2341       G_WRITE_LOCK (&type_rw_lock);
2342     }
2343 }
2344
2345 static inline void
2346 type_data_unref_U (TypeNode *node,
2347                    gboolean  uncached)
2348 {
2349   G_WRITE_LOCK (&type_rw_lock);
2350   g_assert (node->data && NODE_REFCOUNT (node) > 0);
2351   if (NODE_REFCOUNT (node) > 1)
2352     g_atomic_int_add ((int *) &node->ref_count, -1);
2353   else
2354     {
2355       if (!node->plugin)
2356         {
2357           g_warning ("static type `%s' unreferenced too often",
2358                      NODE_NAME (node));
2359           return;
2360         }
2361       G_WRITE_UNLOCK (&type_rw_lock);
2362       g_static_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
2363       G_WRITE_LOCK (&type_rw_lock);
2364       type_data_last_unref_Wm (node, uncached);
2365       g_static_rec_mutex_unlock (&class_init_rec_mutex);
2366     }
2367   G_WRITE_UNLOCK (&type_rw_lock);
2368 }
2369
2370 /**
2371  * g_type_add_class_cache_func:
2372  * @cache_data: data to be passed to @cache_func
2373  * @cache_func: a #GTypeClassCacheFunc
2374  *
2375  * Adds a #GTypeClassCacheFunc to be called before the reference count of a
2376  * class goes from one to zero. This can be used to prevent premature class
2377  * destruction. All installed #GTypeClassCacheFunc functions will be chained
2378  * until one of them returns %TRUE. The functions have to check the class id
2379  * passed in to figure whether they actually want to cache the class of this
2380  * type, since all classes are routed through the same #GTypeClassCacheFunc
2381  * chain.
2382  */
2383 void
2384 g_type_add_class_cache_func (gpointer            cache_data,
2385                              GTypeClassCacheFunc cache_func)
2386 {
2387   guint i;
2388   
2389   g_return_if_fail (cache_func != NULL);
2390   
2391   G_WRITE_LOCK (&type_rw_lock);
2392   i = static_n_class_cache_funcs++;
2393   static_class_cache_funcs = g_renew (ClassCacheFunc, static_class_cache_funcs, static_n_class_cache_funcs);
2394   static_class_cache_funcs[i].cache_data = cache_data;
2395   static_class_cache_funcs[i].cache_func = cache_func;
2396   G_WRITE_UNLOCK (&type_rw_lock);
2397 }
2398
2399 /**
2400  * g_type_remove_class_cache_func:
2401  * @cache_data: data that was given when adding @cache_func
2402  * @cache_func: a #GTypeClassCacheFunc
2403  *
2404  * Removes a previously installed #GTypeClassCacheFunc. The cache
2405  * maintained by @cache_func has to be empty when calling
2406  * g_type_remove_class_cache_func() to avoid leaks.
2407  */
2408 void
2409 g_type_remove_class_cache_func (gpointer            cache_data,
2410                                 GTypeClassCacheFunc cache_func)
2411 {
2412   gboolean found_it = FALSE;
2413   guint i;
2414   
2415   g_return_if_fail (cache_func != NULL);
2416   
2417   G_WRITE_LOCK (&type_rw_lock);
2418   for (i = 0; i < static_n_class_cache_funcs; i++)
2419     if (static_class_cache_funcs[i].cache_data == cache_data &&
2420         static_class_cache_funcs[i].cache_func == cache_func)
2421       {
2422         static_n_class_cache_funcs--;
2423         g_memmove (static_class_cache_funcs + i,
2424                    static_class_cache_funcs + i + 1,
2425                    sizeof (static_class_cache_funcs[0]) * (static_n_class_cache_funcs - i));
2426         static_class_cache_funcs = g_renew (ClassCacheFunc, static_class_cache_funcs, static_n_class_cache_funcs);
2427         found_it = TRUE;
2428         break;
2429       }
2430   G_WRITE_UNLOCK (&type_rw_lock);
2431   
2432   if (!found_it)
2433     g_warning (G_STRLOC ": cannot remove unregistered class cache func %p with data %p",
2434                cache_func, cache_data);
2435 }
2436
2437
2438 /**
2439  * g_type_add_interface_check:
2440  * @check_data: data to pass to @check_func
2441  * @check_func: function to be called after each interface
2442  *              is initialized.
2443  *
2444  * Adds a function to be called after an interface vtable is
2445  * initialized for any class (i.e. after the @interface_init member of
2446  * #GInterfaceInfo has been called).
2447  *
2448  * This function is useful when you want to check an invariant that
2449  * depends on the interfaces of a class. For instance, the
2450  * implementation of #GObject uses this facility to check that an
2451  * object implements all of the properties that are defined on its
2452  * interfaces.
2453  *
2454  * Since: 2.4
2455  */
2456 void
2457 g_type_add_interface_check (gpointer                check_data,
2458                             GTypeInterfaceCheckFunc check_func)
2459 {
2460   guint i;
2461   
2462   g_return_if_fail (check_func != NULL);
2463   
2464   G_WRITE_LOCK (&type_rw_lock);
2465   i = static_n_iface_check_funcs++;
2466   static_iface_check_funcs = g_renew (IFaceCheckFunc, static_iface_check_funcs, static_n_iface_check_funcs);
2467   static_iface_check_funcs[i].check_data = check_data;
2468   static_iface_check_funcs[i].check_func = check_func;
2469   G_WRITE_UNLOCK (&type_rw_lock);
2470 }
2471
2472 /**
2473  * g_type_remove_interface_check:
2474  * @check_data: callback data passed to g_type_add_interface_check()
2475  * @check_func: callback function passed to g_type_add_interface_check()
2476  *
2477  * Removes an interface check function added with
2478  * g_type_add_interface_check().
2479  *
2480  * Since: 2.4
2481  */
2482 void
2483 g_type_remove_interface_check (gpointer                check_data,
2484                                GTypeInterfaceCheckFunc check_func)
2485 {
2486   gboolean found_it = FALSE;
2487   guint i;
2488   
2489   g_return_if_fail (check_func != NULL);
2490   
2491   G_WRITE_LOCK (&type_rw_lock);
2492   for (i = 0; i < static_n_iface_check_funcs; i++)
2493     if (static_iface_check_funcs[i].check_data == check_data &&
2494         static_iface_check_funcs[i].check_func == check_func)
2495       {
2496         static_n_iface_check_funcs--;
2497         g_memmove (static_iface_check_funcs + i,
2498                    static_iface_check_funcs + i + 1,
2499                    sizeof (static_iface_check_funcs[0]) * (static_n_iface_check_funcs - i));
2500         static_iface_check_funcs = g_renew (IFaceCheckFunc, static_iface_check_funcs, static_n_iface_check_funcs);
2501         found_it = TRUE;
2502         break;
2503       }
2504   G_WRITE_UNLOCK (&type_rw_lock);
2505   
2506   if (!found_it)
2507     g_warning (G_STRLOC ": cannot remove unregistered class check func %p with data %p",
2508                check_func, check_data);
2509 }
2510
2511 /* --- type registration --- */
2512 /**
2513  * g_type_register_fundamental:
2514  * @type_id: A predefined type identifier.
2515  * @type_name: 0-terminated string used as the name of the new type.
2516  * @info: The #GTypeInfo structure for this type.
2517  * @finfo: The #GTypeFundamentalInfo structure for this type.
2518  * @flags: Bitwise combination of #GTypeFlags values.
2519  *
2520  * Registers @type_id as the predefined identifier and @type_name as the
2521  * name of a fundamental type.  The type system uses the information
2522  * contained in the #GTypeInfo structure pointed to by @info and the
2523  * #GTypeFundamentalInfo structure pointed to by @finfo to manage the
2524  * type and its instances.  The value of @flags determines additional
2525  * characteristics of the fundamental type.
2526  *
2527  * Returns: The predefined type identifier.
2528  */
2529 GType
2530 g_type_register_fundamental (GType                       type_id,
2531                              const gchar                *type_name,
2532                              const GTypeInfo            *info,
2533                              const GTypeFundamentalInfo *finfo,
2534                              GTypeFlags                  flags)
2535 {
2536   TypeNode *node;
2537   
2538   g_return_val_if_uninitialized (static_quark_type_flags, g_type_init, 0);
2539   g_return_val_if_fail (type_id > 0, 0);
2540   g_return_val_if_fail (type_name != NULL, 0);
2541   g_return_val_if_fail (info != NULL, 0);
2542   g_return_val_if_fail (finfo != NULL, 0);
2543   
2544   if (!check_type_name_I (type_name))
2545     return 0;
2546   if ((type_id & TYPE_ID_MASK) ||
2547       type_id > G_TYPE_FUNDAMENTAL_MAX)
2548     {
2549       g_warning ("attempt to register fundamental type `%s' with invalid type id (%" G_GSIZE_FORMAT ")",
2550                  type_name,
2551                  type_id);
2552       return 0;
2553     }
2554   if ((finfo->type_flags & G_TYPE_FLAG_INSTANTIATABLE) &&
2555       !(finfo->type_flags & G_TYPE_FLAG_CLASSED))
2556     {
2557       g_warning ("cannot register instantiatable fundamental type `%s' as non-classed",
2558                  type_name);
2559       return 0;
2560     }
2561   if (lookup_type_node_I (type_id))
2562     {
2563       g_warning ("cannot register existing fundamental type `%s' (as `%s')",
2564                  type_descriptive_name_I (type_id),
2565                  type_name);
2566       return 0;
2567     }
2568   
2569   G_WRITE_LOCK (&type_rw_lock);
2570   node = type_node_fundamental_new_W (type_id, type_name, finfo->type_flags);
2571   type_add_flags_W (node, flags);
2572   
2573   if (check_type_info_I (NULL, NODE_FUNDAMENTAL_TYPE (node), type_name, info))
2574     type_data_make_W (node, info,
2575                       check_value_table_I (type_name, info->value_table) ? info->value_table : NULL);
2576   G_WRITE_UNLOCK (&type_rw_lock);
2577   
2578   return NODE_TYPE (node);
2579 }
2580
2581 /**
2582  * g_type_register_static_simple:
2583  * @parent_type: Type from which this type will be derived.
2584  * @type_name: 0-terminated string used as the name of the new type.
2585  * @class_size: Size of the class structure (see #GTypeInfo)
2586  * @class_init: Location of the class initialization function (see #GTypeInfo)
2587  * @instance_size: Size of the instance structure (see #GTypeInfo)
2588  * @instance_init: Location of the instance initialization function (see #GTypeInfo)
2589  * @flags: Bitwise combination of #GTypeFlags values.
2590  *
2591  * Registers @type_name as the name of a new static type derived from
2592  * @parent_type.  The value of @flags determines the nature (e.g.
2593  * abstract or not) of the type. It works by filling a #GTypeInfo
2594  * struct and calling g_type_register_static().
2595  *
2596  * Since: 2.12
2597  *
2598  * Returns: The new type identifier.
2599  */
2600 GType
2601 g_type_register_static_simple (GType             parent_type,
2602                                const gchar      *type_name,
2603                                guint             class_size,
2604                                GClassInitFunc    class_init,
2605                                guint             instance_size,
2606                                GInstanceInitFunc instance_init,
2607                                GTypeFlags        flags)
2608 {
2609   GTypeInfo info;
2610
2611   info.class_size = class_size;
2612   info.base_init = NULL;
2613   info.base_finalize = NULL;
2614   info.class_init = class_init;
2615   info.class_finalize = NULL;
2616   info.class_data = NULL;
2617   info.instance_size = instance_size;
2618   info.n_preallocs = 0;
2619   info.instance_init = instance_init;
2620   info.value_table = NULL;
2621
2622   return g_type_register_static (parent_type, type_name, &info, flags);
2623 }
2624
2625 /**
2626  * g_type_register_static:
2627  * @parent_type: Type from which this type will be derived.
2628  * @type_name: 0-terminated string used as the name of the new type.
2629  * @info: The #GTypeInfo structure for this type.
2630  * @flags: Bitwise combination of #GTypeFlags values.
2631  *
2632  * Registers @type_name as the name of a new static type derived from
2633  * @parent_type.  The type system uses the information contained in the
2634  * #GTypeInfo structure pointed to by @info to manage the type and its
2635  * instances (if not abstract).  The value of @flags determines the nature
2636  * (e.g. abstract or not) of the type.
2637  *
2638  * Returns: The new type identifier.
2639  */
2640 GType
2641 g_type_register_static (GType            parent_type,
2642                         const gchar     *type_name,
2643                         const GTypeInfo *info,
2644                         GTypeFlags       flags)
2645 {
2646   TypeNode *pnode, *node;
2647   GType type = 0;
2648   
2649   g_return_val_if_uninitialized (static_quark_type_flags, g_type_init, 0);
2650   g_return_val_if_fail (parent_type > 0, 0);
2651   g_return_val_if_fail (type_name != NULL, 0);
2652   g_return_val_if_fail (info != NULL, 0);
2653   
2654   if (!check_type_name_I (type_name) ||
2655       !check_derivation_I (parent_type, type_name))
2656     return 0;
2657   if (info->class_finalize)
2658     {
2659       g_warning ("class finalizer specified for static type `%s'",
2660                  type_name);
2661       return 0;
2662     }
2663   
2664   pnode = lookup_type_node_I (parent_type);
2665   G_WRITE_LOCK (&type_rw_lock);
2666   type_data_ref_Wm (pnode);
2667   if (check_type_info_I (pnode, NODE_FUNDAMENTAL_TYPE (pnode), type_name, info))
2668     {
2669       node = type_node_new_W (pnode, type_name, NULL);
2670       type_add_flags_W (node, flags);
2671       type = NODE_TYPE (node);
2672       type_data_make_W (node, info,
2673                         check_value_table_I (type_name, info->value_table) ? info->value_table : NULL);
2674     }
2675   G_WRITE_UNLOCK (&type_rw_lock);
2676   
2677   return type;
2678 }
2679
2680 /**
2681  * g_type_register_dynamic:
2682  * @parent_type: Type from which this type will be derived.
2683  * @type_name: 0-terminated string used as the name of the new type.
2684  * @plugin: The #GTypePlugin structure to retrieve the #GTypeInfo from.
2685  * @flags: Bitwise combination of #GTypeFlags values.
2686  *
2687  * Registers @type_name as the name of a new dynamic type derived from
2688  * @parent_type.  The type system uses the information contained in the
2689  * #GTypePlugin structure pointed to by @plugin to manage the type and its
2690  * instances (if not abstract).  The value of @flags determines the nature
2691  * (e.g. abstract or not) of the type.
2692  *
2693  * Returns: The new type identifier or #G_TYPE_INVALID if registration failed.
2694  */
2695 GType
2696 g_type_register_dynamic (GType        parent_type,
2697                          const gchar *type_name,
2698                          GTypePlugin *plugin,
2699                          GTypeFlags   flags)
2700 {
2701   TypeNode *pnode, *node;
2702   GType type;
2703   
2704   g_return_val_if_uninitialized (static_quark_type_flags, g_type_init, 0);
2705   g_return_val_if_fail (parent_type > 0, 0);
2706   g_return_val_if_fail (type_name != NULL, 0);
2707   g_return_val_if_fail (plugin != NULL, 0);
2708   
2709   if (!check_type_name_I (type_name) ||
2710       !check_derivation_I (parent_type, type_name) ||
2711       !check_plugin_U (plugin, TRUE, FALSE, type_name))
2712     return 0;
2713   
2714   G_WRITE_LOCK (&type_rw_lock);
2715   pnode = lookup_type_node_I (parent_type);
2716   node = type_node_new_W (pnode, type_name, plugin);
2717   type_add_flags_W (node, flags);
2718   type = NODE_TYPE (node);
2719   G_WRITE_UNLOCK (&type_rw_lock);
2720   
2721   return type;
2722 }
2723
2724 /**
2725  * g_type_add_interface_static:
2726  * @instance_type: #GType value of an instantiable type.
2727  * @interface_type: #GType value of an interface type.
2728  * @info: The #GInterfaceInfo structure for this
2729  *        (@instance_type, @interface_type) combination.
2730  *
2731  * Adds the static @interface_type to @instantiable_type.  The information
2732  * contained in the #GTypeInterfaceInfo structure pointed to by @info
2733  * is used to manage the relationship.
2734  */
2735 void
2736 g_type_add_interface_static (GType                 instance_type,
2737                              GType                 interface_type,
2738                              const GInterfaceInfo *info)
2739 {
2740   /* G_TYPE_IS_INSTANTIATABLE() is an external call: _U */
2741   g_return_if_fail (G_TYPE_IS_INSTANTIATABLE (instance_type));
2742   g_return_if_fail (g_type_parent (interface_type) == G_TYPE_INTERFACE);
2743
2744   /* we only need to lock class_init_rec_mutex if instance_type already has its
2745    * class initialized, however this function is rarely enough called to take
2746    * the simple route and always acquire class_init_rec_mutex.
2747    */
2748   g_static_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
2749   G_WRITE_LOCK (&type_rw_lock);
2750   if (check_add_interface_L (instance_type, interface_type))
2751     {
2752       TypeNode *node = lookup_type_node_I (instance_type);
2753       TypeNode *iface = lookup_type_node_I (interface_type);
2754       if (check_interface_info_I (iface, NODE_TYPE (node), info))
2755         type_add_interface_Wm (node, iface, info, NULL);
2756     }
2757   G_WRITE_UNLOCK (&type_rw_lock);
2758   g_static_rec_mutex_unlock (&class_init_rec_mutex);
2759 }
2760
2761 /**
2762  * g_type_add_interface_dynamic:
2763  * @instance_type: the #GType value of an instantiable type.
2764  * @interface_type: the #GType value of an interface type.
2765  * @plugin: the #GTypePlugin structure to retrieve the #GInterfaceInfo from.
2766  *
2767  * Adds the dynamic @interface_type to @instantiable_type. The information
2768  * contained in the #GTypePlugin structure pointed to by @plugin
2769  * is used to manage the relationship.
2770  */
2771 void
2772 g_type_add_interface_dynamic (GType        instance_type,
2773                               GType        interface_type,
2774                               GTypePlugin *plugin)
2775 {
2776   TypeNode *node;
2777   /* G_TYPE_IS_INSTANTIATABLE() is an external call: _U */
2778   g_return_if_fail (G_TYPE_IS_INSTANTIATABLE (instance_type));
2779   g_return_if_fail (g_type_parent (interface_type) == G_TYPE_INTERFACE);
2780
2781   node = lookup_type_node_I (instance_type);
2782   if (!check_plugin_U (plugin, FALSE, TRUE, NODE_NAME (node)))
2783     return;
2784
2785   /* see comment in g_type_add_interface_static() about class_init_rec_mutex */
2786   g_static_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
2787   G_WRITE_LOCK (&type_rw_lock);
2788   if (check_add_interface_L (instance_type, interface_type))
2789     {
2790       TypeNode *iface = lookup_type_node_I (interface_type);
2791       type_add_interface_Wm (node, iface, NULL, plugin);
2792     }
2793   G_WRITE_UNLOCK (&type_rw_lock);
2794   g_static_rec_mutex_unlock (&class_init_rec_mutex);
2795 }
2796
2797
2798 /* --- public API functions --- */
2799 /**
2800  * g_type_class_ref:
2801  * @type: Type ID of a classed type.
2802  *
2803  * Increments the reference count of the class structure belonging to
2804  * @type. This function will demand-create the class if it doesn't
2805  * exist already.
2806  *
2807  * Returns: The #GTypeClass structure for the given type ID.
2808  */
2809 gpointer
2810 g_type_class_ref (GType type)
2811 {
2812   TypeNode *node;
2813   GType ptype;
2814
2815   /* optimize for common code path */
2816   G_WRITE_LOCK (&type_rw_lock);
2817   node = lookup_type_node_I (type);
2818   if (node && node->is_classed && node->data &&
2819       node->data->class.class &&
2820       node->data->class.init_state == INITIALIZED)
2821     {
2822       type_data_ref_Wm (node);
2823       G_WRITE_UNLOCK (&type_rw_lock);
2824       return node->data->class.class;
2825     }
2826   if (!node || !node->is_classed ||
2827       (node->data && NODE_REFCOUNT (node) == 0))
2828     {
2829       G_WRITE_UNLOCK (&type_rw_lock);
2830       g_warning ("cannot retrieve class for invalid (unclassed) type `%s'",
2831                  type_descriptive_name_I (type));
2832       return NULL;
2833     }
2834   type_data_ref_Wm (node);
2835   ptype = NODE_PARENT_TYPE (node);
2836   G_WRITE_UNLOCK (&type_rw_lock);
2837
2838   g_static_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
2839   /* here, we either have node->data->class.class == NULL, or a recursive
2840    * call to g_type_class_ref() with a partly initialized class, or
2841    * node->data->class.init_state == INITIALIZED, because any
2842    * concurrently running initialization was guarded by class_init_rec_mutex.
2843    */
2844   if (!node->data->class.class) /* class uninitialized */
2845     {
2846       /* we need an initialized parent class for initializing derived classes */
2847       GTypeClass *pclass = ptype ? g_type_class_ref (ptype) : NULL;
2848       G_WRITE_LOCK (&type_rw_lock);
2849       if (node->data->class.class) /* class was initialized during parent class initialization? */
2850         INVALID_RECURSION ("g_type_plugin_*", node->plugin, NODE_NAME (node));
2851       type_class_init_Wm (node, pclass);
2852       G_WRITE_UNLOCK (&type_rw_lock);
2853       if (pclass)
2854         g_type_class_unref (pclass);
2855     }
2856   g_static_rec_mutex_unlock (&class_init_rec_mutex);
2857
2858   return node->data->class.class;
2859 }
2860
2861 /**
2862  * g_type_class_unref:
2863  * @g_class: The #GTypeClass structure to unreference.
2864  *
2865  * Decrements the reference count of the class structure being passed in.
2866  * Once the last reference count of a class has been released, classes
2867  * may be finalized by the type system, so further dereferencing of a
2868  * class pointer after g_type_class_unref() are invalid.
2869  */
2870 void
2871 g_type_class_unref (gpointer g_class)
2872 {
2873   TypeNode *node;
2874   GTypeClass *class = g_class;
2875   
2876   g_return_if_fail (g_class != NULL);
2877   
2878   node = lookup_type_node_I (class->g_type);
2879   if (node && node->is_classed && NODE_REFCOUNT (node))
2880     type_data_unref_U (node, FALSE);
2881   else
2882     g_warning ("cannot unreference class of invalid (unclassed) type `%s'",
2883                type_descriptive_name_I (class->g_type));
2884 }
2885
2886 /**
2887  * g_type_class_unref_uncached:
2888  * @g_class: The #GTypeClass structure to unreference.
2889  *
2890  * A variant of g_type_class_unref() for use in #GTypeClassCacheFunc
2891  * implementations. It unreferences a class without consulting the chain
2892  * of #GTypeClassCacheFunc<!-- -->s, avoiding the recursion which would occur
2893  * otherwise.
2894  */
2895 void
2896 g_type_class_unref_uncached (gpointer g_class)
2897 {
2898   TypeNode *node;
2899   GTypeClass *class = g_class;
2900   
2901   g_return_if_fail (g_class != NULL);
2902   
2903   node = lookup_type_node_I (class->g_type);
2904   if (node && node->is_classed && NODE_REFCOUNT (node))
2905     type_data_unref_U (node, TRUE);
2906   else
2907     g_warning ("cannot unreference class of invalid (unclassed) type `%s'",
2908                type_descriptive_name_I (class->g_type));
2909 }
2910
2911 /**
2912  * g_type_class_peek:
2913  * @type: Type ID of a classed type.
2914  *
2915  * This function is essentially the same as g_type_class_ref(), except that
2916  * the classes reference count isn't incremented. As a consequence, this function
2917  * may return %NULL if the class of the type passed in does not currently
2918  * exist (hasn't been referenced before).
2919  *
2920  * Returns: The #GTypeClass structure for the given type ID or %NULL
2921  *  if the class does not currently exist.
2922  */
2923 gpointer
2924 g_type_class_peek (GType type)
2925 {
2926   TypeNode *node;
2927   gpointer class;
2928   
2929   node = lookup_type_node_I (type);
2930   G_READ_LOCK (&type_rw_lock);
2931   if (node && node->is_classed && node->data && node->data->class.class) /* ref_count _may_ be 0 */
2932     class = node->data->class.class;
2933   else
2934     class = NULL;
2935   G_READ_UNLOCK (&type_rw_lock);
2936   
2937   return class;
2938 }
2939
2940 /**
2941  * g_type_class_peek_static:
2942  * @type: Type ID of a classed type.
2943  *
2944  * A more efficient version of g_type_class_peek() which works only for
2945  * static types.
2946  * 
2947  * Since: 2.4
2948  * Returns: The #GTypeClass structure for the given type ID or %NULL
2949  *  if the class does not currently exist or is dynamically loaded.
2950  */
2951 gpointer
2952 g_type_class_peek_static (GType type)
2953 {
2954   TypeNode *node;
2955   gpointer class;
2956   
2957   node = lookup_type_node_I (type);
2958   G_READ_LOCK (&type_rw_lock);
2959   if (node && node->is_classed && node->data &&
2960       /* peek only static types: */ node->plugin == NULL &&
2961       node->data->class.class) /* ref_count _may_ be 0 */
2962     class = node->data->class.class;
2963   else
2964     class = NULL;
2965   G_READ_UNLOCK (&type_rw_lock);
2966   
2967   return class;
2968 }
2969
2970 /**
2971  * g_type_class_peek_parent:
2972  * @g_class: The #GTypeClass structure to retrieve the parent class for.
2973  *
2974  * This is a convenience function often needed in class initializers.
2975  * It returns the class structure of the immediate parent type of the
2976  * class passed in.  Since derived classes hold a reference count on
2977  * their parent classes as long as they are instantiated, the returned
2978  * class will always exist. This function is essentially equivalent
2979  * to:
2980  *
2981  * <programlisting>
2982  * g_type_class_peek (g_type_parent (G_TYPE_FROM_CLASS (g_class)));
2983  * </programlisting>
2984  *
2985  * Returns: The parent class of @g_class.
2986  */
2987 gpointer
2988 g_type_class_peek_parent (gpointer g_class)
2989 {
2990   TypeNode *node;
2991   gpointer class = NULL;
2992   
2993   g_return_val_if_fail (g_class != NULL, NULL);
2994   
2995   node = lookup_type_node_I (G_TYPE_FROM_CLASS (g_class));
2996   /* We used to acquire a read lock here. That is not necessary, since 
2997    * parent->data->class.class is constant as long as the derived class
2998    * exists. 
2999    */
3000   if (node && node->is_classed && node->data && NODE_PARENT_TYPE (node))
3001     {
3002       node = lookup_type_node_I (NODE_PARENT_TYPE (node));
3003       class = node->data->class.class;
3004     }
3005   else if (NODE_PARENT_TYPE (node))
3006     g_warning (G_STRLOC ": invalid class pointer `%p'", g_class);
3007   
3008   return class;
3009 }
3010
3011 /**
3012  * g_type_interface_peek:
3013  * @instance_class: A #GTypeClass structure.
3014  * @iface_type: An interface ID which this class conforms to.
3015  *
3016  * Returns the #GTypeInterface structure of an interface to which the
3017  * passed in class conforms.
3018  *
3019  * Returns: The GTypeInterface structure of iface_type if implemented
3020  *          by @instance_class, %NULL otherwise
3021  */
3022 gpointer
3023 g_type_interface_peek (gpointer instance_class,
3024                        GType    iface_type)
3025 {
3026   TypeNode *node;
3027   TypeNode *iface;
3028   gpointer vtable = NULL;
3029   GTypeClass *class = instance_class;
3030   
3031   g_return_val_if_fail (instance_class != NULL, NULL);
3032   
3033   node = lookup_type_node_I (class->g_type);
3034   iface = lookup_type_node_I (iface_type);
3035   if (node && node->is_instantiatable && iface)
3036     type_lookup_iface_vtable_I (node, iface, &vtable);
3037   else
3038     g_warning (G_STRLOC ": invalid class pointer `%p'", class);
3039   
3040   return vtable;
3041 }
3042
3043 /**
3044  * g_type_interface_peek_parent:
3045  * @g_iface: A #GTypeInterface structure.
3046  *
3047  * Returns the corresponding #GTypeInterface structure of the parent type
3048  * of the instance type to which @g_iface belongs. This is useful when
3049  * deriving the implementation of an interface from the parent type and
3050  * then possibly overriding some methods.
3051  *
3052  * Returns: The corresponding #GTypeInterface structure of the parent
3053  *          type of the instance type to which @g_iface belongs, or
3054  *          %NULL if the parent type doesn't conform to the interface.
3055  */
3056 gpointer
3057 g_type_interface_peek_parent (gpointer g_iface)
3058 {
3059   TypeNode *node;
3060   TypeNode *iface;
3061   gpointer vtable = NULL;
3062   GTypeInterface *iface_class = g_iface;
3063   
3064   g_return_val_if_fail (g_iface != NULL, NULL);
3065   
3066   iface = lookup_type_node_I (iface_class->g_type);
3067   node = lookup_type_node_I (iface_class->g_instance_type);
3068   if (node)
3069     node = lookup_type_node_I (NODE_PARENT_TYPE (node));
3070   if (node && node->is_instantiatable && iface)
3071     type_lookup_iface_vtable_I (node, iface, &vtable);
3072   else if (node)
3073     g_warning (G_STRLOC ": invalid interface pointer `%p'", g_iface);
3074   
3075   return vtable;
3076 }
3077
3078 /**
3079  * g_type_default_interface_ref:
3080  * @g_type: an interface type
3081  *
3082  * Increments the reference count for the interface type @g_type,
3083  * and returns the default interface vtable for the type.
3084  *
3085  * If the type is not currently in use, then the default vtable
3086  * for the type will be created and initalized by calling
3087  * the base interface init and default vtable init functions for
3088  * the type (the @<structfield>base_init</structfield>
3089  * and <structfield>class_init</structfield> members of #GTypeInfo).
3090  * Calling g_type_default_interface_ref() is useful when you
3091  * want to make sure that signals and properties for an interface
3092  * have been installed.
3093  *
3094  * Since: 2.4
3095  *
3096  * Returns: the default vtable for the interface; call
3097  *          g_type_default_interface_unref() when you are done using
3098  *          the interface.
3099  */
3100 gpointer
3101 g_type_default_interface_ref (GType g_type)
3102 {
3103   TypeNode *node;
3104   gpointer dflt_vtable;
3105
3106   G_WRITE_LOCK (&type_rw_lock);
3107
3108   node = lookup_type_node_I (g_type);
3109   if (!node || !NODE_IS_IFACE (node) ||
3110       (node->data && NODE_REFCOUNT (node) == 0))
3111     {
3112       G_WRITE_UNLOCK (&type_rw_lock);
3113       g_warning ("cannot retrieve default vtable for invalid or non-interface type '%s'",
3114                  type_descriptive_name_I (g_type));
3115       return NULL;
3116     }
3117
3118   if (!node->data || !node->data->iface.dflt_vtable)
3119     {
3120       G_WRITE_UNLOCK (&type_rw_lock);
3121       g_static_rec_mutex_lock (&class_init_rec_mutex); /* required locking order: 1) class_init_rec_mutex, 2) type_rw_lock */
3122       G_WRITE_LOCK (&type_rw_lock);
3123       node = lookup_type_node_I (g_type);
3124       type_data_ref_Wm (node);
3125       type_iface_ensure_dflt_vtable_Wm (node);
3126       g_static_rec_mutex_unlock (&class_init_rec_mutex);
3127     }
3128   else
3129     type_data_ref_Wm (node); /* ref_count >= 1 already */
3130
3131   dflt_vtable = node->data->iface.dflt_vtable;
3132   G_WRITE_UNLOCK (&type_rw_lock);
3133
3134   return dflt_vtable;
3135 }
3136
3137 /**
3138  * g_type_default_interface_peek:
3139  * @g_type: an interface type
3140  *
3141  * If the interface type @g_type is currently in use, returns its
3142  * default interface vtable.
3143  *
3144  * Since: 2.4
3145  *
3146  * Returns: the default vtable for the interface, or %NULL
3147  *          if the type is not currently in use.
3148  */
3149 gpointer
3150 g_type_default_interface_peek (GType g_type)
3151 {
3152   TypeNode *node;
3153   gpointer vtable;
3154   
3155   node = lookup_type_node_I (g_type);
3156   G_READ_LOCK (&type_rw_lock);
3157   if (node && NODE_IS_IFACE (node) && node->data && node->data->iface.dflt_vtable)
3158     vtable = node->data->iface.dflt_vtable;
3159   else
3160     vtable = NULL;
3161   G_READ_UNLOCK (&type_rw_lock);
3162   
3163   return vtable;
3164 }
3165
3166 /**
3167  * g_type_default_interface_unref:
3168  * @g_iface: the default vtable structure for a interface, as
3169  *           returned by g_type_default_interface_ref()
3170  *
3171  * Decrements the reference count for the type corresponding to the
3172  * interface default vtable @g_iface. If the type is dynamic, then
3173  * when no one is using the interface and all references have
3174  * been released, the finalize function for the interface's default
3175  * vtable (the <structfield>class_finalize</structfield> member of
3176  * #GTypeInfo) will be called.
3177  *
3178  * Since: 2.4
3179  */
3180 void
3181 g_type_default_interface_unref (gpointer g_iface)
3182 {
3183   TypeNode *node;
3184   GTypeInterface *vtable = g_iface;
3185   
3186   g_return_if_fail (g_iface != NULL);
3187   
3188   node = lookup_type_node_I (vtable->g_type);
3189   if (node && NODE_IS_IFACE (node))
3190     type_data_unref_U (node, FALSE);
3191   else
3192     g_warning ("cannot unreference invalid interface default vtable for '%s'",
3193                type_descriptive_name_I (vtable->g_type));
3194 }
3195
3196 /**
3197  * g_type_name:
3198  * @type: Type to return name for.
3199  *
3200  * Get the unique name that is assigned to a type ID.  Note that this
3201  * function (like all other GType API) cannot cope with invalid type
3202  * IDs. %G_TYPE_INVALID may be passed to this function, as may be any
3203  * other validly registered type ID, but randomized type IDs should
3204  * not be passed in and will most likely lead to a crash.
3205  *
3206  * Returns: Static type name or %NULL.
3207  */
3208 G_CONST_RETURN gchar*
3209 g_type_name (GType type)
3210 {
3211   TypeNode *node;
3212   
3213   g_return_val_if_uninitialized (static_quark_type_flags, g_type_init, NULL);
3214   
3215   node = lookup_type_node_I (type);
3216   
3217   return node ? NODE_NAME (node) : NULL;
3218 }
3219
3220 /**
3221  * g_type_qname:
3222  * @type: Type to return quark of type name for.
3223  *
3224  * Get the corresponding quark of the type IDs name.
3225  *
3226  * Returns: The type names quark or 0.
3227  */
3228 GQuark
3229 g_type_qname (GType type)
3230 {
3231   TypeNode *node;
3232   
3233   node = lookup_type_node_I (type);
3234   
3235   return node ? node->qname : 0;
3236 }
3237
3238 /**
3239  * g_type_from_name:
3240  * @name: Type name to lookup.
3241  *
3242  * Lookup the type ID from a given type name, returning 0 if no type
3243  * has been registered under this name (this is the preferred method
3244  * to find out by name whether a specific type has been registered
3245  * yet).
3246  *
3247  * Returns: Corresponding type ID or 0.
3248  */
3249 GType
3250 g_type_from_name (const gchar *name)
3251 {
3252   GType type = 0;
3253   GQuark quark;
3254   
3255   g_return_val_if_fail (name != NULL, 0);
3256   
3257   quark = g_quark_try_string (name);
3258   if (quark)
3259     {
3260       G_READ_LOCK (&type_rw_lock);
3261       type = (GType) g_hash_table_lookup (static_type_nodes_ht, GUINT_TO_POINTER (quark));
3262       G_READ_UNLOCK (&type_rw_lock);
3263     }
3264   
3265   return type;
3266 }
3267
3268 /**
3269  * g_type_parent:
3270  * @type: The derived type.
3271  *
3272  * Return the direct parent type of the passed in type.  If the passed
3273  * in type has no parent, i.e. is a fundamental type, 0 is returned.
3274  *
3275  * Returns: The parent type.
3276  */
3277 GType
3278 g_type_parent (GType type)
3279 {
3280   TypeNode *node;
3281   
3282   node = lookup_type_node_I (type);
3283   
3284   return node ? NODE_PARENT_TYPE (node) : 0;
3285 }
3286
3287 /**
3288  * g_type_depth:
3289  * @type: A #GType value.
3290  *
3291  * Returns the length of the ancestry of the passed in type. This
3292  * includes the type itself, so that e.g. a fundamental type has depth 1.
3293  *
3294  * Returns: The depth of @type.
3295  */
3296 guint
3297 g_type_depth (GType type)
3298 {
3299   TypeNode *node;
3300   
3301   node = lookup_type_node_I (type);
3302   
3303   return node ? node->n_supers + 1 : 0;
3304 }
3305
3306 /**
3307  * g_type_next_base:
3308  * @leaf_type: Descendant of @root_type and the type to be returned.
3309  * @root_type: Immediate parent of the returned type.
3310  *
3311  * Given a @leaf_type and a @root_type which is contained in its
3312  * anchestry, return the type that @root_type is the immediate parent
3313  * of.  In other words, this function determines the type that is
3314  * derived directly from @root_type which is also a base class of
3315  * @leaf_type.  Given a root type and a leaf type, this function can
3316  * be used to determine the types and order in which the leaf type is
3317  * descended from the root type.
3318  *
3319  * Returns: Immediate child of @root_type and anchestor of @leaf_type.
3320  */
3321 GType
3322 g_type_next_base (GType type,
3323                   GType base_type)
3324 {
3325   GType atype = 0;
3326   TypeNode *node;
3327   
3328   node = lookup_type_node_I (type);
3329   if (node)
3330     {
3331       TypeNode *base_node = lookup_type_node_I (base_type);
3332       
3333       if (base_node && base_node->n_supers < node->n_supers)
3334         {
3335           guint n = node->n_supers - base_node->n_supers;
3336           
3337           if (node->supers[n] == base_type)
3338             atype = node->supers[n - 1];
3339         }
3340     }
3341   
3342   return atype;
3343 }
3344
3345 static inline gboolean
3346 type_node_check_conformities_UorL (TypeNode *node,
3347                                    TypeNode *iface_node,
3348                                    /*        support_inheritance */
3349                                    gboolean  support_interfaces,
3350                                    gboolean  support_prerequisites,
3351                                    gboolean  have_lock)
3352 {
3353   gboolean match;
3354
3355   if (/* support_inheritance && */
3356       NODE_IS_ANCESTOR (iface_node, node))
3357     return TRUE;
3358
3359   support_interfaces = support_interfaces && node->is_instantiatable && NODE_IS_IFACE (iface_node);
3360   support_prerequisites = support_prerequisites && NODE_IS_IFACE (node);
3361   match = FALSE;
3362   if (support_interfaces)
3363     {
3364       if (have_lock)
3365         {
3366           if (type_lookup_iface_entry_L (node, iface_node))
3367             match = TRUE;
3368         }
3369       else
3370         {
3371           if (type_lookup_iface_vtable_I (node, iface_node, NULL))
3372             match = TRUE;
3373         }
3374     }
3375   if (!match &&
3376       support_prerequisites)
3377     {
3378       if (!have_lock)
3379         G_READ_LOCK (&type_rw_lock);
3380       if (support_prerequisites && type_lookup_prerequisite_L (node, NODE_TYPE (iface_node)))
3381         match = TRUE;
3382       if (!have_lock)
3383         G_READ_UNLOCK (&type_rw_lock);
3384     }
3385   return match;
3386 }
3387
3388 static gboolean
3389 type_node_is_a_L (TypeNode *node,
3390                   TypeNode *iface_node)
3391 {
3392   return type_node_check_conformities_UorL (node, iface_node, TRUE, TRUE, TRUE);
3393 }
3394
3395 static inline gboolean
3396 type_node_conforms_to_U (TypeNode *node,
3397                          TypeNode *iface_node,
3398                          gboolean  support_interfaces,
3399                          gboolean  support_prerequisites)
3400 {
3401   return type_node_check_conformities_UorL (node, iface_node, support_interfaces, support_prerequisites, FALSE);
3402 }
3403
3404 /**
3405  * g_type_is_a:
3406  * @type: Type to check anchestry for.
3407  * @is_a_type: Possible anchestor of @type or interface @type could conform to.
3408  *
3409  * If @is_a_type is a derivable type, check whether @type is a
3410  * descendant of @is_a_type.  If @is_a_type is an interface, check
3411  * whether @type conforms to it.
3412  *
3413  * Returns: %TRUE if @type is_a @is_a_type holds true.
3414  */
3415 gboolean
3416 g_type_is_a (GType type,
3417              GType iface_type)
3418 {
3419   TypeNode *node, *iface_node;
3420   gboolean is_a;
3421   
3422   node = lookup_type_node_I (type);
3423   iface_node = lookup_type_node_I (iface_type);
3424   is_a = node && iface_node && type_node_conforms_to_U (node, iface_node, TRUE, TRUE);
3425   
3426   return is_a;
3427 }
3428
3429 /**
3430  * g_type_children:
3431  * @type: The parent type.
3432  * @n_children: Optional #guint pointer to contain the number of child types.
3433  *
3434  * Return a newly allocated and 0-terminated array of type IDs, listing the
3435  * child types of @type. The return value has to be g_free()ed after use.
3436  *
3437  * Returns: Newly allocated and 0-terminated array of child types.
3438  */
3439 GType*
3440 g_type_children (GType  type,
3441                  guint *n_children)
3442 {
3443   TypeNode *node;
3444   
3445   node = lookup_type_node_I (type);
3446   if (node)
3447     {
3448       GType *children;
3449       
3450       G_READ_LOCK (&type_rw_lock);      /* ->children is relocatable */
3451       children = g_new (GType, node->n_children + 1);
3452       memcpy (children, node->children, sizeof (GType) * node->n_children);
3453       children[node->n_children] = 0;
3454       
3455       if (n_children)
3456         *n_children = node->n_children;
3457       G_READ_UNLOCK (&type_rw_lock);
3458       
3459       return children;
3460     }
3461   else
3462     {
3463       if (n_children)
3464         *n_children = 0;
3465       
3466       return NULL;
3467     }
3468 }
3469
3470 /**
3471  * g_type_interfaces:
3472  * @type: The type to list interface types for.
3473  * @n_interfaces: Optional #guint pointer to contain the number of
3474  *                interface types.
3475  *
3476  * Return a newly allocated and 0-terminated array of type IDs, listing the
3477  * interface types that @type conforms to. The return value has to be
3478  * g_free()ed after use.
3479  *
3480  * Returns: Newly allocated and 0-terminated array of interface types.
3481  */
3482 GType*
3483 g_type_interfaces (GType  type,
3484                    guint *n_interfaces)
3485 {
3486   TypeNode *node;
3487   
3488   node = lookup_type_node_I (type);
3489   if (node && node->is_instantiatable)
3490     {
3491       IFaceEntries *entries;
3492       GType *ifaces;
3493       guint i;
3494       
3495       G_READ_LOCK (&type_rw_lock);
3496       entries = CLASSED_NODE_IFACES_ENTRIES_LOCKED (node);
3497       if (entries)
3498         {
3499           ifaces = g_new (GType, IFACE_ENTRIES_N_ENTRIES (entries) + 1);
3500           for (i = 0; i < IFACE_ENTRIES_N_ENTRIES (entries); i++)
3501             ifaces[i] = entries->entry[i].iface_type;
3502         }
3503       else
3504         {
3505           ifaces = g_new (GType, 1);
3506           i = 0;
3507         }
3508       ifaces[i] = 0;
3509       
3510       if (n_interfaces)
3511         *n_interfaces = i;
3512       G_READ_UNLOCK (&type_rw_lock);
3513       
3514       return ifaces;
3515     }
3516   else
3517     {
3518       if (n_interfaces)
3519         *n_interfaces = 0;
3520       
3521       return NULL;
3522     }
3523 }
3524
3525 typedef struct _QData QData;
3526 struct _GData
3527 {
3528   guint  n_qdatas;
3529   QData *qdatas;
3530 };
3531 struct _QData
3532 {
3533   GQuark   quark;
3534   gpointer data;
3535 };
3536
3537 static inline gpointer
3538 type_get_qdata_L (TypeNode *node,
3539                   GQuark    quark)
3540 {
3541   GData *gdata = node->global_gdata;
3542   
3543   if (quark && gdata && gdata->n_qdatas)
3544     {
3545       QData *qdatas = gdata->qdatas - 1;
3546       guint n_qdatas = gdata->n_qdatas;
3547       
3548       do
3549         {
3550           guint i;
3551           QData *check;
3552           
3553           i = (n_qdatas + 1) / 2;
3554           check = qdatas + i;
3555           if (quark == check->quark)
3556             return check->data;
3557           else if (quark > check->quark)
3558             {
3559               n_qdatas -= i;
3560               qdatas = check;
3561             }
3562           else /* if (quark < check->quark) */
3563             n_qdatas = i - 1;
3564         }
3565       while (n_qdatas);
3566     }
3567   return NULL;
3568 }
3569
3570 /**
3571  * g_type_get_qdata:
3572  * @type: a #GType
3573  * @quark: a #GQuark id to identify the data
3574  *
3575  * Obtains data which has previously been attached to @type
3576  * with g_type_set_qdata().
3577  *
3578  * Returns: the data, or %NULL if no data was found
3579  */
3580 gpointer
3581 g_type_get_qdata (GType  type,
3582                   GQuark quark)
3583 {
3584   TypeNode *node;
3585   gpointer data;
3586   
3587   node = lookup_type_node_I (type);
3588   if (node)
3589     {
3590       G_READ_LOCK (&type_rw_lock);
3591       data = type_get_qdata_L (node, quark);
3592       G_READ_UNLOCK (&type_rw_lock);
3593     }
3594   else
3595     {
3596       g_return_val_if_fail (node != NULL, NULL);
3597       data = NULL;
3598     }
3599   return data;
3600 }
3601
3602 static inline void
3603 type_set_qdata_W (TypeNode *node,
3604                   GQuark    quark,
3605                   gpointer  data)
3606 {
3607   GData *gdata;
3608   QData *qdata;
3609   guint i;
3610   
3611   /* setup qdata list if necessary */
3612   if (!node->global_gdata)
3613     node->global_gdata = g_new0 (GData, 1);
3614   gdata = node->global_gdata;
3615   
3616   /* try resetting old data */
3617   qdata = gdata->qdatas;
3618   for (i = 0; i < gdata->n_qdatas; i++)
3619     if (qdata[i].quark == quark)
3620       {
3621         qdata[i].data = data;
3622         return;
3623       }
3624   
3625   /* add new entry */
3626   gdata->n_qdatas++;
3627   gdata->qdatas = g_renew (QData, gdata->qdatas, gdata->n_qdatas);
3628   qdata = gdata->qdatas;
3629   for (i = 0; i < gdata->n_qdatas - 1; i++)
3630     if (qdata[i].quark > quark)
3631       break;
3632   g_memmove (qdata + i + 1, qdata + i, sizeof (qdata[0]) * (gdata->n_qdatas - i - 1));
3633   qdata[i].quark = quark;
3634   qdata[i].data = data;
3635 }
3636
3637 /**
3638  * g_type_set_qdata:
3639  * @type: a #GType
3640  * @quark: a #GQuark id to identify the data
3641  * @data: the data
3642  *
3643  * Attaches arbitrary data to a type.
3644  */
3645 void
3646 g_type_set_qdata (GType    type,
3647                   GQuark   quark,
3648                   gpointer data)
3649 {
3650   TypeNode *node;
3651   
3652   g_return_if_fail (quark != 0);
3653   
3654   node = lookup_type_node_I (type);
3655   if (node)
3656     {
3657       G_WRITE_LOCK (&type_rw_lock);
3658       type_set_qdata_W (node, quark, data);
3659       G_WRITE_UNLOCK (&type_rw_lock);
3660     }
3661   else
3662     g_return_if_fail (node != NULL);
3663 }
3664
3665 static void
3666 type_add_flags_W (TypeNode  *node,
3667                   GTypeFlags flags)
3668 {
3669   guint dflags;
3670   
3671   g_return_if_fail ((flags & ~TYPE_FLAG_MASK) == 0);
3672   g_return_if_fail (node != NULL);
3673   
3674   if ((flags & TYPE_FLAG_MASK) && node->is_classed && node->data && node->data->class.class)
3675     g_warning ("tagging type `%s' as abstract after class initialization", NODE_NAME (node));
3676   dflags = GPOINTER_TO_UINT (type_get_qdata_L (node, static_quark_type_flags));
3677   dflags |= flags;
3678   type_set_qdata_W (node, static_quark_type_flags, GUINT_TO_POINTER (dflags));
3679 }
3680
3681 /**
3682  * g_type_query:
3683  * @type: the #GType value of a static, classed type.
3684  * @query: A user provided structure that is filled in with constant values
3685  *  upon success.
3686  *
3687  * Queries the type system for information about a specific type.
3688  * This function will fill in a user-provided structure to hold
3689  * type-specific information. If an invalid #GType is passed in, the
3690  * @type member of the #GTypeQuery is 0. All members filled into the
3691  * #GTypeQuery structure should be considered constant and have to be
3692  * left untouched.
3693  */
3694 void
3695 g_type_query (GType       type,
3696               GTypeQuery *query)
3697 {
3698   TypeNode *node;
3699   
3700   g_return_if_fail (query != NULL);
3701   
3702   /* if node is not static and classed, we won't allow query */
3703   query->type = 0;
3704   node = lookup_type_node_I (type);
3705   if (node && node->is_classed && !node->plugin)
3706     {
3707       /* type is classed and probably even instantiatable */
3708       G_READ_LOCK (&type_rw_lock);
3709       if (node->data)   /* type is static or referenced */
3710         {
3711           query->type = NODE_TYPE (node);
3712           query->type_name = NODE_NAME (node);
3713           query->class_size = node->data->class.class_size;
3714           query->instance_size = node->is_instantiatable ? node->data->instance.instance_size : 0;
3715         }
3716       G_READ_UNLOCK (&type_rw_lock);
3717     }
3718 }
3719
3720
3721 /* --- implementation details --- */
3722 gboolean
3723 g_type_test_flags (GType type,
3724                    guint flags)
3725 {
3726   TypeNode *node;
3727   gboolean result = FALSE;
3728   
3729   node = lookup_type_node_I (type);
3730   if (node)
3731     {
3732       guint fflags = flags & TYPE_FUNDAMENTAL_FLAG_MASK;
3733       guint tflags = flags & TYPE_FLAG_MASK;
3734       
3735       if (fflags)
3736         {
3737           GTypeFundamentalInfo *finfo = type_node_fundamental_info_I (node);
3738           
3739           fflags = (finfo->type_flags & fflags) == fflags;
3740         }
3741       else
3742         fflags = TRUE;
3743       
3744       if (tflags)
3745         {
3746           G_READ_LOCK (&type_rw_lock);
3747           tflags = (tflags & GPOINTER_TO_UINT (type_get_qdata_L (node, static_quark_type_flags))) == tflags;
3748           G_READ_UNLOCK (&type_rw_lock);
3749         }
3750       else
3751         tflags = TRUE;
3752       
3753       result = tflags && fflags;
3754     }
3755   
3756   return result;
3757 }
3758
3759 /**
3760  * g_type_get_plugin:
3761  * @type: The #GType to retrieve the plugin for.
3762  *
3763  * Returns the #GTypePlugin structure for @type or
3764  * %NULL if @type does not have a #GTypePlugin structure.
3765  *
3766  * Returns: The corresponding plugin if @type is a dynamic type,
3767  *  %NULL otherwise.
3768  */
3769 GTypePlugin*
3770 g_type_get_plugin (GType type)
3771 {
3772   TypeNode *node;
3773   
3774   node = lookup_type_node_I (type);
3775   
3776   return node ? node->plugin : NULL;
3777 }
3778
3779 /**
3780  * g_type_interface_get_plugin:
3781  * @instance_type: the #GType value of an instantiatable type.
3782  * @interface_type: the #GType value of an interface type.
3783  *
3784  * Returns the #GTypePlugin structure for the dynamic interface
3785  * @interface_type which has been added to @instance_type, or %NULL if
3786  * @interface_type has not been added to @instance_type or does not
3787  * have a #GTypePlugin structure. See g_type_add_interface_dynamic().
3788  *
3789  * Returns: the #GTypePlugin for the dynamic interface @interface_type
3790  *  of @instance_type.
3791  */
3792 GTypePlugin*
3793 g_type_interface_get_plugin (GType instance_type,
3794                              GType interface_type)
3795 {
3796   TypeNode *node;
3797   TypeNode *iface;
3798   
3799   g_return_val_if_fail (G_TYPE_IS_INTERFACE (interface_type), NULL);    /* G_TYPE_IS_INTERFACE() is an external call: _U */
3800   
3801   node = lookup_type_node_I (instance_type);  
3802   iface = lookup_type_node_I (interface_type);
3803   if (node && iface)
3804     {
3805       IFaceHolder *iholder;
3806       GTypePlugin *plugin;
3807       
3808       G_READ_LOCK (&type_rw_lock);
3809       
3810       iholder = iface_node_get_holders_L (iface);
3811       while (iholder && iholder->instance_type != instance_type)
3812         iholder = iholder->next;
3813       plugin = iholder ? iholder->plugin : NULL;
3814       
3815       G_READ_UNLOCK (&type_rw_lock);
3816       
3817       return plugin;
3818     }
3819   
3820   g_return_val_if_fail (node == NULL, NULL);
3821   g_return_val_if_fail (iface == NULL, NULL);
3822   
3823   g_warning (G_STRLOC ": attempt to look up plugin for invalid instance/interface type pair.");
3824   
3825   return NULL;
3826 }
3827
3828 /**
3829  * g_type_fundamental_next:
3830  *
3831  * Returns the next free fundamental type id which can be used to
3832  * register a new fundamental type with g_type_register_fundamental().
3833  * The returned type ID represents the highest currently registered
3834  * fundamental type identifier.
3835  *
3836  * Returns: The nextmost fundamental type ID to be registered,
3837  *          or 0 if the type system ran out of fundamental type IDs.
3838  */
3839 GType
3840 g_type_fundamental_next (void)
3841 {
3842   GType type;
3843   
3844   G_READ_LOCK (&type_rw_lock);
3845   type = static_fundamental_next;
3846   G_READ_UNLOCK (&type_rw_lock);
3847   type = G_TYPE_MAKE_FUNDAMENTAL (type);
3848   return type <= G_TYPE_FUNDAMENTAL_MAX ? type : 0;
3849 }
3850
3851 /**
3852  * g_type_fundamental:
3853  * @type_id: valid type ID
3854  * 
3855  * Internal function, used to extract the fundamental type ID portion.
3856  * use G_TYPE_FUNDAMENTAL() instead.
3857  * 
3858  * Returns: fundamental type ID
3859  */
3860 GType
3861 g_type_fundamental (GType type_id)
3862 {
3863   TypeNode *node = lookup_type_node_I (type_id);
3864   
3865   return node ? NODE_FUNDAMENTAL_TYPE (node) : 0;
3866 }
3867
3868 gboolean
3869 g_type_check_instance_is_a (GTypeInstance *type_instance,
3870                             GType          iface_type)
3871 {
3872   TypeNode *node, *iface;
3873   gboolean check;
3874   
3875   if (!type_instance || !type_instance->g_class)
3876     return FALSE;
3877   
3878   node = lookup_type_node_I (type_instance->g_class->g_type);
3879   iface = lookup_type_node_I (iface_type);
3880   check = node && node->is_instantiatable && iface && type_node_conforms_to_U (node, iface, TRUE, FALSE);
3881   
3882   return check;
3883 }
3884
3885 gboolean
3886 g_type_check_class_is_a (GTypeClass *type_class,
3887                          GType       is_a_type)
3888 {
3889   TypeNode *node, *iface;
3890   gboolean check;
3891   
3892   if (!type_class)
3893     return FALSE;
3894   
3895   node = lookup_type_node_I (type_class->g_type);
3896   iface = lookup_type_node_I (is_a_type);
3897   check = node && node->is_classed && iface && type_node_conforms_to_U (node, iface, FALSE, FALSE);
3898   
3899   return check;
3900 }
3901
3902 GTypeInstance*
3903 g_type_check_instance_cast (GTypeInstance *type_instance,
3904                             GType          iface_type)
3905 {
3906   if (type_instance)
3907     {
3908       if (type_instance->g_class)
3909         {
3910           TypeNode *node, *iface;
3911           gboolean is_instantiatable, check;
3912           
3913           node = lookup_type_node_I (type_instance->g_class->g_type);
3914           is_instantiatable = node && node->is_instantiatable;
3915           iface = lookup_type_node_I (iface_type);
3916           check = is_instantiatable && iface && type_node_conforms_to_U (node, iface, TRUE, FALSE);
3917           if (check)
3918             return type_instance;
3919           
3920           if (is_instantiatable)
3921             g_warning ("invalid cast from `%s' to `%s'",
3922                        type_descriptive_name_I (type_instance->g_class->g_type),
3923                        type_descriptive_name_I (iface_type));
3924           else
3925             g_warning ("invalid uninstantiatable type `%s' in cast to `%s'",
3926                        type_descriptive_name_I (type_instance->g_class->g_type),
3927                        type_descriptive_name_I (iface_type));
3928         }
3929       else
3930         g_warning ("invalid unclassed pointer in cast to `%s'",
3931                    type_descriptive_name_I (iface_type));
3932     }
3933   
3934   return type_instance;
3935 }
3936
3937 GTypeClass*
3938 g_type_check_class_cast (GTypeClass *type_class,
3939                          GType       is_a_type)
3940 {
3941   if (type_class)
3942     {
3943       TypeNode *node, *iface;
3944       gboolean is_classed, check;
3945       
3946       node = lookup_type_node_I (type_class->g_type);
3947       is_classed = node && node->is_classed;
3948       iface = lookup_type_node_I (is_a_type);
3949       check = is_classed && iface && type_node_conforms_to_U (node, iface, FALSE, FALSE);
3950       if (check)
3951         return type_class;
3952       
3953       if (is_classed)
3954         g_warning ("invalid class cast from `%s' to `%s'",
3955                    type_descriptive_name_I (type_class->g_type),
3956                    type_descriptive_name_I (is_a_type));
3957       else
3958         g_warning ("invalid unclassed type `%s' in class cast to `%s'",
3959                    type_descriptive_name_I (type_class->g_type),
3960                    type_descriptive_name_I (is_a_type));
3961     }
3962   else
3963     g_warning ("invalid class cast from (NULL) pointer to `%s'",
3964                type_descriptive_name_I (is_a_type));
3965   return type_class;
3966 }
3967
3968 /**
3969  * g_type_check_instance:
3970  * @instance: A valid #GTypeInstance structure.
3971  *
3972  * Private helper function to aid implementation of the G_TYPE_CHECK_INSTANCE()
3973  * macro.
3974  *
3975  * @Returns:  #TRUE if @instance is valid, #FALSE otherwise.
3976  */
3977 gboolean
3978 g_type_check_instance (GTypeInstance *type_instance)
3979 {
3980   /* this function is just here to make the signal system
3981    * conveniently elaborated on instance checks
3982    */
3983   if (type_instance)
3984     {
3985       if (type_instance->g_class)
3986         {
3987           TypeNode *node = lookup_type_node_I (type_instance->g_class->g_type);
3988           
3989           if (node && node->is_instantiatable)
3990             return TRUE;
3991           
3992           g_warning ("instance of invalid non-instantiatable type `%s'",
3993                      type_descriptive_name_I (type_instance->g_class->g_type));
3994         }
3995       else
3996         g_warning ("instance with invalid (NULL) class pointer");
3997     }
3998   else
3999     g_warning ("invalid (NULL) pointer instance");
4000   
4001   return FALSE;
4002 }
4003
4004 static inline gboolean
4005 type_check_is_value_type_U (GType type)
4006 {
4007   GTypeFlags tflags = G_TYPE_FLAG_VALUE_ABSTRACT;
4008   TypeNode *node;
4009   
4010   /* common path speed up */
4011   node = lookup_type_node_I (type);
4012   if (node && node->mutatable_check_cache)
4013     return TRUE;
4014   
4015   G_READ_LOCK (&type_rw_lock);
4016  restart_check:
4017   if (node)
4018     {
4019       if (node->data && NODE_REFCOUNT (node) > 0 &&
4020           node->data->common.value_table->value_init)
4021         tflags = GPOINTER_TO_UINT (type_get_qdata_L (node, static_quark_type_flags));
4022       else if (NODE_IS_IFACE (node))
4023         {
4024           guint i;
4025           
4026           for (i = 0; i < IFACE_NODE_N_PREREQUISITES (node); i++)
4027             {
4028               GType prtype = IFACE_NODE_PREREQUISITES (node)[i];
4029               TypeNode *prnode = lookup_type_node_I (prtype);
4030               
4031               if (prnode->is_instantiatable)
4032                 {
4033                   type = prtype;
4034                   node = lookup_type_node_I (type);
4035                   goto restart_check;
4036                 }
4037             }
4038         }
4039     }
4040   G_READ_UNLOCK (&type_rw_lock);
4041   
4042   return !(tflags & G_TYPE_FLAG_VALUE_ABSTRACT);
4043 }
4044
4045 gboolean
4046 g_type_check_is_value_type (GType type)
4047 {
4048   return type_check_is_value_type_U (type);
4049 }
4050
4051 gboolean
4052 g_type_check_value (GValue *value)
4053 {
4054   return value && type_check_is_value_type_U (value->g_type);
4055 }
4056
4057 gboolean
4058 g_type_check_value_holds (GValue *value,
4059                           GType   type)
4060 {
4061   return value && type_check_is_value_type_U (value->g_type) && g_type_is_a (value->g_type, type);
4062 }
4063
4064 /**
4065  * g_type_value_table_peek:
4066  * @type: A #GType value.
4067  *
4068  * Returns the location of the #GTypeValueTable associated with @type.
4069  * <emphasis>Note that this function should only be used from source code
4070  * that implements or has internal knowledge of the implementation of
4071  * @type.</emphasis>
4072  *
4073  * Returns: Location of the #GTypeValueTable associated with @type or
4074  *  %NULL if there is no #GTypeValueTable associated with @type.
4075  */
4076 GTypeValueTable*
4077 g_type_value_table_peek (GType type)
4078 {
4079   GTypeValueTable *vtable = NULL;
4080   TypeNode *node = lookup_type_node_I (type);
4081   gboolean has_refed_data, has_table;
4082   TypeData *data;
4083
4084   /* speed up common code path, we're not 100% safe here,
4085    * but we should only get called with referenced types anyway
4086    */
4087   data = node ? node->data : NULL;
4088   if (node && node->mutatable_check_cache)
4089     return data->common.value_table;
4090
4091   G_READ_LOCK (&type_rw_lock);
4092   
4093  restart_table_peek:
4094   has_refed_data = node && node->data && NODE_REFCOUNT (node) > 0;
4095   has_table = has_refed_data && node->data->common.value_table->value_init;
4096   if (has_refed_data)
4097     {
4098       if (has_table)
4099         vtable = node->data->common.value_table;
4100       else if (NODE_IS_IFACE (node))
4101         {
4102           guint i;
4103           
4104           for (i = 0; i < IFACE_NODE_N_PREREQUISITES (node); i++)
4105             {
4106               GType prtype = IFACE_NODE_PREREQUISITES (node)[i];
4107               TypeNode *prnode = lookup_type_node_I (prtype);
4108               
4109               if (prnode->is_instantiatable)
4110                 {
4111                   type = prtype;
4112                   node = lookup_type_node_I (type);
4113                   goto restart_table_peek;
4114                 }
4115             }
4116         }
4117     }
4118   
4119   G_READ_UNLOCK (&type_rw_lock);
4120   
4121   if (vtable)
4122     return vtable;
4123   
4124   if (!node)
4125     g_warning (G_STRLOC ": type id `%" G_GSIZE_FORMAT "' is invalid", type);
4126   if (!has_refed_data)
4127     g_warning ("can't peek value table for type `%s' which is not currently referenced",
4128                type_descriptive_name_I (type));
4129   
4130   return NULL;
4131 }
4132
4133 G_CONST_RETURN gchar*
4134 g_type_name_from_instance (GTypeInstance *instance)
4135 {
4136   if (!instance)
4137     return "<NULL-instance>";
4138   else
4139     return g_type_name_from_class (instance->g_class);
4140 }
4141
4142 G_CONST_RETURN gchar*
4143 g_type_name_from_class (GTypeClass *g_class)
4144 {
4145   if (!g_class)
4146     return "<NULL-class>";
4147   else
4148     return g_type_name (g_class->g_type);
4149 }
4150
4151
4152 /* --- initialization --- */
4153 /**
4154  * g_type_init_with_debug_flags:
4155  * @debug_flags: Bitwise combination of #GTypeDebugFlags values for
4156  *               debugging purposes.
4157  *
4158  * Similar to g_type_init(), but additionally sets debug flags.
4159  */
4160 void
4161 g_type_init_with_debug_flags (GTypeDebugFlags debug_flags)
4162 {
4163   G_LOCK_DEFINE_STATIC (type_init_lock);
4164   const gchar *env_string;
4165   GTypeInfo info;
4166   TypeNode *node;
4167   volatile GType votype;
4168   
4169   G_LOCK (type_init_lock);
4170   
4171   G_WRITE_LOCK (&type_rw_lock);
4172   
4173   if (static_quark_type_flags)
4174     {
4175       G_WRITE_UNLOCK (&type_rw_lock);
4176       G_UNLOCK (type_init_lock);
4177       return;
4178     }
4179   
4180   /* setup GObject library wide debugging flags */
4181   _g_type_debug_flags = debug_flags & G_TYPE_DEBUG_MASK;
4182   env_string = g_getenv ("GOBJECT_DEBUG");
4183   if (env_string != NULL)
4184     {
4185       static GDebugKey debug_keys[] = {
4186         { "objects", G_TYPE_DEBUG_OBJECTS },
4187         { "signals", G_TYPE_DEBUG_SIGNALS },
4188       };
4189       
4190       _g_type_debug_flags |= g_parse_debug_string (env_string,
4191                                                    debug_keys,
4192                                                    sizeof (debug_keys) / sizeof (debug_keys[0]));
4193       env_string = NULL;
4194     }
4195   
4196   /* quarks */
4197   static_quark_type_flags = g_quark_from_static_string ("-g-type-private--GTypeFlags");
4198   static_quark_iface_holder = g_quark_from_static_string ("-g-type-private--IFaceHolder");
4199   static_quark_dependants_array = g_quark_from_static_string ("-g-type-private--dependants-array");
4200   
4201   /* type qname hash table */
4202   static_type_nodes_ht = g_hash_table_new (g_direct_hash, g_direct_equal);
4203   
4204   /* invalid type G_TYPE_INVALID (0)
4205    */
4206   static_fundamental_type_nodes[0] = NULL;
4207   
4208   /* void type G_TYPE_NONE
4209    */
4210   node = type_node_fundamental_new_W (G_TYPE_NONE, g_intern_static_string ("void"), 0);
4211   votype = NODE_TYPE (node);
4212   g_assert (votype == G_TYPE_NONE);
4213   
4214   /* interface fundamental type G_TYPE_INTERFACE (!classed)
4215    */
4216   memset (&info, 0, sizeof (info));
4217   node = type_node_fundamental_new_W (G_TYPE_INTERFACE, g_intern_static_string ("GInterface"), G_TYPE_FLAG_DERIVABLE);
4218   votype = NODE_TYPE (node);
4219   type_data_make_W (node, &info, NULL);
4220   g_assert (votype == G_TYPE_INTERFACE);
4221   
4222   G_WRITE_UNLOCK (&type_rw_lock);
4223   
4224   g_value_c_init ();
4225
4226   /* G_TYPE_TYPE_PLUGIN
4227    */
4228   votype = g_type_plugin_get_type ();
4229   
4230   /* G_TYPE_* value types
4231    */
4232   g_value_types_init ();
4233   
4234   /* G_TYPE_ENUM & G_TYPE_FLAGS
4235    */
4236   g_enum_types_init ();
4237   
4238   /* G_TYPE_BOXED
4239    */
4240   g_boxed_type_init ();
4241   
4242   /* G_TYPE_PARAM
4243    */
4244   g_param_type_init ();
4245   
4246   /* G_TYPE_OBJECT
4247    */
4248   g_object_type_init ();
4249   
4250   /* G_TYPE_PARAM_* pspec types
4251    */
4252   g_param_spec_types_init ();
4253   
4254   /* Value Transformations
4255    */
4256   g_value_transforms_init ();
4257   
4258   /* Signal system
4259    */
4260   g_signal_init ();
4261   
4262   G_UNLOCK (type_init_lock);
4263 }
4264
4265 /**
4266  * g_type_init:
4267  *
4268  * Prior to any use of the type system, g_type_init() has to be called
4269  * to initialize the type system and assorted other code portions
4270  * (such as the various fundamental type implementations or the signal
4271  * system).
4272  */
4273 void
4274 g_type_init (void)
4275 {
4276   g_type_init_with_debug_flags (0);
4277 }
4278
4279 /**
4280  * g_type_class_add_private:
4281  * @g_class: class structure for an instantiatable type
4282  * @private_size: size of private structure.
4283  *
4284  * Registers a private structure for an instantiatable type;
4285  * when an object is allocated, the private structures for
4286  * the type and all of its parent types are allocated
4287  * sequentially in the same memory block as the public
4288  * structures. This function should be called in the
4289  * type's class_init() function. The private structure can
4290  * be retrieved using the G_TYPE_INSTANCE_GET_PRIVATE() macro.
4291  * The following example shows attaching a private structure
4292  * <structname>MyObjectPrivate</structname> to an object
4293  * <structname>MyObject</structname> defined in the standard GObject
4294  * fashion.
4295  *
4296  * |[
4297  * typedef struct _MyObjectPrivate MyObjectPrivate;
4298  *
4299  * struct _MyObjectPrivate {
4300  *   int some_field;
4301  * };
4302  *
4303  * #define MY_OBJECT_GET_PRIVATE(o)  \
4304  *    (G_TYPE_INSTANCE_GET_PRIVATE ((o), MY_TYPE_OBJECT, MyObjectPrivate))
4305  *
4306  * static void
4307  * my_object_class_init (MyObjectClass *klass)
4308  * {
4309  *   g_type_class_add_private (klass, sizeof (MyObjectPrivate));
4310  * }
4311  *
4312  * static int
4313  * my_object_get_some_field (MyObject *my_object)
4314  * {
4315  *   MyObjectPrivate *priv = MY_OBJECT_GET_PRIVATE (my_object);
4316  *
4317  *   return priv->some_field;
4318  * }
4319  * ]|
4320  *
4321  * Since: 2.4
4322  */
4323 void
4324 g_type_class_add_private (gpointer g_class,
4325                           gsize    private_size)
4326 {
4327   GType instance_type = ((GTypeClass *)g_class)->g_type;
4328   TypeNode *node = lookup_type_node_I (instance_type);
4329   gsize offset;
4330
4331   g_return_if_fail (private_size > 0);
4332
4333   if (!node || !node->is_instantiatable || !node->data || node->data->class.class != g_class)
4334     {
4335       g_warning ("cannot add private field to invalid (non-instantiatable) type '%s'",
4336                  type_descriptive_name_I (instance_type));
4337       return;
4338     }
4339
4340   if (NODE_PARENT_TYPE (node))
4341     {
4342       TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
4343       if (node->data->instance.private_size != pnode->data->instance.private_size)
4344         {
4345           g_warning ("g_type_add_private() called multiple times for the same type");
4346           return;
4347         }
4348     }
4349   
4350   G_WRITE_LOCK (&type_rw_lock);
4351
4352   offset = ALIGN_STRUCT (node->data->instance.private_size);
4353   node->data->instance.private_size = offset + private_size;
4354   
4355   G_WRITE_UNLOCK (&type_rw_lock);
4356 }
4357
4358 gpointer
4359 g_type_instance_get_private (GTypeInstance *instance,
4360                              GType          private_type)
4361 {
4362   TypeNode *instance_node;
4363   TypeNode *private_node;
4364   TypeNode *parent_node;
4365   GTypeClass *class;
4366   gsize offset;
4367
4368   g_return_val_if_fail (instance != NULL && instance->g_class != NULL, NULL);
4369
4370   /* while instances are initialized, their class pointers change,
4371    * so figure the instances real class first
4372    */
4373   class = instance_real_class_get (instance);
4374   if (!class)
4375     class = instance->g_class;
4376
4377   instance_node = lookup_type_node_I (class->g_type);
4378   if (G_UNLIKELY (!instance_node || !instance_node->is_instantiatable))
4379     {
4380       g_warning ("instance of invalid non-instantiatable type `%s'",
4381                  type_descriptive_name_I (instance->g_class->g_type));
4382       return NULL;
4383     }
4384
4385   private_node = lookup_type_node_I (private_type);
4386   if (G_UNLIKELY (!private_node || !NODE_IS_ANCESTOR (private_node, instance_node)))
4387     {
4388       g_warning ("attempt to retrieve private data for invalid type '%s'",
4389                  type_descriptive_name_I (private_type));
4390       return NULL;
4391     }
4392
4393   /* Note that we don't need a read lock, since instance existing
4394    * means that the instance class and all parent classes
4395    * exist, so the node->data, node->data->instance.instance_size,
4396    * and node->data->instance.private_size are not going to be changed.
4397    * for any of the relevant types.
4398    */
4399
4400   offset = ALIGN_STRUCT (instance_node->data->instance.instance_size);
4401
4402   if (NODE_PARENT_TYPE (private_node))
4403     {
4404       parent_node = lookup_type_node_I (NODE_PARENT_TYPE (private_node));
4405       g_assert (parent_node->data && NODE_REFCOUNT (parent_node) > 0);
4406
4407       if (G_UNLIKELY (private_node->data->instance.private_size == parent_node->data->instance.private_size))
4408         {
4409           g_warning ("g_type_instance_get_private() requires a prior call to g_type_class_add_private()");
4410           return NULL;
4411         }
4412
4413       offset += ALIGN_STRUCT (parent_node->data->instance.private_size);
4414     }
4415
4416   return G_STRUCT_MEMBER_P (instance, offset);
4417 }
4418
4419 #define __G_TYPE_C__
4420 #include "gobjectaliasdef.c"