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