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