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