gtype.c 126 KB
Newer Older
1
/* GObject - GLib Type, Object, Parameter and Signal Library
2
 * Copyright (C) 1998-1999, 2000-2001 Tim Janik and Red Hat, Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

/*
 * MT safe
 */

#include "config.h"

#include <string.h>

#include "gtype.h"
#include "gtypeplugin.h"
#include "gvaluecollector.h"
#include "gbsearcharray.h"
#include "gobjectalias.h"


Stefan Kost's avatar
Stefan Kost committed
35 36
/**
 * SECTION:gtype
Matthias Clasen's avatar
Matthias Clasen committed
37 38 39
 * @short_description: The GLib Runtime type identification and
 *     management system
 * @title:Type Information
40
 *
Stefan Kost's avatar
Stefan Kost committed
41 42 43 44 45
 * The GType API is the foundation of the GObject system.  It provides the
 * facilities for registering and managing all fundamental data types,
 * user-defined object and interface types.  Before using any GType
 * or GObject functions, g_type_init() must be called to initialize the
 * type system.
46
 *
Stefan Kost's avatar
Stefan Kost committed
47 48 49 50 51 52 53 54 55
 * For type creation and registration purposes, all types fall into one of
 * two categories: static or dynamic.  Static types are never loaded or
 * unloaded at run-time as dynamic types may be.  Static types are created
 * with g_type_register_static() that gets type specific information passed
 * in via a #GTypeInfo structure.
 * Dynamic types are created with g_type_register_dynamic() which takes a
 * #GTypePlugin structure instead. The remaining type information (the
 * #GTypeInfo structure) is retrieved during runtime through #GTypePlugin
 * and the g_type_plugin_*() API.
56 57
 * These registration functions are usually called only once from a
 * function whose only purpose is to return the type identifier for a
Stefan Kost's avatar
Stefan Kost committed
58 59 60 61 62 63 64
 * specific class.  Once the type (or class or interface) is registered,
 * it may be instantiated, inherited, or implemented depending on exactly
 * what sort of type it is.
 * There is also a third registration function for registering fundamental
 * types called g_type_register_fundamental() which requires both a #GTypeInfo
 * structure and a #GTypeFundamentalInfo structure but it is seldom used
 * since most fundamental types are predefined rather than user-defined.
65
 *
Stefan Kost's avatar
Stefan Kost committed
66 67 68 69 70 71
 * A final word about type names.
 * Such an identifier needs to be at least three characters long. There is no
 * upper length limit. The first character needs to be a letter (a-z or A-Z)
 * or an underscore '_'. Subsequent characters can be letters, numbers or
 * any of '-_+'.
 */
72 73 74 75 76 77


/* NOTE: some functions (some internal variants and exported ones)
 * invalidate data portions of the TypeNodes. if external functions/callbacks
 * are called, pointers to memory maintained by TypeNodes have to be looked up
 * again. this affects most of the struct TypeNode fields, e.g. ->children or
78 79 80
 * CLASSED_NODE_IFACES_ENTRIES() respectively IFACE_NODE_PREREQUISITES() (but
 * not ->supers[]), as all those memory portions can get realloc()ed during
 * callback invocation.
81 82 83 84
 *
 * TODO:
 * - g_type_from_name() should do an ordered array lookup after fetching the
 *   the quark, instead of a second hashtable lookup.
85 86 87 88 89 90 91 92 93 94 95 96 97 98
 *
 * LOCKING:
 * lock handling issues when calling static functions are indicated by
 * uppercase letter postfixes, all static functions have to have
 * one of the below postfixes:
 * - _I:	[Indifferent about locking]
 *   function doesn't care about locks at all
 * - _U:	[Unlocked invocation]
 *   no read or write lock has to be held across function invocation
 *   (locks may be acquired and released during invocation though)
 * - _L:	[Locked invocation]
 *   a write lock or more than 0 read locks have to be held across
 *   function invocation
 * - _W:	[Write-locked invocation]
99
 *   a write lock has to be held across function invocation
100 101 102
 * - _Wm:	[Write-locked invocation, mutatable]
 *   like _W, but the write lock might be released and reacquired
 *   during invocation, watch your pointers
103 104
 * - _WmREC:    [Write-locked invocation, mutatable, recursive]
 *   like _Wm, but also acquires recursive mutex class_init_rec_mutex
105 106
 */

107 108 109 110 111 112
#ifdef LOCK_DEBUG
#define G_READ_LOCK(rw_lock)    do { g_printerr (G_STRLOC ": readL++\n"); g_static_rw_lock_reader_lock (rw_lock); } while (0)
#define G_READ_UNLOCK(rw_lock)  do { g_printerr (G_STRLOC ": readL--\n"); g_static_rw_lock_reader_unlock (rw_lock); } while (0)
#define G_WRITE_LOCK(rw_lock)   do { g_printerr (G_STRLOC ": writeL++\n"); g_static_rw_lock_writer_lock (rw_lock); } while (0)
#define G_WRITE_UNLOCK(rw_lock) do { g_printerr (G_STRLOC ": writeL--\n"); g_static_rw_lock_writer_unlock (rw_lock); } while (0)
#else
113 114 115 116
#define G_READ_LOCK(rw_lock)    g_static_rw_lock_reader_lock (rw_lock)
#define G_READ_UNLOCK(rw_lock)  g_static_rw_lock_reader_unlock (rw_lock)
#define G_WRITE_LOCK(rw_lock)   g_static_rw_lock_writer_lock (rw_lock)
#define G_WRITE_UNLOCK(rw_lock) g_static_rw_lock_writer_unlock (rw_lock)
117
#endif
118
#define	INVALID_RECURSION(func, arg, type_name) G_STMT_START{ \
119
    static const gchar _action[] = " invalidly modified type ";  \
Havoc Pennington's avatar
Havoc Pennington committed
120
    gpointer _arg = (gpointer) (arg); const gchar *_tname = (type_name), *_fname = (func); \
121 122 123 124 125
    if (_arg) \
      g_error ("%s(%p)%s`%s'", _fname, _arg, _action, _tname); \
    else \
      g_error ("%s()%s`%s'", _fname, _action, _tname); \
}G_STMT_END
126 127 128 129 130 131 132 133 134 135
#define	g_return_val_if_uninitialized(condition, init_function, return_value) G_STMT_START{	\
  if (!(condition))										\
    {												\
      g_log (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL,						\
	     "%s: initialization assertion failed, use %s() prior to this function",		\
	     G_STRLOC, G_STRINGIFY (init_function));						\
      return (return_value);									\
    }												\
}G_STMT_END

136 137 138 139 140 141 142 143
#ifdef  G_ENABLE_DEBUG
#define DEBUG_CODE(debug_type, code_block)  G_STMT_START {    \
    if (_g_type_debug_flags & G_TYPE_DEBUG_ ## debug_type) \
      { code_block; }                                     \
} G_STMT_END
#else /* !G_ENABLE_DEBUG */
#define DEBUG_CODE(debug_type, code_block)  /* code_block */
#endif  /* G_ENABLE_DEBUG */
144

145 146 147 148
#define TYPE_FUNDAMENTAL_FLAG_MASK (G_TYPE_FLAG_CLASSED | \
				    G_TYPE_FLAG_INSTANTIATABLE | \
				    G_TYPE_FLAG_DERIVABLE | \
				    G_TYPE_FLAG_DEEP_DERIVABLE)
149
#define	TYPE_FLAG_MASK		   (G_TYPE_FLAG_ABSTRACT | G_TYPE_FLAG_VALUE_ABSTRACT)
150 151 152
#define	SIZEOF_FUNDAMENTAL_INFO	   ((gssize) MAX (MAX (sizeof (GTypeFundamentalInfo), \
						       sizeof (gpointer)), \
                                                  sizeof (glong)))
153

154 155 156 157 158 159 160 161 162 163 164 165
/* The 2*sizeof(size_t) alignment here is borrowed from
 * GNU libc, so it should be good most everywhere.
 * It is more conservative than is needed on some 64-bit
 * platforms, but ia64 does require a 16-byte alignment.
 * The SIMD extensions for x86 and ppc32 would want a
 * larger alignment than this, but we don't need to
 * do better than malloc.
 */
#define STRUCT_ALIGNMENT (2 * sizeof (gsize))
#define ALIGN_STRUCT(offset) \
      ((offset + (STRUCT_ALIGNMENT - 1)) & -STRUCT_ALIGNMENT)

166

167
/* --- typedefs --- */
168 169 170 171 172 173 174 175 176 177 178
typedef struct _TypeNode        TypeNode;
typedef struct _CommonData      CommonData;
typedef struct _IFaceData       IFaceData;
typedef struct _ClassData       ClassData;
typedef struct _InstanceData    InstanceData;
typedef union  _TypeData        TypeData;
typedef struct _IFaceEntry      IFaceEntry;
typedef struct _IFaceHolder	IFaceHolder;


/* --- prototypes --- */
179
static inline GTypeFundamentalInfo*	type_node_fundamental_info_I	(TypeNode		*node);
180
static	      void			type_add_flags_W		(TypeNode		*node,
181
									 GTypeFlags		 flags);
182
static	      void			type_data_make_W		(TypeNode		*node,
183 184
									 const GTypeInfo	*info,
									 const GTypeValueTable	*value_table);
185
static inline void			type_data_ref_Wm		(TypeNode		*node);
186
static inline void			type_data_unref_WmREC		(TypeNode		*node,
187
									 gboolean		 uncached);
188
static void				type_data_last_unref_Wm		(GType			 type,
189
									 gboolean		 uncached);
190 191 192 193 194
static inline gpointer			type_get_qdata_L		(TypeNode		*node,
									 GQuark			 quark);
static inline void			type_set_qdata_W		(TypeNode		*node,
									 GQuark			 quark,
									 gpointer		 data);
195 196
static IFaceHolder*			type_iface_peek_holder_L	(TypeNode		*iface,
									 GType			 instance_type);
197 198 199 200
static gboolean                         type_iface_vtable_base_init_Wm  (TypeNode               *iface,
                                                                         TypeNode               *node);
static void                             type_iface_vtable_iface_init_Wm (TypeNode               *iface,
                                                                         TypeNode               *node);
201 202
static gboolean				type_node_is_a_L		(TypeNode		*node,
									 TypeNode		*iface_node);
203 204


205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
/* --- enumeration --- */

/* The InitState enumeration is used to track the progress of initializing
 * both classes and interface vtables. Keeping the state of initialization
 * is necessary to handle new interfaces being added while we are initializing
 * the class or other interfaces.
 */
typedef enum
{
  UNINITIALIZED,
  BASE_CLASS_INIT,
  BASE_IFACE_INIT,
  CLASS_INIT,
  IFACE_INIT,
  INITIALIZED
} InitState;

222 223 224 225 226 227
/* --- structures --- */
struct _TypeNode
{
  GTypePlugin *plugin;
  guint        n_children : 12;
  guint        n_supers : 8;
228
  guint        _prot_n_ifaces_prerequisites : 9;
229 230
  guint        is_classed : 1;
  guint        is_instantiatable : 1;
231
  guint        mutatable_check_cache : 1;	/* combines some common path checks */
232
  GType       *children;
233
  TypeData * volatile data;
234
  GQuark       qname;
235
  GData       *global_gdata;
236
  union {
237 238 239
    IFaceEntry  *iface_entries;		/* for !iface types */
    GType       *prerequisistes;
  } _prot;
240 241
  GType        supers[1]; /* flexible array */
};
242

243 244 245 246 247 248 249
#define SIZEOF_BASE_TYPE_NODE()			(G_STRUCT_OFFSET (TypeNode, supers))
#define MAX_N_SUPERS				(255)
#define MAX_N_CHILDREN				(4095)
#define MAX_N_IFACES				(511)
#define	MAX_N_PREREQUISITES			(MAX_N_IFACES)
#define NODE_TYPE(node)				(node->supers[0])
#define NODE_PARENT_TYPE(node)			(node->supers[1])
250
#define NODE_FUNDAMENTAL_TYPE(node)		(node->supers[node->n_supers])
251
#define NODE_NAME(node)				(g_quark_to_string (node->qname))
252
#define	NODE_IS_IFACE(node)			(NODE_FUNDAMENTAL_TYPE (node) == G_TYPE_INTERFACE)
253 254 255 256 257 258 259 260
#define	CLASSED_NODE_N_IFACES(node)		((node)->_prot_n_ifaces_prerequisites)
#define	CLASSED_NODE_IFACES_ENTRIES(node)	((node)->_prot.iface_entries)
#define	IFACE_NODE_N_PREREQUISITES(node)	((node)->_prot_n_ifaces_prerequisites)
#define	IFACE_NODE_PREREQUISITES(node)		((node)->_prot.prerequisistes)
#define	iface_node_get_holders_L(node)		((IFaceHolder*) type_get_qdata_L ((node), static_quark_iface_holder))
#define	iface_node_set_holders_W(node, holders)	(type_set_qdata_W ((node), static_quark_iface_holder, (holders)))
#define	iface_node_get_dependants_array_L(n)	((GType*) type_get_qdata_L ((n), static_quark_dependants_array))
#define	iface_node_set_dependants_array_W(n,d)	(type_set_qdata_W ((n), static_quark_dependants_array, (d)))
261 262
#define	TYPE_ID_MASK				((GType) ((1 << G_TYPE_FUNDAMENTAL_SHIFT) - 1))

263 264 265 266
#define NODE_IS_ANCESTOR(ancestor, node)                                                    \
        ((ancestor)->n_supers <= (node)->n_supers &&                                        \
	 (node)->supers[(node)->n_supers - (ancestor)->n_supers] == NODE_TYPE (ancestor))

267 268 269 270 271 272 273 274

struct _IFaceHolder
{
  GType           instance_type;
  GInterfaceInfo *info;
  GTypePlugin    *plugin;
  IFaceHolder    *next;
};
275

276 277 278 279
struct _IFaceEntry
{
  GType           iface_type;
  GTypeInterface *vtable;
280
  InitState       init_state;
281
};
282

283 284
struct _CommonData
{
285 286
  guint             ref_count;
  GTypeValueTable  *value_table;
287
};
288

289 290 291
struct _IFaceData
{
  CommonData         common;
292
  guint16            vtable_size;
293 294
  GBaseInitFunc      vtable_init_base;
  GBaseFinalizeFunc  vtable_finalize_base;
295 296 297 298
  GClassInitFunc     dflt_init;
  GClassFinalizeFunc dflt_finalize;
  gconstpointer      dflt_data;
  gpointer           dflt_vtable;
299
};
300

301 302 303
struct _ClassData
{
  CommonData         common;
304
  guint16            class_size;
305
  guint              init_state : 4;
306 307 308 309 310 311 312
  GBaseInitFunc      class_init_base;
  GBaseFinalizeFunc  class_finalize_base;
  GClassInitFunc     class_init;
  GClassFinalizeFunc class_finalize;
  gconstpointer      class_data;
  gpointer           class;
};
313

314 315 316
struct _InstanceData
{
  CommonData         common;
317
  guint16            class_size;
318
  guint              init_state : 4;
319 320 321 322 323 324 325
  GBaseInitFunc      class_init_base;
  GBaseFinalizeFunc  class_finalize_base;
  GClassInitFunc     class_init;
  GClassFinalizeFunc class_finalize;
  gconstpointer      class_data;
  gpointer           class;
  guint16            instance_size;
326
  guint16            private_size;
327 328 329
  guint16            n_preallocs;
  GInstanceInitFunc  instance_init;
};
330

331 332 333 334 335 336 337
union _TypeData
{
  CommonData         common;
  IFaceData          iface;
  ClassData          class;
  InstanceData       instance;
};
338

339 340 341 342
typedef struct {
  gpointer            cache_data;
  GTypeClassCacheFunc cache_func;
} ClassCacheFunc;
343

344 345 346 347
typedef struct {
  gpointer                check_data;
  GTypeInterfaceCheckFunc check_func;
} IFaceCheckFunc;
348 349 350


/* --- variables --- */
351 352
static GStaticRWLock   type_rw_lock = G_STATIC_RW_LOCK_INIT;
static GStaticRecMutex class_init_rec_mutex = G_STATIC_REC_MUTEX_INIT;
353 354
static guint           static_n_class_cache_funcs = 0;
static ClassCacheFunc *static_class_cache_funcs = NULL;
355 356
static guint           static_n_iface_check_funcs = 0;
static IFaceCheckFunc *static_iface_check_funcs = NULL;
357
static GQuark          static_quark_type_flags = 0;
358 359
static GQuark          static_quark_iface_holder = 0;
static GQuark          static_quark_dependants_array = 0;
360
GTypeDebugFlags	       _g_type_debug_flags = 0;
361 362 363


/* --- type nodes --- */
364
static GHashTable       *static_type_nodes_ht = NULL;
365
static TypeNode		*static_fundamental_type_nodes[(G_TYPE_FUNDAMENTAL_MAX >> G_TYPE_FUNDAMENTAL_SHIFT) + 1] = { NULL, };
366
static GType		 static_fundamental_next = G_TYPE_RESERVED_USER_FIRST;
367 368

static inline TypeNode*
369
lookup_type_node_I (register GType utype)
370
{
371 372
  if (utype > G_TYPE_FUNDAMENTAL_MAX)
    return (TypeNode*) (utype & ~TYPE_ID_MASK);
373
  else
374
    return static_fundamental_type_nodes[utype >> G_TYPE_FUNDAMENTAL_SHIFT];
375 376 377
}

static TypeNode*
378 379 380 381 382
type_node_any_new_W (TypeNode             *pnode,
		     GType                 ftype,
		     const gchar          *name,
		     GTypePlugin          *plugin,
		     GTypeFundamentalFlags type_flags)
383
{
384
  guint n_supers;
385 386 387
  GType type;
  TypeNode *node;
  guint i, node_size = 0;
388 389 390
  
  n_supers = pnode ? pnode->n_supers + 1 : 0;
  
391
  if (!pnode)
392
    node_size += SIZEOF_FUNDAMENTAL_INFO;	      /* fundamental type info */
393
  node_size += SIZEOF_BASE_TYPE_NODE ();	      /* TypeNode structure */
394
  node_size += (sizeof (GType) * (1 + n_supers + 1)); /* self + ancestors + (0) for ->supers[] */
395
  node = g_malloc0 (node_size);
396
  if (!pnode)					      /* offset fundamental types */
397 398
    {
      node = G_STRUCT_MEMBER_P (node, SIZEOF_FUNDAMENTAL_INFO);
399
      static_fundamental_type_nodes[ftype >> G_TYPE_FUNDAMENTAL_SHIFT] = node;
400 401 402 403
      type = ftype;
    }
  else
    type = (GType) node;
404
  
405 406
  g_assert ((type & TYPE_ID_MASK) == 0);
  
407 408 409 410 411
  node->n_supers = n_supers;
  if (!pnode)
    {
      node->supers[0] = type;
      node->supers[1] = 0;
412
      
413 414
      node->is_classed = (type_flags & G_TYPE_FLAG_CLASSED) != 0;
      node->is_instantiatable = (type_flags & G_TYPE_FLAG_INSTANTIATABLE) != 0;
415
      
416 417 418 419 420
      if (NODE_IS_IFACE (node))
	{
          IFACE_NODE_N_PREREQUISITES (node) = 0;
	  IFACE_NODE_PREREQUISITES (node) = NULL;
	}
421
      else
422 423 424 425
	{
	  CLASSED_NODE_N_IFACES (node) = 0;
	  CLASSED_NODE_IFACES_ENTRIES (node) = NULL;
	}
426 427 428 429
    }
  else
    {
      node->supers[0] = type;
430
      memcpy (node->supers + 1, pnode->supers, sizeof (GType) * (1 + pnode->n_supers + 1));
431
      
432 433
      node->is_classed = pnode->is_classed;
      node->is_instantiatable = pnode->is_instantiatable;
434
      
435
      if (NODE_IS_IFACE (node))
436
	{
437 438
	  IFACE_NODE_N_PREREQUISITES (node) = 0;
	  IFACE_NODE_PREREQUISITES (node) = NULL;
439 440 441
	}
      else
	{
442
	  guint j;
443
	  
444 445 446 447
	  CLASSED_NODE_N_IFACES (node) = CLASSED_NODE_N_IFACES (pnode);
	  CLASSED_NODE_IFACES_ENTRIES (node) = g_memdup (CLASSED_NODE_IFACES_ENTRIES (pnode),
							 sizeof (CLASSED_NODE_IFACES_ENTRIES (pnode)[0]) *
							 CLASSED_NODE_N_IFACES (node));
448
	  for (j = 0; j < CLASSED_NODE_N_IFACES (node); j++)
449 450 451 452
	    {
	      CLASSED_NODE_IFACES_ENTRIES (node)[j].vtable = NULL;
	      CLASSED_NODE_IFACES_ENTRIES (node)[j].init_state = UNINITIALIZED;
	    }
453 454 455 456 457 458
	}
      
      i = pnode->n_children++;
      pnode->children = g_renew (GType, pnode->children, pnode->n_children);
      pnode->children[i] = type;
    }
459
  
460 461 462 463 464
  node->plugin = plugin;
  node->n_children = 0;
  node->children = NULL;
  node->data = NULL;
  node->qname = g_quark_from_string (name);
465 466 467
  node->global_gdata = NULL;
  
  g_hash_table_insert (static_type_nodes_ht,
468
		       GUINT_TO_POINTER (node->qname),
469
		       (gpointer) type);
470 471 472 473
  return node;
}

static inline GTypeFundamentalInfo*
474
type_node_fundamental_info_I (TypeNode *node)
475
{
476
  GType ftype = NODE_FUNDAMENTAL_TYPE (node);
477 478
  
  if (ftype != NODE_TYPE (node))
479
    node = lookup_type_node_I (ftype);
480
  
481
  return node ? G_STRUCT_MEMBER_P (node, -SIZEOF_FUNDAMENTAL_INFO) : NULL;
482 483 484
}

static TypeNode*
485 486 487
type_node_fundamental_new_W (GType                 ftype,
			     const gchar          *name,
			     GTypeFundamentalFlags type_flags)
488 489 490
{
  GTypeFundamentalInfo *finfo;
  TypeNode *node;
491 492
  
  g_assert ((ftype & TYPE_ID_MASK) == 0);
493
  g_assert (ftype <= G_TYPE_FUNDAMENTAL_MAX);
494
  
495 496
  if (ftype >> G_TYPE_FUNDAMENTAL_SHIFT == static_fundamental_next)
    static_fundamental_next++;
497
  
498
  type_flags &= TYPE_FUNDAMENTAL_FLAG_MASK;
499 500 501
  
  node = type_node_any_new_W (NULL, ftype, name, NULL, type_flags);
  
502
  finfo = type_node_fundamental_info_I (node);
503
  finfo->type_flags = type_flags;
504
  
505 506 507 508
  return node;
}

static TypeNode*
509 510 511 512
type_node_new_W (TypeNode    *pnode,
		 const gchar *name,
		 GTypePlugin *plugin)
     
513 514 515 516
{
  g_assert (pnode);
  g_assert (pnode->n_supers < MAX_N_SUPERS);
  g_assert (pnode->n_children < MAX_N_CHILDREN);
517
  
518
  return type_node_any_new_W (pnode, NODE_FUNDAMENTAL_TYPE (pnode), name, plugin, 0);
519 520 521
}

static inline IFaceEntry*
522
type_lookup_iface_entry_L (TypeNode *node,
523
			   TypeNode *iface_node)
524
{
525
  if (NODE_IS_IFACE (iface_node) && CLASSED_NODE_N_IFACES (node))
526
    {
527 528 529
      IFaceEntry *ifaces = CLASSED_NODE_IFACES_ENTRIES (node) - 1;
      guint n_ifaces = CLASSED_NODE_N_IFACES (node);
      GType iface_type = NODE_TYPE (iface_node);
530
      
531
      do
532 533 534
	{
	  guint i;
	  IFaceEntry *check;
535
	  
536
	  i = (n_ifaces + 1) >> 1;
537 538 539 540 541 542 543 544 545 546 547 548 549
	  check = ifaces + i;
	  if (iface_type == check->iface_type)
	    return check;
	  else if (iface_type > check->iface_type)
	    {
	      n_ifaces -= i;
	      ifaces = check;
	    }
	  else /* if (iface_type < check->iface_type) */
	    n_ifaces = i - 1;
	}
      while (n_ifaces);
    }
550
  
551 552 553
  return NULL;
}

554
static inline gboolean
555 556
type_lookup_prerequisite_L (TypeNode *iface,
			    GType     prerequisite_type)
557 558 559 560 561
{
  if (NODE_IS_IFACE (iface) && IFACE_NODE_N_PREREQUISITES (iface))
    {
      GType *prerequisites = IFACE_NODE_PREREQUISITES (iface) - 1;
      guint n_prerequisites = IFACE_NODE_N_PREREQUISITES (iface);
562
      
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
      do
	{
	  guint i;
	  GType *check;
	  
	  i = (n_prerequisites + 1) >> 1;
	  check = prerequisites + i;
	  if (prerequisite_type == *check)
	    return TRUE;
	  else if (prerequisite_type > *check)
	    {
	      n_prerequisites -= i;
	      prerequisites = check;
	    }
	  else /* if (prerequisite_type < *check) */
	    n_prerequisites = i - 1;
	}
      while (n_prerequisites);
    }
  return FALSE;
}

585
static gchar*
586
type_descriptive_name_I (GType type)
587 588 589
{
  if (type)
    {
590
      TypeNode *node = lookup_type_node_I (type);
591 592
      
      return node ? NODE_NAME (node) : "<unknown>";
593 594 595 596 597 598 599 600
    }
  else
    return "<invalid>";
}


/* --- type consistency checks --- */
static gboolean
601 602 603 604
check_plugin_U (GTypePlugin *plugin,
		gboolean     need_complete_type_info,
		gboolean     need_complete_interface_info,
		const gchar *type_name)
605
{
606 607
  /* G_IS_TYPE_PLUGIN() and G_TYPE_PLUGIN_GET_CLASS() are external calls: _U 
   */
608 609 610 611 612 613
  if (!plugin)
    {
      g_warning ("plugin handle for type `%s' is NULL",
		 type_name);
      return FALSE;
    }
614
  if (!G_IS_TYPE_PLUGIN (plugin))
615
    {
616 617
      g_warning ("plugin pointer (%p) for type `%s' is invalid",
		 plugin, type_name);
618 619
      return FALSE;
    }
620
  if (need_complete_type_info && !G_TYPE_PLUGIN_GET_CLASS (plugin)->complete_type_info)
621 622 623 624 625
    {
      g_warning ("plugin for type `%s' has no complete_type_info() implementation",
		 type_name);
      return FALSE;
    }
626
  if (need_complete_interface_info && !G_TYPE_PLUGIN_GET_CLASS (plugin)->complete_interface_info)
627 628 629 630 631 632 633 634 635
    {
      g_warning ("plugin for type `%s' has no complete_interface_info() implementation",
		 type_name);
      return FALSE;
    }
  return TRUE;
}

static gboolean
636
check_type_name_I (const gchar *type_name)
637
{
638
  static const gchar extra_chars[] = "-_+";
639 640
  const gchar *p = type_name;
  gboolean name_valid;
641
  
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  if (!type_name[0] || !type_name[1] || !type_name[2])
    {
      g_warning ("type name `%s' is too short", type_name);
      return FALSE;
    }
  /* check the first letter */
  name_valid = (p[0] >= 'A' && p[0] <= 'Z') || (p[0] >= 'a' && p[0] <= 'z') || p[0] == '_';
  for (p = type_name + 1; *p; p++)
    name_valid &= ((p[0] >= 'A' && p[0] <= 'Z') ||
		   (p[0] >= 'a' && p[0] <= 'z') ||
		   (p[0] >= '0' && p[0] <= '9') ||
		   strchr (extra_chars, p[0]));
  if (!name_valid)
    {
      g_warning ("type name `%s' contains invalid characters", type_name);
      return FALSE;
    }
  if (g_type_from_name (type_name))
    {
      g_warning ("cannot register existing type `%s'", type_name);
      return FALSE;
    }
664
  
665 666 667 668
  return TRUE;
}

static gboolean
669
check_derivation_I (GType        parent_type,
670
		    const gchar *type_name)
671
{
672 673
  TypeNode *pnode;
  GTypeFundamentalInfo* finfo;
674
  
675
  pnode = lookup_type_node_I (parent_type);
676 677 678 679
  if (!pnode)
    {
      g_warning ("cannot derive type `%s' from invalid parent type `%s'",
		 type_name,
680
		 type_descriptive_name_I (parent_type));
681 682
      return FALSE;
    }
683
  finfo = type_node_fundamental_info_I (pnode);
684 685 686 687 688 689 690 691 692
  /* ensure flat derivability */
  if (!(finfo->type_flags & G_TYPE_FLAG_DERIVABLE))
    {
      g_warning ("cannot derive `%s' from non-derivable parent type `%s'",
		 type_name,
		 NODE_NAME (pnode));
      return FALSE;
    }
  /* ensure deep derivability */
693
  if (parent_type != NODE_FUNDAMENTAL_TYPE (pnode) &&
694 695 696 697 698 699 700 701 702 703 704
      !(finfo->type_flags & G_TYPE_FLAG_DEEP_DERIVABLE))
    {
      g_warning ("cannot derive `%s' from non-fundamental parent type `%s'",
		 type_name,
		 NODE_NAME (pnode));
      return FALSE;
    }
  
  return TRUE;
}

705 706 707 708 709
static gboolean
check_collect_format_I (const gchar *collect_format)
{
  const gchar *p = collect_format;
  gchar valid_format[] = { G_VALUE_COLLECT_INT, G_VALUE_COLLECT_LONG,
710 711
			   G_VALUE_COLLECT_INT64, G_VALUE_COLLECT_DOUBLE,
			   G_VALUE_COLLECT_POINTER, 0 };
712
  
713 714 715 716 717 718
  while (*p)
    if (!strchr (valid_format, *p++))
      return FALSE;
  return p - collect_format <= G_VALUE_COLLECT_FORMAT_MAX_LENGTH;
}

719
static gboolean
720 721
check_value_table_I (const gchar           *type_name,
		     const GTypeValueTable *value_table)
722 723 724 725 726 727
{
  if (!value_table)
    return FALSE;
  else if (value_table->value_init == NULL)
    {
      if (value_table->value_free || value_table->value_copy ||
728
	  value_table->value_peek_pointer ||
729 730
	  value_table->collect_format || value_table->collect_value ||
	  value_table->lcopy_format || value_table->lcopy_value)
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
	g_warning ("cannot handle uninitializable values of type `%s'",
		   type_name);
      return FALSE;
    }
  else /* value_table->value_init != NULL */
    {
      if (!value_table->value_free)
	{
	  /* +++ optional +++
	   * g_warning ("missing `value_free()' for type `%s'", type_name);
	   * return FALSE;
	   */
	}
      if (!value_table->value_copy)
	{
	  g_warning ("missing `value_copy()' for type `%s'", type_name);
	  return FALSE;
	}
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
      if ((value_table->collect_format || value_table->collect_value) &&
	  (!value_table->collect_format || !value_table->collect_value))
	{
	  g_warning ("one of `collect_format' and `collect_value()' is unspecified for type `%s'",
		     type_name);
	  return FALSE;
	}
      if (value_table->collect_format && !check_collect_format_I (value_table->collect_format))
	{
	  g_warning ("the `%s' specification for type `%s' is too long or invalid",
		     "collect_format",
		     type_name);
	  return FALSE;
	}
      if ((value_table->lcopy_format || value_table->lcopy_value) &&
	  (!value_table->lcopy_format || !value_table->lcopy_value))
765
	{
766
	  g_warning ("one of `lcopy_format' and `lcopy_value()' is unspecified for type `%s'",
767 768 769
		     type_name);
	  return FALSE;
	}
770
      if (value_table->lcopy_format && !check_collect_format_I (value_table->lcopy_format))
771
	{
772 773
	  g_warning ("the `%s' specification for type `%s' is too long or invalid",
		     "lcopy_format",
774 775 776 777 778 779 780 781
		     type_name);
	  return FALSE;
	}
    }
  return TRUE;
}

static gboolean
782
check_type_info_I (TypeNode        *pnode,
783 784 785
		   GType            ftype,
		   const gchar     *type_name,
		   const GTypeInfo *info)
786
{
787
  GTypeFundamentalInfo *finfo = type_node_fundamental_info_I (lookup_type_node_I (ftype));
788
  gboolean is_interface = ftype == G_TYPE_INTERFACE;
789 790
  
  g_assert (ftype <= G_TYPE_FUNDAMENTAL_MAX && !(ftype & TYPE_ID_MASK));
791
  
792 793 794 795 796 797 798 799 800 801 802 803 804 805
  /* check instance members */
  if (!(finfo->type_flags & G_TYPE_FLAG_INSTANTIATABLE) &&
      (info->instance_size || info->n_preallocs || info->instance_init))
    {
      if (pnode)
	g_warning ("cannot instantiate `%s', derived from non-instantiatable parent type `%s'",
		   type_name,
		   NODE_NAME (pnode));
      else
	g_warning ("cannot instantiate `%s' as non-instantiatable fundamental",
		   type_name);
      return FALSE;
    }
  /* check class & interface members */
806
  if (!((finfo->type_flags & G_TYPE_FLAG_CLASSED) || is_interface) &&
807
      (info->class_init || info->class_finalize || info->class_data ||
808
       info->class_size || info->base_init || info->base_finalize))
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    {
      if (pnode)
	g_warning ("cannot create class for `%s', derived from non-classed parent type `%s'",
		   type_name,
                   NODE_NAME (pnode));
      else
	g_warning ("cannot create class for `%s' as non-classed fundamental",
		   type_name);
      return FALSE;
    }
  /* check interface size */
  if (is_interface && info->class_size < sizeof (GTypeInterface))
    {
      g_warning ("specified interface size for type `%s' is smaller than `GTypeInterface' size",
		 type_name);
      return FALSE;
    }
  /* check class size */
  if (finfo->type_flags & G_TYPE_FLAG_CLASSED)
    {
      if (info->class_size < sizeof (GTypeClass))
	{
	  g_warning ("specified class size for type `%s' is smaller than `GTypeClass' size",
		     type_name);
	  return FALSE;
	}
      if (pnode && info->class_size < pnode->data->class.class_size)
	{
	  g_warning ("specified class size for type `%s' is smaller "
		     "than the parent type's `%s' class size",
		     type_name,
		     NODE_NAME (pnode));
	  return FALSE;
	}
    }
  /* check instance size */
  if (finfo->type_flags & G_TYPE_FLAG_INSTANTIATABLE)
    {
      if (info->instance_size < sizeof (GTypeInstance))
	{
	  g_warning ("specified instance size for type `%s' is smaller than `GTypeInstance' size",
		     type_name);
	  return FALSE;
	}
      if (pnode && info->instance_size < pnode->data->instance.instance_size)
	{
	  g_warning ("specified instance size for type `%s' is smaller "
		     "than the parent type's `%s' instance size",
		     type_name,
		     NODE_NAME (pnode));
	  return FALSE;
	}
    }
862
  
863 864 865 866
  return TRUE;
}

static TypeNode*
867 868
find_conforming_child_type_L (TypeNode *pnode,
			      TypeNode *iface)
869 870 871
{
  TypeNode *node = NULL;
  guint i;
872 873
  
  if (type_lookup_iface_entry_L (pnode, iface))
874
    return pnode;
875
  
876
  for (i = 0; i < pnode->n_children && !node; i++)
877
    node = find_conforming_child_type_L (lookup_type_node_I (pnode->children[i]), iface);
878
  
879 880 881 882
  return node;
}

static gboolean
883 884
check_add_interface_L (GType instance_type,
		       GType iface_type)
885
{
886 887
  TypeNode *node = lookup_type_node_I (instance_type);
  TypeNode *iface = lookup_type_node_I (iface_type);
888
  IFaceEntry *entry;
889
  TypeNode *tnode;
890 891 892
  GType *prerequisites;
  guint i;

893
  
894 895 896
  if (!node || !node->is_instantiatable)
    {
      g_warning ("cannot add interfaces to invalid (non-instantiatable) type `%s'",
897
		 type_descriptive_name_I (instance_type));
898 899
      return FALSE;
    }
900
  if (!iface || !NODE_IS_IFACE (iface))
901 902
    {
      g_warning ("cannot add invalid (non-interface) type `%s' to type `%s'",
903
		 type_descriptive_name_I (iface_type),
904 905 906
		 NODE_NAME (node));
      return FALSE;
    }
907
  tnode = lookup_type_node_I (NODE_PARENT_TYPE (iface));
908
  if (NODE_PARENT_TYPE (tnode) && !type_lookup_iface_entry_L (node, tnode))
909
    {
910
      /* 2001/7/31:timj: erk, i guess this warning is junk as interface derivation is flat */
911 912 913 914 915 916
      g_warning ("cannot add sub-interface `%s' to type `%s' which does not conform to super-interface `%s'",
		 NODE_NAME (iface),
		 NODE_NAME (node),
		 NODE_NAME (tnode));
      return FALSE;
    }
917 918 919 920 921 922 923 924 925 926 927 928 929 930
  /* allow overriding of interface type introduced for parent type */
  entry = type_lookup_iface_entry_L (node, iface);
  if (entry && entry->vtable == NULL && !type_iface_peek_holder_L (iface, NODE_TYPE (node)))
    {
      /* ok, we do conform to this interface already, but the interface vtable was not
       * yet intialized, and we just conform to the interface because it got added to
       * one of our parents. so we allow overriding of holder info here.
       */
      return TRUE;
    }
  /* check whether one of our children already conforms (or whether the interface
   * got added to this node already)
   */
  tnode = find_conforming_child_type_L (node, iface);  /* tnode is_a node */
931 932 933 934 935 936 937 938
  if (tnode)
    {
      g_warning ("cannot add interface type `%s' to type `%s', since type `%s' already conforms to interface",
		 NODE_NAME (iface),
		 NODE_NAME (node),
		 NODE_NAME (tnode));
      return FALSE;
    }
939 940 941 942 943 944 945 946 947 948 949 950 951
  prerequisites = IFACE_NODE_PREREQUISITES (iface);
  for (i = 0; i < IFACE_NODE_N_PREREQUISITES (iface); i++)
    {
      tnode = lookup_type_node_I (prerequisites[i]);
      if (!type_node_is_a_L (node, tnode))
	{
	  g_warning ("cannot add interface type `%s' to type `%s' which does not conform to prerequisite `%s'",
		     NODE_NAME (iface),
		     NODE_NAME (node),
		     NODE_NAME (tnode));
	  return FALSE;
	}
    }
952 953 954 955
  return TRUE;
}

static gboolean
956
check_interface_info_I (TypeNode             *iface,
957 958
			GType                 instance_type,
			const GInterfaceInfo *info)
959 960 961 962 963
{
  if ((info->interface_finalize || info->interface_data) && !info->interface_init)
    {
      g_warning ("interface type `%s' for type `%s' comes without initializer",
		 NODE_NAME (iface),
964
		 type_descriptive_name_I (instance_type));
965 966
      return FALSE;
    }
967
  
968 969 970 971
  return TRUE;
}

/* --- type info (type node data) --- */
972
static void
973 974 975
type_data_make_W (TypeNode              *node,
		  const GTypeInfo       *info,
		  const GTypeValueTable *value_table)
976
{
977 978 979 980
  TypeData *data;
  GTypeValueTable *vtable = NULL;
  guint vtable_size = 0;
  
981 982
  g_assert (node->data == NULL && info != NULL);
  
983 984
  if (!value_table)
    {
985
      TypeNode *pnode = lookup_type_node_I (NODE_PARENT_TYPE (node));
986 987 988 989 990 991 992 993 994 995 996
      
      if (pnode)
	vtable = pnode->data->common.value_table;
      else
	{
	  static const GTypeValueTable zero_vtable = { NULL, };
	  
	  value_table = &zero_vtable;
	}
    }
  if (value_table)
997 998 999 1000 1001 1002 1003 1004 1005
    {
      /* need to setup vtable_size since we have to allocate it with data in one chunk */
      vtable_size = sizeof (GTypeValueTable);
      if (value_table->collect_format)
	vtable_size += strlen (value_table->collect_format);
      if (value_table->lcopy_format)
	vtable_size += strlen (value_table->lcopy_format);
      vtable_size += 2;
    }
1006
   
1007 1008
  if (node->is_instantiatable) /* carefull, is_instantiatable is also is_classed */
    {
1009 1010 1011
      data = g_malloc0 (sizeof (InstanceData) + vtable_size);
      if (vtable_size)
	vtable = G_STRUCT_MEMBER_P (data, sizeof (InstanceData));
1012 1013 1014 1015 1016 1017 1018
      data->instance.class_size = info->class_size;
      data->instance.class_init_base = info->base_init;
      data->instance.class_finalize_base = info->base_finalize;
      data->instance.class_init = info->class_init;
      data->instance.class_finalize = info->class_finalize;
      data->instance.class_data = info->class_data;
      data->instance.class = NULL;
1019
      data->instance.init_state = UNINITIALIZED;
1020
      data->instance.instance_size = info->instance_size;
1021 1022 1023 1024
      /* We'll set the final value for data->instance.private size
       * after the parent class has been initialized
       */
      data->instance.private_size = 0;
1025
#ifdef	DISABLE_MEM_POOLS
1026
      data->instance.n_preallocs = 0;
1027 1028 1029
#else	/* !DISABLE_MEM_POOLS */
      data->instance.n_preallocs = MIN (info->n_preallocs, 1024);
#endif	/* !DISABLE_MEM_POOLS */
1030 1031 1032 1033
      data->instance.instance_init = info->instance_init;
    }
  else if (node->is_classed) /* only classed */
    {
1034 1035 1036
      data = g_malloc0 (sizeof (ClassData) + vtable_size);
      if (vtable_size)
	vtable = G_STRUCT_MEMBER_P (data, sizeof (ClassData));
1037 1038 1039