2004-01-19 Zoltan Varga <vargaz@freemail.hu>
[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/tabledefs.h>
27 #include <mono/metadata/tokentype.h>
28 #include <mono/metadata/class.h>
29 #include <mono/metadata/object.h>
30 #include <mono/metadata/appdomain.h>
31 #include <mono/metadata/mono-endian.h>
32 #include <mono/metadata/debug-helpers.h>
33 #include <mono/metadata/reflection.h>
34 #include <mono/os/gc_wrapper.h>
35
36 #define CSIZE(x) (sizeof (x) / 4)
37
38 MonoStats mono_stats;
39
40 gboolean mono_print_vtable = FALSE;
41
42 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
43
44 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
45
46 MonoClass *
47 mono_class_from_typeref (MonoImage *image, guint32 type_token)
48 {
49         guint32 cols [MONO_TYPEREF_SIZE];
50         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
51         guint32 idx;
52         const char *name, *nspace;
53         MonoClass *res;
54         MonoAssembly **references;
55
56         mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
57
58         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
59         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
60         
61         idx = cols [MONO_TYPEREF_SCOPE] >> RESOLTION_SCOPE_BITS;
62         switch (cols [MONO_TYPEREF_SCOPE] & RESOLTION_SCOPE_MASK) {
63         case RESOLTION_SCOPE_MODULE:
64                 if (!idx)
65                         g_error ("null ResolutionScope not yet handled");
66                 /* a typedef in disguise */
67                 return mono_class_from_name (image, nspace, name);
68         case RESOLTION_SCOPE_MODULEREF:
69                 return mono_class_from_name (image->modules [idx - 1], nspace, name);
70         case RESOLTION_SCOPE_TYPEREF: {
71                 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
72                 GList *tmp;
73                 mono_class_init (enclosing);
74                 for (tmp = enclosing->nested_classes; tmp; tmp = tmp->next) {
75                         res = tmp->data;
76                         if (strcmp (res->name, name) == 0)
77                                 return res;
78                 }
79                 g_warning ("TypeRef ResolutionScope not yet handled (%d)", idx);
80                 return NULL;
81         }
82         case RESOLTION_SCOPE_ASSEMBLYREF:
83                 break;
84         }
85
86         references = image->references;
87         if (!references ||  !references [idx-1]) {
88                 /* 
89                  * detected a reference to mscorlib, we simply return a reference to a dummy 
90                  * until we have a better solution.
91                  */
92                 fprintf(stderr, "Sending dummy where %s.%s expected\n", mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]), mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME])); 
93                 
94                 res = mono_class_from_name (image, "System", "MonoDummy");
95                 /* prevent method loading */
96                 res->dummy = 1;
97                 /* some storage if the type is used  - very ugly hack */
98                 res->instance_size = 2*sizeof (gpointer);
99                 return res;
100         }       
101
102         /* load referenced assembly */
103         image = references [idx-1]->image;
104
105         return mono_class_from_name (image, nspace, name);
106 }
107
108 static MonoType*
109 dup_type (MonoType* t)
110 {
111         MonoType *r = g_new0 (MonoType, 1);
112         *r = *t;
113         return r;
114 }
115
116 static void
117 mono_type_get_name_recurse (MonoType *type, GString *str)
118 {
119         MonoClass *klass;
120         
121         switch (type->type) {
122         case MONO_TYPE_ARRAY: {
123                 int i, rank = type->data.array->rank;
124
125                 mono_type_get_name_recurse (&type->data.array->eklass->byval_arg, str);
126                 g_string_append_c (str, '[');
127                 for (i = 1; i < rank; i++)
128                         g_string_append_c (str, ',');
129                 g_string_append_c (str, ']');
130                 break;
131         }
132         case MONO_TYPE_SZARRAY:
133                 mono_type_get_name_recurse (&type->data.klass->byval_arg, str);
134                 g_string_append (str, "[]");
135                 break;
136         case MONO_TYPE_PTR:
137                 mono_type_get_name_recurse (type->data.type, str);
138                 g_string_append_c (str, '*');
139                 break;
140         default:
141                 klass = mono_class_from_mono_type (type);
142                 if (klass->nested_in) {
143                         mono_type_get_name_recurse (&klass->nested_in->byval_arg, str);
144                         g_string_append_c (str, '+');
145                 }
146                 if (*klass->name_space) {
147                         g_string_append (str, klass->name_space);
148                         g_string_append_c (str, '.');
149                 }
150                 g_string_append (str, klass->name);
151                 break;
152         }
153 }
154
155 /*
156  * mono_type_get_name:
157  * @type: a type
158  *
159  * Returns the string representation for type as required by System.Reflection.
160  * The inverse of mono_reflection_parse_type ().
161  */
162 char*
163 mono_type_get_name (MonoType *type)
164 {
165         GString* result = g_string_new ("");
166         mono_type_get_name_recurse (type, result);
167
168         if (type->byref)
169                 g_string_append_c (result, '&');
170
171         return g_string_free (result, FALSE);
172 }
173
174 gboolean
175 mono_class_is_open_constructed_type (MonoType *t)
176 {
177         switch (t->type) {
178         case MONO_TYPE_VAR:
179         case MONO_TYPE_MVAR:
180                 return TRUE;
181         case MONO_TYPE_SZARRAY:
182                 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
183         case MONO_TYPE_ARRAY:
184                 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
185         case MONO_TYPE_PTR:
186                 return mono_class_is_open_constructed_type (t->data.type);
187         case MONO_TYPE_GENERICINST: {
188                 MonoGenericInst *ginst = t->data.generic_inst;
189                 int i;
190
191                 if (mono_class_is_open_constructed_type (ginst->generic_type))
192                         return TRUE;
193                 for (i = 0; i < ginst->type_argc; i++)
194                         if (mono_class_is_open_constructed_type (ginst->type_argv [i]))
195                                 return TRUE;
196                 return FALSE;
197         }
198         default:
199                 return FALSE;
200         }
201 }
202
203 MonoType*
204 mono_class_inflate_generic_type (MonoType *type, MonoGenericInst *ginst)
205 {
206         switch (type->type) {
207         case MONO_TYPE_MVAR:
208                 if (ginst)
209                         return dup_type (ginst->type_argv [type->data.generic_param->num]);
210                 else
211                         return type;
212         case MONO_TYPE_VAR: {
213                 MonoType *t = ginst->type_argv [type->data.generic_param->num];
214
215                 if ((t->type == MONO_TYPE_VAR) || (t->type == MONO_TYPE_MVAR))
216                         return type;
217                 else
218                         return dup_type (t);
219         }
220         case MONO_TYPE_SZARRAY: {
221                 MonoClass *eclass = type->data.klass;
222                 MonoClass *nclass;
223                 MonoType *nt;
224                 if (eclass->byval_arg.type == MONO_TYPE_MVAR) {
225                         nclass = mono_class_from_mono_type (ginst->type_argv [eclass->byval_arg.data.generic_param->num]);
226                 } else if (eclass->byval_arg.type == MONO_TYPE_VAR) {
227                         nclass = mono_class_from_mono_type (ginst->type_argv [eclass->byval_arg.data.generic_param->num]);
228                 } else {
229                         return type;
230                 }
231                 nt = dup_type (type);
232                 nt->data.klass = nclass;
233                 return nt;
234         }
235         default:
236                 return type;
237         }
238         return type;
239 }
240
241 MonoMethodSignature*
242 mono_class_inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericInst *ginst)
243 {
244         MonoMethodSignature *res;
245         int i;
246         res = mono_metadata_signature_alloc (image, sig->param_count);
247         res->ret = mono_class_inflate_generic_type (sig->ret, ginst);
248         for (i = 0; i < sig->param_count; ++i) {
249                 res->params [i] = mono_class_inflate_generic_type (sig->params [i], ginst);
250         }
251         res->hasthis = sig->hasthis;
252         res->explicit_this = sig->explicit_this;
253         res->call_convention = sig->call_convention;
254         res->generic_param_count = sig->generic_param_count;
255         return res;
256 }
257
258 static MonoMethodHeader*
259 inflate_generic_header (MonoMethodHeader *header, MonoGenericInst *ginst)
260 {
261         MonoMethodHeader *res;
262         int i;
263         res = g_malloc0 (sizeof (MonoMethodHeader) + sizeof (gpointer) * header->num_locals);
264         res->code = header->code;
265         res->code_size = header->code_size;
266         res->max_stack = header->max_stack;
267         res->num_clauses = header->num_clauses;
268         res->init_locals = header->init_locals;
269         res->num_locals = header->num_locals;
270         res->clauses = header->clauses;
271         res->gen_params = header->gen_params;
272         res->geninst = ginst;
273         for (i = 0; i < header->num_locals; ++i) {
274                 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], ginst);
275         }
276         return res;
277 }
278
279 MonoMethod*
280 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericInst *ginst)
281 {
282         MonoMethod *result;
283         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
284                 MonoMethodPInvoke *nmethod = g_new0 (MonoMethodPInvoke, 1);
285                 *nmethod = *(MonoMethodPInvoke*)method;
286                 result = (MonoMethod*)nmethod;
287         } else {
288                 MonoMethodNormal *nmethod = g_new0 (MonoMethodNormal, 1);
289                 *nmethod = *(MonoMethodNormal*)method;
290                 result = (MonoMethod*)nmethod;
291                 if (nmethod->header)
292                         nmethod->header = inflate_generic_header (nmethod->header, ginst);
293         }
294         if (ginst->klass)
295                 result->klass = ginst->klass;
296         result->signature = mono_class_inflate_generic_signature (method->klass->image, result->signature, ginst);
297         return result;
298 }
299
300 /** 
301  * class_compute_field_layout:
302  * @m: pointer to the metadata.
303  * @class: The class to initialize
304  *
305  * Initializes the class->fields.
306  *
307  * Currently we only support AUTO_LAYOUT, and do not even try to do
308  * a good job at it.  This is temporary to get the code for Paolo.
309  */
310 static void
311 class_compute_field_layout (MonoClass *class)
312 {
313         MonoImage *m = class->image; 
314         const int top = class->field.count;
315         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
316         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
317         int i, blittable = TRUE, real_size = 0;
318         guint32 rva;
319         guint32 packing_size = 0;
320         gboolean explicit_size;
321         MonoClassField *field;
322
323         if (class->size_inited)
324                 return;
325
326         if (class->parent) {
327                 if (!class->parent->size_inited)
328                         class_compute_field_layout (class->parent);
329                 class->instance_size += class->parent->instance_size;
330                 class->min_align = class->parent->min_align;
331                 blittable = class->blittable;
332         } else {
333                 class->instance_size = sizeof (MonoObject);
334                 class->min_align = 1;
335         }
336
337         /* Get the real size */
338         explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
339
340         if (explicit_size) {
341                 g_assert ((packing_size & 0xfffffff0) == 0);
342                 class->packing_size = packing_size;
343                 real_size += class->instance_size;
344         }
345
346         if (!top) {
347                 if (explicit_size && real_size) {
348                         class->instance_size = MAX (real_size, class->instance_size);
349                 }
350                 class->size_inited = 1;
351                 return;
352         }
353
354         class->fields = g_new0 (MonoClassField, top);
355
356         /*
357          * Fetch all the field information.
358          */
359         for (i = 0; i < top; i++){
360                 const char *sig;
361                 guint32 cols [MONO_FIELD_SIZE];
362                 int idx = class->field.first + i;
363
364                 field = &class->fields [i];
365                 mono_metadata_decode_row (t, idx, cols, CSIZE (cols));
366                 /* The name is needed for fieldrefs */
367                 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
368                 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
369                 mono_metadata_decode_value (sig, &sig);
370                 /* FIELD signature == 0x06 */
371                 g_assert (*sig == 0x06);
372                 field->type = mono_metadata_parse_field_type (
373                         m, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
374                 if (mono_field_is_deleted (field))
375                         continue;
376                 if (class->generic_inst) {
377                         field->type = mono_class_inflate_generic_type (field->type, class->generic_inst->data.generic_inst);
378                         field->type->attrs = cols [MONO_FIELD_FLAGS];
379                 }
380
381                 field->parent = class;
382
383                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
384                         if (field->type->byref) {
385                                 blittable = FALSE;
386                         } else {
387                                 MonoClass *field_class = mono_class_from_mono_type (field->type);
388                                 if (!field_class || !field_class->blittable)
389                                         blittable = FALSE;
390                         }
391                 }
392                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
393                         mono_metadata_field_info (m, idx, &field->offset, NULL, NULL);
394                         if (field->offset == (guint32)-1)
395                                 g_warning ("%s not initialized correctly (missing field layout info for %s)", class->name, field->name);
396                 }
397
398                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
399                         mono_metadata_field_info (m, idx, NULL, &rva, NULL);
400                         if (!rva)
401                                 g_warning ("field %s in %s should have RVA data, but hasn't", field->name, class->name);
402                         field->data = mono_cli_rva_map (class->image->image_info, rva);
403                 }
404
405                 if (class->enumtype && !(cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC)) {
406                         class->enum_basetype = field->type;
407                         class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
408                         blittable = class->element_class->blittable;
409                 }
410
411                 /* The def_value of fields is compute lazily during vtable creation */
412         }
413
414         if (class == mono_defaults.string_class)
415                 blittable = FALSE;
416
417         class->blittable = blittable;
418
419         if (class->enumtype && !class->enum_basetype) {
420                 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
421                         G_BREAKPOINT ();
422         }
423         if (explicit_size && real_size) {
424                 class->instance_size = MAX (real_size, class->instance_size);
425         }
426
427         if (class->gen_params)
428                 return;
429
430         mono_class_layout_fields (class);
431 }
432
433 void
434 mono_class_layout_fields (MonoClass *class)
435 {
436         int i;
437         const int top = class->field.count;
438         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
439         guint32 pass, passes, real_size;
440         gboolean gc_aware_layout = FALSE;
441         MonoClassField *field;
442
443         /*
444          * Enable GC aware auto layout: in this mode, reference
445          * fields are grouped together inside objects, increasing collector 
446          * performance.
447          * Requires that all classes whose layout is known to native code be annotated
448          * with [StructLayout (LayoutKind.Sequential)]
449          */
450          /* corlib is missing [StructLayout] directives in many places */
451         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
452                 if (class->image != mono_defaults.corlib)
453                         gc_aware_layout = TRUE;
454         }
455
456         /*
457          * Compute field layout and total size (not considering static fields)
458          */
459
460         switch (layout) {
461         case TYPE_ATTRIBUTE_AUTO_LAYOUT:
462         case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
463
464                 if (gc_aware_layout)
465                         passes = 2;
466                 else
467                         passes = 1;
468
469                 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
470                         passes = 1;
471
472                 if (class->parent)
473                         real_size = class->parent->instance_size;
474                 else
475                         real_size = sizeof (MonoObject);
476
477                 for (pass = 0; pass < passes; ++pass) {
478                         for (i = 0; i < top; i++){
479                                 int size, align;
480                                 field = &class->fields [i];
481
482                                 if (mono_field_is_deleted (field))
483                                         continue;
484                                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
485                                         continue;
486
487                                 if (gc_aware_layout) {
488                                         /* 
489                                          * We process fields with reference type in the first pass,
490                                          * and fields with non-reference type in the second pass.
491                                          * We use IS_POINTER instead of IS_REFERENCE because in
492                                          * some internal structures, we store GC_MALLOCed memory
493                                          * in IntPtr fields...
494                                          */
495                                         if (MONO_TYPE_IS_POINTER (field->type)) {
496                                                 if (pass == 1)
497                                                         continue;
498                                         } else {
499                                                 if (pass == 0)
500                                                         continue;
501                                         }
502                                 }
503
504                                 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
505                                         (strcmp (field->name, "$PRIVATE$") == 0)) {
506                                         /* This field is a hack inserted by MCS to empty structures */
507                                         continue;
508                                 }
509
510                                 size = mono_type_size (field->type, &align);
511                         
512                                 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
513                                 align = class->packing_size ? MIN (class->packing_size, align): align;
514                                 class->min_align = MAX (align, class->min_align);
515                                 field->offset = real_size;
516                                 field->offset += align - 1;
517                                 field->offset &= ~(align - 1);
518                                 real_size = field->offset + size;
519                         }
520
521                         class->instance_size = MAX (real_size, class->instance_size);
522        
523                         if (class->instance_size & (class->min_align - 1)) {
524                                 class->instance_size += class->min_align - 1;
525                                 class->instance_size &= ~(class->min_align - 1);
526                         }
527                 }
528                 break;
529         case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
530                 real_size = 0;
531                 for (i = 0; i < top; i++) {
532                         int size, align;
533                         field = &class->fields [i];
534
535                         /*
536                          * There must be info about all the fields in a type if it
537                          * uses explicit layout.
538                          */
539
540                         if (mono_field_is_deleted (field))
541                                 continue;
542                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
543                                 continue;
544
545                         size = mono_type_size (field->type, &align);
546                         
547                         /*
548                          * When we get here, field->offset is already set by the
549                          * loader (for either runtime fields or fields loaded from metadata).
550                          * The offset is from the start of the object: this works for both
551                          * classes and valuetypes.
552                          */
553                         field->offset += sizeof (MonoObject);
554
555                         /*
556                          * Calc max size.
557                          */
558                         real_size = MAX (real_size, size + field->offset);
559                 }
560                 class->instance_size = MAX (real_size, class->instance_size);
561                 break;
562         }
563
564         class->size_inited = 1;
565
566         /*
567          * Compute static field layout and size
568          */
569         for (i = 0; i < top; i++){
570                 int size, align;
571                 field = &class->fields [i];
572                         
573                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
574                         continue;
575                 if (mono_field_is_deleted (field))
576                         continue;
577                         
578                 size = mono_type_size (field->type, &align);
579                 field->offset = class->class_size;
580                 field->offset += align - 1;
581                 field->offset &= ~(align - 1);
582                 class->class_size = field->offset + size;
583         }
584 }
585
586 static void
587 init_properties (MonoClass *class)
588 {
589         guint startm, endm, i, j;
590         guint32 cols [MONO_PROPERTY_SIZE];
591         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_PROPERTY];
592         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
593
594         class->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->property.last);
595         class->property.count = class->property.last - class->property.first;
596
597         class->properties = g_new0 (MonoProperty, class->property.count);
598         for (i = class->property.first; i < class->property.last; ++i) {
599                 mono_metadata_decode_row (pt, i, cols, MONO_PROPERTY_SIZE);
600                 class->properties [i - class->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
601                 class->properties [i - class->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
602
603                 startm = mono_metadata_methods_from_property (class->image, i, &endm);
604                 for (j = startm; j < endm; ++j) {
605                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
606                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
607                         case METHOD_SEMANTIC_SETTER:
608                                 class->properties [i - class->property.first].set = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
609                                 break;
610                         case METHOD_SEMANTIC_GETTER:
611                                 class->properties [i - class->property.first].get = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
612                                 break;
613                         default:
614                                 break;
615                         }
616                 }
617         }
618 }
619
620 static void
621 init_events (MonoClass *class)
622 {
623         guint startm, endm, i, j;
624         guint32 cols [MONO_EVENT_SIZE];
625         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_EVENT];
626         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
627
628         class->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->event.last);
629         class->event.count = class->event.last - class->event.first;
630
631         class->events = g_new0 (MonoEvent, class->event.count);
632         for (i = class->event.first; i < class->event.last; ++i) {
633                 mono_metadata_decode_row (pt, i, cols, MONO_EVENT_SIZE);
634                 class->events [i - class->event.first].attrs = cols [MONO_EVENT_FLAGS];
635                 class->events [i - class->event.first].name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
636
637                 startm = mono_metadata_methods_from_event (class->image, i, &endm);
638                 for (j = startm; j < endm; ++j) {
639                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
640                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
641                         case METHOD_SEMANTIC_ADD_ON:
642                                 class->events [i - class->event.first].add = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
643                                 break;
644                         case METHOD_SEMANTIC_REMOVE_ON:
645                                 class->events [i - class->event.first].remove = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
646                                 break;
647                         case METHOD_SEMANTIC_FIRE:
648                                 class->events [i - class->event.first].raise = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
649                                 break;
650                         case METHOD_SEMANTIC_OTHER: /* don't care for now */
651                         default:
652                                 break;
653                         }
654                 }
655         }
656 }
657
658 static guint
659 mono_get_unique_iid (MonoClass *class)
660 {
661         static GHashTable *iid_hash = NULL;
662         static guint iid = 0;
663
664         char *str;
665         gpointer value;
666         
667         g_assert (class->flags & TYPE_ATTRIBUTE_INTERFACE);
668
669         mono_loader_lock ();
670
671         if (!iid_hash)
672                 iid_hash = g_hash_table_new (g_str_hash, g_str_equal);
673
674         str = g_strdup_printf ("%s|%s.%s\n", class->image->name, class->name_space, class->name);
675
676         if (g_hash_table_lookup_extended (iid_hash, str, NULL, &value)) {
677                 mono_loader_unlock ();
678                 g_free (str);
679                 return (guint)value;
680         } else {
681                 g_hash_table_insert (iid_hash, str, (gpointer)iid);
682                 ++iid;
683         }
684
685         mono_loader_unlock ();
686
687         return iid - 1;
688 }
689
690 static void
691 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
692 {
693         int i;
694         MonoClass *ic;
695         
696         for (i = 0; i < klass->interface_count; i++) {
697                 ic = klass->interfaces [i];
698
699                 if (*res == NULL)
700                         *res = g_ptr_array_new ();
701                 g_ptr_array_add (*res, ic);
702
703                 collect_implemented_interfaces_aux (ic, res);
704         }
705 }
706
707 static inline GPtrArray*
708 collect_implemented_interfaces (MonoClass *klass)
709 {
710         GPtrArray *res = NULL;
711
712         collect_implemented_interfaces_aux (klass, &res);
713         return res;
714 }
715
716 static int
717 setup_interface_offsets (MonoClass *class, int cur_slot)
718 {
719         MonoClass *k, *ic;
720         int i, max_iid;
721         GPtrArray *ifaces;
722
723         /* compute maximum number of slots and maximum interface id */
724         max_iid = 0;
725         for (k = class; k ; k = k->parent) {
726                 for (i = 0; i < k->interface_count; i++) {
727                         ic = k->interfaces [i];
728
729                         if (!ic->inited)
730                                 mono_class_init (ic);
731
732                         if (max_iid < ic->interface_id)
733                                 max_iid = ic->interface_id;
734                 }
735         }
736
737         if (class->flags & TYPE_ATTRIBUTE_INTERFACE) {
738                 if (max_iid < class->interface_id)
739                         max_iid = class->interface_id;
740         }
741         class->max_interface_id = max_iid;
742         /* compute vtable offset for interfaces */
743         class->interface_offsets = g_malloc (sizeof (gpointer) * (max_iid + 1));
744
745         for (i = 0; i <= max_iid; i++)
746                 class->interface_offsets [i] = -1;
747
748         ifaces = collect_implemented_interfaces (class);
749         if (ifaces) {
750                 for (i = 0; i < ifaces->len; ++i) {
751                         ic = g_ptr_array_index (ifaces, i);
752                         class->interface_offsets [ic->interface_id] = cur_slot;
753                         cur_slot += ic->method.count;
754                 }
755                 g_ptr_array_free (ifaces, TRUE);
756         }
757
758         for (k = class->parent; k ; k = k->parent) {
759                 ifaces = collect_implemented_interfaces (k);
760                 if (ifaces) {
761                         for (i = 0; i < ifaces->len; ++i) {
762                                 ic = g_ptr_array_index (ifaces, i);
763
764                                 if (class->interface_offsets [ic->interface_id] == -1) {
765                                         int io = k->interface_offsets [ic->interface_id];
766
767                                         g_assert (io >= 0);
768
769                                         class->interface_offsets [ic->interface_id] = io;
770                                 }
771                         }
772                         g_ptr_array_free (ifaces, TRUE);
773                 }
774         }
775
776         if (class->flags & TYPE_ATTRIBUTE_INTERFACE)
777                 class->interface_offsets [class->interface_id] = cur_slot;
778
779         return cur_slot;
780 }
781
782 void
783 mono_class_setup_vtable (MonoClass *class, MonoMethod **overrides, int onum)
784 {
785         MonoClass *k, *ic;
786         MonoMethod **vtable;
787         int i, max_vtsize = 0, max_iid, cur_slot = 0;
788         GPtrArray *ifaces;
789         MonoGHashTable *override_map = NULL;
790
791         /* setup_vtable() must be called only once on the type */
792         if (class->interface_offsets) {
793                 g_warning ("vtable already computed in %s.%s", class->name_space, class->name);
794                 return;
795         }
796
797         ifaces = collect_implemented_interfaces (class);
798         if (ifaces) {
799                 for (i = 0; i < ifaces->len; i++) {
800                         MonoClass *ic = g_ptr_array_index (ifaces, i);
801                         max_vtsize += ic->method.count;
802                 }
803                 g_ptr_array_free (ifaces, TRUE);
804         }
805         
806         if (class->parent) {
807                 max_vtsize += class->parent->vtable_size;
808                 cur_slot = class->parent->vtable_size;
809         }
810
811         max_vtsize += class->method.count;
812
813         vtable = alloca (sizeof (gpointer) * max_vtsize);
814         memset (vtable, 0, sizeof (gpointer) * max_vtsize);
815
816         /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
817
818         cur_slot = setup_interface_offsets (class, cur_slot);
819         max_iid = class->max_interface_id;
820
821         if (class->parent && class->parent->vtable_size)
822                 memcpy (vtable, class->parent->vtable,  sizeof (gpointer) * class->parent->vtable_size);
823
824         /* override interface methods */
825         for (i = 0; i < onum; i++) {
826                 MonoMethod *decl = overrides [i*2];
827                 if (decl->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
828                         int dslot;
829                         g_assert (decl->slot != -1);
830                         dslot = decl->slot + class->interface_offsets [decl->klass->interface_id];
831                         vtable [dslot] = overrides [i*2 + 1];
832                         vtable [dslot]->slot = dslot;
833                         if (!override_map)
834                                 override_map = mono_g_hash_table_new (NULL, NULL);
835
836                         mono_g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
837                 }
838         }
839
840         for (k = class; k ; k = k->parent) {
841                 int nifaces = 0;
842                 ifaces = collect_implemented_interfaces (k);
843                 if (ifaces)
844                         nifaces = ifaces->len;
845                 for (i = 0; i < nifaces; i++) {
846                         int j, l, io;
847
848                         ic = g_ptr_array_index (ifaces, i);
849                         io = k->interface_offsets [ic->interface_id];
850
851                         g_assert (io >= 0);
852                         g_assert (io <= max_vtsize);
853
854                         if (k == class) {
855                                 for (l = 0; l < ic->method.count; l++) {
856                                         MonoMethod *im = ic->methods [l];                                               
857
858                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
859                                                 continue;
860
861                                         for (j = 0; j < class->method.count; ++j) {
862                                                 MonoMethod *cm = class->methods [j];
863                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
864                                                     !((cm->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) ||
865                                                     !(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT))
866                                                         continue;
867                                                 if (!strcmp(cm->name, im->name) && 
868                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
869                                                         g_assert (io + l <= max_vtsize);
870                                                         vtable [io + l] = cm;
871                                                 }
872                                         }
873                                 }
874                         } else {
875                                 /* already implemented */
876                                 if (io >= k->vtable_size)
877                                         continue;
878                         }
879                                 
880                         for (l = 0; l < ic->method.count; l++) {
881                                 MonoMethod *im = ic->methods [l];                                               
882                                 MonoClass *k1;
883
884                                 g_assert (io + l <= max_vtsize);
885
886                                 if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
887                                         continue;
888                                         
889                                 for (k1 = class; k1; k1 = k1->parent) {
890                                         for (j = 0; j < k1->method.count; ++j) {
891                                                 MonoMethod *cm = k1->methods [j];
892
893                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
894                                                     !(cm->flags & METHOD_ATTRIBUTE_PUBLIC))
895                                                         continue;
896                                                 
897                                                 if (!strcmp(cm->name, im->name) && 
898                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
899                                                         g_assert (io + l <= max_vtsize);
900                                                         vtable [io + l] = cm;
901                                                         break;
902                                                 }
903                                                 
904                                         }
905                                         g_assert (io + l <= max_vtsize);
906                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
907                                                 break;
908                                 }
909                         }
910
911                         for (l = 0; l < ic->method.count; l++) {
912                                 MonoMethod *im = ic->methods [l];                                               
913                                 char *qname, *fqname;
914                                 MonoClass *k1;
915                                 
916                                 if (vtable [io + l])
917                                         continue;
918                                         
919                                 qname = g_strconcat (ic->name, ".", im->name, NULL); 
920                                 if (ic->name_space && ic->name_space [0])
921                                         fqname = g_strconcat (ic->name_space, ".", ic->name, ".", im->name, NULL);
922                                 else
923                                         fqname = NULL;
924
925                                 for (k1 = class; k1; k1 = k1->parent) {
926                                         for (j = 0; j < k1->method.count; ++j) {
927                                                 MonoMethod *cm = k1->methods [j];
928
929                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
930                                                         continue;
931                                         
932                                                 if (((fqname && !strcmp (cm->name, fqname)) || !strcmp (cm->name, qname)) &&
933                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
934                                                         g_assert (io + l <= max_vtsize);
935                                                         vtable [io + l] = cm;
936                                                         break;
937                                                 }
938                                         }
939                                 }
940                                 g_free (qname);
941                                 g_free (fqname);
942                         }
943
944                         
945                         if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
946                                 for (l = 0; l < ic->method.count; l++) {
947                                         char *msig;
948                                         MonoMethod *im = ic->methods [l];
949                                         if (im->flags & METHOD_ATTRIBUTE_STATIC)
950                                                         continue;
951                                         g_assert (io + l <= max_vtsize);
952                                         if (!(vtable [io + l])) {
953                                                 for (j = 0; j < onum; ++j) {
954                                                         g_print (" at slot %d: %s (%d) overrides %s (%d)\n", io+l, overrides [j*2+1]->name, 
955                                                                  overrides [j*2+1]->slot, overrides [j*2]->name, overrides [j*2]->slot);
956                                                 }
957                                                 msig = mono_signature_get_desc (im->signature, FALSE);
958                                                 printf ("no implementation for interface method %s.%s::%s(%s) in class %s.%s\n",
959                                                         ic->name_space, ic->name, im->name, msig, class->name_space, class->name);
960                                                 g_free (msig);
961                                                 for (j = 0; j < class->method.count; ++j) {
962                                                         MonoMethod *cm = class->methods [j];
963                                                         msig = mono_signature_get_desc (cm->signature, FALSE);
964                                                         
965                                                         printf ("METHOD %s(%s)\n", cm->name, msig);
966                                                         g_free (msig);
967                                                 }
968                                                 g_assert_not_reached ();
969                                         }
970                                 }
971                         }
972                 
973                         for (l = 0; l < ic->method.count; l++) {
974                                 MonoMethod *im = vtable [io + l];
975
976                                 if (im) {
977                                         g_assert (io + l <= max_vtsize);
978                                         if (im->slot < 0) {
979                                                 /* FIXME: why do we need this ? */
980                                                 im->slot = io + l;
981                                                 /* g_assert_not_reached (); */
982                                         }
983                                 }
984                         }
985                 }
986                 if (ifaces)
987                         g_ptr_array_free (ifaces, TRUE);
988         } 
989
990         for (i = 0; i < class->method.count; ++i) {
991                 MonoMethod *cm;
992                
993                 cm = class->methods [i];
994
995                 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && (cm->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
996                         int slot = -1;
997                         for (k = class->parent; k ; k = k->parent) {
998                                 int j;
999                                 for (j = 0; j < k->method.count; ++j) {
1000                                         MonoMethod *m1 = k->methods [j];
1001                                         if (!(m1->flags & METHOD_ATTRIBUTE_VIRTUAL))
1002                                                 continue;
1003                                         if (!strcmp(cm->name, m1->name) && 
1004                                             mono_metadata_signature_equal (cm->signature, m1->signature)) {
1005                                                 slot = k->methods [j]->slot;
1006                                                 g_assert (cm->slot < max_vtsize);
1007                                                 if (!override_map)
1008                                                         override_map = mono_g_hash_table_new (NULL, NULL);
1009                                                 mono_g_hash_table_insert (override_map, m1, cm);
1010                                                 break;
1011                                         }
1012                                 }
1013                                 if (slot >= 0) 
1014                                         break;
1015                         }
1016                         if (slot >= 0)
1017                                 cm->slot = slot;
1018                 }
1019
1020                 if (cm->slot < 0)
1021                         cm->slot = cur_slot++;
1022
1023                 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT) && !cm->signature->generic_param_count)
1024                         vtable [cm->slot] = cm;
1025         }
1026
1027         /* override non interface methods */
1028         for (i = 0; i < onum; i++) {
1029                 MonoMethod *decl = overrides [i*2];
1030                 if (!(decl->klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
1031                         g_assert (decl->slot != -1);
1032                         vtable [decl->slot] = overrides [i*2 + 1];
1033                         overrides [i * 2 + 1]->slot = decl->slot;
1034                         if (!override_map)
1035                                 override_map = mono_g_hash_table_new (NULL, NULL);
1036                         mono_g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
1037                 }
1038         }
1039
1040         /*
1041          * If a method occupies more than one place in the vtable, and it is
1042          * overriden, then change the other occurances too.
1043          */
1044         if (override_map) {
1045                 for (i = 0; i < max_vtsize; ++i)
1046                         if (vtable [i]) {
1047                                 MonoMethod *cm = mono_g_hash_table_lookup (override_map, vtable [i]);
1048                                 if (cm)
1049                                         vtable [i] = cm;
1050                         }
1051
1052                 mono_g_hash_table_destroy (override_map);
1053         }
1054        
1055         class->vtable_size = cur_slot;
1056         class->vtable = g_malloc0 (sizeof (gpointer) * class->vtable_size);
1057         memcpy (class->vtable, vtable,  sizeof (gpointer) * class->vtable_size);
1058
1059         if (mono_print_vtable) {
1060                 int icount = 0;
1061
1062                 for (i = 0; i <= max_iid; i++)
1063                         if (class->interface_offsets [i] != -1)
1064                                 icount++;
1065
1066                 printf ("VTable %s.%s (size = %d, interfaces = %d)\n", class->name_space, 
1067                         class->name, class->vtable_size, icount); 
1068
1069                 for (i = 0; i < class->vtable_size; ++i) {
1070                         MonoMethod *cm;
1071                
1072                         cm = vtable [i];
1073                         if (cm) {
1074                                 printf ("  slot %03d(%03d) %s.%s:%s\n", i, cm->slot,
1075                                         cm->klass->name_space, cm->klass->name,
1076                                         cm->name);
1077                         }
1078                 }
1079
1080
1081                 if (icount) {
1082                         printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space, 
1083                                 class->name, max_iid);
1084         
1085                         for (i = 0; i < class->interface_count; i++) {
1086                                 ic = class->interfaces [i];
1087                                 printf ("  slot %03d(%03d) %s.%s\n",  
1088                                         class->interface_offsets [ic->interface_id],
1089                                         ic->method.count, ic->name_space, ic->name);
1090                         }
1091
1092                         for (k = class->parent; k ; k = k->parent) {
1093                                 for (i = 0; i < k->interface_count; i++) {
1094                                         ic = k->interfaces [i]; 
1095                                         printf ("  slot %03d(%03d) %s.%s\n", 
1096                                                 class->interface_offsets [ic->interface_id],
1097                                                 ic->method.count, ic->name_space, ic->name);
1098                                 }
1099                         }
1100                 }
1101         }
1102 }
1103
1104 /**
1105  * mono_class_init:
1106  * @class: the class to initialize
1107  *
1108  * compute the instance_size, class_size and other infos that cannot be 
1109  * computed at mono_class_get() time. Also compute a generic vtable and 
1110  * the method slot numbers. We use this infos later to create a domain
1111  * specific vtable.  
1112  */
1113 void
1114 mono_class_init (MonoClass *class)
1115 {
1116         int i;
1117         static MonoMethod *default_ghc = NULL;
1118         static MonoMethod *default_finalize = NULL;
1119         static int finalize_slot = -1;
1120         static int ghc_slot = -1;
1121         MonoMethod **overrides;
1122         int onum = 0;
1123
1124         g_assert (class);
1125
1126         if (class->inited)
1127                 return;
1128
1129         /*g_print ("Init class %s\n", class->name);*/
1130
1131         /* We do everything inside the lock to prevent races */
1132         mono_loader_lock ();
1133
1134         if (class->inited) {
1135                 mono_loader_unlock ();
1136                 /* Somebody might have gotten in before us */
1137                 return;
1138         }
1139
1140         if (class->init_pending) {
1141                 /* this indicates a cyclic dependency */
1142                 g_error ("pending init %s.%s\n", class->name_space, class->name);
1143         }
1144
1145         class->init_pending = 1;
1146
1147         mono_stats.initialized_class_count++;
1148
1149         if (class->parent && !class->parent->inited)
1150                 mono_class_init (class->parent);
1151
1152         /*
1153          * Computes the size used by the fields, and their locations
1154          */
1155         if (!class->size_inited)
1156                 class_compute_field_layout (class);
1157
1158         /* initialize method pointers */
1159         if (class->rank) {
1160                 MonoMethod *ctor;
1161                 MonoMethodSignature *sig;
1162                 class->method.count = class->rank > 1? 2: 1;
1163                 sig = mono_metadata_signature_alloc (class->image, class->rank);
1164                 sig->ret = &mono_defaults.void_class->byval_arg;
1165                 sig->pinvoke = TRUE;
1166                 for (i = 0; i < class->rank; ++i)
1167                         sig->params [i] = &mono_defaults.int32_class->byval_arg;
1168
1169                 ctor = (MonoMethod *) g_new0 (MonoMethodPInvoke, 1);
1170                 ctor->klass = class;
1171                 ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1172                 ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1173                 ctor->signature = sig;
1174                 ctor->name = ".ctor";
1175                 ctor->slot = -1;
1176                 class->methods = g_new (MonoMethod*, class->method.count);
1177                 class->methods [0] = ctor;
1178                 if (class->rank > 1) {
1179                         sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1180                         sig->ret = &mono_defaults.void_class->byval_arg;
1181                         sig->pinvoke = TRUE;
1182                         for (i = 0; i < class->rank * 2; ++i)
1183                                 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1184
1185                         ctor = (MonoMethod *) g_new0 (MonoMethodPInvoke, 1);
1186                         ctor->klass = class;
1187                         ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1188                         ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1189                         ctor->signature = sig;
1190                         ctor->name = ".ctor";
1191                         ctor->slot = -1;
1192                         class->methods [1] = ctor;
1193                 }
1194         } else {
1195                 if (!class->generic_inst && !class->methods) {
1196                         class->methods = g_new (MonoMethod*, class->method.count);
1197                         for (i = 0; i < class->method.count; ++i) {
1198                                 class->methods [i] = mono_get_method (class->image,
1199                                                                       MONO_TOKEN_METHOD_DEF | (i + class->method.first + 1), class);
1200                         }
1201                 }
1202         }
1203
1204         init_properties (class);
1205         init_events (class);
1206
1207         i = mono_metadata_nesting_typedef (class->image, class->type_token, 1);
1208         while (i) {
1209                 MonoClass* nclass;
1210                 guint32 cols [MONO_NESTED_CLASS_SIZE];
1211                 mono_metadata_decode_row (&class->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
1212                 nclass = mono_class_create_from_typedef (class->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
1213                 class->nested_classes = g_list_prepend (class->nested_classes, nclass);
1214
1215                 i = mono_metadata_nesting_typedef (class->image, class->type_token, i + 1);
1216         }
1217
1218         mono_class_setup_supertypes (class);
1219
1220         if (class->flags & TYPE_ATTRIBUTE_INTERFACE) {
1221                 for (i = 0; i < class->method.count; ++i)
1222                         class->methods [i]->slot = i;
1223                 class->init_pending = 0;
1224                 class->inited = 1;
1225                 /* 
1226                  * class->interface_offsets is needed for the castclass/isinst code, so
1227                  * we have to setup them for interfaces, too.
1228                  */
1229                 setup_interface_offsets (class, 0);
1230                 mono_loader_unlock ();
1231                 return;
1232         }
1233
1234         overrides = mono_class_get_overrides (class->image, class->type_token, &onum);  
1235         mono_class_setup_vtable (class, overrides, onum);
1236         g_free (overrides);
1237
1238         class->inited = 1;
1239         class->init_pending = 0;
1240
1241         if (!default_ghc) {
1242                 if (class == mono_defaults.object_class) { 
1243                        
1244                         for (i = 0; i < class->vtable_size; ++i) {
1245                                 MonoMethod *cm = class->vtable [i];
1246                
1247                                 if (!strcmp (cm->name, "GetHashCode")) {
1248                                         ghc_slot = i;
1249                                         break;
1250                                 }
1251                         }
1252
1253                         g_assert (ghc_slot > 0);
1254
1255                         default_ghc = class->vtable [ghc_slot];
1256                 }
1257         }
1258         
1259         class->ghcimpl = 1;
1260         if (class->parent) { 
1261
1262                 if (class->vtable [ghc_slot] == default_ghc) {
1263                         class->ghcimpl = 0;
1264                 }
1265         }
1266
1267         if (!default_finalize) {
1268                 if (class == mono_defaults.object_class) { 
1269                        
1270                         for (i = 0; i < class->vtable_size; ++i) {
1271                                 MonoMethod *cm = class->vtable [i];
1272                
1273                                 if (!strcmp (cm->name, "Finalize")) {
1274                                         finalize_slot = i;
1275                                         break;
1276                                 }
1277                         }
1278
1279                         g_assert (finalize_slot > 0);
1280
1281                         default_finalize = class->vtable [finalize_slot];
1282                 }
1283         }
1284
1285         /* Object::Finalize should have empty implemenatation */
1286         class->has_finalize = 0;
1287         if (class->parent) { 
1288                 if (class->vtable [finalize_slot] != default_finalize)
1289                         class->has_finalize = 1;
1290         }
1291
1292         mono_loader_unlock ();
1293
1294         if (mono_debugger_class_init_func)
1295                 mono_debugger_class_init_func (class);
1296 }
1297
1298
1299 void
1300 mono_class_setup_mono_type (MonoClass *class)
1301 {
1302         const char *name = class->name;
1303         const char *nspace = class->name_space;
1304
1305         if (class->flags & TYPE_ATTRIBUTE_INTERFACE)
1306                 class->interface_id = mono_get_unique_iid (class);
1307
1308         class->this_arg.byref = 1;
1309         class->this_arg.data.klass = class;
1310         class->this_arg.type = MONO_TYPE_CLASS;
1311         class->byval_arg.data.klass = class;
1312         class->byval_arg.type = MONO_TYPE_CLASS;
1313
1314         if (!strcmp (nspace, "System")) {
1315                 if (!strcmp (name, "ValueType")) {
1316                         /*
1317                          * do not set the valuetype bit for System.ValueType.
1318                          * class->valuetype = 1;
1319                          */
1320                 } else if (!strcmp (name, "Enum")) {
1321                         /*
1322                          * do not set the valuetype bit for System.Enum.
1323                          * class->valuetype = 1;
1324                          */
1325                         class->valuetype = 0;
1326                         class->enumtype = 0;
1327                 } else if (!strcmp (name, "Object")) {
1328                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
1329                 } else if (!strcmp (name, "String")) {
1330                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
1331                 } else if (!strcmp (name, "TypedReference")) {
1332                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
1333                 }
1334         }
1335         
1336         if (class->valuetype) {
1337                 int t = MONO_TYPE_VALUETYPE;
1338                 if (!strcmp (nspace, "System")) {
1339                         switch (*name) {
1340                         case 'B':
1341                                 if (!strcmp (name, "Boolean")) {
1342                                         t = MONO_TYPE_BOOLEAN;
1343                                 } else if (!strcmp(name, "Byte")) {
1344                                         t = MONO_TYPE_U1;
1345                                         class->blittable = TRUE;                                                
1346                                 }
1347                                 break;
1348                         case 'C':
1349                                 if (!strcmp (name, "Char")) {
1350                                         t = MONO_TYPE_CHAR;
1351                                 }
1352                                 break;
1353                         case 'D':
1354                                 if (!strcmp (name, "Double")) {
1355                                         t = MONO_TYPE_R8;
1356                                         class->blittable = TRUE;                                                
1357                                 }
1358                                 break;
1359                         case 'I':
1360                                 if (!strcmp (name, "Int32")) {
1361                                         t = MONO_TYPE_I4;
1362                                         class->blittable = TRUE;
1363                                 } else if (!strcmp(name, "Int16")) {
1364                                         t = MONO_TYPE_I2;
1365                                         class->blittable = TRUE;
1366                                 } else if (!strcmp(name, "Int64")) {
1367                                         t = MONO_TYPE_I8;
1368                                         class->blittable = TRUE;
1369                                 } else if (!strcmp(name, "IntPtr")) {
1370                                         t = MONO_TYPE_I;
1371                                         class->blittable = TRUE;
1372                                 }
1373                                 break;
1374                         case 'S':
1375                                 if (!strcmp (name, "Single")) {
1376                                         t = MONO_TYPE_R4;
1377                                         class->blittable = TRUE;                                                
1378                                 } else if (!strcmp(name, "SByte")) {
1379                                         t = MONO_TYPE_I1;
1380                                         class->blittable = TRUE;
1381                                 }
1382                                 break;
1383                         case 'U':
1384                                 if (!strcmp (name, "UInt32")) {
1385                                         t = MONO_TYPE_U4;
1386                                         class->blittable = TRUE;
1387                                 } else if (!strcmp(name, "UInt16")) {
1388                                         t = MONO_TYPE_U2;
1389                                         class->blittable = TRUE;
1390                                 } else if (!strcmp(name, "UInt64")) {
1391                                         t = MONO_TYPE_U8;
1392                                         class->blittable = TRUE;
1393                                 } else if (!strcmp(name, "UIntPtr")) {
1394                                         t = MONO_TYPE_U;
1395                                         class->blittable = TRUE;
1396                                 }
1397                                 break;
1398                         case 'T':
1399                                 if (!strcmp (name, "TypedReference")) {
1400                                         t = MONO_TYPE_TYPEDBYREF;
1401                                         class->blittable = TRUE;
1402                                 }
1403                                 break;
1404                         case 'V':
1405                                 if (!strcmp (name, "Void")) {
1406                                         t = MONO_TYPE_VOID;
1407                                 }
1408                                 break;
1409                         default:
1410                                 break;
1411                         }
1412                 }
1413                 class->this_arg.type = class->byval_arg.type = t;
1414         }
1415 }
1416
1417 void
1418 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
1419 {
1420         gboolean system_namespace;
1421
1422         system_namespace = !strcmp (class->name_space, "System");
1423
1424         /* if root of the hierarchy */
1425         if (system_namespace && !strcmp (class->name, "Object")) {
1426                 class->parent = NULL;
1427                 class->instance_size = sizeof (MonoObject);
1428                 return;
1429         }
1430         if (!strcmp (class->name, "<Module>")) {
1431                 class->parent = NULL;
1432                 class->instance_size = 0;
1433                 return;
1434         }
1435
1436         if (!(class->flags & TYPE_ATTRIBUTE_INTERFACE)) {
1437                 class->parent = parent;
1438
1439                 if (!parent)
1440                         g_assert_not_reached (); /* FIXME */
1441
1442                 if (parent->generic_inst && !parent->name) {
1443                         /*
1444                          * If the parent is a generic instance, we may get
1445                          * called before it is fully initialized, especially
1446                          * before it has its name.
1447                          */
1448                         return;
1449                 }
1450
1451                 class->marshalbyref = parent->marshalbyref;
1452                 class->contextbound  = parent->contextbound;
1453                 class->delegate  = parent->delegate;
1454                 
1455                 if (system_namespace) {
1456                         if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
1457                                 class->marshalbyref = 1;
1458
1459                         if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject")) 
1460                                 class->contextbound  = 1;
1461
1462                         if (*class->name == 'D' && !strcmp (class->name, "Delegate")) 
1463                                 class->delegate  = 1;
1464                 }
1465
1466                 if (class->parent->enumtype || ((strcmp (class->parent->name, "ValueType") == 0) && 
1467                                                 (strcmp (class->parent->name_space, "System") == 0)))
1468                         class->valuetype = 1;
1469                 if (((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
1470                         class->valuetype = class->enumtype = 1;
1471                 }
1472                 /*class->enumtype = class->parent->enumtype; */
1473                 mono_class_setup_supertypes (class);
1474         } else {
1475                 class->parent = NULL;
1476         }
1477
1478 }
1479
1480 void
1481 mono_class_setup_supertypes (MonoClass *class)
1482 {
1483         MonoClass *k;
1484         int ms, i;
1485
1486         if (class->supertypes)
1487                 return;
1488
1489         class->idepth = 0;
1490         for (k = class; k ; k = k->parent) {
1491                 class->idepth++;
1492         }
1493
1494         ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
1495         class->supertypes = g_new0 (MonoClass *, ms);
1496
1497         if (class->parent) {
1498                 for (i = class->idepth, k = class; k ; k = k->parent)
1499                         class->supertypes [--i] = k;
1500         } else {
1501                 class->supertypes [0] = class;
1502         }
1503 }       
1504
1505 /**
1506  * @image: context where the image is created
1507  * @type_token:  typedef token
1508  */
1509 static MonoClass *
1510 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
1511 {
1512         MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
1513         MonoClass *class, *parent = NULL;
1514         guint32 cols [MONO_TYPEDEF_SIZE];
1515         guint32 cols_next [MONO_TYPEDEF_SIZE];
1516         guint tidx = mono_metadata_token_index (type_token);
1517         const char *name, *nspace;
1518         guint icount = 0; 
1519         MonoClass **interfaces;
1520
1521         mono_loader_lock ();
1522
1523         if ((class = g_hash_table_lookup (image->class_cache, GUINT_TO_POINTER (type_token)))) {
1524                 mono_loader_unlock ();
1525                 return class;
1526         }
1527
1528         g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
1529         
1530         mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
1531         
1532         name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1533         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1534
1535         if (cols [MONO_TYPEDEF_EXTENDS])
1536                 parent = mono_class_get (image, mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]));
1537         interfaces = mono_metadata_interfaces_from_typedef (image, type_token, &icount);
1538
1539         class = g_malloc0 (sizeof (MonoClass));
1540                            
1541         g_hash_table_insert (image->class_cache, GUINT_TO_POINTER (type_token), class);
1542
1543         class->interfaces = interfaces;
1544         class->interface_count = icount;
1545
1546         class->name = name;
1547         class->name_space = nspace;
1548
1549         class->image = image;
1550         class->type_token = type_token;
1551         class->flags = cols [MONO_TYPEDEF_FLAGS];
1552
1553         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
1554                 class->unicode = 1;
1555         /* fixme: maybe we must set this on windows 
1556         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
1557                 class->unicode = 1;
1558         */
1559
1560         class->cast_class = class->element_class = class;
1561
1562         /*g_print ("Load class %s\n", name);*/
1563
1564         mono_class_setup_parent (class, parent);
1565
1566         mono_class_setup_mono_type (class);
1567
1568         /*
1569          * Compute the field and method lists
1570          */
1571         class->field.first  = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
1572         class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
1573
1574         if (tt->rows > tidx){           
1575                 mono_metadata_decode_row (tt, tidx, cols_next, CSIZE (cols_next));
1576                 class->field.last  = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1577                 class->method.last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1578         } else {
1579                 class->field.last  = image->tables [MONO_TABLE_FIELD].rows;
1580                 class->method.last = image->tables [MONO_TABLE_METHOD].rows;
1581         }
1582
1583         if (cols [MONO_TYPEDEF_FIELD_LIST] && 
1584             cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
1585                 class->field.count = class->field.last - class->field.first;
1586         else
1587                 class->field.count = 0;
1588
1589         if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
1590                 class->method.count = class->method.last - class->method.first;
1591         else
1592                 class->method.count = 0;
1593
1594         /* reserve space to store vector pointer in arrays */
1595         if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
1596                 class->instance_size += 2 * sizeof (gpointer);
1597                 g_assert (class->field.count == 0);
1598         }
1599
1600         if (class->enumtype)
1601                 class_compute_field_layout (class);
1602
1603         if ((type_token = mono_metadata_nested_in_typedef (image, type_token)))
1604                 class->nested_in = mono_class_create_from_typedef (image, type_token);
1605
1606         class->gen_params = mono_metadata_load_generic_params (image, class->type_token, &icount);
1607         class->num_gen_params = icount;
1608
1609         mono_loader_unlock ();
1610
1611         return class;
1612 }
1613
1614 static char*
1615 get_instantiation_name (const char *name, MonoGenericInst *ginst)
1616 {
1617         GString *res = g_string_new (name);
1618         const char *p;
1619         int i;
1620         MonoClass *argclass;
1621         
1622         p = strchr (name, '<');
1623         if (p) {
1624                 g_string_truncate (res, (p - name) + 1);
1625         } else {
1626                 g_string_append_c (res, '<');
1627         }
1628         for (i = 0; i < ginst->type_argc; ++i) {
1629                 if (i > 0)
1630                         g_string_append_c (res, ',');
1631                 argclass = mono_class_from_mono_type (ginst->type_argv [i]);
1632                 g_string_append (res, argclass->name);
1633         }
1634         g_string_append_c (res, '>');
1635         return g_string_free (res, FALSE);
1636 }
1637
1638 static void
1639 mono_class_initialize_generic (MonoGenericInst *ginst, gboolean inflate_methods)
1640 {
1641         MonoClass *klass, *gklass;
1642
1643         if (ginst->initialized || ginst->init_pending)
1644                 return;
1645
1646         gklass = mono_class_from_mono_type (ginst->generic_type);
1647         mono_class_init (gklass);
1648
1649         klass = ginst->klass;
1650         klass->name = get_instantiation_name (gklass->name, ginst);
1651
1652         mono_class_setup_parent (klass, gklass->parent);
1653         mono_class_setup_mono_type (klass);
1654
1655         if (inflate_methods) {
1656                 int i;
1657
1658                 klass->field = gklass->field;
1659                 klass->method = gklass->method;
1660                 klass->methods = g_new0 (MonoMethod *, klass->method.count);
1661                 for (i = 0; i < klass->method.count; i++)
1662                         klass->methods [i] = mono_class_inflate_generic_method (gklass->methods [i], ginst);
1663         }
1664
1665         g_hash_table_insert (klass->image->generics_cache, ginst->generic_type, klass);
1666         ginst->initialized = TRUE;
1667 }
1668
1669 MonoClass*
1670 mono_class_from_generic (MonoType *gtype, gboolean inflate_methods)
1671 {
1672         MonoGenericInst *ginst = gtype->data.generic_inst;
1673         MonoClass *class, *gklass;
1674         MonoImage *image;
1675
1676         if (ginst->klass) {
1677                 mono_class_initialize_generic (ginst, TRUE);
1678                 return ginst->klass;
1679         }
1680
1681         mono_loader_lock ();
1682
1683         gklass = mono_class_from_mono_type (ginst->generic_type);
1684         mono_class_init (gklass);
1685
1686         image = gklass->image;
1687         if ((class = g_hash_table_lookup (image->generics_cache, gtype))) {
1688                 mono_loader_unlock ();
1689                 return class;
1690         }
1691
1692         class = g_malloc0 (sizeof (MonoClass));
1693         class->name_space = gklass->name_space;
1694         class->name = get_instantiation_name (gklass->name, ginst);
1695         class->image = image;
1696         class->flags = gklass->flags;
1697
1698         class->generic_inst = gtype;
1699
1700         class->cast_class = class->element_class = class;
1701
1702         if (inflate_methods) {
1703                 int i;
1704
1705                 mono_class_setup_parent (class, gklass->parent);
1706                 mono_class_setup_mono_type (class);
1707
1708                 class->field = gklass->field;
1709                 class->method = gklass->method;
1710                 class->methods = g_new0 (MonoMethod *, class->method.count);
1711                 for (i = 0; i < class->method.count; i++)
1712                         class->methods [i] = mono_class_inflate_generic_method (gklass->methods [i], ginst);
1713         }
1714
1715         g_hash_table_insert (image->generics_cache, gtype, class);
1716
1717         mono_loader_unlock ();
1718
1719         return class;
1720 }
1721
1722 MonoClass *
1723 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
1724 {
1725         MonoClass *klass, **ptr;
1726         int count, pos, i;
1727
1728         if (param->pklass)
1729                 return param->pklass;
1730
1731         klass = param->pklass = g_new0 (MonoClass, 1);
1732
1733         for (count = 0, ptr = param->constraints; ptr && *ptr; ptr++, count++)
1734                 ;
1735
1736         pos = 0;
1737         if ((count > 0) && !(param->constraints [0]->flags & TYPE_ATTRIBUTE_INTERFACE)) {
1738                 klass->parent = param->constraints [0];
1739                 pos++;
1740         } else
1741                 klass->parent = mono_defaults.object_class;
1742
1743         if (count - pos > 0) {
1744                 int j;
1745
1746                 klass->interface_count = count - pos;
1747                 klass->interfaces = g_new0 (MonoClass *, count - pos);
1748                 for (i = pos; i < count; i++) {
1749                         klass->interfaces [i - pos] = param->constraints [i];
1750                         klass->method.count += param->constraints [i]->method.count;
1751                 }
1752
1753                 klass->methods = g_new0 (MonoMethod *, klass->method.count);
1754                 for (i = pos; i < count; i++) {
1755                         MonoClass *iface = klass->interfaces [i - pos];
1756                         for (j = 0; j < iface->method.count; j++)
1757                                 klass->methods [klass->method.last++] = iface->methods [j];
1758                 }
1759         }
1760
1761         klass->name = g_strdup_printf (is_mvar ? "!!%d" : "!%d", param->num);
1762         klass->name_space = "";
1763         klass->image = image;
1764         klass->cast_class = klass->element_class = klass;
1765         klass->enum_basetype = &klass->element_class->byval_arg;
1766         klass->flags = TYPE_ATTRIBUTE_INTERFACE;
1767
1768         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
1769         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
1770         klass->this_arg.byref = TRUE;
1771
1772         mono_class_init (klass);
1773
1774         return klass;
1775 }
1776
1777 static MonoClass *
1778 my_mono_class_from_generic_parameter (MonoGenericParam *param, gboolean is_mvar)
1779 {
1780         MonoClass *klass;
1781
1782         if (param->pklass)
1783                 return param->pklass;
1784
1785         klass = g_new0 (MonoClass, 1);
1786
1787         klass->name = g_strdup_printf (is_mvar ? "!!%d" : "!%d", param->num);
1788         klass->name_space = "";
1789         klass->image = mono_defaults.corlib;
1790         klass->cast_class = klass->element_class = klass;
1791         klass->enum_basetype = &klass->element_class->byval_arg;
1792         klass->flags = TYPE_ATTRIBUTE_INTERFACE;
1793
1794         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
1795         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
1796         klass->this_arg.byref = TRUE;
1797
1798         mono_class_init (klass);
1799
1800         return klass;
1801 }
1802
1803 MonoClass *
1804 mono_ptr_class_get (MonoType *type)
1805 {
1806         MonoClass *result;
1807         MonoClass *el_class;
1808         static GHashTable *ptr_hash = NULL;
1809
1810         mono_loader_lock ();
1811
1812         if (!ptr_hash)
1813                 ptr_hash = g_hash_table_new (NULL, NULL);
1814         el_class = mono_class_from_mono_type (type);
1815         if ((result = g_hash_table_lookup (ptr_hash, el_class))) {
1816                 mono_loader_unlock ();
1817                 return result;
1818         }
1819         result = g_new0 (MonoClass, 1);
1820
1821         result->parent = NULL; /* no parent for PTR types */
1822         result->name = "System";
1823         result->name_space = "MonoPtrFakeClass";
1824         result->image = el_class->image;
1825         result->inited = TRUE;
1826         result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
1827         /* Can pointers get boxed? */
1828         result->instance_size = sizeof (gpointer);
1829         result->cast_class = result->element_class = el_class;
1830         result->enum_basetype = &result->element_class->byval_arg;
1831
1832         result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
1833         result->this_arg.data.type = result->byval_arg.data.type = result->enum_basetype;
1834         result->this_arg.byref = TRUE;
1835
1836         mono_class_setup_supertypes (result);
1837
1838         g_hash_table_insert (ptr_hash, el_class, result);
1839
1840         mono_loader_unlock ();
1841
1842         return result;
1843 }
1844
1845 static MonoClass *
1846 mono_fnptr_class_get (MonoMethodSignature *sig)
1847 {
1848         MonoClass *result;
1849         static GHashTable *ptr_hash = NULL;
1850
1851         mono_loader_lock ();
1852
1853         if (!ptr_hash)
1854                 ptr_hash = g_hash_table_new (NULL, NULL);
1855         
1856         if ((result = g_hash_table_lookup (ptr_hash, sig))) {
1857                 mono_loader_unlock ();
1858                 return result;
1859         }
1860         result = g_new0 (MonoClass, 1);
1861
1862         result->parent = NULL; /* no parent for PTR types */
1863         result->name = "System";
1864         result->name_space = "MonoFNPtrFakeClass";
1865         result->image = NULL; /* need to fix... */
1866         result->inited = TRUE;
1867         result->flags = TYPE_ATTRIBUTE_CLASS; // | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
1868         /* Can pointers get boxed? */
1869         result->instance_size = sizeof (gpointer);
1870         result->cast_class = result->element_class = result;
1871
1872         result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
1873         result->this_arg.data.method = result->byval_arg.data.method = sig;
1874         result->this_arg.byref = TRUE;
1875         result->enum_basetype = &result->element_class->byval_arg;
1876
1877         mono_class_setup_supertypes (result);
1878
1879         g_hash_table_insert (ptr_hash, sig, result);
1880
1881         mono_loader_unlock ();
1882
1883         return result;
1884 }
1885
1886 MonoClass *
1887 mono_class_from_mono_type (MonoType *type)
1888 {
1889         switch (type->type) {
1890         case MONO_TYPE_OBJECT:
1891                 return type->data.klass? type->data.klass: mono_defaults.object_class;
1892         case MONO_TYPE_VOID:
1893                 return type->data.klass? type->data.klass: mono_defaults.void_class;
1894         case MONO_TYPE_BOOLEAN:
1895                 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
1896         case MONO_TYPE_CHAR:
1897                 return type->data.klass? type->data.klass: mono_defaults.char_class;
1898         case MONO_TYPE_I1:
1899                 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
1900         case MONO_TYPE_U1:
1901                 return type->data.klass? type->data.klass: mono_defaults.byte_class;
1902         case MONO_TYPE_I2:
1903                 return type->data.klass? type->data.klass: mono_defaults.int16_class;
1904         case MONO_TYPE_U2:
1905                 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
1906         case MONO_TYPE_I4:
1907                 return type->data.klass? type->data.klass: mono_defaults.int32_class;
1908         case MONO_TYPE_U4:
1909                 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
1910         case MONO_TYPE_I:
1911                 return type->data.klass? type->data.klass: mono_defaults.int_class;
1912         case MONO_TYPE_U:
1913                 return type->data.klass? type->data.klass: mono_defaults.uint_class;
1914         case MONO_TYPE_I8:
1915                 return type->data.klass? type->data.klass: mono_defaults.int64_class;
1916         case MONO_TYPE_U8:
1917                 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
1918         case MONO_TYPE_R4:
1919                 return type->data.klass? type->data.klass: mono_defaults.single_class;
1920         case MONO_TYPE_R8:
1921                 return type->data.klass? type->data.klass: mono_defaults.double_class;
1922         case MONO_TYPE_STRING:
1923                 return type->data.klass? type->data.klass: mono_defaults.string_class;
1924         case MONO_TYPE_TYPEDBYREF:
1925                 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
1926         case MONO_TYPE_ARRAY:
1927                 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
1928         case MONO_TYPE_PTR:
1929                 return mono_ptr_class_get (type->data.type);
1930         case MONO_TYPE_FNPTR:
1931                 return mono_fnptr_class_get (type->data.method);
1932         case MONO_TYPE_SZARRAY:
1933                 return mono_array_class_get (type->data.klass, 1);
1934         case MONO_TYPE_CLASS:
1935         case MONO_TYPE_VALUETYPE:
1936                 return type->data.klass;
1937         case MONO_TYPE_GENERICINST:
1938                 return mono_class_from_generic (type, TRUE);
1939         case MONO_TYPE_VAR:
1940                 return my_mono_class_from_generic_parameter (type->data.generic_param, FALSE);
1941         case MONO_TYPE_MVAR:
1942                 return my_mono_class_from_generic_parameter (type->data.generic_param, TRUE);
1943         default:
1944                 g_warning ("implement me 0x%02x\n", type->type);
1945                 g_assert_not_reached ();
1946         }
1947         
1948         return NULL;
1949 }
1950
1951 /**
1952  * @image: context where the image is created
1953  * @type_spec:  typespec token
1954  */
1955 static MonoClass *
1956 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec)
1957 {
1958         MonoType *type;
1959         MonoClass *class;
1960
1961         type = mono_type_create_from_typespec (image, type_spec);
1962
1963         switch (type->type) {
1964         case MONO_TYPE_ARRAY:
1965                 class = mono_array_class_get (type->data.array->eklass, type->data.array->rank);
1966                 break;
1967         case MONO_TYPE_SZARRAY:
1968                 class = mono_array_class_get (type->data.klass, 1);
1969                 break;
1970         case MONO_TYPE_PTR:
1971                 class = mono_class_from_mono_type (type->data.type);
1972                 break;
1973         case MONO_TYPE_GENERICINST:
1974                 class = mono_class_from_generic (type, TRUE);
1975                 break;
1976         default:
1977                 /* it seems any type can be stored in TypeSpec as well */
1978                 class = mono_class_from_mono_type (type);
1979                 break;
1980         }
1981
1982         return class;
1983 }
1984
1985 /**
1986  * mono_bounded_array_class_get:
1987  * @element_class: element class 
1988  * @rank: the dimension of the array class
1989  * @bounded: whenever the array has non-zero bounds
1990  *
1991  * Returns: a class object describing the array with element type @element_type and 
1992  * dimension @rank. 
1993  */
1994 MonoClass *
1995 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
1996 {
1997         MonoImage *image;
1998         MonoClass *class;
1999         MonoClass *parent = NULL;
2000         GSList *list, *rootlist;
2001         int nsize;
2002         char *name;
2003         gboolean corlib_type = FALSE;
2004
2005         g_assert (rank <= 255);
2006
2007         if (rank > 1)
2008                 /* bounded only matters for one-dimensional arrays */
2009                 bounded = FALSE;
2010
2011         image = eclass->image;
2012
2013         mono_loader_lock ();
2014
2015         if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
2016                 for (; list; list = list->next) {
2017                         class = list->data;
2018                         if ((class->rank == rank) && (class->byval_arg.type == (bounded ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
2019                                 mono_loader_unlock ();
2020                                 return class;
2021                         }
2022                 }
2023         }
2024
2025         /* for the building corlib use System.Array from it */
2026         if (image->assembly && image->assembly->dynamic && strcmp (image->assembly_name, "mscorlib") == 0) {
2027                 parent = mono_class_from_name (image, "System", "Array");
2028                 corlib_type = TRUE;
2029         } else {
2030                 parent = mono_defaults.array_class;
2031                 if (!parent->inited)
2032                         mono_class_init (parent);
2033         }
2034
2035         class = g_malloc0 (sizeof (MonoClass));
2036
2037         class->image = image;
2038         class->name_space = eclass->name_space;
2039         nsize = strlen (eclass->name);
2040         name = g_malloc (nsize + 2 + rank);
2041         memcpy (name, eclass->name, nsize);
2042         name [nsize] = '[';
2043         if (rank > 1)
2044                 memset (name + nsize + 1, ',', rank - 1);
2045         name [nsize + rank] = ']';
2046         name [nsize + rank + 1] = 0;
2047         class->name = name;
2048         class->type_token = 0;
2049         /* all arrays are marked serializable and sealed, bug #42779 */
2050         class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
2051                 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
2052         class->parent = parent;
2053         class->instance_size = mono_class_instance_size (class->parent);
2054         class->class_size = 0;
2055         mono_class_setup_supertypes (class);
2056
2057         class->rank = rank;
2058         
2059         if (eclass->enumtype)
2060                 class->cast_class = eclass->element_class;
2061         else
2062                 class->cast_class = eclass;
2063
2064         class->element_class = eclass;
2065
2066         if ((rank > 1) || bounded) {
2067                 MonoArrayType *at = g_new0 (MonoArrayType, 1);
2068                 class->byval_arg.type = MONO_TYPE_ARRAY;
2069                 class->byval_arg.data.array = at;
2070                 at->eklass = eclass;
2071                 at->rank = rank;
2072                 /* FIXME: complete.... */
2073         } else {
2074                 class->byval_arg.type = MONO_TYPE_SZARRAY;
2075                 class->byval_arg.data.klass = eclass;
2076         }
2077         class->this_arg = class->byval_arg;
2078         class->this_arg.byref = 1;
2079         if (corlib_type) {
2080                 class->inited = 1;
2081         }
2082
2083         list = g_slist_append (rootlist, class);
2084         g_hash_table_insert (image->array_cache, eclass, list);
2085
2086         mono_loader_unlock ();
2087
2088         return class;
2089 }
2090
2091 /**
2092  * mono_array_class_get:
2093  * @element_class: element class 
2094  * @rank: the dimension of the array class
2095  *
2096  * Returns: a class object describing the array with element type @element_type and 
2097  * dimension @rank. 
2098  */
2099 MonoClass *
2100 mono_array_class_get (MonoClass *eclass, guint32 rank)
2101 {
2102         return mono_bounded_array_class_get (eclass, rank, FALSE);
2103 }
2104
2105 /**
2106  * mono_class_instance_size:
2107  * @klass: a class 
2108  * 
2109  * Returns: the size of an object instance
2110  */
2111 gint32
2112 mono_class_instance_size (MonoClass *klass)
2113 {       
2114         if (!klass->size_inited)
2115                 mono_class_init (klass);
2116
2117         return klass->instance_size;
2118 }
2119
2120 /**
2121  * mono_class_min_align:
2122  * @klass: a class 
2123  * 
2124  * Returns: minimm alignment requirements 
2125  */
2126 gint32
2127 mono_class_min_align (MonoClass *klass)
2128 {       
2129         if (!klass->size_inited)
2130                 mono_class_init (klass);
2131
2132         return klass->min_align;
2133 }
2134
2135 /**
2136  * mono_class_value_size:
2137  * @klass: a class 
2138  *
2139  * This function is used for value types, and return the
2140  * space and the alignment to store that kind of value object.
2141  *
2142  * Returns: the size of a value of kind @klass
2143  */
2144 gint32
2145 mono_class_value_size      (MonoClass *klass, guint32 *align)
2146 {
2147         gint32 size;
2148
2149         /* fixme: check disable, because we still have external revereces to
2150          * mscorlib and Dummy Objects 
2151          */
2152         /*g_assert (klass->valuetype);*/
2153
2154         size = mono_class_instance_size (klass) - sizeof (MonoObject);
2155
2156         if (align)
2157                 *align = klass->min_align;
2158
2159         return size;
2160 }
2161
2162 /**
2163  * mono_class_data_size:
2164  * @klass: a class 
2165  * 
2166  * Returns: the size of the static class data
2167  */
2168 gint32
2169 mono_class_data_size (MonoClass *klass)
2170 {       
2171         if (!klass->inited)
2172                 mono_class_init (klass);
2173
2174         return klass->class_size;
2175 }
2176
2177 /*
2178  * Auxiliary routine to mono_class_get_field
2179  *
2180  * Takes a field index instead of a field token.
2181  */
2182 static MonoClassField *
2183 mono_class_get_field_idx (MonoClass *class, int idx)
2184 {
2185         if (class->field.count){
2186                 if ((idx >= class->field.first) && (idx < class->field.last)){
2187                         return &class->fields [idx - class->field.first];
2188                 }
2189         }
2190
2191         if (!class->parent)
2192                 return NULL;
2193         
2194         return mono_class_get_field_idx (class->parent, idx);
2195 }
2196
2197 /**
2198  * mono_class_get_field:
2199  * @class: the class to lookup the field.
2200  * @field_token: the field token
2201  *
2202  * Returns: A MonoClassField representing the type and offset of
2203  * the field, or a NULL value if the field does not belong to this
2204  * class.
2205  */
2206 MonoClassField *
2207 mono_class_get_field (MonoClass *class, guint32 field_token)
2208 {
2209         int idx = mono_metadata_token_index (field_token);
2210
2211         g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
2212
2213         return mono_class_get_field_idx (class, idx - 1);
2214 }
2215
2216 MonoClassField *
2217 mono_class_get_field_from_name (MonoClass *klass, const char *name)
2218 {
2219         int i;
2220
2221         while (klass) {
2222                 for (i = 0; i < klass->field.count; ++i) {
2223                         if (strcmp (name, klass->fields [i].name) == 0)
2224                                 return &klass->fields [i];
2225                 }
2226                 klass = klass->parent;
2227         }
2228         return NULL;
2229 }
2230
2231 MonoProperty*
2232 mono_class_get_property_from_name (MonoClass *klass, const char *name)
2233 {
2234         int i;
2235
2236         while (klass) {
2237                 for (i = 0; i < klass->property.count; ++i) {
2238                         if (strcmp (name, klass->properties [i].name) == 0)
2239                                 return &klass->properties [i];
2240                 }
2241                 klass = klass->parent;
2242         }
2243         return NULL;
2244 }
2245
2246 /**
2247  * mono_class_get:
2248  * @image: the image where the class resides
2249  * @type_token: the token for the class
2250  * @at: an optional pointer to return the array element type
2251  *
2252  * Returns: the MonoClass that represents @type_token in @image
2253  */
2254 MonoClass *
2255 mono_class_get (MonoImage *image, guint32 type_token)
2256 {
2257         MonoClass *class = NULL;
2258
2259         if (image->dynamic)
2260                 return mono_lookup_dynamic_token (image, type_token);
2261
2262         switch (type_token & 0xff000000){
2263         case MONO_TOKEN_TYPE_DEF:
2264                 class = mono_class_create_from_typedef (image, type_token);
2265                 break;          
2266         case MONO_TOKEN_TYPE_REF:
2267                 class = mono_class_from_typeref (image, type_token);
2268                 break;
2269         case MONO_TOKEN_TYPE_SPEC:
2270                 class = mono_class_create_from_typespec (image, type_token);
2271                 break;
2272         default:
2273                 g_warning ("unknown token type %x", type_token & 0xff000000);
2274                 g_assert_not_reached ();
2275         }
2276
2277         if (!class)
2278                 g_warning ("Could not load class from token 0x%08x in %s", type_token, image->name);
2279
2280         return class;
2281 }
2282
2283 MonoClass *
2284 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
2285 {
2286         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
2287         guint32 cols [MONO_TYPEDEF_SIZE];
2288         const char *n;
2289         const char *nspace;
2290         guint32 i, visib;
2291
2292         /* add a cache if needed */
2293         for (i = 1; i <= t->rows; ++i) {
2294                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
2295                 /* nested types are accessed from the nesting name */
2296                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
2297                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
2298                         continue;
2299                 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2300                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2301                 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
2302                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
2303         }
2304         return NULL;
2305 }
2306
2307 static MonoClass*
2308 return_nested_in (MonoClass *class, char *nested) {
2309         MonoClass *found;
2310         char *s = strchr (nested, '/');
2311         GList *tmp;
2312
2313         if (s) {
2314                 *s = 0;
2315                 s++;
2316         }
2317         for (tmp = class->nested_classes; tmp; tmp = tmp->next) {
2318                 found = tmp->data;
2319                 if (strcmp (found->name, nested) == 0) {
2320                         if (s)
2321                                 return return_nested_in (found, s);
2322                         return found;
2323                 }
2324         }
2325         return NULL;
2326 }
2327
2328 MonoClass *
2329 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
2330 {
2331         GHashTable *nspace_table;
2332         MonoImage *loaded_image;
2333         guint32 token = 0;
2334         MonoClass *class;
2335         char *nested;
2336         char buf [1024];
2337
2338         if ((nested = strchr (name, '/'))) {
2339                 int pos = nested - name;
2340                 int len = strlen (name);
2341                 if (len > 1023)
2342                         return NULL;
2343                 memcpy (buf, name, len + 1);
2344                 buf [pos] = 0;
2345                 nested = buf + pos + 1;
2346                 name = buf;
2347         }
2348
2349         mono_loader_lock ();
2350
2351         nspace_table = g_hash_table_lookup (image->name_cache, name_space);
2352
2353         if (nspace_table)
2354                 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
2355
2356         mono_loader_unlock ();
2357
2358         if (!token)
2359                 return NULL;
2360
2361         if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
2362                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
2363                 guint32 cols [MONO_EXP_TYPE_SIZE];
2364                 guint32 idx, impl;
2365
2366                 idx = mono_metadata_token_index (token);
2367
2368                 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
2369
2370                 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
2371                 if ((impl & IMPLEMENTATION_MASK) == IMPLEMENTATION_FILE) {
2372                         loaded_image = mono_assembly_load_module (image->assembly, impl >> IMPLEMENTATION_BITS);
2373                         if (!loaded_image)
2374                                 return NULL;
2375                         class = mono_class_from_name (loaded_image, name_space, name);
2376                         if (nested)
2377                                 return return_nested_in (class, nested);
2378                         return class;
2379                 } else {
2380                         g_error ("not yet implemented");
2381                 }
2382         }
2383
2384         token = MONO_TOKEN_TYPE_DEF | token;
2385
2386         class = mono_class_get (image, token);
2387         if (nested)
2388                 return return_nested_in (class, nested);
2389         return class;
2390 }
2391
2392 gboolean
2393 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc, 
2394                                                    gboolean check_interfaces)
2395 {
2396         if (check_interfaces && (klassc->flags & TYPE_ATTRIBUTE_INTERFACE) && !(klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
2397                 if ((klassc->interface_id <= klass->max_interface_id) &&
2398                         (klass->interface_offsets [klassc->interface_id] >= 0))
2399                         return TRUE;
2400         } else if (check_interfaces && (klassc->flags & TYPE_ATTRIBUTE_INTERFACE) && (klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
2401                 int i;
2402
2403                 for (i = 0; i < klass->interface_count; i ++) {
2404                         MonoClass *ic =  klass->interfaces [i];
2405                         if (ic == klassc)
2406                                 return TRUE;
2407                 }
2408         } else {
2409                 if (!(klass->flags & TYPE_ATTRIBUTE_INTERFACE) && mono_class_has_parent (klass, klassc))
2410                         return TRUE;
2411         }
2412
2413         /* 
2414          * MS.NET thinks interfaces are a subclass of Object, so we think it as
2415          * well.
2416          */
2417         if (klassc == mono_defaults.object_class)
2418                 return TRUE;
2419         
2420         return FALSE;
2421 }
2422
2423 gboolean
2424 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
2425 {
2426         if (!klass->inited)
2427                 mono_class_init (klass);
2428
2429         if (!oklass->inited)
2430                 mono_class_init (oklass);
2431
2432         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
2433                 if ((klass->interface_id <= oklass->max_interface_id) &&
2434                     (oklass->interface_offsets [klass->interface_id] != -1))
2435                         return TRUE;
2436         } else
2437                 if (klass->rank) {
2438                         MonoClass *eclass, *eoclass;
2439
2440                         if (oklass->rank != klass->rank)
2441                                 return FALSE;
2442
2443                         /* vectors vs. one dimensional arrays */
2444                         if (oklass->byval_arg.type != klass->byval_arg.type)
2445                                 return FALSE;
2446
2447                         eclass = klass->cast_class;
2448                         eoclass = oklass->cast_class;
2449
2450
2451                         /* 
2452                          * a is b does not imply a[] is b[] when a is a valuetype, and
2453                          * b is a reference type.
2454                          */
2455
2456                         if (eoclass->valuetype) {
2457                                 if ((eclass == mono_defaults.enum_class) || 
2458                                         (eclass == mono_defaults.enum_class->parent) ||
2459                                         (eclass == mono_defaults.object_class))
2460                                         return FALSE;
2461                         }
2462
2463                         return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
2464                 }
2465         else
2466                 if (klass == mono_defaults.object_class)
2467                         return TRUE;
2468
2469         return mono_class_has_parent (oklass, klass);
2470 }       
2471
2472 /*
2473  * mono_class_needs_cctor_run:
2474  *
2475  *  Determines whenever the class has a static constructor and whenever it
2476  * needs to be called when executing CALLER.
2477  */
2478 gboolean
2479 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
2480 {
2481         int i;
2482         MonoMethod *method;
2483         
2484         for (i = 0; i < klass->method.count; ++i) {
2485                 method = klass->methods [i];
2486                 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
2487                     (strcmp (".cctor", method->name) == 0)) {
2488                         if (caller == method)
2489                                 return FALSE;
2490                         return TRUE;
2491                 }
2492         }
2493         return FALSE;
2494 }
2495
2496 /*
2497  * Returns the nnumber of bytes an element of type klass
2498  * uses when stored into an array.
2499  */
2500 gint32
2501 mono_class_array_element_size (MonoClass *klass)
2502 {
2503         int t = klass->byval_arg.type;
2504         
2505 handle_enum:
2506         switch (t) {
2507         case MONO_TYPE_I1:
2508         case MONO_TYPE_U1:
2509         case MONO_TYPE_BOOLEAN:
2510                 return 1;
2511         case MONO_TYPE_I2:
2512         case MONO_TYPE_U2:
2513         case MONO_TYPE_CHAR:
2514                 return 2;
2515         case MONO_TYPE_I4:
2516         case MONO_TYPE_U4:
2517         case MONO_TYPE_R4:
2518                 return 4;
2519         case MONO_TYPE_I:
2520         case MONO_TYPE_U:
2521         case MONO_TYPE_PTR:
2522         case MONO_TYPE_CLASS:
2523         case MONO_TYPE_STRING:
2524         case MONO_TYPE_OBJECT:
2525         case MONO_TYPE_SZARRAY:
2526         case MONO_TYPE_ARRAY: 
2527         case MONO_TYPE_VAR:
2528         case MONO_TYPE_MVAR:   
2529                 return sizeof (gpointer);
2530         case MONO_TYPE_I8:
2531         case MONO_TYPE_U8:
2532         case MONO_TYPE_R8:
2533                 return 8;
2534         case MONO_TYPE_VALUETYPE:
2535                 if (klass->enumtype) {
2536                         t = klass->enum_basetype->type;
2537                         goto handle_enum;
2538                 }
2539                 return mono_class_instance_size (klass) - sizeof (MonoObject);
2540         default:
2541                 g_error ("unknown type 0x%02x in mono_class_array_element_size", t);
2542         }
2543         return -1;
2544 }
2545
2546 /**
2547  * mono_array_element_size:
2548  * @ac: pointer to a #MonoArrayClass
2549  *
2550  * Returns: the size of single array element.
2551  */
2552 gint32
2553 mono_array_element_size (MonoClass *ac)
2554 {
2555         return mono_class_array_element_size (ac->element_class);
2556 }
2557
2558 gpointer
2559 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class)
2560 {
2561         if (image->dynamic) {
2562                 gpointer obj = mono_lookup_dynamic_token (image, token);
2563
2564                 switch (token & 0xff000000) {
2565                 case MONO_TOKEN_TYPE_DEF:
2566                 case MONO_TOKEN_TYPE_REF:
2567                 case MONO_TOKEN_TYPE_SPEC:
2568                         if (handle_class)
2569                                 *handle_class = mono_defaults.typehandle_class;
2570                         return &((MonoClass*)obj)->byval_arg;
2571                 case MONO_TOKEN_METHOD_DEF:
2572                         if (handle_class)
2573                                 *handle_class = mono_defaults.methodhandle_class;
2574                         return obj;
2575                 case MONO_TOKEN_FIELD_DEF:
2576                         if (handle_class)
2577                                 *handle_class = mono_defaults.fieldhandle_class;
2578                         return obj;
2579                 default:
2580                         g_assert_not_reached ();
2581                 }
2582         }
2583
2584         switch (token & 0xff000000) {
2585         case MONO_TOKEN_TYPE_DEF:
2586         case MONO_TOKEN_TYPE_REF: {
2587                 MonoClass *class;
2588                 if (handle_class)
2589                         *handle_class = mono_defaults.typehandle_class;
2590                 class = mono_class_get (image, token);
2591                 mono_class_init (class);
2592                 /* We return a MonoType* as handle */
2593                 return &class->byval_arg;
2594         }
2595         case MONO_TOKEN_TYPE_SPEC: {
2596                 MonoClass *class;
2597                 if (handle_class)
2598                         *handle_class = mono_defaults.typehandle_class;
2599                 class = mono_class_create_from_typespec (image, token);
2600                 mono_class_init (class);
2601                 return &class->byval_arg;
2602         }
2603         case MONO_TOKEN_FIELD_DEF: {
2604                 MonoClass *class;
2605                 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
2606                 class = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
2607                 mono_class_init (class);
2608                 if (handle_class)
2609                         *handle_class = mono_defaults.fieldhandle_class;
2610                 return mono_class_get_field (class, token);
2611         }
2612         case MONO_TOKEN_METHOD_DEF: {
2613                 MonoMethod *meth;
2614                 meth = mono_get_method (image, token, NULL);
2615                 if (handle_class)
2616                         *handle_class = mono_defaults.methodhandle_class;
2617                 return meth;
2618         }
2619         case MONO_TOKEN_MEMBER_REF: {
2620                 guint32 cols [MONO_MEMBERREF_SIZE];
2621                 const char *sig;
2622                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
2623                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
2624                 mono_metadata_decode_blob_size (sig, &sig);
2625                 if (*sig == 0x6) { /* it's a field */
2626                         MonoClass *klass;
2627                         MonoClassField *field;
2628                         field = mono_field_from_token (image, token, &klass);
2629                         if (handle_class)
2630                                 *handle_class = mono_defaults.fieldhandle_class;
2631                         return field;
2632                 } else {
2633                         MonoMethod *meth;
2634                         meth = mono_get_method (image, token, NULL);
2635                         if (handle_class)
2636                                 *handle_class = mono_defaults.methodhandle_class;
2637                         return meth;
2638                 }
2639         }
2640         default:
2641                 g_warning ("Unknown token 0x%08x in ldtoken", token);
2642                 break;
2643         }
2644         return NULL;
2645 }
2646
2647 /**
2648  * This function might need to call runtime functions so it can't be part
2649  * of the metadata library.
2650  */
2651 static MonoLookupDynamicToken lookup_dynamic = NULL;
2652
2653 void
2654 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
2655 {
2656         lookup_dynamic = func;
2657 }
2658
2659 gpointer
2660 mono_lookup_dynamic_token (MonoImage *image, guint32 token)
2661 {
2662         return lookup_dynamic (image, token);
2663 }
2664
2665
2666