2004-11-15 Martin Baulig <martin@ximian.com>
[mono.git] / mono / metadata / class.c
1 /*
2  * class.c: Class management for the Mono runtime
3  *
4  * Author:
5  *   Miguel de Icaza (miguel@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.
8  *
9  * Possible Optimizations:
10  *     in mono_class_create, do not allocate the class right away,
11  *     but wait until you know the size of the FieldMap, so that
12  *     the class embeds directly the FieldMap after the vtable.
13  *
14  * 
15  */
16 #include <config.h>
17 #include <glib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
22 #include <mono/metadata/image.h>
23 #include <mono/metadata/assembly.h>
24 #include <mono/metadata/cil-coff.h>
25 #include <mono/metadata/metadata.h>
26 #include <mono/metadata/metadata-internals.h>
27 #include <mono/metadata/tabledefs.h>
28 #include <mono/metadata/tokentype.h>
29 #include <mono/metadata/class-internals.h>
30 #include <mono/metadata/object.h>
31 #include <mono/metadata/appdomain.h>
32 #include <mono/metadata/mono-endian.h>
33 #include <mono/metadata/debug-helpers.h>
34 #include <mono/metadata/reflection.h>
35 #include <mono/metadata/mono-debug-debugger.h>
36 #include <mono/os/gc_wrapper.h>
37
38 MonoStats mono_stats;
39
40 gboolean mono_print_vtable = FALSE;
41
42 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
43
44 void (*mono_debugger_start_class_init_func) (MonoClass *klass) = NULL;
45 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
46
47 MonoClass *
48 mono_class_from_typeref (MonoImage *image, guint32 type_token)
49 {
50         guint32 cols [MONO_TYPEREF_SIZE];
51         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
52         guint32 idx;
53         const char *name, *nspace;
54         MonoClass *res;
55         MonoAssembly **references;
56
57         mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
58
59         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
60         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
61         
62         idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
63         switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
64         case MONO_RESOLTION_SCOPE_MODULE:
65                 if (!idx)
66                         g_error ("null ResolutionScope not yet handled");
67                 /* a typedef in disguise */
68                 return mono_class_from_name (image, nspace, name);
69         case MONO_RESOLTION_SCOPE_MODULEREF:
70                 return mono_class_from_name (image->modules [idx - 1], nspace, name);
71         case MONO_RESOLTION_SCOPE_TYPEREF: {
72                 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
73                 GList *tmp;
74                 mono_class_init (enclosing);
75                 for (tmp = enclosing->nested_classes; tmp; tmp = tmp->next) {
76                         res = tmp->data;
77                         if (strcmp (res->name, name) == 0)
78                                 return res;
79                 }
80                 g_warning ("TypeRef ResolutionScope not yet handled (%d)", idx);
81                 return NULL;
82         }
83         case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
84                 break;
85         }
86
87         references = image->references;
88         if (!references [idx-1])
89                 mono_assembly_load_reference (image, idx - 1);
90         if (references [idx - 1] == (gpointer)-1)
91                 return NULL;
92
93         image = references [idx-1]->image;
94
95         return mono_class_from_name (image, nspace, name);
96 }
97
98 static MonoType*
99 dup_type (MonoType* t, const MonoType *original)
100 {
101         MonoType *r = g_new0 (MonoType, 1);
102         *r = *t;
103         r->attrs = original->attrs;
104         r->byref = original->byref;
105         mono_stats.generics_metadata_size += sizeof (MonoType);
106         return r;
107 }
108
109 static void
110 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
111                             gboolean include_ns, gboolean include_arity)
112 {
113         MonoClass *klass;
114         
115         switch (type->type) {
116         case MONO_TYPE_ARRAY: {
117                 int i, rank = type->data.array->rank;
118
119                 mono_type_get_name_recurse (
120                         &type->data.array->eklass->byval_arg, str,
121                         FALSE, include_ns, include_arity);
122                 g_string_append_c (str, '[');
123                 for (i = 1; i < rank; i++)
124                         g_string_append_c (str, ',');
125                 g_string_append_c (str, ']');
126                 break;
127         }
128         case MONO_TYPE_SZARRAY:
129                 mono_type_get_name_recurse (
130                         &type->data.klass->byval_arg, str, FALSE, include_ns, include_arity);
131                 g_string_append (str, "[]");
132                 break;
133         case MONO_TYPE_PTR:
134                 mono_type_get_name_recurse (type->data.type, str, FALSE, include_ns, include_arity);
135                 g_string_append_c (str, '*');
136                 break;
137         default:
138                 klass = mono_class_from_mono_type (type);
139                 if (klass->nested_in) {
140                         mono_type_get_name_recurse (
141                                 &klass->nested_in->byval_arg, str, TRUE, include_ns, include_arity);
142                         g_string_append_c (str, '+');
143                 }
144                 if (include_ns && *klass->name_space) {
145                         g_string_append (str, klass->name_space);
146                         g_string_append_c (str, '.');
147                 }
148                 if (!include_arity) {
149                         char *s = strchr (klass->name, '`');
150                         int len = s ? s - klass->name : strlen (klass->name);
151
152                         g_string_append_len (str, klass->name, len);
153                 } else
154                         g_string_append (str, klass->name);
155                 if (is_recursed)
156                         break;
157                 if (klass->generic_inst) {
158                         MonoGenericInst *ginst = klass->generic_inst;
159                         int i;
160
161                         g_string_append_c (str, '[');
162                         for (i = 0; i < ginst->type_argc; i++) {
163                                 if (i)
164                                         g_string_append_c (str, ',');
165                                 mono_type_get_name_recurse (
166                                         ginst->type_argv [i], str, FALSE, include_ns, include_arity);
167                         }
168                         g_string_append_c (str, ']');
169                 } else if (klass->generic_container) {
170                         int i;
171
172                         g_string_append_c (str, '[');
173                         for (i = 0; i < klass->generic_container->type_argc; i++) {
174                                 if (i)
175                                         g_string_append_c (str, ',');
176                                 g_string_append (str, klass->generic_container->type_params [i].name);
177                         }
178                         g_string_append_c (str, ']');
179                 }
180                 break;
181         }
182 }
183
184 /*
185  * mono_type_get_name:
186  * @type: a type
187  *
188  * Returns the string representation for type as required by System.Reflection.
189  * The inverse of mono_reflection_parse_type ().
190  */
191 static char*
192 _mono_type_get_name (MonoType *type, gboolean is_recursed, gboolean include_ns,
193                      gboolean include_arity)
194 {
195         GString* result = g_string_new ("");
196         mono_type_get_name_recurse (type, result, is_recursed, include_ns, include_arity);
197
198         if (type->byref)
199                 g_string_append_c (result, '&');
200
201         return g_string_free (result, FALSE);
202 }
203
204 char*
205 mono_type_get_name (MonoType *type)
206 {
207         return _mono_type_get_name (type, TRUE, TRUE, TRUE);
208 }
209
210 char*
211 mono_type_get_full_name (MonoType *type)
212 {
213         return _mono_type_get_name (type, FALSE, TRUE, TRUE);
214 }
215
216 MonoType*
217 mono_type_get_underlying_type (MonoType *type)
218 {
219         switch (type->type) {
220         case MONO_TYPE_VALUETYPE:
221                 if (type->data.klass->enumtype)
222                         return type->data.klass->enum_basetype;
223                 break;
224         case MONO_TYPE_GENERICINST:
225                 return mono_type_get_underlying_type (type->data.generic_inst->generic_type);
226         default:
227                 break;
228         }
229
230         return type;
231 }
232
233 gboolean
234 mono_class_is_open_constructed_type (MonoType *t)
235 {
236         switch (t->type) {
237         case MONO_TYPE_VAR:
238         case MONO_TYPE_MVAR:
239                 return TRUE;
240         case MONO_TYPE_SZARRAY:
241                 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
242         case MONO_TYPE_ARRAY:
243                 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
244         case MONO_TYPE_PTR:
245                 return mono_class_is_open_constructed_type (t->data.type);
246         case MONO_TYPE_GENERICINST: {
247                 MonoGenericInst *ginst = t->data.generic_inst;
248                 int i;
249
250                 if (mono_class_is_open_constructed_type (ginst->generic_type))
251                         return TRUE;
252                 for (i = 0; i < ginst->type_argc; i++)
253                         if (mono_class_is_open_constructed_type (ginst->type_argv [i]))
254                                 return TRUE;
255                 return FALSE;
256         }
257         default:
258                 return FALSE;
259         }
260 }
261
262 static MonoType*
263 inflate_generic_type (MonoType *type, MonoGenericContext *context)
264 {
265         switch (type->type) {
266         case MONO_TYPE_MVAR:
267                 if (context->gmethod && context->gmethod->mtype_argv)
268                         return dup_type (
269                                 context->gmethod->mtype_argv [type->data.generic_param->num],
270                                 type);
271                 else
272                         return NULL;
273         case MONO_TYPE_VAR:
274                 if (context->ginst)
275                         return dup_type (
276                                 context->ginst->type_argv [type->data.generic_param->num],
277                                 type);
278                 else
279                         return NULL;
280         case MONO_TYPE_SZARRAY: {
281                 MonoClass *eclass = type->data.klass;
282                 MonoType *nt, *inflated = inflate_generic_type (&eclass->byval_arg, context);
283                 if (!inflated)
284                         return NULL;
285                 nt = dup_type (type, type);
286                 nt->data.klass = mono_class_from_mono_type (inflated);
287                 return nt;
288         }
289         case MONO_TYPE_GENERICINST: {
290                 MonoGenericInst *oginst = type->data.generic_inst;
291                 MonoGenericInst *nginst, *cached;
292                 MonoType *nt;
293                 int i;
294
295                 nginst = g_new0 (MonoGenericInst, 1);
296                 *nginst = *oginst;
297
298                 nginst->is_open = FALSE;
299
300                 nginst->type_argv = g_new0 (MonoType *, oginst->type_argc);
301
302                 for (i = 0; i < oginst->type_argc; i++) {
303                         MonoType *t = oginst->type_argv [i];
304                         nginst->type_argv [i] = mono_class_inflate_generic_type (t, context);
305
306                         if (!nginst->is_open)
307                                 nginst->is_open = mono_class_is_open_constructed_type (nginst->type_argv [i]);
308                 };
309
310                 nginst->klass = NULL;
311
312                 nginst->context = g_new0 (MonoGenericContext, 1);
313                 nginst->context->ginst = nginst;
314
315                 mono_loader_lock ();
316                 cached = g_hash_table_lookup (oginst->klass->image->generic_inst_cache, nginst);
317
318                 if (cached) {
319                         g_free (nginst->type_argv);
320                         g_free (nginst);
321                         mono_loader_unlock ();
322
323                         nt = dup_type (type, type);
324                         nt->data.generic_inst = cached;
325                         return nt;
326                 }
327
328                 nginst->dynamic_info = NULL;
329                 nginst->initialized = FALSE;
330
331                 mono_class_create_generic (nginst);
332                 mono_class_create_generic_2 (nginst);
333
334                 mono_stats.generic_instance_count++;
335                 mono_stats.generics_metadata_size += sizeof (MonoGenericInst) +
336                         sizeof (MonoGenericContext) +
337                         nginst->type_argc * sizeof (MonoType);
338
339                 nt = dup_type (type, type);
340                 nt->data.generic_inst = nginst;
341                 g_hash_table_insert (oginst->klass->image->generic_inst_cache, nginst, nginst);
342                 mono_loader_unlock ();
343                 return nt;
344         }
345         default:
346                 return NULL;
347         }
348         return NULL;
349 }
350
351 MonoType*
352 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
353 {
354         MonoType *inflated = inflate_generic_type (type, context);
355
356         if (!inflated)
357                 return type;
358
359         mono_stats.inflated_type_count++;
360         return inflated;
361 }
362
363 static MonoMethodSignature*
364 inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig,
365                            MonoGenericContext *context)
366 {
367         MonoMethodSignature *res;
368         int i;
369         res = mono_metadata_signature_alloc (image, sig->param_count);
370         res->ret = mono_class_inflate_generic_type (sig->ret, context);
371         for (i = 0; i < sig->param_count; ++i)
372                 res->params [i] = mono_class_inflate_generic_type (sig->params [i], context);
373         res->hasthis = sig->hasthis;
374         res->explicit_this = sig->explicit_this;
375         res->call_convention = sig->call_convention;
376         res->generic_param_count = sig->generic_param_count;
377         res->is_inflated = 1;
378         return res;
379 }
380
381 static MonoMethodHeader*
382 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
383 {
384         MonoMethodHeader *res;
385         int i;
386         res = g_malloc0 (sizeof (MonoMethodHeader) + sizeof (gpointer) * header->num_locals);
387         res->code = header->code;
388         res->code_size = header->code_size;
389         res->max_stack = header->max_stack;
390         res->num_clauses = header->num_clauses;
391         res->init_locals = header->init_locals;
392         res->num_locals = header->num_locals;
393         res->clauses = header->clauses;
394         for (i = 0; i < header->num_locals; ++i)
395                 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
396         return res;
397 }
398
399 MonoMethod*
400 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context,
401                                    MonoClass *klass)
402 {
403         MonoMethodInflated *result;
404         MonoClass *rklass;
405
406         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
407             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
408                 return method;
409
410         mono_stats.inflated_method_count++;
411         mono_stats.generics_metadata_size +=
412                 sizeof (MonoMethodInflated) - sizeof (MonoMethodNormal);
413
414         result = g_new0 (MonoMethodInflated, 1);
415         result->nmethod = *(MonoMethodNormal*)method;
416
417         if (mono_method_get_header (method))
418                 result->nmethod.header = inflate_generic_header (
419                         mono_method_get_header (method), context);
420
421         if (klass)
422                 rklass = result->nmethod.method.klass = klass;
423         else {
424                 MonoType *declaring = mono_class_inflate_generic_type (&method->klass->byval_arg, context);
425                 rklass = result->nmethod.method.klass = mono_class_from_mono_type (declaring);
426         }
427
428         result->nmethod.method.signature = inflate_generic_signature (
429                 method->klass->image, method->signature, context);
430
431         if (context->gmethod) {
432                 result->context = g_new0 (MonoGenericContext, 1);
433                 result->context->gmethod = context->gmethod;
434                 result->context->ginst = rklass->generic_inst;
435
436                 mono_stats.generics_metadata_size += sizeof (MonoGenericContext);
437         } else if (rklass->generic_inst)
438                 result->context = rklass->generic_inst->context;
439
440         if (method->signature->is_inflated)
441                 result->declaring = ((MonoMethodInflated *) method)->declaring;
442         else
443                 result->declaring = method;
444
445         return (MonoMethod *) result;
446 }
447
448 /** 
449  * class_compute_field_layout:
450  * @m: pointer to the metadata.
451  * @class: The class to initialize
452  *
453  * Initializes the class->fields.
454  *
455  * Currently we only support AUTO_LAYOUT, and do not even try to do
456  * a good job at it.  This is temporary to get the code for Paolo.
457  */
458 static void
459 class_compute_field_layout (MonoClass *class)
460 {
461         MonoImage *m = class->image; 
462         const int top = class->field.count;
463         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
464         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
465         int i, blittable = TRUE, real_size = 0;
466         guint32 rva;
467         guint32 packing_size = 0;
468         gboolean explicit_size;
469         MonoClassField *field;
470
471         if (class->size_inited)
472                 return;
473
474         if (class->parent) {
475                 if (!class->parent->size_inited)
476                         class_compute_field_layout (class->parent);
477                 class->instance_size += class->parent->instance_size;
478                 class->min_align = class->parent->min_align;
479                 blittable = class->parent->blittable;
480         } else {
481                 class->instance_size = sizeof (MonoObject);
482                 class->min_align = 1;
483         }
484
485         /* Get the real size */
486         explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
487
488         if (explicit_size) {
489                 g_assert ((packing_size & 0xfffffff0) == 0);
490                 class->packing_size = packing_size;
491                 real_size += class->instance_size;
492         }
493
494         if (!top) {
495                 if (explicit_size && real_size) {
496                         class->instance_size = MAX (real_size, class->instance_size);
497                 }
498                 class->size_inited = 1;
499                 class->blittable = blittable;
500                 return;
501         }
502
503         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
504                 blittable = FALSE;
505
506         class->fields = g_new0 (MonoClassField, top);
507
508         /*
509          * Fetch all the field information.
510          */
511         for (i = 0; i < top; i++){
512                 const char *sig;
513                 guint32 cols [MONO_FIELD_SIZE];
514                 int idx = class->field.first + i;
515                 MonoGenericContainer *container = NULL;
516
517                 field = &class->fields [i];
518                 mono_metadata_decode_row (t, idx, cols, MONO_FIELD_SIZE);
519                 /* The name is needed for fieldrefs */
520                 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
521                 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
522                 mono_metadata_decode_value (sig, &sig);
523                 /* FIELD signature == 0x06 */
524                 g_assert (*sig == 0x06);
525                 if (class->generic_container)
526                         container = class->generic_container;
527                 else if (class->generic_inst) {
528                         g_assert (class->generic_inst->container);
529                         container = class->generic_inst->container;
530                 }
531                 field->type = mono_metadata_parse_type_full (
532                         m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
533                 if (mono_field_is_deleted (field))
534                         continue;
535                 if (class->generic_inst) {
536                         field->type = mono_class_inflate_generic_type (
537                                 field->type, class->generic_inst->context);
538                         field->type->attrs = cols [MONO_FIELD_FLAGS];
539                 }
540
541                 field->parent = class;
542
543                 /* Only do these checks if we still think this type is blittable */
544                 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
545                         if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
546                                 blittable = FALSE;
547                         } else {
548                                 MonoClass *field_class = mono_class_from_mono_type (field->type);
549                                 if (!field_class || !field_class->blittable)
550                                         blittable = FALSE;
551                         }
552                 }
553
554                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
555                         mono_metadata_field_info (m, idx, &field->offset, NULL, NULL);
556                         if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
557                                 g_warning ("%s not initialized correctly (missing field layout info for %s)", class->name, field->name);
558                 }
559
560                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
561                         mono_metadata_field_info (m, idx, NULL, &rva, NULL);
562                         if (!rva)
563                                 g_warning ("field %s in %s should have RVA data, but hasn't", field->name, class->name);
564                         field->data = mono_image_rva_map (class->image, rva);
565                 }
566
567                 if (class->enumtype && !(cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC)) {
568                         class->enum_basetype = field->type;
569                         class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
570                         blittable = class->element_class->blittable;
571                 }
572
573                 /* The def_value of fields is compute lazily during vtable creation */
574         }
575
576         if (class == mono_defaults.string_class)
577                 blittable = FALSE;
578
579         class->blittable = blittable;
580
581         if (class->enumtype && !class->enum_basetype) {
582                 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
583                         G_BREAKPOINT ();
584         }
585         if (explicit_size && real_size) {
586                 class->instance_size = MAX (real_size, class->instance_size);
587         }
588
589         if (class->generic_container ||
590             (class->generic_inst && class->generic_inst->is_open))
591                 return;
592
593         mono_class_layout_fields (class);
594 }
595
596 void
597 mono_class_layout_fields (MonoClass *class)
598 {
599         int i;
600         const int top = class->field.count;
601         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
602         guint32 pass, passes, real_size;
603         gboolean gc_aware_layout = FALSE;
604         MonoClassField *field;
605
606         /*
607          * Enable GC aware auto layout: in this mode, reference
608          * fields are grouped together inside objects, increasing collector 
609          * performance.
610          * Requires that all classes whose layout is known to native code be annotated
611          * with [StructLayout (LayoutKind.Sequential)]
612          * Value types have gc_aware_layout disabled by default, as per
613          * what the default is for other runtimes.
614          */
615          /* corlib is missing [StructLayout] directives in many places */
616         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
617                 if (class->image != mono_defaults.corlib &&
618                         class->byval_arg.type != MONO_TYPE_VALUETYPE)
619                         gc_aware_layout = TRUE;
620         }
621
622         /*
623          * Compute field layout and total size (not considering static fields)
624          */
625
626         switch (layout) {
627         case TYPE_ATTRIBUTE_AUTO_LAYOUT:
628         case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
629
630                 if (gc_aware_layout)
631                         passes = 2;
632                 else
633                         passes = 1;
634
635                 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
636                         passes = 1;
637
638                 if (class->parent)
639                         real_size = class->parent->instance_size;
640                 else
641                         real_size = sizeof (MonoObject);
642
643                 for (pass = 0; pass < passes; ++pass) {
644                         for (i = 0; i < top; i++){
645                                 int size, align;
646                                 field = &class->fields [i];
647
648                                 if (mono_field_is_deleted (field))
649                                         continue;
650                                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
651                                         continue;
652
653                                 if (gc_aware_layout) {
654                                         /* 
655                                          * We process fields with reference type in the first pass,
656                                          * and fields with non-reference type in the second pass.
657                                          * We use IS_POINTER instead of IS_REFERENCE because in
658                                          * some internal structures, we store GC_MALLOCed memory
659                                          * in IntPtr fields...
660                                          */
661                                         if (MONO_TYPE_IS_POINTER (field->type)) {
662                                                 if (pass == 1)
663                                                         continue;
664                                         } else {
665                                                 if (pass == 0)
666                                                         continue;
667                                         }
668                                 }
669
670                                 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
671                                         (strcmp (field->name, "$PRIVATE$") == 0)) {
672                                         /* This field is a hack inserted by MCS to empty structures */
673                                         continue;
674                                 }
675
676                                 size = mono_type_size (field->type, &align);
677                         
678                                 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
679                                 align = class->packing_size ? MIN (class->packing_size, align): align;
680                                 class->min_align = MAX (align, class->min_align);
681                                 field->offset = real_size;
682                                 field->offset += align - 1;
683                                 field->offset &= ~(align - 1);
684                                 real_size = field->offset + size;
685                         }
686
687                         class->instance_size = MAX (real_size, class->instance_size);
688        
689                         if (class->instance_size & (class->min_align - 1)) {
690                                 class->instance_size += class->min_align - 1;
691                                 class->instance_size &= ~(class->min_align - 1);
692                         }
693                 }
694                 break;
695         case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
696                 real_size = 0;
697                 for (i = 0; i < top; i++) {
698                         int size, align;
699                         field = &class->fields [i];
700
701                         /*
702                          * There must be info about all the fields in a type if it
703                          * uses explicit layout.
704                          */
705
706                         if (mono_field_is_deleted (field))
707                                 continue;
708                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
709                                 continue;
710
711                         size = mono_type_size (field->type, &align);
712                         
713                         /*
714                          * When we get here, field->offset is already set by the
715                          * loader (for either runtime fields or fields loaded from metadata).
716                          * The offset is from the start of the object: this works for both
717                          * classes and valuetypes.
718                          */
719                         field->offset += sizeof (MonoObject);
720
721                         /*
722                          * Calc max size.
723                          */
724                         real_size = MAX (real_size, size + field->offset);
725                 }
726                 class->instance_size = MAX (real_size, class->instance_size);
727                 break;
728         }
729
730         class->size_inited = 1;
731
732         /*
733          * Compute static field layout and size
734          */
735         for (i = 0; i < top; i++){
736                 int size, align;
737                 field = &class->fields [i];
738                         
739                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
740                         continue;
741                 if (mono_field_is_deleted (field))
742                         continue;
743                         
744                 size = mono_type_size (field->type, &align);
745                 field->offset = class->class_size;
746                 field->offset += align - 1;
747                 field->offset &= ~(align - 1);
748                 class->class_size = field->offset + size;
749         }
750 }
751
752 static void
753 init_properties (MonoClass *class)
754 {
755         guint startm, endm, i, j;
756         guint32 cols [MONO_PROPERTY_SIZE];
757         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_PROPERTY];
758         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
759
760         class->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->property.last);
761         class->property.count = class->property.last - class->property.first;
762
763         class->properties = g_new0 (MonoProperty, class->property.count);
764         for (i = class->property.first; i < class->property.last; ++i) {
765                 mono_metadata_decode_row (pt, i, cols, MONO_PROPERTY_SIZE);
766                 class->properties [i - class->property.first].parent = class;
767                 class->properties [i - class->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
768                 class->properties [i - class->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
769
770                 startm = mono_metadata_methods_from_property (class->image, i, &endm);
771                 for (j = startm; j < endm; ++j) {
772                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
773                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
774                         case METHOD_SEMANTIC_SETTER:
775                                 class->properties [i - class->property.first].set = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
776                                 break;
777                         case METHOD_SEMANTIC_GETTER:
778                                 class->properties [i - class->property.first].get = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
779                                 break;
780                         default:
781                                 break;
782                         }
783                 }
784         }
785 }
786
787 static void
788 init_events (MonoClass *class)
789 {
790         guint startm, endm, i, j;
791         guint32 cols [MONO_EVENT_SIZE];
792         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_EVENT];
793         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
794
795         class->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->event.last);
796         class->event.count = class->event.last - class->event.first;
797
798         class->events = g_new0 (MonoEvent, class->event.count);
799         for (i = class->event.first; i < class->event.last; ++i) {
800                 MonoEvent *event = &class->events [i - class->event.first];
801                         
802                 mono_metadata_decode_row (pt, i, cols, MONO_EVENT_SIZE);
803                 event->parent = class;
804                 event->attrs = cols [MONO_EVENT_FLAGS];
805                 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
806
807                 startm = mono_metadata_methods_from_event (class->image, i, &endm);
808                 for (j = startm; j < endm; ++j) {
809                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
810                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
811                         case METHOD_SEMANTIC_ADD_ON:
812                                 event->add = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
813                                 break;
814                         case METHOD_SEMANTIC_REMOVE_ON:
815                                 event->remove = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
816                                 break;
817                         case METHOD_SEMANTIC_FIRE:
818                                 event->raise = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
819                                 break;
820                         case METHOD_SEMANTIC_OTHER: {
821                                 int n = 0;
822
823                                 if (event->other == NULL) {
824                                         event->other = g_new0 (MonoMethod*, 1);
825                                 } else {
826                                         while (event->other [n])
827                                                 n++;
828                                         event->other = g_realloc (event->other, (n + 1) * sizeof (MonoMethod*));
829                                 }
830                                 event->other [n] = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
831                                 break;
832                         }
833                         default:
834                                 break;
835                         }
836                 }
837         }
838 }
839
840 static guint
841 mono_get_unique_iid (MonoClass *class)
842 {
843         static GHashTable *iid_hash = NULL;
844         static guint iid = 0;
845
846         char *str;
847         gpointer value;
848         
849         g_assert (MONO_CLASS_IS_INTERFACE (class));
850
851         mono_loader_lock ();
852
853         if (!iid_hash)
854                 iid_hash = g_hash_table_new (g_str_hash, g_str_equal);
855
856         str = g_strdup_printf ("%s|%s.%s\n", class->image->name, class->name_space, class->name);
857
858         if (g_hash_table_lookup_extended (iid_hash, str, NULL, &value)) {
859                 mono_loader_unlock ();
860                 g_free (str);
861                 return (guint)value;
862         } else {
863                 g_hash_table_insert (iid_hash, str, (gpointer)iid);
864                 ++iid;
865         }
866
867         mono_loader_unlock ();
868
869         return iid - 1;
870 }
871
872 static void
873 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
874 {
875         int i;
876         MonoClass *ic;
877         
878         for (i = 0; i < klass->interface_count; i++) {
879                 ic = klass->interfaces [i];
880
881                 if (*res == NULL)
882                         *res = g_ptr_array_new ();
883                 g_ptr_array_add (*res, ic);
884
885                 collect_implemented_interfaces_aux (ic, res);
886         }
887 }
888
889 GPtrArray*
890 mono_class_get_implemented_interfaces (MonoClass *klass)
891 {
892         GPtrArray *res = NULL;
893
894         collect_implemented_interfaces_aux (klass, &res);
895         return res;
896 }
897
898 static int
899 setup_interface_offsets (MonoClass *class, int cur_slot)
900 {
901         MonoClass *k, *ic;
902         int i, max_iid;
903         GPtrArray *ifaces;
904
905         /* compute maximum number of slots and maximum interface id */
906         max_iid = 0;
907         for (k = class; k ; k = k->parent) {
908                 for (i = 0; i < k->interface_count; i++) {
909                         ic = k->interfaces [i];
910
911                         if (!ic->inited)
912                                 mono_class_init (ic);
913
914                         if (max_iid < ic->interface_id)
915                                 max_iid = ic->interface_id;
916                 }
917         }
918
919         if (MONO_CLASS_IS_INTERFACE (class)) {
920                 if (max_iid < class->interface_id)
921                         max_iid = class->interface_id;
922         }
923         class->max_interface_id = max_iid;
924         /* compute vtable offset for interfaces */
925         class->interface_offsets = g_malloc (sizeof (gpointer) * (max_iid + 1));
926
927         for (i = 0; i <= max_iid; i++)
928                 class->interface_offsets [i] = -1;
929
930         ifaces = mono_class_get_implemented_interfaces (class);
931         if (ifaces) {
932                 for (i = 0; i < ifaces->len; ++i) {
933                         ic = g_ptr_array_index (ifaces, i);
934                         class->interface_offsets [ic->interface_id] = cur_slot;
935                         cur_slot += ic->method.count;
936                 }
937                 g_ptr_array_free (ifaces, TRUE);
938         }
939
940         for (k = class->parent; k ; k = k->parent) {
941                 ifaces = mono_class_get_implemented_interfaces (k);
942                 if (ifaces) {
943                         for (i = 0; i < ifaces->len; ++i) {
944                                 ic = g_ptr_array_index (ifaces, i);
945
946                                 if (class->interface_offsets [ic->interface_id] == -1) {
947                                         int io = k->interface_offsets [ic->interface_id];
948
949                                         g_assert (io >= 0);
950
951                                         class->interface_offsets [ic->interface_id] = io;
952                                 }
953                         }
954                         g_ptr_array_free (ifaces, TRUE);
955                 }
956         }
957
958         if (MONO_CLASS_IS_INTERFACE (class))
959                 class->interface_offsets [class->interface_id] = cur_slot;
960
961         return cur_slot;
962 }
963
964 void
965 mono_class_setup_vtable (MonoClass *class, MonoMethod **overrides, int onum)
966 {
967         MonoClass *k, *ic;
968         MonoMethod **vtable;
969         int i, max_vtsize = 0, max_iid, cur_slot = 0;
970         GPtrArray *ifaces;
971         MonoGHashTable *override_map = NULL;
972
973         /* setup_vtable() must be called only once on the type */
974         if (class->interface_offsets) {
975                 g_warning ("vtable already computed in %s.%s", class->name_space, class->name);
976                 return;
977         }
978
979         ifaces = mono_class_get_implemented_interfaces (class);
980         if (ifaces) {
981                 for (i = 0; i < ifaces->len; i++) {
982                         MonoClass *ic = g_ptr_array_index (ifaces, i);
983                         max_vtsize += ic->method.count;
984                 }
985                 g_ptr_array_free (ifaces, TRUE);
986         }
987         
988         if (class->parent) {
989                 max_vtsize += class->parent->vtable_size;
990                 cur_slot = class->parent->vtable_size;
991         }
992
993         max_vtsize += class->method.count;
994
995         vtable = alloca (sizeof (gpointer) * max_vtsize);
996         memset (vtable, 0, sizeof (gpointer) * max_vtsize);
997
998         /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
999
1000         cur_slot = setup_interface_offsets (class, cur_slot);
1001         max_iid = class->max_interface_id;
1002
1003         if (class->parent && class->parent->vtable_size)
1004                 memcpy (vtable, class->parent->vtable,  sizeof (gpointer) * class->parent->vtable_size);
1005
1006         /* override interface methods */
1007         for (i = 0; i < onum; i++) {
1008                 MonoMethod *decl = overrides [i*2];
1009                 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
1010                         int dslot;
1011                         g_assert (decl->slot != -1);
1012                         dslot = decl->slot + class->interface_offsets [decl->klass->interface_id];
1013                         vtable [dslot] = overrides [i*2 + 1];
1014                         vtable [dslot]->slot = dslot;
1015                         if (!override_map)
1016                                 override_map = mono_g_hash_table_new (NULL, NULL);
1017
1018                         mono_g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
1019                 }
1020         }
1021
1022         for (k = class; k ; k = k->parent) {
1023                 int nifaces = 0;
1024                 ifaces = mono_class_get_implemented_interfaces (k);
1025                 if (ifaces)
1026                         nifaces = ifaces->len;
1027                 for (i = 0; i < nifaces; i++) {
1028                         int j, l, io;
1029
1030                         ic = g_ptr_array_index (ifaces, i);
1031                         io = k->interface_offsets [ic->interface_id];
1032
1033                         g_assert (io >= 0);
1034                         g_assert (io <= max_vtsize);
1035
1036                         if (k == class) {
1037                                 for (l = 0; l < ic->method.count; l++) {
1038                                         MonoMethod *im = ic->methods [l];                                               
1039
1040                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1041                                                 continue;
1042
1043                                         for (j = 0; j < class->method.count; ++j) {
1044                                                 MonoMethod *cm = class->methods [j];
1045                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
1046                                                     !((cm->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) ||
1047                                                     !(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT))
1048                                                         continue;
1049                                                 if (!strcmp(cm->name, im->name) && 
1050                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
1051                                                         g_assert (io + l <= max_vtsize);
1052                                                         vtable [io + l] = cm;
1053                                                 }
1054                                         }
1055                                 }
1056                         } else {
1057                                 /* already implemented */
1058                                 if (io >= k->vtable_size)
1059                                         continue;
1060                         }
1061                                 
1062                         for (l = 0; l < ic->method.count; l++) {
1063                                 MonoMethod *im = ic->methods [l];                                               
1064                                 MonoClass *k1;
1065
1066                                 g_assert (io + l <= max_vtsize);
1067
1068                                 if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1069                                         continue;
1070                                         
1071                                 for (k1 = class; k1; k1 = k1->parent) {
1072                                         for (j = 0; j < k1->method.count; ++j) {
1073                                                 MonoMethod *cm = k1->methods [j];
1074
1075                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
1076                                                     !(cm->flags & METHOD_ATTRIBUTE_PUBLIC))
1077                                                         continue;
1078                                                 
1079                                                 if (!strcmp(cm->name, im->name) && 
1080                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
1081                                                         g_assert (io + l <= max_vtsize);
1082                                                         vtable [io + l] = cm;
1083                                                         break;
1084                                                 }
1085                                                 
1086                                         }
1087                                         g_assert (io + l <= max_vtsize);
1088                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1089                                                 break;
1090                                 }
1091                         }
1092
1093                         for (l = 0; l < ic->method.count; l++) {
1094                                 MonoMethod *im = ic->methods [l];                                               
1095                                 char *qname, *fqname, *cname, *the_cname;
1096                                 MonoClass *k1;
1097                                 
1098                                 if (vtable [io + l])
1099                                         continue;
1100
1101                                 if (ic->generic_inst) {
1102                                         MonoClass *the_ic = mono_class_from_mono_type (ic->generic_inst->generic_type);
1103                                         the_cname = _mono_type_get_name (&the_ic->byval_arg, TRUE, FALSE, TRUE);
1104                                         cname = the_cname;
1105                                 } else {
1106                                         the_cname = NULL;
1107                                         cname = (char*)ic->name;
1108                                 }
1109                                         
1110                                 qname = g_strconcat (cname, ".", im->name, NULL);
1111                                 if (ic->name_space && ic->name_space [0])
1112                                         fqname = g_strconcat (ic->name_space, ".", cname, ".", im->name, NULL);
1113                                 else
1114                                         fqname = NULL;
1115
1116                                 for (k1 = class; k1; k1 = k1->parent) {
1117                                         for (j = 0; j < k1->method.count; ++j) {
1118                                                 MonoMethod *cm = k1->methods [j];
1119
1120                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
1121                                                         continue;
1122                                         
1123                                                 if (((fqname && !strcmp (cm->name, fqname)) || !strcmp (cm->name, qname)) &&
1124                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
1125                                                         g_assert (io + l <= max_vtsize);
1126                                                         vtable [io + l] = cm;
1127                                                         break;
1128                                                 }
1129                                         }
1130                                 }
1131                                 g_free (the_cname);
1132                                 g_free (qname);
1133                                 g_free (fqname);
1134                         }
1135
1136                         
1137                         if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
1138                                 for (l = 0; l < ic->method.count; l++) {
1139                                         char *msig;
1140                                         MonoMethod *im = ic->methods [l];
1141                                         if (im->flags & METHOD_ATTRIBUTE_STATIC)
1142                                                         continue;
1143                                         g_assert (io + l <= max_vtsize);
1144
1145                                         /* 
1146                                          * If one of our parents already implements this interface
1147                                          * we can inherit the implementation.
1148                                          */
1149                                         if (!(vtable [io + l])) {
1150                                                 MonoClass *parent = class->parent;
1151
1152                                                 if ((ic->interface_id <= parent->max_interface_id) && 
1153                                                         (parent->interface_offsets [ic->interface_id]) &&
1154                                                         parent->vtable)
1155                                                         vtable [io + l] = parent->vtable [parent->interface_offsets [ic->interface_id] + l];
1156                                         }
1157
1158                                         if (!(vtable [io + l])) {
1159                                                 for (j = 0; j < onum; ++j) {
1160                                                         g_print (" at slot %d: %s (%d) overrides %s (%d)\n", io+l, overrides [j*2+1]->name, 
1161                                                                  overrides [j*2+1]->slot, overrides [j*2]->name, overrides [j*2]->slot);
1162                                                 }
1163                                                 msig = mono_signature_get_desc (im->signature, FALSE);
1164                                                 printf ("no implementation for interface method %s.%s::%s(%s) in class %s.%s\n",
1165                                                         ic->name_space, ic->name, im->name, msig, class->name_space, class->name);
1166                                                 g_free (msig);
1167                                                 for (j = 0; j < class->method.count; ++j) {
1168                                                         MonoMethod *cm = class->methods [j];
1169                                                         msig = mono_signature_get_desc (cm->signature, FALSE);
1170                                                         
1171                                                         printf ("METHOD %s(%s)\n", cm->name, msig);
1172                                                         g_free (msig);
1173                                                 }
1174                                                 g_assert_not_reached ();
1175                                         }
1176                                 }
1177                         }
1178                 
1179                         for (l = 0; l < ic->method.count; l++) {
1180                                 MonoMethod *im = vtable [io + l];
1181
1182                                 if (im) {
1183                                         g_assert (io + l <= max_vtsize);
1184                                         if (im->slot < 0) {
1185                                                 /* FIXME: why do we need this ? */
1186                                                 im->slot = io + l;
1187                                                 /* g_assert_not_reached (); */
1188                                         }
1189                                 }
1190                         }
1191                 }
1192                 if (ifaces)
1193                         g_ptr_array_free (ifaces, TRUE);
1194         } 
1195
1196         for (i = 0; i < class->method.count; ++i) {
1197                 MonoMethod *cm;
1198                
1199                 cm = class->methods [i];
1200                 
1201                 /*
1202                  * Non-virtual method have no place in the vtable.
1203                  * This also catches static methods (since they are not virtual).
1204                  */
1205                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
1206                         continue;
1207                 
1208                 /*
1209                  * If the method is REUSE_SLOT, we must check in the
1210                  * base class for a method to override.
1211                  */
1212                 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
1213                         int slot = -1;
1214                         for (k = class->parent; k ; k = k->parent) {
1215                                 int j;
1216                                 for (j = 0; j < k->method.count; ++j) {
1217                                         MonoMethod *m1 = k->methods [j];
1218                                         if (!(m1->flags & METHOD_ATTRIBUTE_VIRTUAL))
1219                                                 continue;
1220                                         if (!strcmp(cm->name, m1->name) && 
1221                                             mono_metadata_signature_equal (cm->signature, m1->signature)) {
1222                                                 slot = k->methods [j]->slot;
1223                                                 g_assert (cm->slot < max_vtsize);
1224                                                 if (!override_map)
1225                                                         override_map = mono_g_hash_table_new (NULL, NULL);
1226                                                 mono_g_hash_table_insert (override_map, m1, cm);
1227                                                 break;
1228                                         }
1229                                 }
1230                                 if (slot >= 0) 
1231                                         break;
1232                         }
1233                         if (slot >= 0)
1234                                 cm->slot = slot;
1235                 }
1236
1237                 if (cm->slot < 0)
1238                         cm->slot = cur_slot++;
1239
1240                 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT) && !cm->signature->generic_param_count)
1241                         vtable [cm->slot] = cm;
1242         }
1243
1244         /* override non interface methods */
1245         for (i = 0; i < onum; i++) {
1246                 MonoMethod *decl = overrides [i*2];
1247                 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
1248                         g_assert (decl->slot != -1);
1249                         vtable [decl->slot] = overrides [i*2 + 1];
1250                         overrides [i * 2 + 1]->slot = decl->slot;
1251                         if (!override_map)
1252                                 override_map = mono_g_hash_table_new (NULL, NULL);
1253                         mono_g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
1254                 }
1255         }
1256
1257         /*
1258          * If a method occupies more than one place in the vtable, and it is
1259          * overriden, then change the other occurances too.
1260          */
1261         if (override_map) {
1262                 for (i = 0; i < max_vtsize; ++i)
1263                         if (vtable [i]) {
1264                                 MonoMethod *cm = mono_g_hash_table_lookup (override_map, vtable [i]);
1265                                 if (cm)
1266                                         vtable [i] = cm;
1267                         }
1268
1269                 mono_g_hash_table_destroy (override_map);
1270         }
1271
1272         if (class->generic_inst) {
1273                 MonoClass *gklass = mono_class_from_mono_type (class->generic_inst->generic_type);
1274
1275                 mono_class_init (gklass);
1276                 class->vtable_size = gklass->vtable_size;
1277         } else       
1278                 class->vtable_size = cur_slot;
1279
1280         class->vtable = g_malloc0 (sizeof (gpointer) * class->vtable_size);
1281         memcpy (class->vtable, vtable,  sizeof (gpointer) * class->vtable_size);
1282
1283         if (mono_print_vtable) {
1284                 int icount = 0;
1285
1286                 for (i = 0; i <= max_iid; i++)
1287                         if (class->interface_offsets [i] != -1)
1288                                 icount++;
1289
1290                 printf ("VTable %s.%s (size = %d, interfaces = %d)\n", class->name_space, 
1291                         class->name, class->vtable_size, icount); 
1292
1293                 for (i = 0; i < class->vtable_size; ++i) {
1294                         MonoMethod *cm;
1295                
1296                         cm = vtable [i];
1297                         if (cm) {
1298                                 printf ("  slot %03d(%03d) %s.%s:%s\n", i, cm->slot,
1299                                         cm->klass->name_space, cm->klass->name,
1300                                         cm->name);
1301                         }
1302                 }
1303
1304
1305                 if (icount) {
1306                         printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space, 
1307                                 class->name, max_iid);
1308         
1309                         for (i = 0; i < class->interface_count; i++) {
1310                                 ic = class->interfaces [i];
1311                                 printf ("  slot %03d(%03d) %s.%s\n",  
1312                                         class->interface_offsets [ic->interface_id],
1313                                         ic->method.count, ic->name_space, ic->name);
1314                         }
1315
1316                         for (k = class->parent; k ; k = k->parent) {
1317                                 for (i = 0; i < k->interface_count; i++) {
1318                                         ic = k->interfaces [i]; 
1319                                         printf ("  slot %03d(%03d) %s.%s\n", 
1320                                                 class->interface_offsets [ic->interface_id],
1321                                                 ic->method.count, ic->name_space, ic->name);
1322                                 }
1323                         }
1324                 }
1325         }
1326 }
1327
1328 /**
1329  * mono_class_init:
1330  * @class: the class to initialize
1331  *
1332  * compute the instance_size, class_size and other infos that cannot be 
1333  * computed at mono_class_get() time. Also compute a generic vtable and 
1334  * the method slot numbers. We use this infos later to create a domain
1335  * specific vtable.  
1336  */
1337 void
1338 mono_class_init (MonoClass *class)
1339 {
1340         int i;
1341         static MonoMethod *default_ghc = NULL;
1342         static MonoMethod *default_finalize = NULL;
1343         static int finalize_slot = -1;
1344         static int ghc_slot = -1;
1345         MonoMethod **overrides;
1346         int onum = 0;
1347
1348         g_assert (class);
1349
1350         if (class->inited)
1351                 return;
1352
1353         /*g_print ("Init class %s\n", class->name);*/
1354
1355         /* We do everything inside the lock to prevent races */
1356         mono_loader_lock ();
1357
1358         if (class->inited) {
1359                 mono_loader_unlock ();
1360                 /* Somebody might have gotten in before us */
1361                 return;
1362         }
1363
1364         if (class->init_pending) {
1365                 /* this indicates a cyclic dependency */
1366                 g_error ("pending init %s.%s\n", class->name_space, class->name);
1367         }
1368
1369         class->init_pending = 1;
1370
1371         if (mono_debugger_start_class_init_func)
1372                 mono_debugger_start_class_init_func (class);
1373
1374         mono_stats.initialized_class_count++;
1375
1376         if (class->generic_inst && !class->generic_inst->is_dynamic) {
1377                 MonoGenericInst *ginst = class->generic_inst;
1378                 MonoClass *gklass;
1379
1380                 gklass = mono_class_from_mono_type (ginst->generic_type);
1381                 mono_class_init (gklass);
1382
1383                 if (ginst->parent)
1384                         class->parent = mono_class_from_mono_type (ginst->parent);
1385                 else
1386                         class->parent = gklass->parent;
1387
1388                 mono_class_setup_parent (class, class->parent);
1389
1390                 if (MONO_CLASS_IS_INTERFACE (class))
1391                         class->interface_id = mono_get_unique_iid (class);
1392
1393                 g_assert (class->method.count == gklass->method.count);
1394                 class->methods = g_new0 (MonoMethod *, class->method.count);
1395
1396                 for (i = 0; i < class->method.count; i++)
1397                         class->methods [i] = mono_class_inflate_generic_method (
1398                                 gklass->methods [i], ginst->context, ginst->klass);
1399
1400                 g_assert (class->field.count == gklass->field.count);
1401                 class->fields = g_new0 (MonoClassField, class->field.count);
1402
1403                 for (i = 0; i < class->field.count; i++) {
1404                         MonoInflatedField *ifield = g_new0 (MonoInflatedField, 1);
1405                         ifield->generic_type = gklass->fields [i].type;
1406
1407                         class->fields [i] = gklass->fields [i];
1408                         class->fields [i].generic_info = ifield;
1409                         class->fields [i].parent = class;
1410                         class->fields [i].type = mono_class_inflate_generic_type (
1411                                 class->fields [i].type, ginst->context);
1412                 }
1413
1414                 class->property = gklass->property;
1415                 class->properties = g_new0 (MonoProperty, class->property.count);
1416
1417                 for (i = 0; i < class->property.count; i++) {
1418                         MonoProperty *prop = &class->properties [i];
1419
1420                         *prop = gklass->properties [i];
1421
1422                         if (prop->get)
1423                                 prop->get = mono_class_inflate_generic_method (
1424                                         prop->get, ginst->context, ginst->klass);
1425                         if (prop->set)
1426                                 prop->set = mono_class_inflate_generic_method (
1427                                         prop->set, ginst->context, ginst->klass);
1428
1429                         prop->parent = class;
1430                 }
1431
1432                 g_assert (class->interface_count == gklass->interface_count);
1433         }
1434
1435         if (class->parent && !class->parent->inited)
1436                 mono_class_init (class->parent);
1437
1438         /*
1439          * Computes the size used by the fields, and their locations
1440          */
1441         if (!class->size_inited)
1442                 class_compute_field_layout (class);
1443
1444         /* initialize method pointers */
1445         if (class->rank) {
1446                 MonoMethod *ctor;
1447                 MonoMethodSignature *sig;
1448                 class->method.count = class->rank > 1? 2: 1;
1449                 sig = mono_metadata_signature_alloc (class->image, class->rank);
1450                 sig->ret = &mono_defaults.void_class->byval_arg;
1451                 sig->pinvoke = TRUE;
1452                 for (i = 0; i < class->rank; ++i)
1453                         sig->params [i] = &mono_defaults.int32_class->byval_arg;
1454
1455                 ctor = (MonoMethod *) g_new0 (MonoMethodPInvoke, 1);
1456                 ctor->klass = class;
1457                 ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1458                 ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1459                 ctor->signature = sig;
1460                 ctor->name = ".ctor";
1461                 ctor->slot = -1;
1462                 class->methods = g_new (MonoMethod*, class->method.count);
1463                 class->methods [0] = ctor;
1464                 if (class->rank > 1) {
1465                         sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1466                         sig->ret = &mono_defaults.void_class->byval_arg;
1467                         sig->pinvoke = TRUE;
1468                         for (i = 0; i < class->rank * 2; ++i)
1469                                 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1470
1471                         ctor = (MonoMethod *) g_new0 (MonoMethodPInvoke, 1);
1472                         ctor->klass = class;
1473                         ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1474                         ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1475                         ctor->signature = sig;
1476                         ctor->name = ".ctor";
1477                         ctor->slot = -1;
1478                         class->methods [1] = ctor;
1479                 }
1480         } else {
1481                 if (!class->generic_inst && !class->methods) {
1482                         class->methods = g_new (MonoMethod*, class->method.count);
1483                         for (i = 0; i < class->method.count; ++i) {
1484                                 class->methods [i] = mono_get_method (class->image,
1485                                                                       MONO_TOKEN_METHOD_DEF | (i + class->method.first + 1), class);
1486                         }
1487                 }
1488         }
1489
1490         if (!class->generic_inst) {
1491                 init_properties (class);
1492                 init_events (class);
1493
1494                 i = mono_metadata_nesting_typedef (class->image, class->type_token, 1);
1495                 while (i) {
1496                         MonoClass* nclass;
1497                         guint32 cols [MONO_NESTED_CLASS_SIZE];
1498                         mono_metadata_decode_row (&class->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
1499                         nclass = mono_class_create_from_typedef (class->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
1500                         class->nested_classes = g_list_prepend (class->nested_classes, nclass);
1501
1502                         i = mono_metadata_nesting_typedef (class->image, class->type_token, i + 1);
1503                 }
1504         }
1505
1506         mono_class_setup_supertypes (class);
1507
1508         if (MONO_CLASS_IS_INTERFACE (class)) {
1509                 for (i = 0; i < class->method.count; ++i)
1510                         class->methods [i]->slot = i;
1511                 class->init_pending = 0;
1512                 class->inited = 1;
1513                 /* 
1514                  * class->interface_offsets is needed for the castclass/isinst code, so
1515                  * we have to setup them for interfaces, too.
1516                  */
1517                 setup_interface_offsets (class, 0);
1518                 mono_loader_unlock ();
1519
1520                 if (mono_debugger_class_init_func)
1521                         mono_debugger_class_init_func (class);
1522
1523                 return;
1524         }
1525
1526         overrides = mono_class_get_overrides (class->image, class->type_token, &onum);  
1527         mono_class_setup_vtable (class, overrides, onum);
1528         g_free (overrides);
1529
1530         class->inited = 1;
1531         class->init_pending = 0;
1532
1533         if (!default_ghc) {
1534                 if (class == mono_defaults.object_class) { 
1535                        
1536                         for (i = 0; i < class->vtable_size; ++i) {
1537                                 MonoMethod *cm = class->vtable [i];
1538                
1539                                 if (!strcmp (cm->name, "GetHashCode")) {
1540                                         ghc_slot = i;
1541                                         break;
1542                                 }
1543                         }
1544
1545                         g_assert (ghc_slot > 0);
1546
1547                         default_ghc = class->vtable [ghc_slot];
1548                 }
1549         }
1550         
1551         class->ghcimpl = 1;
1552         if (class->parent) { 
1553
1554                 if (class->vtable [ghc_slot] == default_ghc) {
1555                         class->ghcimpl = 0;
1556                 }
1557         }
1558
1559         if (!default_finalize) {
1560                 if (class == mono_defaults.object_class) { 
1561                        
1562                         for (i = 0; i < class->vtable_size; ++i) {
1563                                 MonoMethod *cm = class->vtable [i];
1564                
1565                                 if (!strcmp (cm->name, "Finalize")) {
1566                                         finalize_slot = i;
1567                                         break;
1568                                 }
1569                         }
1570
1571                         g_assert (finalize_slot > 0);
1572
1573                         default_finalize = class->vtable [finalize_slot];
1574                 }
1575         }
1576
1577         /* Object::Finalize should have empty implemenatation */
1578         class->has_finalize = 0;
1579         if (class->parent) { 
1580                 if (class->vtable [finalize_slot] != default_finalize)
1581                         class->has_finalize = 1;
1582         }
1583
1584         mono_loader_unlock ();
1585
1586         if (mono_debugger_class_init_func)
1587                 mono_debugger_class_init_func (class);
1588 }
1589
1590 void
1591 mono_class_setup_mono_type (MonoClass *class)
1592 {
1593         const char *name = class->name;
1594         const char *nspace = class->name_space;
1595
1596         if (MONO_CLASS_IS_INTERFACE (class))
1597                 class->interface_id = mono_get_unique_iid (class);
1598
1599         class->this_arg.byref = 1;
1600         class->this_arg.data.klass = class;
1601         class->this_arg.type = MONO_TYPE_CLASS;
1602         class->byval_arg.data.klass = class;
1603         class->byval_arg.type = MONO_TYPE_CLASS;
1604
1605         if (!strcmp (nspace, "System")) {
1606                 if (!strcmp (name, "ValueType")) {
1607                         /*
1608                          * do not set the valuetype bit for System.ValueType.
1609                          * class->valuetype = 1;
1610                          */
1611                         class->blittable = TRUE;
1612                 } else if (!strcmp (name, "Enum")) {
1613                         /*
1614                          * do not set the valuetype bit for System.Enum.
1615                          * class->valuetype = 1;
1616                          */
1617                         class->valuetype = 0;
1618                         class->enumtype = 0;
1619                 } else if (!strcmp (name, "Object")) {
1620                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
1621                 } else if (!strcmp (name, "String")) {
1622                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
1623                 } else if (!strcmp (name, "TypedReference")) {
1624                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
1625                 }
1626         }
1627         
1628         if (class->valuetype) {
1629                 int t = MONO_TYPE_VALUETYPE;
1630                 if (!strcmp (nspace, "System")) {
1631                         switch (*name) {
1632                         case 'B':
1633                                 if (!strcmp (name, "Boolean")) {
1634                                         t = MONO_TYPE_BOOLEAN;
1635                                 } else if (!strcmp(name, "Byte")) {
1636                                         t = MONO_TYPE_U1;
1637                                         class->blittable = TRUE;                                                
1638                                 }
1639                                 break;
1640                         case 'C':
1641                                 if (!strcmp (name, "Char")) {
1642                                         t = MONO_TYPE_CHAR;
1643                                 }
1644                                 break;
1645                         case 'D':
1646                                 if (!strcmp (name, "Double")) {
1647                                         t = MONO_TYPE_R8;
1648                                         class->blittable = TRUE;                                                
1649                                 }
1650                                 break;
1651                         case 'I':
1652                                 if (!strcmp (name, "Int32")) {
1653                                         t = MONO_TYPE_I4;
1654                                         class->blittable = TRUE;
1655                                 } else if (!strcmp(name, "Int16")) {
1656                                         t = MONO_TYPE_I2;
1657                                         class->blittable = TRUE;
1658                                 } else if (!strcmp(name, "Int64")) {
1659                                         t = MONO_TYPE_I8;
1660                                         class->blittable = TRUE;
1661                                 } else if (!strcmp(name, "IntPtr")) {
1662                                         t = MONO_TYPE_I;
1663                                         class->blittable = TRUE;
1664                                 }
1665                                 break;
1666                         case 'S':
1667                                 if (!strcmp (name, "Single")) {
1668                                         t = MONO_TYPE_R4;
1669                                         class->blittable = TRUE;                                                
1670                                 } else if (!strcmp(name, "SByte")) {
1671                                         t = MONO_TYPE_I1;
1672                                         class->blittable = TRUE;
1673                                 }
1674                                 break;
1675                         case 'U':
1676                                 if (!strcmp (name, "UInt32")) {
1677                                         t = MONO_TYPE_U4;
1678                                         class->blittable = TRUE;
1679                                 } else if (!strcmp(name, "UInt16")) {
1680                                         t = MONO_TYPE_U2;
1681                                         class->blittable = TRUE;
1682                                 } else if (!strcmp(name, "UInt64")) {
1683                                         t = MONO_TYPE_U8;
1684                                         class->blittable = TRUE;
1685                                 } else if (!strcmp(name, "UIntPtr")) {
1686                                         t = MONO_TYPE_U;
1687                                         class->blittable = TRUE;
1688                                 }
1689                                 break;
1690                         case 'T':
1691                                 if (!strcmp (name, "TypedReference")) {
1692                                         t = MONO_TYPE_TYPEDBYREF;
1693                                         class->blittable = TRUE;
1694                                 }
1695                                 break;
1696                         case 'V':
1697                                 if (!strcmp (name, "Void")) {
1698                                         t = MONO_TYPE_VOID;
1699                                 }
1700                                 break;
1701                         default:
1702                                 break;
1703                         }
1704                 }
1705                 class->this_arg.type = class->byval_arg.type = t;
1706         }
1707 }
1708
1709 void
1710 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
1711 {
1712         gboolean system_namespace;
1713
1714         system_namespace = !strcmp (class->name_space, "System");
1715
1716         /* if root of the hierarchy */
1717         if (system_namespace && !strcmp (class->name, "Object")) {
1718                 class->parent = NULL;
1719                 class->instance_size = sizeof (MonoObject);
1720                 return;
1721         }
1722         if (!strcmp (class->name, "<Module>")) {
1723                 class->parent = NULL;
1724                 class->instance_size = 0;
1725                 return;
1726         }
1727
1728         if (!MONO_CLASS_IS_INTERFACE (class)) {
1729                 class->parent = parent;
1730
1731                 if (!parent)
1732                         g_assert_not_reached (); /* FIXME */
1733
1734                 if (parent->generic_inst && !parent->name) {
1735                         /*
1736                          * If the parent is a generic instance, we may get
1737                          * called before it is fully initialized, especially
1738                          * before it has its name.
1739                          */
1740                         return;
1741                 }
1742
1743                 class->marshalbyref = parent->marshalbyref;
1744                 class->contextbound  = parent->contextbound;
1745                 class->delegate  = parent->delegate;
1746                 
1747                 if (system_namespace) {
1748                         if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
1749                                 class->marshalbyref = 1;
1750
1751                         if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject")) 
1752                                 class->contextbound  = 1;
1753
1754                         if (*class->name == 'D' && !strcmp (class->name, "Delegate")) 
1755                                 class->delegate  = 1;
1756                 }
1757
1758                 if (class->parent->enumtype || ((strcmp (class->parent->name, "ValueType") == 0) && 
1759                                                 (strcmp (class->parent->name_space, "System") == 0)))
1760                         class->valuetype = 1;
1761                 if (((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
1762                         class->valuetype = class->enumtype = 1;
1763                 }
1764                 /*class->enumtype = class->parent->enumtype; */
1765                 mono_class_setup_supertypes (class);
1766         } else {
1767                 class->parent = NULL;
1768         }
1769
1770 }
1771
1772 void
1773 mono_class_setup_supertypes (MonoClass *class)
1774 {
1775         MonoClass *k;
1776         int ms, i;
1777
1778         if (class->supertypes)
1779                 return;
1780
1781         class->idepth = 0;
1782         for (k = class; k ; k = k->parent) {
1783                 class->idepth++;
1784         }
1785
1786         ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
1787         class->supertypes = g_new0 (MonoClass *, ms);
1788
1789         if (class->parent) {
1790                 for (i = class->idepth, k = class; k ; k = k->parent)
1791                         class->supertypes [--i] = k;
1792         } else {
1793                 class->supertypes [0] = class;
1794         }
1795 }       
1796
1797 /**
1798  * @image: context where the image is created
1799  * @type_token:  typedef token
1800  */
1801 static MonoClass *
1802 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
1803 {
1804         MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
1805         MonoClass *class, *parent = NULL;
1806         guint32 cols [MONO_TYPEDEF_SIZE];
1807         guint32 cols_next [MONO_TYPEDEF_SIZE];
1808         guint tidx = mono_metadata_token_index (type_token);
1809         MonoGenericContext *context = NULL;
1810         const char *name, *nspace;
1811         guint icount = 0; 
1812         MonoClass **interfaces;
1813
1814         mono_loader_lock ();
1815
1816         if ((class = g_hash_table_lookup (image->class_cache, GUINT_TO_POINTER (type_token)))) {
1817                 mono_loader_unlock ();
1818                 return class;
1819         }
1820
1821         g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
1822
1823         mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
1824         
1825         name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1826         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1827
1828         class = g_malloc0 (sizeof (MonoClass));
1829
1830         class->name = name;
1831         class->name_space = nspace;
1832
1833         class->image = image;
1834         class->type_token = type_token;
1835         class->flags = cols [MONO_TYPEDEF_FLAGS];
1836
1837         g_hash_table_insert (image->class_cache, GUINT_TO_POINTER (type_token), class);
1838
1839         class->generic_container = mono_metadata_load_generic_params (image, class->type_token);
1840         if (class->generic_container) {
1841                 class->generic_container->klass = class;
1842                 context = g_new0 (MonoGenericContext, 1);
1843                 context->container = class->generic_container;
1844         }
1845
1846         if (cols [MONO_TYPEDEF_EXTENDS])
1847                 parent = mono_class_get_full (
1848                         image, mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]), context);
1849         interfaces = mono_metadata_interfaces_from_typedef_full (image, type_token, &icount, context);
1850
1851         class->interfaces = interfaces;
1852         class->interface_count = icount;
1853
1854         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
1855                 class->unicode = 1;
1856         /* fixme: maybe we must set this on windows 
1857         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
1858                 class->unicode = 1;
1859         */
1860
1861         class->cast_class = class->element_class = class;
1862
1863         /*g_print ("Load class %s\n", name);*/
1864
1865         mono_class_setup_parent (class, parent);
1866
1867         mono_class_setup_mono_type (class);
1868
1869         /*
1870          * Compute the field and method lists
1871          */
1872         class->field.first  = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
1873         class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
1874
1875         if (tt->rows > tidx){           
1876                 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
1877                 class->field.last  = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1878                 class->method.last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1879         } else {
1880                 class->field.last  = image->tables [MONO_TABLE_FIELD].rows;
1881                 class->method.last = image->tables [MONO_TABLE_METHOD].rows;
1882         }
1883
1884         if (cols [MONO_TYPEDEF_FIELD_LIST] && 
1885             cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
1886                 class->field.count = class->field.last - class->field.first;
1887         else
1888                 class->field.count = 0;
1889
1890         if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
1891                 class->method.count = class->method.last - class->method.first;
1892         else
1893                 class->method.count = 0;
1894
1895         /* reserve space to store vector pointer in arrays */
1896         if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
1897                 class->instance_size += 2 * sizeof (gpointer);
1898                 g_assert (class->field.count == 0);
1899         }
1900
1901         if (class->enumtype)
1902                 class_compute_field_layout (class);
1903
1904         if ((type_token = mono_metadata_nested_in_typedef (image, type_token)))
1905                 class->nested_in = mono_class_create_from_typedef (image, type_token);
1906
1907         mono_loader_unlock ();
1908
1909         return class;
1910 }
1911
1912 void
1913 mono_class_create_generic (MonoGenericInst *ginst)
1914 {
1915         MonoClass *klass, *gklass;
1916
1917         if (!ginst->klass)
1918                 ginst->klass = g_malloc0 (sizeof (MonoClass));
1919         klass = ginst->klass;
1920
1921         gklass = mono_class_from_mono_type (ginst->generic_type);
1922
1923         klass->nested_in = gklass->nested_in;
1924
1925         klass->name = gklass->name;
1926         klass->name_space = gklass->name_space;
1927         klass->image = gklass->image;
1928         klass->flags = gklass->flags;
1929
1930         klass->generic_inst = ginst;
1931
1932         klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
1933         klass->this_arg.data.generic_inst = klass->byval_arg.data.generic_inst = ginst;
1934         klass->this_arg.byref = TRUE;
1935
1936         klass->cast_class = klass->element_class = klass;
1937
1938         if (ginst->is_dynamic) {
1939                 klass->instance_size = gklass->instance_size;
1940                 klass->class_size = gklass->class_size;
1941                 klass->size_inited = 1;
1942
1943                 klass->valuetype = gklass->valuetype;
1944         }
1945 }
1946
1947 void
1948 mono_class_create_generic_2 (MonoGenericInst *ginst)
1949 {
1950         MonoClass *klass, *gklass;
1951         GList *list;
1952         int i;
1953
1954         klass = ginst->klass;
1955         gklass = mono_class_from_mono_type (ginst->generic_type);
1956         while (gklass->generic_inst)
1957                 gklass = mono_class_from_mono_type (gklass->generic_inst->generic_type);
1958
1959         klass->method = gklass->method;
1960         klass->field = gklass->field;
1961
1962         klass->interface_count = gklass->interface_count;
1963         klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
1964         for (i = 0; i < klass->interface_count; i++) {
1965                 MonoType *it = &gklass->interfaces [i]->byval_arg;
1966                 MonoType *inflated = mono_class_inflate_generic_type (it, ginst->context);
1967                 klass->interfaces [i] = mono_class_from_mono_type (inflated);
1968         }
1969
1970         for (list = gklass->nested_classes; list; list = list->next)
1971                 klass->nested_classes = g_list_append (
1972                         klass->nested_classes, list->data);
1973 }
1974
1975 MonoClass *
1976 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
1977 {
1978         MonoClass *klass, **ptr;
1979         int count, pos, i;
1980
1981         if (param->pklass)
1982                 return param->pklass;
1983
1984         klass = param->pklass = g_new0 (MonoClass, 1);
1985
1986         for (count = 0, ptr = param->constraints; ptr && *ptr; ptr++, count++)
1987                 ;
1988
1989         pos = 0;
1990         if ((count > 0) && !MONO_CLASS_IS_INTERFACE (param->constraints [0])) {
1991                 klass->parent = param->constraints [0];
1992                 pos++;
1993         }
1994
1995         if (count - pos > 0) {
1996                 klass->interface_count = count - pos;
1997                 klass->interfaces = g_new0 (MonoClass *, count - pos);
1998                 for (i = pos; i < count; i++)
1999                         klass->interfaces [i - pos] = param->constraints [i];
2000         }
2001
2002         g_assert (param->name && param->owner);
2003
2004         klass->name = param->name;
2005         klass->name_space = "";
2006         klass->image = image;
2007         klass->cast_class = klass->element_class = klass;
2008         klass->enum_basetype = &klass->element_class->byval_arg;
2009         klass->flags = TYPE_ATTRIBUTE_PUBLIC;
2010
2011         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
2012         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
2013         klass->this_arg.byref = TRUE;
2014
2015         mono_class_init (klass);
2016
2017         return klass;
2018 }
2019
2020 static MonoClass *
2021 my_mono_class_from_generic_parameter (MonoGenericParam *param, gboolean is_mvar)
2022 {
2023         MonoClass *klass;
2024
2025         if (param->pklass)
2026                 return param->pklass;
2027
2028         g_assert (param->owner);
2029
2030         klass = g_new0 (MonoClass, 1);
2031
2032         if (param->name)
2033                 klass->name = param->name;
2034         else
2035                 klass->name = g_strdup_printf (is_mvar ? "!!%d" : "!%d", param->num);
2036         klass->name_space = "";
2037         klass->image = mono_defaults.corlib;
2038         klass->cast_class = klass->element_class = klass;
2039         klass->enum_basetype = &klass->element_class->byval_arg;
2040         klass->flags = TYPE_ATTRIBUTE_PUBLIC;
2041
2042         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
2043         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
2044         klass->this_arg.byref = TRUE;
2045
2046         mono_class_init (klass);
2047
2048         return klass;
2049 }
2050
2051 MonoClass *
2052 mono_ptr_class_get (MonoType *type)
2053 {
2054         MonoClass *result;
2055         MonoClass *el_class;
2056         static GHashTable *ptr_hash = NULL;
2057
2058         mono_loader_lock ();
2059
2060         if (!ptr_hash)
2061                 ptr_hash = g_hash_table_new (NULL, NULL);
2062         el_class = mono_class_from_mono_type (type);
2063         if ((result = g_hash_table_lookup (ptr_hash, el_class))) {
2064                 mono_loader_unlock ();
2065                 return result;
2066         }
2067         result = g_new0 (MonoClass, 1);
2068
2069         result->parent = NULL; /* no parent for PTR types */
2070         result->name_space = el_class->name_space;
2071         result->name = g_strdup_printf ("%s*", el_class->name);
2072         result->image = el_class->image;
2073         result->inited = TRUE;
2074         result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
2075         /* Can pointers get boxed? */
2076         result->instance_size = sizeof (gpointer);
2077         result->cast_class = result->element_class = el_class;
2078         result->enum_basetype = &result->element_class->byval_arg;
2079         result->blittable = TRUE;
2080
2081         result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
2082         result->this_arg.data.type = result->byval_arg.data.type = result->enum_basetype;
2083         result->this_arg.byref = TRUE;
2084
2085         mono_class_setup_supertypes (result);
2086
2087         g_hash_table_insert (ptr_hash, el_class, result);
2088
2089         mono_loader_unlock ();
2090
2091         return result;
2092 }
2093
2094 static MonoClass *
2095 mono_fnptr_class_get (MonoMethodSignature *sig)
2096 {
2097         MonoClass *result;
2098         static GHashTable *ptr_hash = NULL;
2099
2100         mono_loader_lock ();
2101
2102         if (!ptr_hash)
2103                 ptr_hash = g_hash_table_new (NULL, NULL);
2104         
2105         if ((result = g_hash_table_lookup (ptr_hash, sig))) {
2106                 mono_loader_unlock ();
2107                 return result;
2108         }
2109         result = g_new0 (MonoClass, 1);
2110
2111         result->parent = NULL; /* no parent for PTR types */
2112         result->name = "System";
2113         result->name_space = "MonoFNPtrFakeClass";
2114         result->image = NULL; /* need to fix... */
2115         result->inited = TRUE;
2116         result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
2117         /* Can pointers get boxed? */
2118         result->instance_size = sizeof (gpointer);
2119         result->cast_class = result->element_class = result;
2120         result->blittable = TRUE;
2121
2122         result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
2123         result->this_arg.data.method = result->byval_arg.data.method = sig;
2124         result->this_arg.byref = TRUE;
2125         result->enum_basetype = &result->element_class->byval_arg;
2126         result->blittable = TRUE;
2127
2128         mono_class_setup_supertypes (result);
2129
2130         g_hash_table_insert (ptr_hash, sig, result);
2131
2132         mono_loader_unlock ();
2133
2134         return result;
2135 }
2136
2137 MonoClass *
2138 mono_class_from_mono_type (MonoType *type)
2139 {
2140         switch (type->type) {
2141         case MONO_TYPE_OBJECT:
2142                 return type->data.klass? type->data.klass: mono_defaults.object_class;
2143         case MONO_TYPE_VOID:
2144                 return type->data.klass? type->data.klass: mono_defaults.void_class;
2145         case MONO_TYPE_BOOLEAN:
2146                 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
2147         case MONO_TYPE_CHAR:
2148                 return type->data.klass? type->data.klass: mono_defaults.char_class;
2149         case MONO_TYPE_I1:
2150                 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
2151         case MONO_TYPE_U1:
2152                 return type->data.klass? type->data.klass: mono_defaults.byte_class;
2153         case MONO_TYPE_I2:
2154                 return type->data.klass? type->data.klass: mono_defaults.int16_class;
2155         case MONO_TYPE_U2:
2156                 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
2157         case MONO_TYPE_I4:
2158                 return type->data.klass? type->data.klass: mono_defaults.int32_class;
2159         case MONO_TYPE_U4:
2160                 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
2161         case MONO_TYPE_I:
2162                 return type->data.klass? type->data.klass: mono_defaults.int_class;
2163         case MONO_TYPE_U:
2164                 return type->data.klass? type->data.klass: mono_defaults.uint_class;
2165         case MONO_TYPE_I8:
2166                 return type->data.klass? type->data.klass: mono_defaults.int64_class;
2167         case MONO_TYPE_U8:
2168                 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
2169         case MONO_TYPE_R4:
2170                 return type->data.klass? type->data.klass: mono_defaults.single_class;
2171         case MONO_TYPE_R8:
2172                 return type->data.klass? type->data.klass: mono_defaults.double_class;
2173         case MONO_TYPE_STRING:
2174                 return type->data.klass? type->data.klass: mono_defaults.string_class;
2175         case MONO_TYPE_TYPEDBYREF:
2176                 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
2177         case MONO_TYPE_ARRAY:
2178                 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
2179         case MONO_TYPE_PTR:
2180                 return mono_ptr_class_get (type->data.type);
2181         case MONO_TYPE_FNPTR:
2182                 return mono_fnptr_class_get (type->data.method);
2183         case MONO_TYPE_SZARRAY:
2184                 return mono_array_class_get (type->data.klass, 1);
2185         case MONO_TYPE_CLASS:
2186         case MONO_TYPE_VALUETYPE:
2187                 return type->data.klass;
2188         case MONO_TYPE_GENERICINST:
2189                 g_assert (type->data.generic_inst->klass);
2190                 return type->data.generic_inst->klass;
2191         case MONO_TYPE_VAR:
2192                 return my_mono_class_from_generic_parameter (type->data.generic_param, FALSE);
2193         case MONO_TYPE_MVAR:
2194                 return my_mono_class_from_generic_parameter (type->data.generic_param, TRUE);
2195         default:
2196                 g_warning ("implement me 0x%02x\n", type->type);
2197                 g_assert_not_reached ();
2198         }
2199         
2200         return NULL;
2201 }
2202
2203 /**
2204  * @image: context where the image is created
2205  * @type_spec:  typespec token
2206  */
2207 static MonoClass *
2208 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec,
2209                                  MonoGenericContext *context)
2210 {
2211         MonoType *type, *inflated;
2212         MonoGenericContainer *container = NULL;
2213         MonoClass *class;
2214
2215         if (context) {
2216                 if (context->gmethod && context->gmethod->container) {
2217                         g_assert (context->gmethod->container);
2218                         container = context->gmethod->container;
2219                 } else if (context->ginst) {
2220                         g_assert (context->ginst->container);
2221                         container = context->ginst->container;
2222                 } else if (context->container)
2223                         container = context->container;
2224         }
2225
2226         type = mono_type_create_from_typespec_full (image, container, type_spec);
2227
2228         switch (type->type) {
2229         case MONO_TYPE_ARRAY:
2230                 class = mono_array_class_get (type->data.array->eklass, type->data.array->rank);
2231                 break;
2232         case MONO_TYPE_SZARRAY:
2233                 class = mono_array_class_get (type->data.klass, 1);
2234                 break;
2235         case MONO_TYPE_PTR:
2236                 class = mono_ptr_class_get (type->data.type);
2237                 break;
2238         case MONO_TYPE_GENERICINST:
2239                 g_assert (type->data.generic_inst->klass);
2240                 class = type->data.generic_inst->klass;
2241                 break;
2242         default:
2243                 /* it seems any type can be stored in TypeSpec as well */
2244                 class = mono_class_from_mono_type (type);
2245                 break;
2246         }
2247
2248         if (!class || !context)
2249                 return class;
2250
2251         inflated = mono_class_inflate_generic_type (&class->byval_arg, context);
2252
2253         return mono_class_from_mono_type (inflated);
2254 }
2255
2256 /**
2257  * mono_bounded_array_class_get:
2258  * @element_class: element class 
2259  * @rank: the dimension of the array class
2260  * @bounded: whenever the array has non-zero bounds
2261  *
2262  * Returns: a class object describing the array with element type @element_type and 
2263  * dimension @rank. 
2264  */
2265 MonoClass *
2266 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
2267 {
2268         MonoImage *image;
2269         MonoClass *class;
2270         MonoClass *parent = NULL;
2271         GSList *list, *rootlist;
2272         int nsize;
2273         char *name;
2274         gboolean corlib_type = FALSE;
2275
2276         g_assert (rank <= 255);
2277
2278         if (rank > 1)
2279                 /* bounded only matters for one-dimensional arrays */
2280                 bounded = FALSE;
2281
2282         image = eclass->image;
2283
2284         mono_loader_lock ();
2285
2286         if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
2287                 for (; list; list = list->next) {
2288                         class = list->data;
2289                         if ((class->rank == rank) && (class->byval_arg.type == (bounded ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
2290                                 mono_loader_unlock ();
2291                                 return class;
2292                         }
2293                 }
2294         }
2295
2296         /* for the building corlib use System.Array from it */
2297         if (image->assembly && image->assembly->dynamic && strcmp (image->assembly_name, "mscorlib") == 0) {
2298                 parent = mono_class_from_name (image, "System", "Array");
2299                 corlib_type = TRUE;
2300         } else {
2301                 parent = mono_defaults.array_class;
2302                 if (!parent->inited)
2303                         mono_class_init (parent);
2304         }
2305
2306         class = g_malloc0 (sizeof (MonoClass));
2307
2308         class->image = image;
2309         class->name_space = eclass->name_space;
2310         nsize = strlen (eclass->name);
2311         name = g_malloc (nsize + 2 + rank);
2312         memcpy (name, eclass->name, nsize);
2313         name [nsize] = '[';
2314         if (rank > 1)
2315                 memset (name + nsize + 1, ',', rank - 1);
2316         name [nsize + rank] = ']';
2317         name [nsize + rank + 1] = 0;
2318         class->name = name;
2319         class->type_token = 0;
2320         /* all arrays are marked serializable and sealed, bug #42779 */
2321         class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
2322                 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
2323         class->parent = parent;
2324         class->instance_size = mono_class_instance_size (class->parent);
2325         class->class_size = 0;
2326         mono_class_setup_supertypes (class);
2327
2328         class->rank = rank;
2329         
2330         if (eclass->enumtype)
2331                 class->cast_class = eclass->element_class;
2332         else
2333                 class->cast_class = eclass;
2334
2335         class->element_class = eclass;
2336
2337         if ((rank > 1) || bounded) {
2338                 MonoArrayType *at = g_new0 (MonoArrayType, 1);
2339                 class->byval_arg.type = MONO_TYPE_ARRAY;
2340                 class->byval_arg.data.array = at;
2341                 at->eklass = eclass;
2342                 at->rank = rank;
2343                 /* FIXME: complete.... */
2344         } else {
2345                 class->byval_arg.type = MONO_TYPE_SZARRAY;
2346                 class->byval_arg.data.klass = eclass;
2347         }
2348         class->this_arg = class->byval_arg;
2349         class->this_arg.byref = 1;
2350         if (corlib_type) {
2351                 class->inited = 1;
2352         }
2353
2354         list = g_slist_append (rootlist, class);
2355         g_hash_table_insert (image->array_cache, eclass, list);
2356
2357         mono_loader_unlock ();
2358
2359         return class;
2360 }
2361
2362 /**
2363  * mono_array_class_get:
2364  * @element_class: element class 
2365  * @rank: the dimension of the array class
2366  *
2367  * Returns: a class object describing the array with element type @element_type and 
2368  * dimension @rank. 
2369  */
2370 MonoClass *
2371 mono_array_class_get (MonoClass *eclass, guint32 rank)
2372 {
2373         return mono_bounded_array_class_get (eclass, rank, FALSE);
2374 }
2375
2376 /**
2377  * mono_class_instance_size:
2378  * @klass: a class 
2379  * 
2380  * Returns: the size of an object instance
2381  */
2382 gint32
2383 mono_class_instance_size (MonoClass *klass)
2384 {       
2385         if (!klass->size_inited)
2386                 mono_class_init (klass);
2387
2388         g_assert (!klass->generic_container &&
2389                   (!klass->generic_inst || !klass->generic_inst->is_open));
2390         return klass->instance_size;
2391 }
2392
2393 /**
2394  * mono_class_min_align:
2395  * @klass: a class 
2396  * 
2397  * Returns: minimm alignment requirements 
2398  */
2399 gint32
2400 mono_class_min_align (MonoClass *klass)
2401 {       
2402         if (!klass->size_inited)
2403                 mono_class_init (klass);
2404
2405         return klass->min_align;
2406 }
2407
2408 /**
2409  * mono_class_value_size:
2410  * @klass: a class 
2411  *
2412  * This function is used for value types, and return the
2413  * space and the alignment to store that kind of value object.
2414  *
2415  * Returns: the size of a value of kind @klass
2416  */
2417 gint32
2418 mono_class_value_size      (MonoClass *klass, guint32 *align)
2419 {
2420         gint32 size;
2421
2422         /* fixme: check disable, because we still have external revereces to
2423          * mscorlib and Dummy Objects 
2424          */
2425         /*g_assert (klass->valuetype);*/
2426
2427         size = mono_class_instance_size (klass) - sizeof (MonoObject);
2428
2429         if (align)
2430                 *align = klass->min_align;
2431
2432         return size;
2433 }
2434
2435 /**
2436  * mono_class_data_size:
2437  * @klass: a class 
2438  * 
2439  * Returns: the size of the static class data
2440  */
2441 gint32
2442 mono_class_data_size (MonoClass *klass)
2443 {       
2444         if (!klass->inited)
2445                 mono_class_init (klass);
2446
2447         return klass->class_size;
2448 }
2449
2450 /*
2451  * Auxiliary routine to mono_class_get_field
2452  *
2453  * Takes a field index instead of a field token.
2454  */
2455 static MonoClassField *
2456 mono_class_get_field_idx (MonoClass *class, int idx)
2457 {
2458         if (class->field.count){
2459                 if ((idx >= class->field.first) && (idx < class->field.last)){
2460                         return &class->fields [idx - class->field.first];
2461                 }
2462         }
2463
2464         if (!class->parent)
2465                 return NULL;
2466         
2467         return mono_class_get_field_idx (class->parent, idx);
2468 }
2469
2470 /**
2471  * mono_class_get_field:
2472  * @class: the class to lookup the field.
2473  * @field_token: the field token
2474  *
2475  * Returns: A MonoClassField representing the type and offset of
2476  * the field, or a NULL value if the field does not belong to this
2477  * class.
2478  */
2479 MonoClassField *
2480 mono_class_get_field (MonoClass *class, guint32 field_token)
2481 {
2482         int idx = mono_metadata_token_index (field_token);
2483
2484         g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
2485
2486         return mono_class_get_field_idx (class, idx - 1);
2487 }
2488
2489 MonoClassField *
2490 mono_class_get_field_from_name (MonoClass *klass, const char *name)
2491 {
2492         int i;
2493
2494         while (klass) {
2495                 for (i = 0; i < klass->field.count; ++i) {
2496                         if (strcmp (name, klass->fields [i].name) == 0)
2497                                 return &klass->fields [i];
2498                 }
2499                 klass = klass->parent;
2500         }
2501         return NULL;
2502 }
2503
2504 guint32
2505 mono_class_get_field_token (MonoClassField *field)
2506 {
2507         MonoClass *klass = field->parent;
2508         int i;
2509
2510         while (klass) {
2511                 for (i = 0; i < klass->field.count; ++i) {
2512                         if (&klass->fields [i] == field)
2513                                 return mono_metadata_make_token (MONO_TABLE_FIELD, klass->field.first + i + 1);
2514                 }
2515                 klass = klass->parent;
2516         }
2517
2518         g_assert_not_reached ();
2519         return 0;
2520 }
2521
2522 guint32
2523 mono_class_get_event_token (MonoEvent *event)
2524 {
2525         MonoClass *klass = event->parent;
2526         int i;
2527
2528         while (klass) {
2529                 for (i = 0; i < klass->event.count; ++i) {
2530                         if (&klass->events [i] == event)
2531                                 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->event.first + i + 1);
2532                 }
2533                 klass = klass->parent;
2534         }
2535
2536         g_assert_not_reached ();
2537         return 0;
2538 }
2539
2540 void *
2541 mono_vtable_get_static_field_data (MonoVTable *vt)
2542 {
2543         return vt->data;
2544 }
2545
2546 MonoProperty*
2547 mono_class_get_property_from_name (MonoClass *klass, const char *name)
2548 {
2549         int i;
2550
2551         while (klass) {
2552                 for (i = 0; i < klass->property.count; ++i) {
2553                         if (strcmp (name, klass->properties [i].name) == 0)
2554                                 return &klass->properties [i];
2555                 }
2556                 klass = klass->parent;
2557         }
2558         return NULL;
2559 }
2560
2561 guint32
2562 mono_class_get_property_token (MonoProperty *prop)
2563 {
2564         MonoClass *klass = prop->parent;
2565         int i;
2566
2567         while (klass) {
2568                 for (i = 0; i < klass->property.count; ++i) {
2569                         if (&klass->properties [i] == prop)
2570                                 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->property.first + i + 1);
2571                 }
2572                 klass = klass->parent;
2573         }
2574
2575         g_assert_not_reached ();
2576         return 0;
2577 }
2578
2579 /**
2580  * mono_class_get:
2581  * @image: the image where the class resides
2582  * @type_token: the token for the class
2583  * @at: an optional pointer to return the array element type
2584  *
2585  * Returns: the MonoClass that represents @type_token in @image
2586  */
2587 static MonoClass *
2588 _mono_class_get (MonoImage *image, guint32 type_token, MonoGenericContext *context)
2589 {
2590         MonoClass *class = NULL;
2591
2592         if (image->dynamic)
2593                 return mono_lookup_dynamic_token (image, type_token);
2594
2595         switch (type_token & 0xff000000){
2596         case MONO_TOKEN_TYPE_DEF:
2597                 class = mono_class_create_from_typedef (image, type_token);
2598                 break;          
2599         case MONO_TOKEN_TYPE_REF:
2600                 class = mono_class_from_typeref (image, type_token);
2601                 break;
2602         case MONO_TOKEN_TYPE_SPEC:
2603                 class = mono_class_create_from_typespec (image, type_token, context);
2604                 break;
2605         default:
2606                 g_warning ("unknown token type %x", type_token & 0xff000000);
2607                 g_assert_not_reached ();
2608         }
2609
2610         if (!class)
2611                 g_warning ("Could not load class from token 0x%08x in %s", type_token, image->name);
2612
2613         return class;
2614 }
2615
2616 MonoClass *
2617 mono_class_get (MonoImage *image, guint32 type_token)
2618 {
2619         return _mono_class_get (image, type_token, NULL);
2620 }
2621
2622 MonoClass *
2623 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
2624 {
2625         MonoClass *class = _mono_class_get (image, type_token, context);
2626         MonoType *inflated;
2627
2628         if (!class || !context || (!context->ginst && !context->gmethod))
2629                 return class;
2630
2631         switch (class->byval_arg.type) {
2632         case MONO_TYPE_GENERICINST:
2633                 if (!class->generic_inst->is_open)
2634                         return class;
2635                 break;
2636         case MONO_TYPE_VAR:
2637         case MONO_TYPE_MVAR:
2638                 break;
2639         default:
2640                 return class;
2641         }
2642
2643         inflated = inflate_generic_type (&class->byval_arg, context);
2644         if (!inflated)
2645                 return class;
2646
2647         return mono_class_from_mono_type (inflated);
2648 }
2649
2650 /**
2651  * mono_class_from_name_case:
2652  * @image: The MonoImage where the type is looked up in, or NULL for looking up in all loaded assemblies
2653  * @name_space: the type namespace
2654  * @name: the type short name.
2655  *
2656  * Obtains a MonoClass with a given namespace and a given name which
2657  * is located in the given MonoImage.   The namespace and name
2658  * lookups are case insensitive.
2659  *
2660  * You can also pass `NULL' to the image, and that will lookup for
2661  * a type with the given namespace and name in all of the loaded
2662  * assemblies: notice that since there might be a name clash in this
2663  * case, passing NULL is not encouraged if you need a precise type.
2664  *
2665  */
2666 MonoClass *
2667 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
2668 {
2669         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
2670         guint32 cols [MONO_TYPEDEF_SIZE];
2671         const char *n;
2672         const char *nspace;
2673         guint32 i, visib;
2674
2675         /* add a cache if needed */
2676         for (i = 1; i <= t->rows; ++i) {
2677                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
2678                 /* nested types are accessed from the nesting name */
2679                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
2680                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
2681                         continue;
2682                 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2683                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2684                 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
2685                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
2686         }
2687         return NULL;
2688 }
2689
2690 static MonoClass*
2691 return_nested_in (MonoClass *class, char *nested) {
2692         MonoClass *found;
2693         char *s = strchr (nested, '/');
2694         GList *tmp;
2695
2696         if (s) {
2697                 *s = 0;
2698                 s++;
2699         }
2700         for (tmp = class->nested_classes; tmp; tmp = tmp->next) {
2701                 found = tmp->data;
2702                 if (strcmp (found->name, nested) == 0) {
2703                         if (s)
2704                                 return return_nested_in (found, s);
2705                         return found;
2706                 }
2707         }
2708         return NULL;
2709 }
2710
2711
2712 /**
2713  * mono_class_from_name_case:
2714  * @image: The MonoImage where the type is looked up in, or NULL for looking up in all loaded assemblies
2715  * @name_space: the type namespace
2716  * @name: the type short name.
2717  *
2718  * Obtains a MonoClass with a given namespace and a given name which
2719  * is located in the given MonoImage.   
2720  *
2721  * You can also pass `NULL' to the image, and that will lookup for
2722  * a type with the given namespace and name in all of the loaded
2723  * assemblies: notice that since there might be a name clash in this
2724  * case, passing NULL is not encouraged if you need a precise type.
2725  *
2726  */
2727 MonoClass *
2728 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
2729 {
2730         GHashTable *nspace_table;
2731         MonoImage *loaded_image;
2732         guint32 token = 0;
2733         MonoClass *class;
2734         char *nested;
2735         char buf [1024];
2736
2737         if ((nested = strchr (name, '/'))) {
2738                 int pos = nested - name;
2739                 int len = strlen (name);
2740                 if (len > 1023)
2741                         return NULL;
2742                 memcpy (buf, name, len + 1);
2743                 buf [pos] = 0;
2744                 nested = buf + pos + 1;
2745                 name = buf;
2746         }
2747
2748         mono_loader_lock ();
2749
2750         nspace_table = g_hash_table_lookup (image->name_cache, name_space);
2751
2752         if (nspace_table)
2753                 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
2754
2755         mono_loader_unlock ();
2756
2757         if (!token)
2758                 return NULL;
2759
2760         if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
2761                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
2762                 guint32 cols [MONO_EXP_TYPE_SIZE];
2763                 guint32 idx, impl;
2764
2765                 idx = mono_metadata_token_index (token);
2766
2767                 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
2768
2769                 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
2770                 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
2771                         loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
2772                         if (!loaded_image)
2773                                 return NULL;
2774                         class = mono_class_from_name (loaded_image, name_space, name);
2775                         if (nested)
2776                                 return return_nested_in (class, nested);
2777                         return class;
2778                 } else {
2779                         g_error ("not yet implemented");
2780                 }
2781         }
2782
2783         token = MONO_TOKEN_TYPE_DEF | token;
2784
2785         class = mono_class_get (image, token);
2786         if (nested)
2787                 return return_nested_in (class, nested);
2788         return class;
2789 }
2790
2791 gboolean
2792 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc, 
2793                            gboolean check_interfaces)
2794 {
2795  again:
2796         if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
2797                 if ((klassc->interface_id <= klass->max_interface_id) &&
2798                         (klass->interface_offsets [klassc->interface_id] >= 0))
2799                         return TRUE;
2800         } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
2801                 int i;
2802
2803                 for (i = 0; i < klass->interface_count; i ++) {
2804                         MonoClass *ic =  klass->interfaces [i];
2805                         if (ic == klassc)
2806                                 return TRUE;
2807                 }
2808         } else {
2809                 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
2810                         return TRUE;
2811         }
2812
2813         /* 
2814          * MS.NET thinks interfaces are a subclass of Object, so we think it as
2815          * well.
2816          */
2817         if (klassc == mono_defaults.object_class)
2818                 return TRUE;
2819
2820         if (klass->generic_inst) {
2821                 MonoType *parent = klass->generic_inst->parent;
2822                 if (!parent)
2823                         return FALSE;
2824
2825                 if (mono_metadata_type_equal (parent, &klassc->byval_arg))
2826                         return TRUE;
2827                 klass = mono_class_from_mono_type (parent);
2828                 goto again;
2829         }
2830         
2831         return FALSE;
2832 }
2833
2834 gboolean
2835 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
2836 {
2837         if (!klass->inited)
2838                 mono_class_init (klass);
2839
2840         if (!oklass->inited)
2841                 mono_class_init (oklass);
2842
2843         if (MONO_CLASS_IS_INTERFACE (klass)) {
2844                 if ((klass->interface_id <= oklass->max_interface_id) &&
2845                     (oklass->interface_offsets [klass->interface_id] != -1))
2846                         return TRUE;
2847         } else
2848                 if (klass->rank) {
2849                         MonoClass *eclass, *eoclass;
2850
2851                         if (oklass->rank != klass->rank)
2852                                 return FALSE;
2853
2854                         /* vectors vs. one dimensional arrays */
2855                         if (oklass->byval_arg.type != klass->byval_arg.type)
2856                                 return FALSE;
2857
2858                         eclass = klass->cast_class;
2859                         eoclass = oklass->cast_class;
2860
2861
2862                         /* 
2863                          * a is b does not imply a[] is b[] when a is a valuetype, and
2864                          * b is a reference type.
2865                          */
2866
2867                         if (eoclass->valuetype) {
2868                                 if ((eclass == mono_defaults.enum_class) || 
2869                                         (eclass == mono_defaults.enum_class->parent) ||
2870                                         (eclass == mono_defaults.object_class))
2871                                         return FALSE;
2872                         }
2873
2874                         return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
2875                 }
2876         else
2877                 if (klass == mono_defaults.object_class)
2878                         return TRUE;
2879
2880         return mono_class_has_parent (oklass, klass);
2881 }       
2882
2883 /*
2884  * mono_class_needs_cctor_run:
2885  *
2886  *  Determines whenever the class has a static constructor and whenever it
2887  * needs to be called when executing CALLER.
2888  */
2889 gboolean
2890 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
2891 {
2892         int i;
2893         MonoMethod *method;
2894         
2895         for (i = 0; i < klass->method.count; ++i) {
2896                 method = klass->methods [i];
2897                 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
2898                     (strcmp (".cctor", method->name) == 0)) {
2899                         if (caller == method)
2900                                 return FALSE;
2901                         return TRUE;
2902                 }
2903         }
2904         return FALSE;
2905 }
2906
2907 /*
2908  * Returns the nnumber of bytes an element of type klass
2909  * uses when stored into an array.
2910  */
2911 gint32
2912 mono_class_array_element_size (MonoClass *klass)
2913 {
2914         MonoType *type = &klass->byval_arg;
2915         
2916 handle_enum:
2917         switch (type->type) {
2918         case MONO_TYPE_I1:
2919         case MONO_TYPE_U1:
2920         case MONO_TYPE_BOOLEAN:
2921                 return 1;
2922         case MONO_TYPE_I2:
2923         case MONO_TYPE_U2:
2924         case MONO_TYPE_CHAR:
2925                 return 2;
2926         case MONO_TYPE_I4:
2927         case MONO_TYPE_U4:
2928         case MONO_TYPE_R4:
2929                 return 4;
2930         case MONO_TYPE_I:
2931         case MONO_TYPE_U:
2932         case MONO_TYPE_PTR:
2933         case MONO_TYPE_CLASS:
2934         case MONO_TYPE_STRING:
2935         case MONO_TYPE_OBJECT:
2936         case MONO_TYPE_SZARRAY:
2937         case MONO_TYPE_ARRAY: 
2938         case MONO_TYPE_VAR:
2939         case MONO_TYPE_MVAR:   
2940                 return sizeof (gpointer);
2941         case MONO_TYPE_I8:
2942         case MONO_TYPE_U8:
2943         case MONO_TYPE_R8:
2944                 return 8;
2945         case MONO_TYPE_VALUETYPE:
2946                 if (type->data.klass->enumtype) {
2947                         type = type->data.klass->enum_basetype;
2948                         klass = klass->element_class;
2949                         goto handle_enum;
2950                 }
2951                 return mono_class_instance_size (klass) - sizeof (MonoObject);
2952         case MONO_TYPE_GENERICINST:
2953                 type = type->data.generic_inst->generic_type;
2954                 goto handle_enum;
2955         default:
2956                 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
2957         }
2958         return -1;
2959 }
2960
2961 /**
2962  * mono_array_element_size:
2963  * @ac: pointer to a #MonoArrayClass
2964  *
2965  * Returns: the size of single array element.
2966  */
2967 gint32
2968 mono_array_element_size (MonoClass *ac)
2969 {
2970         return mono_class_array_element_size (ac->element_class);
2971 }
2972
2973 gpointer
2974 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
2975               MonoGenericContext *context)
2976 {
2977         if (image->dynamic) {
2978                 gpointer obj = mono_lookup_dynamic_token (image, token);
2979
2980                 switch (token & 0xff000000) {
2981                 case MONO_TOKEN_TYPE_DEF:
2982                 case MONO_TOKEN_TYPE_REF:
2983                 case MONO_TOKEN_TYPE_SPEC:
2984                         if (handle_class)
2985                                 *handle_class = mono_defaults.typehandle_class;
2986                         return &((MonoClass*)obj)->byval_arg;
2987                 case MONO_TOKEN_METHOD_DEF:
2988                         if (handle_class)
2989                                 *handle_class = mono_defaults.methodhandle_class;
2990                         return obj;
2991                 case MONO_TOKEN_FIELD_DEF:
2992                         if (handle_class)
2993                                 *handle_class = mono_defaults.fieldhandle_class;
2994                         return obj;
2995                 default:
2996                         g_assert_not_reached ();
2997                 }
2998         }
2999
3000         switch (token & 0xff000000) {
3001         case MONO_TOKEN_TYPE_DEF:
3002         case MONO_TOKEN_TYPE_REF: {
3003                 MonoClass *class;
3004                 if (handle_class)
3005                         *handle_class = mono_defaults.typehandle_class;
3006                 class = mono_class_get_full (image, token, context);
3007                 mono_class_init (class);
3008                 /* We return a MonoType* as handle */
3009                 return &class->byval_arg;
3010         }
3011         case MONO_TOKEN_TYPE_SPEC: {
3012                 MonoClass *class;
3013                 if (handle_class)
3014                         *handle_class = mono_defaults.typehandle_class;
3015                 class = mono_class_create_from_typespec (image, token, context);
3016                 mono_class_init (class);
3017                 return &class->byval_arg;
3018         }
3019         case MONO_TOKEN_FIELD_DEF: {
3020                 MonoClass *class;
3021                 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
3022                 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
3023                 mono_class_init (class);
3024                 if (handle_class)
3025                         *handle_class = mono_defaults.fieldhandle_class;
3026                 return mono_class_get_field (class, token);
3027         }
3028         case MONO_TOKEN_METHOD_DEF: {
3029                 MonoMethod *meth;
3030                 meth = mono_get_method_full (image, token, NULL, context);
3031                 if (handle_class)
3032                         *handle_class = mono_defaults.methodhandle_class;
3033                 return meth;
3034         }
3035         case MONO_TOKEN_MEMBER_REF: {
3036                 guint32 cols [MONO_MEMBERREF_SIZE];
3037                 const char *sig;
3038                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
3039                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
3040                 mono_metadata_decode_blob_size (sig, &sig);
3041                 if (*sig == 0x6) { /* it's a field */
3042                         MonoClass *klass;
3043                         MonoClassField *field;
3044                         field = mono_field_from_token (image, token, &klass, context);
3045                         if (handle_class)
3046                                 *handle_class = mono_defaults.fieldhandle_class;
3047                         return field;
3048                 } else {
3049                         MonoMethod *meth;
3050                         meth = mono_get_method_full (image, token, NULL, context);
3051                         if (handle_class)
3052                                 *handle_class = mono_defaults.methodhandle_class;
3053                         return meth;
3054                 }
3055         }
3056         default:
3057                 g_warning ("Unknown token 0x%08x in ldtoken", token);
3058                 break;
3059         }
3060         return NULL;
3061 }
3062
3063 /**
3064  * This function might need to call runtime functions so it can't be part
3065  * of the metadata library.
3066  */
3067 static MonoLookupDynamicToken lookup_dynamic = NULL;
3068
3069 void
3070 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
3071 {
3072         lookup_dynamic = func;
3073 }
3074
3075 gpointer
3076 mono_lookup_dynamic_token (MonoImage *image, guint32 token)
3077 {
3078         return lookup_dynamic (image, token);
3079 }
3080
3081 MonoImage*
3082 mono_class_get_image (MonoClass *klass)
3083 {
3084         return klass->image;
3085 }
3086
3087 /**
3088  * mono_class_get_element_class:
3089  * @klass: the MonoClass to act on
3090  *
3091  * Returns the element class of an array or an enumeration.
3092  */
3093 MonoClass*
3094 mono_class_get_element_class (MonoClass *klass)
3095 {
3096         return klass->element_class;
3097 }
3098
3099 /**
3100  * mono_class_is_valuetype:
3101  * @klass: the MonoClass to act on
3102  *
3103  * Returns true if the MonoClass represents a ValueType.
3104  */
3105 gboolean
3106 mono_class_is_valuetype (MonoClass *klass)
3107 {
3108         return klass->valuetype;
3109 }
3110
3111 /**
3112  * mono_class_is_enum:
3113  * @klass: the MonoClass to act on
3114  *
3115  * Returns true if the MonoClass represents an enumeration.
3116  */
3117 gboolean
3118 mono_class_is_enum (MonoClass *klass)
3119 {
3120         return klass->enumtype;
3121 }
3122
3123 /**
3124  * mono_class_enum_basetype:
3125  * @klass: the MonoClass to act on
3126  *
3127  * Returns the underlying type representation for an enumeration.
3128  */
3129 MonoType*
3130 mono_class_enum_basetype (MonoClass *klass)
3131 {
3132         return klass->enum_basetype;
3133 }
3134
3135 /**
3136  * mono_class_get_parent
3137  * @klass: the MonoClass to act on
3138  *
3139  * Returns the parent class for this class.
3140  */
3141 MonoClass*
3142 mono_class_get_parent (MonoClass *klass)
3143 {
3144         return klass->parent;
3145 }
3146
3147 /**
3148  * mono_class_get_nesting_type;
3149  * @klass: the MonoClass to act on
3150  *
3151  * Returns the container type where this type is nested or NULL if this type is not a nested type.
3152  */
3153 MonoClass*
3154 mono_class_get_nesting_type (MonoClass *klass)
3155 {
3156         return klass->nested_in;
3157 }
3158
3159 /**
3160  * mono_class_get_rank:
3161  * @klass: the MonoClass to act on
3162  *
3163  * Returns the rank for the array (the number of dimensions).
3164  */
3165 int
3166 mono_class_get_rank (MonoClass *klass)
3167 {
3168         return klass->rank;
3169 }
3170
3171 /**
3172  * mono_class_get_flags:
3173  * @klass: the MonoClass to act on
3174  *
3175  * The type flags from the TypeDef table from the metadata.
3176  * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
3177  * different values.
3178  *
3179  * Returns the flags from the TypeDef table.
3180  */
3181 guint32
3182 mono_class_get_flags (MonoClass *klass)
3183 {
3184         return klass->flags;
3185 }
3186
3187 /**
3188  * mono_class_get_name
3189  * @klass: the MonoClass to act on
3190  *
3191  * Returns the name of the class.
3192  */
3193 const char*
3194 mono_class_get_name (MonoClass *klass)
3195 {
3196         return klass->name;
3197 }
3198
3199 /**
3200  * mono_class_get_namespace:
3201  * @klass: the MonoClass to act on
3202  *
3203  * Returns the namespace of the class.
3204  */
3205 const char*
3206 mono_class_get_namespace (MonoClass *klass)
3207 {
3208         return klass->name_space;
3209 }
3210
3211 /**
3212  * mono_class_get_type:
3213  * @klass: the MonoClass to act on
3214  *
3215  * This method returns the internal Type representation for the class.
3216  *
3217  * Returns the MonoType from the class.
3218  */
3219 MonoType*
3220 mono_class_get_type (MonoClass *klass)
3221 {
3222         return &klass->byval_arg;
3223 }
3224
3225 /**
3226  * mono_class_get_byref_type:
3227  * @klass: the MonoClass to act on
3228  *
3229  * 
3230  */
3231 MonoType*
3232 mono_class_get_byref_type (MonoClass *klass)
3233 {
3234         return &klass->this_arg;
3235 }
3236
3237 /**
3238  * mono_class_num_fields:
3239  * @klass: the MonoClass to act on
3240  *
3241  * Returns the number of static and instance fields in the class.
3242  */
3243 int
3244 mono_class_num_fields (MonoClass *klass)
3245 {
3246         return klass->field.count;
3247 }
3248
3249 /**
3250  * mono_class_num_methods:
3251  * @klass: the MonoClass to act on
3252  *
3253  * Returns the number of methods in the class.
3254  */
3255 int
3256 mono_class_num_methods (MonoClass *klass)
3257 {
3258         return klass->method.count;
3259 }
3260
3261 /**
3262  * mono_class_num_properties
3263  * @klass: the MonoClass to act on
3264  *
3265  * Returns the number of properties in the class.
3266  */
3267 int
3268 mono_class_num_properties (MonoClass *klass)
3269 {
3270         return klass->property.count;
3271 }
3272
3273 /**
3274  * mono_class_num_events:
3275  * @klass: the MonoClass to act on
3276  *
3277  * Returns the number of events in the class.
3278  */
3279 int
3280 mono_class_num_events (MonoClass *klass)
3281 {
3282         return klass->event.count;
3283 }
3284
3285 /**
3286  * mono_class_get_fields:
3287  * @klass: the MonoClass to act on
3288  *
3289  * This routine is an iterator routine for retrieving the fields in a class.
3290  *
3291  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3292  * iterate over all of the elements.  When no more values are
3293  * available, the return value is NULL.
3294  *
3295  * Returns a `MonoClassField *' on each iteration, or NULL when no more fields are available.
3296  */
3297 MonoClassField*
3298 mono_class_get_fields (MonoClass* klass, gpointer *iter)
3299 {
3300         MonoClassField* field;
3301         if (!iter)
3302                 return NULL;
3303         if (!klass->inited)
3304                 mono_class_init (klass);
3305         if (!*iter) {
3306                 /* start from the first */
3307                 if (klass->field.count) {
3308                         return *iter = &klass->fields [0];
3309                 } else {
3310                         /* no fields */
3311                         return NULL;
3312                 }
3313         }
3314         field = *iter;
3315         field++;
3316         if (field < &klass->fields [klass->field.count]) {
3317                 return *iter = field;
3318         }
3319         return NULL;
3320 }
3321
3322 /**
3323  * mono_class_get_methods
3324  * @klass: the MonoClass to act on
3325  *
3326  * This routine is an iterator routine for retrieving the fields in a class.
3327  *
3328  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3329  * iterate over all of the elements.  When no more values are
3330  * available, the return value is NULL.
3331  *
3332  * Returns a MonoMethod on each iteration or NULL when no more methods are available.
3333  */
3334 MonoMethod*
3335 mono_class_get_methods (MonoClass* klass, gpointer *iter)
3336 {
3337         MonoMethod** method;
3338         if (!iter)
3339                 return NULL;
3340         if (!klass->inited)
3341                 mono_class_init (klass);
3342         if (!*iter) {
3343                 /* start from the first */
3344                 if (klass->method.count) {
3345                         *iter = &klass->methods [0];
3346                         return klass->methods [0];
3347                 } else {
3348                         /* no method */
3349                         return NULL;
3350                 }
3351         }
3352         method = *iter;
3353         method++;
3354         if (method < &klass->methods [klass->method.count]) {
3355                 *iter = method;
3356                 return *method;
3357         }
3358         return NULL;
3359 }
3360
3361 /**
3362  * mono_class_get_properties:
3363  * @klass: the MonoClass to act on
3364  *
3365  * This routine is an iterator routine for retrieving the properties in a class.
3366  *
3367  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3368  * iterate over all of the elements.  When no more values are
3369  * available, the return value is NULL.
3370  *
3371  * Returns a `MonoProperty *' on each invocation, or NULL when no more are available.
3372  */
3373 MonoProperty*
3374 mono_class_get_properties (MonoClass* klass, gpointer *iter)
3375 {
3376         MonoProperty* property;
3377         if (!iter)
3378                 return NULL;
3379         if (!klass->inited)
3380                 mono_class_init (klass);
3381         if (!*iter) {
3382                 /* start from the first */
3383                 if (klass->property.count) {
3384                         return *iter = &klass->properties [0];
3385                 } else {
3386                         /* no fields */
3387                         return NULL;
3388                 }
3389         }
3390         property = *iter;
3391         property++;
3392         if (property < &klass->properties [klass->property.count]) {
3393                 return *iter = property;
3394         }
3395         return NULL;
3396 }
3397
3398 /**
3399  * mono_class_get_events:
3400  * @klass: the MonoClass to act on
3401  *
3402  * This routine is an iterator routine for retrieving the properties in a class.
3403  *
3404  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3405  * iterate over all of the elements.  When no more values are
3406  * available, the return value is NULL.
3407  *
3408  * Returns a `MonoEvent *' on each invocation, or NULL when no more are available.
3409  */
3410 MonoEvent*
3411 mono_class_get_events (MonoClass* klass, gpointer *iter)
3412 {
3413         MonoEvent* event;
3414         if (!iter)
3415                 return NULL;
3416         if (!klass->inited)
3417                 mono_class_init (klass);
3418         if (!*iter) {
3419                 /* start from the first */
3420                 if (klass->event.count) {
3421                         return *iter = &klass->events [0];
3422                 } else {
3423                         /* no fields */
3424                         return NULL;
3425                 }
3426         }
3427         event = *iter;
3428         event++;
3429         if (event < &klass->events [klass->event.count]) {
3430                 return *iter = event;
3431         }
3432         return NULL;
3433 }
3434
3435 /**
3436  * mono_class_get_interfaces
3437  * @klass: the MonoClass to act on
3438  *
3439  * This routine is an iterator routine for retrieving the interfaces implemented by this class.
3440  *
3441  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3442  * iterate over all of the elements.  When no more values are
3443  * available, the return value is NULL.
3444  *
3445  * Returns a `Monoclass *' on each invocation, or NULL when no more are available.
3446  */
3447 MonoClass*
3448 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
3449 {
3450         MonoClass** iface;
3451         if (!iter)
3452                 return NULL;
3453         if (!klass->inited)
3454                 mono_class_init (klass);
3455         if (!*iter) {
3456                 /* start from the first */
3457                 if (klass->interface_count) {
3458                         *iter = &klass->interfaces [0];
3459                         return klass->interfaces [0];
3460                 } else {
3461                         /* no interface */
3462                         return NULL;
3463                 }
3464         }
3465         iface = *iter;
3466         iface++;
3467         if (iface < &klass->interfaces [klass->interface_count]) {
3468                 *iter = iface;
3469                 return *iface;
3470         }
3471         return NULL;
3472 }
3473
3474 /**
3475  * mono_class_get_nested_types
3476  * @klass: the MonoClass to act on
3477  *
3478  * This routine is an iterator routine for retrieving the nested types of a class.
3479  *
3480  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3481  * iterate over all of the elements.  When no more values are
3482  * available, the return value is NULL.
3483  *
3484  * Returns a `Monoclass *' on each invocation, or NULL when no more are available.
3485  */
3486 MonoClass*
3487 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
3488 {
3489         GList *item;
3490         if (!iter)
3491                 return NULL;
3492         if (!klass->inited)
3493                 mono_class_init (klass);
3494         if (!*iter) {
3495                 /* start from the first */
3496                 if (klass->nested_classes) {
3497                         *iter = klass->nested_classes;
3498                         return klass->nested_classes->data;
3499                 } else {
3500                         /* no nested types */
3501                         return NULL;
3502                 }
3503         }
3504         item = *iter;
3505         item = item->next;
3506         if (item) {
3507                 *iter = item;
3508                 return item->data;
3509         }
3510         return NULL;
3511 }
3512
3513 /**
3514  * mono_field_get_name:
3515  * @field: the MonoClassField to act on
3516  *
3517  * Returns the name of the field.
3518  */
3519 const char*
3520 mono_field_get_name (MonoClassField *field)
3521 {
3522         return field->name;
3523 }
3524
3525 /**
3526  * mono_field_get_type:
3527  * @field: the MonoClassField to act on
3528  *
3529  * Returns MonoType of the field.
3530  */
3531 MonoType*
3532 mono_field_get_type (MonoClassField *field)
3533 {
3534         return field->type;
3535 }
3536
3537 /**
3538  * mono_field_get_type:
3539  * @field: the MonoClassField to act on
3540  *
3541  * Returns MonoClass where the field was defined.
3542  */
3543 MonoClass*
3544 mono_field_get_parent (MonoClassField *field)
3545 {
3546         return field->parent;
3547 }
3548
3549 /**
3550  * mono_field_get_flags;
3551  * @field: the MonoClassField to act on
3552  *
3553  * The metadata flags for a field are encoded using the
3554  * FIELD_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
3555  *
3556  * Returns the flags for the field.
3557  */
3558 guint32
3559 mono_field_get_flags (MonoClassField *field)
3560 {
3561         return field->type->attrs;
3562 }
3563
3564 /**
3565  * mono_property_get_name: 
3566  * @prop: the MonoProperty to act on
3567  *
3568  * Returns the name of the property
3569  */
3570 const char*
3571 mono_property_get_name (MonoProperty *prop)
3572 {
3573         return prop->name;
3574 }
3575
3576 /**
3577  * mono_property_get_set_method
3578  * @prop: the MonoProperty to act on.
3579  *
3580  * Returns the setter method of the property (A MonoMethod)
3581  */
3582 MonoMethod*
3583 mono_property_get_set_method (MonoProperty *prop)
3584 {
3585         return prop->set;
3586 }
3587
3588 /**
3589  * mono_property_get_get_method
3590  * @prop: the MonoProperty to act on.
3591  *
3592  * Returns the setter method of the property (A MonoMethod)
3593  */
3594 MonoMethod*
3595 mono_property_get_get_method (MonoProperty *prop)
3596 {
3597         return prop->get;
3598 }
3599
3600 /**
3601  * mono_property_get_parent:
3602  * @prop: the MonoProperty to act on.
3603  *
3604  * Returns the MonoClass where the property was defined.
3605  */
3606 MonoClass*
3607 mono_property_get_parent (MonoProperty *prop)
3608 {
3609         return prop->parent;
3610 }
3611
3612 /**
3613  * mono_property_get_flags:
3614  * @prop: the MonoProperty to act on.
3615  *
3616  * The metadata flags for a property are encoded using the
3617  * PROPERTY_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
3618  *
3619  * Returns the flags for the property.
3620  */
3621 guint32
3622 mono_property_get_flags (MonoProperty *prop)
3623 {
3624         return prop->attrs;
3625 }
3626
3627 /**
3628  * mono_event_get_name:
3629  * @event: the MonoEvent to act on
3630  *
3631  * Returns the name of the event.
3632  */
3633 const char*
3634 mono_event_get_name (MonoEvent *event)
3635 {
3636         return event->name;
3637 }
3638
3639 /**
3640  * mono_event_get_add_method:
3641  * @event: The MonoEvent to act on.
3642  *
3643  * Returns the `add' method for the event (a MonoMethod).
3644  */
3645 MonoMethod*
3646 mono_event_get_add_method (MonoEvent *event)
3647 {
3648         return event->add;
3649 }
3650
3651 /**
3652  * mono_event_get_remove_method:
3653  * @event: The MonoEvent to act on.
3654  *
3655  * Returns the `remove' method for the event (a MonoMethod).
3656  */
3657 MonoMethod*
3658 mono_event_get_remove_method (MonoEvent *event)
3659 {
3660         return event->remove;
3661 }
3662
3663 /**
3664  * mono_event_get_raise_method:
3665  * @event: The MonoEvent to act on.
3666  *
3667  * Returns the `raise' method for the event (a MonoMethod).
3668  */
3669 MonoMethod*
3670 mono_event_get_raise_method (MonoEvent *event)
3671 {
3672         return event->raise;
3673 }
3674
3675 /**
3676  * mono_event_get_parent:
3677  * @event: the MonoEvent to act on.
3678  *
3679  * Returns the MonoClass where the event is defined.
3680  */
3681 MonoClass*
3682 mono_event_get_parent (MonoEvent *event)
3683 {
3684         return event->parent;
3685 }
3686
3687 /**
3688  * mono_event_get_flags
3689  * @event: the MonoEvent to act on.
3690  *
3691  * The metadata flags for an event are encoded using the
3692  * EVENT_* constants.  See the tabledefs.h file for details.
3693  *
3694  * Returns the flags for the event.
3695  */
3696 guint32
3697 mono_event_get_flags (MonoEvent *event)
3698 {
3699         return event->attrs;
3700 }
3701
3702 /**
3703  * mono_find_method_by_name:
3704  * @klass: where to look for the method
3705  * @name_space: name of the method
3706  * @param_count: number of parameters. -1 for any number.
3707  *
3708  * Obtains a MonoMethod with a given name and number of parameters.
3709  * It only works if there are no multiple signatures for any given method name.
3710  */
3711 MonoMethod *
3712 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
3713 {
3714         MonoMethod *res = NULL;
3715         int i;
3716
3717         mono_class_init (klass);
3718
3719         for (i = 0; i < klass->method.count; ++i) {
3720                 if (klass->methods [i]->name[0] == name [0] && 
3721                     !strcmp (name, klass->methods [i]->name) &&
3722                     (param_count == -1 || klass->methods [i]->signature->param_count == param_count)) {
3723                         res = klass->methods [i];
3724                         break;
3725                 }
3726         }
3727         return res;
3728 }