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