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