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