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