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