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