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