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