2003-04-24 Martin Baulig <martin@ximian.com>
[mono.git] / mono / metadata / class.c
1 /*
2  * class.c: Class management for the Mono runtime
3  *
4  * Author:
5  *   Miguel de Icaza (miguel@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.
8  *
9  * Possible Optimizations:
10  *     in mono_class_create, do not allocate the class right away,
11  *     but wait until you know the size of the FieldMap, so that
12  *     the class embeds directly the FieldMap after the vtable.
13  *
14  * 
15  */
16 #include <config.h>
17 #include <glib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
22 #include <mono/metadata/image.h>
23 #include <mono/metadata/cil-coff.h>
24 #include <mono/metadata/metadata.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/tokentype.h>
27 #include <mono/metadata/class.h>
28 #include <mono/metadata/object.h>
29 #include <mono/metadata/appdomain.h>
30 #include <mono/metadata/mono-endian.h>
31 #include <mono/metadata/debug-helpers.h>
32 #include <mono/os/gc_wrapper.h>
33
34 #define CSIZE(x) (sizeof (x) / 4)
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         MonoImageOpenStatus status;
54
55         mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
56
57         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
58         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
59         
60         idx = cols [MONO_TYPEREF_SCOPE] >> RESOLTION_SCOPE_BITS;
61         switch (cols [MONO_TYPEREF_SCOPE] & RESOLTION_SCOPE_MASK) {
62         case RESOLTION_SCOPE_MODULE:
63                 if (!idx)
64                         g_error ("null ResolutionScope not yet handled");
65                 /* a typedef in disguise */
66                 return mono_class_from_name (image, nspace, name);
67         case RESOLTION_SCOPE_MODULEREF:
68                 return mono_class_from_name (image->modules [idx - 1], nspace, name);
69         case RESOLTION_SCOPE_TYPEREF: {
70                 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
71                 GList *tmp;
72                 mono_class_init (enclosing);
73                 for (tmp = enclosing->nested_classes; tmp; tmp = tmp->next) {
74                         res = tmp->data;
75                         if (strcmp (res->name, name) == 0)
76                                 return res;
77                 }
78                 g_warning ("TypeRef ResolutionScope not yet handled (%d)", idx);
79                 return NULL;
80         }
81         case RESOLTION_SCOPE_ASSEMBLYREF:
82                 break;
83         }
84
85         mono_image_load_references (image, &status);
86         references = image->references;
87         if (!references ||  !references [idx-1]) {
88                 /* 
89                  * detected a reference to mscorlib, we simply return a reference to a dummy 
90                  * until we have a better solution.
91                  */
92                 fprintf(stderr, "Sending dummy where %s.%s expected\n", mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]), mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME])); 
93                 
94                 res = mono_class_from_name (image, "System", "MonoDummy");
95                 /* prevent method loading */
96                 res->dummy = 1;
97                 /* some storage if the type is used  - very ugly hack */
98                 res->instance_size = 2*sizeof (gpointer);
99                 return res;
100         }       
101
102         /* load referenced assembly */
103         image = references [idx-1]->image;
104
105         return mono_class_from_name (image, nspace, name);
106 }
107
108 MonoMarshalType *
109 mono_marshal_load_type_info (MonoClass* klass)
110 {
111         int i, j, count = 0;
112         MonoMarshalType *info;
113         guint32 layout;
114
115         g_assert (klass != NULL);
116
117         if (klass->marshal_info)
118                 return klass->marshal_info;
119
120         if (!klass->inited)
121                 mono_class_init (klass);
122         
123         for (i = 0; i < klass->field.count; ++i) {
124                 if (klass->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)
125                         continue;
126                 count++;
127         }
128
129         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
130
131         klass->marshal_info = info = g_malloc0 (sizeof (MonoMarshalType) + sizeof (MonoMarshalField) * count);
132         info->num_fields = count;
133         
134         if (klass->parent)
135                 info->native_size = mono_class_native_size (klass->parent, NULL);
136
137         for (j = i = 0; i < klass->field.count; ++i) {
138                 int size, align;
139                 
140                 if (klass->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)
141                         continue;
142
143                 if (klass->fields [i].type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
144                         mono_metadata_field_info (klass->image, klass->field.first + i, 
145                                                   NULL, NULL, &info->fields [j].mspec);
146
147                 info->fields [j].field = &klass->fields [i];
148
149                 switch (layout) {
150                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
151                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
152                         size = mono_marshal_type_size (klass->fields [i].type, info->fields [j].mspec, 
153                                                        &align, TRUE, klass->unicode);
154                         align = klass->packing_size ? MIN (klass->packing_size, align): align;  
155                         info->fields [j].offset = info->native_size;
156                         info->fields [j].offset += align - 1;
157                         info->fields [j].offset &= ~(align - 1);
158                         info->native_size = info->fields [j].offset + size;
159                         break;
160                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
161                         /* FIXME: */
162                         info->fields [j].offset = klass->fields [i].offset - sizeof (MonoObject);
163                         info->native_size = klass->instance_size - sizeof (MonoObject);
164                         break;
165                 }       
166                 j++;
167         }
168
169         if (info->native_size & (klass->min_align - 1)) {
170                 info->native_size += klass->min_align - 1;
171                 info->native_size &= ~(klass->min_align - 1);
172         }
173
174         return klass->marshal_info;
175 }
176
177 /** 
178  * class_compute_field_layout:
179  * @m: pointer to the metadata.
180  * @class: The class to initialize
181  *
182  * Initializes the class->fields.
183  *
184  * Currently we only support AUTO_LAYOUT, and do not even try to do
185  * a good job at it.  This is temporary to get the code for Paolo.
186  */
187 static void
188 class_compute_field_layout (MonoClass *class)
189 {
190         MonoImage *m = class->image; 
191         const int top = class->field.count;
192         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
193         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
194         int i, blittable = TRUE;
195         guint32 rva;
196         guint32 packing_size = 0;
197
198         if (class->size_inited)
199                 return;
200
201         if (class->parent) {
202                 if (!class->parent->size_inited)
203                         class_compute_field_layout (class->parent);
204                 class->instance_size += class->parent->instance_size;
205                 class->min_align = class->parent->min_align;
206         } else {
207                 class->instance_size = sizeof (MonoObject);
208                 class->min_align = 1;
209         }
210
211         if (mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &class->instance_size)) {
212                 class->instance_size += sizeof (MonoObject);
213         }
214
215         g_assert ((packing_size & 0xfffffff0) == 0);
216         class->packing_size = packing_size;
217
218         if (!top) {
219                 class->size_inited = 1;
220                 return;
221         }
222
223         class->fields = g_new0 (MonoClassField, top);
224
225         /*
226          * Fetch all the field information.
227          */
228         for (i = 0; i < top; i++){
229                 const char *sig;
230                 guint32 cols [MONO_FIELD_SIZE];
231                 int idx = class->field.first + i;
232                 
233                 mono_metadata_decode_row (t, idx, cols, CSIZE (cols));
234                 /* The name is needed for fieldrefs */
235                 class->fields [i].name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
236                 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
237                 mono_metadata_decode_value (sig, &sig);
238                 /* FIELD signature == 0x06 */
239                 g_assert (*sig == 0x06);
240                 class->fields [i].type = mono_metadata_parse_field_type (
241                         m, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
242
243                 class->fields [i].parent = class;
244
245                 if (!(class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)) {
246                         if (class->fields [i].type->byref) {
247                                 blittable = FALSE;
248                         } else {
249                                 MonoClass *field_class = mono_class_from_mono_type (class->fields [i].type);
250                                 if (!field_class || !field_class->blittable)
251                                         blittable = FALSE;
252                         }
253                 }
254                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
255                         mono_metadata_field_info (m, idx, &class->fields [i].offset, NULL, NULL);
256                         if (class->fields [i].offset == (guint32)-1)
257                                 g_warning ("%s not initialized correctly (missing field layout info for %s)", class->name, class->fields [i].name);
258                 }
259
260                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
261                         mono_metadata_field_info (m, idx, NULL, &rva, NULL);
262                         if (!rva)
263                                 g_warning ("field %s in %s should have RVA data, but hasn't", class->fields [i].name, class->name);
264                         class->fields [i].data = mono_cli_rva_map (class->image->image_info, rva);
265                 }
266
267                 if (class->enumtype && !(cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC)) {
268                         class->enum_basetype = class->fields [i].type;
269                         class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
270                         blittable = class->element_class->blittable;
271                 }
272         }
273
274         if (class == mono_defaults.string_class)
275                 blittable = FALSE;
276
277         class->blittable = blittable;
278
279         if (class->enumtype && !class->enum_basetype) {
280                 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
281                         G_BREAKPOINT ();
282         }
283         mono_class_layout_fields (class);
284 }
285
286 void
287 mono_class_layout_fields (MonoClass *class)
288 {
289         int i;
290         const int top = class->field.count;
291         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
292
293         /*
294          * Compute field layout and total size (not considering static fields)
295          */
296         switch (layout) {
297         case TYPE_ATTRIBUTE_AUTO_LAYOUT:
298         case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
299                 for (i = 0; i < top; i++){
300                         int size, align;
301                         
302                         if (class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)
303                                 continue;
304
305                         size = mono_type_size (class->fields [i].type, &align);
306                         
307                         /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
308                         align = class->packing_size ? MIN (class->packing_size, align): align;
309                         class->min_align = MAX (align, class->min_align);
310                         class->fields [i].offset = class->instance_size;
311                         class->fields [i].offset += align - 1;
312                         class->fields [i].offset &= ~(align - 1);
313                         class->instance_size = class->fields [i].offset + size;
314
315                 }
316        
317                 if (class->instance_size & (class->min_align - 1)) {
318                         class->instance_size += class->min_align - 1;
319                         class->instance_size &= ~(class->min_align - 1);
320                 }
321                 break;
322         case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
323                 for (i = 0; i < top; i++) {
324                         int size, align;
325
326                         /*
327                          * There must be info about all the fields in a type if it
328                          * uses explicit layout.
329                          */
330
331                         if (class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC)
332                                 continue;
333
334                         size = mono_type_size (class->fields [i].type, &align);
335                         
336                         /*
337                          * When we get here, class->fields [i].offset is already set by the
338                          * loader (for either runtime fields or fields loaded from metadata).
339                          * The offset is from the start of the object: this works for both
340                          * classes and valuetypes.
341                          */
342                         class->fields [i].offset += sizeof (MonoObject);
343
344                         /*
345                          * Calc max size.
346                          */
347                         class->instance_size = MAX (class->instance_size, size + class->fields [i].offset);
348                 }
349                 break;
350         }
351
352         class->size_inited = 1;
353
354         /*
355          * Compute static field layout and size
356          */
357         switch (layout) {
358         case TYPE_ATTRIBUTE_AUTO_LAYOUT:
359         case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
360                 for (i = 0; i < top; i++){
361                         int size, align;
362                         
363                         if (!(class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC))
364                                 continue;
365                         
366                         size = mono_type_size (class->fields [i].type, &align);
367                         class->fields [i].offset = class->class_size;
368                         class->fields [i].offset += align - 1;
369                         class->fields [i].offset &= ~(align - 1);
370                         class->class_size = class->fields [i].offset + size;
371
372                 }
373                 break;
374         case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
375                 for (i = 0; i < top; i++){
376                         int size, align;
377
378                         /*
379                          * There must be info about all the fields in a type if it
380                          * uses explicit layout.
381                          */
382                         
383                         if (!(class->fields [i].type->attrs & FIELD_ATTRIBUTE_STATIC))
384                                 continue;
385
386                         size = mono_type_size (class->fields [i].type, &align);
387                         class->fields [i].offset = class->class_size;
388                         class->fields [i].offset += align - 1;
389                         class->fields [i].offset &= ~(align - 1);
390                         class->class_size = class->fields [i].offset + size;
391                 }
392                 break;
393         }
394 }
395
396 static void
397 init_properties (MonoClass *class)
398 {
399         guint startm, endm, i, j;
400         guint32 cols [MONO_PROPERTY_SIZE];
401         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_PROPERTY];
402         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
403
404         class->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->property.last);
405         class->property.count = class->property.last - class->property.first;
406
407         class->properties = g_new0 (MonoProperty, class->property.count);
408         for (i = class->property.first; i < class->property.last; ++i) {
409                 mono_metadata_decode_row (pt, i, cols, MONO_PROPERTY_SIZE);
410                 class->properties [i - class->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
411                 class->properties [i - class->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
412
413                 startm = mono_metadata_methods_from_property (class->image, i, &endm);
414                 for (j = startm; j < endm; ++j) {
415                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
416                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
417                         case METHOD_SEMANTIC_SETTER:
418                                 class->properties [i - class->property.first].set = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
419                                 break;
420                         case METHOD_SEMANTIC_GETTER:
421                                 class->properties [i - class->property.first].get = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
422                                 break;
423                         default:
424                                 break;
425                         }
426                 }
427         }
428 }
429
430 static void
431 init_events (MonoClass *class)
432 {
433         guint startm, endm, i, j;
434         guint32 cols [MONO_EVENT_SIZE];
435         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_EVENT];
436         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
437
438         class->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->event.last);
439         class->event.count = class->event.last - class->event.first;
440
441         class->events = g_new0 (MonoEvent, class->event.count);
442         for (i = class->event.first; i < class->event.last; ++i) {
443                 mono_metadata_decode_row (pt, i, cols, MONO_EVENT_SIZE);
444                 class->events [i - class->event.first].attrs = cols [MONO_EVENT_FLAGS];
445                 class->events [i - class->event.first].name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
446
447                 startm = mono_metadata_methods_from_event (class->image, i, &endm);
448                 for (j = startm; j < endm; ++j) {
449                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
450                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
451                         case METHOD_SEMANTIC_ADD_ON:
452                                 class->events [i - class->event.first].add = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
453                                 break;
454                         case METHOD_SEMANTIC_REMOVE_ON:
455                                 class->events [i - class->event.first].remove = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
456                                 break;
457                         case METHOD_SEMANTIC_FIRE:
458                                 class->events [i - class->event.first].raise = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
459                                 break;
460                         case METHOD_SEMANTIC_OTHER: /* don't care for now */
461                         default:
462                                 break;
463                         }
464                 }
465         }
466 }
467
468 static guint
469 mono_get_unique_iid (MonoClass *class)
470 {
471         static GHashTable *iid_hash = NULL;
472         static guint iid = 0;
473
474         char *str;
475         gpointer value;
476         
477         g_assert (class->flags & TYPE_ATTRIBUTE_INTERFACE);
478
479         if (!iid_hash)
480                 iid_hash = g_hash_table_new (g_str_hash, g_str_equal);
481
482         str = g_strdup_printf ("%s|%s.%s\n", class->image->name, class->name_space, class->name);
483
484         if (g_hash_table_lookup_extended (iid_hash, str, NULL, &value)) {
485                 g_free (str);
486                 return (guint)value;
487         } else {
488                 g_hash_table_insert (iid_hash, str, (gpointer)iid);
489                 ++iid;
490         }
491
492         return iid - 1;
493 }
494
495 static void
496 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray *res)
497 {
498         int i;
499         MonoClass *ic;
500         
501         for (i = 0; i < klass->interface_count; i++) {
502                 ic = klass->interfaces [i];
503
504                 g_ptr_array_add (res, ic);
505
506                 collect_implemented_interfaces_aux (ic, res);
507         }
508 }
509
510 static GPtrArray*
511 collect_implemented_interfaces (MonoClass *klass)
512 {
513         GPtrArray *res = g_ptr_array_new ();
514
515         collect_implemented_interfaces_aux (klass, res);
516         return res;
517 }
518
519 static int
520 setup_interface_offsets (MonoClass *class, int cur_slot)
521 {
522         MonoClass *k, *ic;
523         int i, max_iid;
524         GPtrArray *ifaces;
525
526         /* compute maximum number of slots and maximum interface id */
527         max_iid = 0;
528         for (k = class; k ; k = k->parent) {
529                 for (i = 0; i < k->interface_count; i++) {
530                         ic = k->interfaces [i];
531
532                         if (!ic->inited)
533                                 mono_class_init (ic);
534
535                         if (max_iid < ic->interface_id)
536                                 max_iid = ic->interface_id;
537                 }
538         }
539
540         if (class->flags & TYPE_ATTRIBUTE_INTERFACE) {
541                 if (max_iid < class->interface_id)
542                         max_iid = class->interface_id;
543         }
544         class->max_interface_id = max_iid;
545         /* compute vtable offset for interfaces */
546         class->interface_offsets = g_malloc (sizeof (gpointer) * (max_iid + 1));
547
548         for (i = 0; i <= max_iid; i++)
549                 class->interface_offsets [i] = -1;
550
551         ifaces = collect_implemented_interfaces (class);
552         for (i = 0; i < ifaces->len; ++i) {
553                 ic = g_ptr_array_index (ifaces, i);
554                 class->interface_offsets [ic->interface_id] = cur_slot;
555                 cur_slot += ic->method.count;
556         }
557         g_ptr_array_free (ifaces, TRUE);
558
559         for (k = class->parent; k ; k = k->parent) {
560                 ifaces = collect_implemented_interfaces (k);
561                 for (i = 0; i < ifaces->len; ++i) {
562                         ic = g_ptr_array_index (ifaces, i);
563
564                         if (class->interface_offsets [ic->interface_id] == -1) {
565                                 int io = k->interface_offsets [ic->interface_id];
566
567                                 g_assert (io >= 0);
568
569                                 class->interface_offsets [ic->interface_id] = io;
570                         }
571                 }
572                 g_ptr_array_free (ifaces, TRUE);
573         }
574         return cur_slot;
575 }
576
577 void
578 mono_class_setup_vtable (MonoClass *class, MonoMethod **overrides, int onum)
579 {
580         MonoClass *k, *ic;
581         MonoMethod **vtable;
582         int i, max_vtsize = 0, max_iid, cur_slot = 0;
583         GPtrArray *ifaces;
584         MonoGHashTable *override_map;
585
586         /* setup_vtable() must be called only once on the type */
587         if (class->interface_offsets) {
588                 g_warning ("vtable already computed in %s.%s", class->name_space, class->name);
589                 return;
590         }
591
592         ifaces = collect_implemented_interfaces (class);
593         for (i = 0; i < ifaces->len; i++) {
594                 MonoClass *ic = g_ptr_array_index (ifaces, i);
595                 max_vtsize += ic->method.count;
596         }
597         g_ptr_array_free (ifaces, TRUE);
598         
599         if (class->parent) {
600                 max_vtsize += class->parent->vtable_size;
601                 cur_slot = class->parent->vtable_size;
602         }
603
604         max_vtsize += class->method.count;
605
606         vtable = alloca (sizeof (gpointer) * max_vtsize);
607         memset (vtable, 0, sizeof (gpointer) * max_vtsize);
608
609         /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
610
611         cur_slot = setup_interface_offsets (class, cur_slot);
612         max_iid = class->max_interface_id;
613
614         if (class->parent && class->parent->vtable_size)
615                 memcpy (vtable, class->parent->vtable,  sizeof (gpointer) * class->parent->vtable_size);
616
617         override_map = mono_g_hash_table_new (NULL, NULL);
618
619         /* override interface methods */
620         for (i = 0; i < onum; i++) {
621                 MonoMethod *decl = overrides [i*2];
622                 if (decl->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
623                         int dslot;
624                         g_assert (decl->slot != -1);
625                         dslot = decl->slot + class->interface_offsets [decl->klass->interface_id];
626                         vtable [dslot] = overrides [i*2 + 1];
627                         vtable [dslot]->slot = dslot;
628                         mono_g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
629                 }
630         }
631
632         for (k = class; k ; k = k->parent) {
633                 ifaces = collect_implemented_interfaces (k);
634                 for (i = 0; i < ifaces->len; i++) {
635                         int j, l, io;
636
637                         ic = g_ptr_array_index (ifaces, i);
638                         io = k->interface_offsets [ic->interface_id];
639
640                         g_assert (io >= 0);
641                         g_assert (io <= max_vtsize);
642
643                         if (k == class) {
644                                 for (l = 0; l < ic->method.count; l++) {
645                                         MonoMethod *im = ic->methods [l];                                               
646                                         for (j = 0; j < class->method.count; ++j) {
647                                                 MonoMethod *cm = class->methods [j];
648                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
649                                                     !((cm->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) ||
650                                                     !(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT))
651                                                         continue;
652                                                 if (!strcmp(cm->name, im->name) && 
653                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
654                                                         g_assert (io + l <= max_vtsize);
655                                                         vtable [io + l] = cm;
656                                                 }
657                                         }
658                                 }
659                         } else {
660                                 /* already implemented */
661                                 if (io >= k->vtable_size)
662                                         continue;
663                         }
664                                 
665                         for (l = 0; l < ic->method.count; l++) {
666                                 MonoMethod *im = ic->methods [l];                                               
667                                 MonoClass *k1;
668
669                                 g_assert (io + l <= max_vtsize);
670
671                                 if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
672                                         continue;
673                                         
674                                 for (k1 = class; k1; k1 = k1->parent) {
675                                         for (j = 0; j < k1->method.count; ++j) {
676                                                 MonoMethod *cm = k1->methods [j];
677
678                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
679                                                     !(cm->flags & METHOD_ATTRIBUTE_PUBLIC))
680                                                         continue;
681                                                 
682                                                 if (!strcmp(cm->name, im->name) && 
683                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
684                                                         g_assert (io + l <= max_vtsize);
685                                                         vtable [io + l] = cm;
686                                                         break;
687                                                 }
688                                                 
689                                         }
690                                         g_assert (io + l <= max_vtsize);
691                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
692                                                 break;
693                                 }
694                         }
695
696                         for (l = 0; l < ic->method.count; l++) {
697                                 MonoMethod *im = ic->methods [l];                                               
698                                 char *qname, *fqname;
699                                 MonoClass *k1;
700                                 
701                                 if (vtable [io + l])
702                                         continue;
703                                         
704                                 qname = g_strconcat (ic->name, ".", im->name, NULL); 
705                                 if (ic->name_space && ic->name_space [0])
706                                         fqname = g_strconcat (ic->name_space, ".", ic->name, ".", im->name, NULL);
707                                 else
708                                         fqname = NULL;
709
710                                 for (k1 = class; k1; k1 = k1->parent) {
711                                         for (j = 0; j < k1->method.count; ++j) {
712                                                 MonoMethod *cm = k1->methods [j];
713
714                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
715                                                         continue;
716                                         
717                                                 if (((fqname && !strcmp (cm->name, fqname)) || !strcmp (cm->name, qname)) &&
718                                                     mono_metadata_signature_equal (cm->signature, im->signature)) {
719                                                         g_assert (io + l <= max_vtsize);
720                                                         vtable [io + l] = cm;
721                                                         break;
722                                                 }
723                                         }
724                                 }
725                                 g_free (qname);
726                                 g_free (fqname);
727                         }
728
729                         
730                         if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
731                                 for (l = 0; l < ic->method.count; l++) {
732                                         char *msig;
733                                         MonoMethod *im = ic->methods [l];
734                                         if (im->flags & METHOD_ATTRIBUTE_STATIC)
735                                                         continue;
736                                         g_assert (io + l <= max_vtsize);
737                                         if (!(vtable [io + l])) {
738                                                 for (j = 0; j < onum; ++j) {
739                                                         g_print (" at slot %d: %s (%d) overrides %s (%d)\n", io+l, overrides [j*2+1]->name, 
740                                                                  overrides [j*2+1]->slot, overrides [j*2]->name, overrides [j*2]->slot);
741                                                 }
742                                                 msig = mono_signature_get_desc (im->signature, FALSE);
743                                                 printf ("no implementation for interface method %s.%s::%s(%s) in class %s.%s\n",
744                                                         ic->name_space, ic->name, im->name, msig, class->name_space, class->name);
745                                                 g_free (msig);
746                                                 for (j = 0; j < class->method.count; ++j) {
747                                                         MonoMethod *cm = class->methods [j];
748                                                         msig = mono_signature_get_desc (cm->signature, FALSE);
749                                                         
750                                                         printf ("METHOD %s(%s)\n", cm->name, msig);
751                                                         g_free (msig);
752                                                 }
753                                                 g_assert_not_reached ();
754                                         }
755                                 }
756                         }
757                 
758                         for (l = 0; l < ic->method.count; l++) {
759                                 MonoMethod *im = vtable [io + l];
760
761                                 if (im) {
762                                         g_assert (io + l <= max_vtsize);
763                                         if (im->slot < 0) {
764                                                 /* FIXME: why do we need this ? */
765                                                 im->slot = io + l;
766                                                 /* g_assert_not_reached (); */
767                                         }
768                                 }
769                         }
770                 }
771                 g_ptr_array_free (ifaces, TRUE);
772         } 
773
774         for (i = 0; i < class->method.count; ++i) {
775                 MonoMethod *cm;
776                
777                 cm = class->methods [i];
778
779                 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && (cm->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
780                         int slot = -1;
781                         for (k = class->parent; k ; k = k->parent) {
782                                 int j;
783                                 for (j = 0; j < k->method.count; ++j) {
784                                         MonoMethod *m1 = k->methods [j];
785                                         if (!(m1->flags & METHOD_ATTRIBUTE_VIRTUAL))
786                                                 continue;
787                                         if (!strcmp(cm->name, m1->name) && 
788                                             mono_metadata_signature_equal (cm->signature, m1->signature)) {
789                                                 slot = k->methods [j]->slot;
790                                                 g_assert (cm->slot < max_vtsize);
791                                                 mono_g_hash_table_insert (override_map, m1, cm);
792                                                 break;
793                                         }
794                                 }
795                                 if (slot >= 0) 
796                                         break;
797                         }
798                         if (slot >= 0)
799                                 cm->slot = slot;
800                 }
801
802                 if (cm->slot < 0)
803                         cm->slot = cur_slot++;
804
805                 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
806                         vtable [cm->slot] = cm;
807         }
808
809         /* override non interface methods */
810         for (i = 0; i < onum; i++) {
811                 MonoMethod *decl = overrides [i*2];
812                 if (!(decl->klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
813                         g_assert (decl->slot != -1);
814                         vtable [decl->slot] = overrides [i*2 + 1];
815                         overrides [i * 2 + 1]->slot = decl->slot;
816                         mono_g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
817                 }
818         }
819
820         /*
821          * If a method occupies more than one place in the vtable, and it is
822          * overriden, then change the other occurances too.
823          */
824         for (i = 0; i < max_vtsize; ++i)
825                 if (vtable [i]) {
826                         MonoMethod *cm = mono_g_hash_table_lookup (override_map, vtable [i]);
827                         if (cm)
828                                 vtable [i] = cm;
829                 }
830         mono_g_hash_table_destroy (override_map);
831
832        
833         class->vtable_size = cur_slot;
834         class->vtable = g_malloc0 (sizeof (gpointer) * class->vtable_size);
835         memcpy (class->vtable, vtable,  sizeof (gpointer) * class->vtable_size);
836
837         if (mono_print_vtable) {
838                 int icount = 0;
839
840                 for (i = 0; i <= max_iid; i++)
841                         if (class->interface_offsets [i] != -1)
842                                 icount++;
843
844                 printf ("VTable %s.%s (size = %d, interfaces = %d)\n", class->name_space, 
845                         class->name, class->vtable_size, icount); 
846
847                 for (i = 0; i < class->vtable_size; ++i) {
848                         MonoMethod *cm;
849                
850                         cm = vtable [i];
851                         if (cm) {
852                                 printf ("  slot %03d(%03d) %s.%s:%s\n", i, cm->slot,
853                                         cm->klass->name_space, cm->klass->name,
854                                         cm->name);
855                         }
856                 }
857
858
859                 if (icount) {
860                         printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space, 
861                                 class->name, max_iid);
862         
863                         for (i = 0; i < class->interface_count; i++) {
864                                 ic = class->interfaces [i];
865                                 printf ("  slot %03d(%03d) %s.%s\n",  
866                                         class->interface_offsets [ic->interface_id],
867                                         ic->method.count, ic->name_space, ic->name);
868                         }
869
870                         for (k = class->parent; k ; k = k->parent) {
871                                 for (i = 0; i < k->interface_count; i++) {
872                                         ic = k->interfaces [i]; 
873                                         printf ("  slot %03d(%03d) %s.%s\n", 
874                                                 class->interface_offsets [ic->interface_id],
875                                                 ic->method.count, ic->name_space, ic->name);
876                                 }
877                         }
878                 }
879         }
880 }
881
882 /**
883  * mono_class_init:
884  * @class: the class to initialize
885  *
886  * compute the instance_size, class_size and other infos that cannot be 
887  * computed at mono_class_get() time. Also compute a generic vtable and 
888  * the method slot numbers. We use this infos later to create a domain
889  * specific vtable.  
890  */
891 void
892 mono_class_init (MonoClass *class)
893 {
894         int i;
895         static MonoMethod *default_ghc = NULL;
896         static MonoMethod *default_finalize = NULL;
897         static int finalize_slot = -1;
898         static int ghc_slot = -1;
899         MonoMethod **overrides;
900         int onum = 0;
901
902         g_assert (class);
903
904         if (class->inited)
905                 return;
906
907         if (class->init_pending) {
908                 /* this indicates a cyclic dependency */
909                 g_error ("pending init %s.%s\n", class->name_space, class->name);
910         }
911
912         class->init_pending = 1;
913
914         mono_stats.initialized_class_count++;
915
916         if (class->parent && !class->parent->inited)
917                 mono_class_init (class->parent);
918
919         /*
920          * Computes the size used by the fields, and their locations
921          */
922         if (!class->size_inited)
923                 class_compute_field_layout (class);
924
925         /* initialize method pointers */
926         class->methods = g_new (MonoMethod*, class->method.count);
927         for (i = 0; i < class->method.count; ++i)
928                 class->methods [i] = mono_get_method (class->image,
929                         MONO_TOKEN_METHOD_DEF | (i + class->method.first + 1), class);
930
931         init_properties (class);
932         init_events (class);
933
934         i = mono_metadata_nesting_typedef (class->image, class->type_token, 1);
935         while (i) {
936                 MonoClass* nclass;
937                 guint32 cols [MONO_NESTED_CLASS_SIZE];
938                 mono_metadata_decode_row (&class->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
939                 nclass = mono_class_create_from_typedef (class->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
940                 class->nested_classes = g_list_prepend (class->nested_classes, nclass);
941
942                 i = mono_metadata_nesting_typedef (class->image, class->type_token, i + 1);
943         }
944
945         mono_class_setup_supertypes (class);
946
947         if (class->flags & TYPE_ATTRIBUTE_INTERFACE) {
948                 for (i = 0; i < class->method.count; ++i)
949                         class->methods [i]->slot = i;
950                 class->init_pending = 0;
951                 class->inited = 1;
952                 /* 
953                  * class->interface_offsets is needed for the castclass/isinst code, so
954                  * we have to setup them for interfaces, too.
955                  */
956                 setup_interface_offsets (class, 0);
957                 return;
958         }
959
960         overrides = mono_class_get_overrides (class->image, class->type_token, &onum);  
961         mono_class_setup_vtable (class, overrides, onum);
962         g_free (overrides);
963
964         class->inited = 1;
965         class->init_pending = 0;
966
967         if (!default_ghc) {
968                 if (class == mono_defaults.object_class) { 
969                        
970                         for (i = 0; i < class->vtable_size; ++i) {
971                                 MonoMethod *cm = class->vtable [i];
972                
973                                 if (!strcmp (cm->name, "GetHashCode")) {
974                                         ghc_slot = i;
975                                         break;
976                                 }
977                         }
978
979                         g_assert (ghc_slot > 0);
980
981                         default_ghc = class->vtable [ghc_slot];
982                 }
983         }
984         
985         class->ghcimpl = 1;
986         if (class->parent) { 
987
988                 if (class->vtable [ghc_slot] == default_ghc) {
989                         class->ghcimpl = 0;
990                 }
991         }
992
993         if (!default_finalize) {
994                 if (class == mono_defaults.object_class) { 
995                        
996                         for (i = 0; i < class->vtable_size; ++i) {
997                                 MonoMethod *cm = class->vtable [i];
998                
999                                 if (!strcmp (cm->name, "Finalize")) {
1000                                         finalize_slot = i;
1001                                         break;
1002                                 }
1003                         }
1004
1005                         g_assert (finalize_slot > 0);
1006
1007                         default_finalize = class->vtable [finalize_slot];
1008                 }
1009         }
1010
1011         /* Object::Finalize should have empty implemenatation */
1012         class->has_finalize = 0;
1013         if (class->parent) { 
1014                 if (class->vtable [finalize_slot] != default_finalize)
1015                         class->has_finalize = 1;
1016         }
1017
1018         if (mono_debugger_class_init_func)
1019                 mono_debugger_class_init_func (class);
1020 }
1021
1022
1023 /*
1024  * Compute a relative numbering of the class hierarchy as described in
1025  * "Java for Large-Scale Scientific Computations?"
1026  */
1027 static void
1028 mono_compute_relative_numbering (MonoClass *class, int *c)
1029 {
1030         GList *s;
1031
1032         (*c)++;
1033
1034         class->baseval = *c;
1035
1036         for (s = class->subclasses; s; s = s->next)
1037                 mono_compute_relative_numbering ((MonoClass *)s->data, c); 
1038         
1039         class->diffval = *c -  class->baseval;
1040 }
1041
1042 void
1043 mono_class_setup_mono_type (MonoClass *class)
1044 {
1045         const char *name = class->name;
1046         const char *nspace = class->name_space;
1047
1048         if (class->flags & TYPE_ATTRIBUTE_INTERFACE)
1049                 class->interface_id = mono_get_unique_iid (class);
1050
1051         class->this_arg.byref = 1;
1052         class->this_arg.data.klass = class;
1053         class->this_arg.type = MONO_TYPE_CLASS;
1054         class->byval_arg.data.klass = class;
1055         class->byval_arg.type = MONO_TYPE_CLASS;
1056
1057         if (!strcmp (nspace, "System")) {
1058                 if (!strcmp (name, "ValueType")) {
1059                         /*
1060                          * do not set the valuetype bit for System.ValueType.
1061                          * class->valuetype = 1;
1062                          */
1063                 } else if (!strcmp (name, "Enum")) {
1064                         /*
1065                          * do not set the valuetype bit for System.Enum.
1066                          * class->valuetype = 1;
1067                          */
1068                         class->valuetype = 0;
1069                         class->enumtype = 0;
1070                 } else if (!strcmp (name, "Object")) {
1071                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
1072                 } else if (!strcmp (name, "String")) {
1073                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
1074                 } else if (!strcmp (name, "TypedReference")) {
1075                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
1076                 }
1077         }
1078         
1079         if (class->valuetype) {
1080                 int t = MONO_TYPE_VALUETYPE;
1081                 if (!strcmp (nspace, "System")) {
1082                         switch (*name) {
1083                         case 'B':
1084                                 if (!strcmp (name, "Boolean")) {
1085                                         t = MONO_TYPE_BOOLEAN;
1086                                 } else if (!strcmp(name, "Byte")) {
1087                                         t = MONO_TYPE_U1;
1088                                         class->blittable = TRUE;                                                
1089                                 }
1090                                 break;
1091                         case 'C':
1092                                 if (!strcmp (name, "Char")) {
1093                                         t = MONO_TYPE_CHAR;
1094                                 }
1095                                 break;
1096                         case 'D':
1097                                 if (!strcmp (name, "Double")) {
1098                                         t = MONO_TYPE_R8;
1099                                         class->blittable = TRUE;                                                
1100                                 }
1101                                 break;
1102                         case 'I':
1103                                 if (!strcmp (name, "Int32")) {
1104                                         t = MONO_TYPE_I4;
1105                                         class->blittable = TRUE;
1106                                 } else if (!strcmp(name, "Int16")) {
1107                                         t = MONO_TYPE_I2;
1108                                         class->blittable = TRUE;
1109                                 } else if (!strcmp(name, "Int64")) {
1110                                         t = MONO_TYPE_I8;
1111                                         class->blittable = TRUE;
1112                                 } else if (!strcmp(name, "IntPtr")) {
1113                                         t = MONO_TYPE_I;
1114                                         class->blittable = TRUE;
1115                                 }
1116                                 break;
1117                         case 'S':
1118                                 if (!strcmp (name, "Single")) {
1119                                         t = MONO_TYPE_R4;
1120                                         class->blittable = TRUE;                                                
1121                                 } else if (!strcmp(name, "SByte")) {
1122                                         t = MONO_TYPE_I1;
1123                                         class->blittable = TRUE;
1124                                 }
1125                                 break;
1126                         case 'U':
1127                                 if (!strcmp (name, "UInt32")) {
1128                                         t = MONO_TYPE_U4;
1129                                         class->blittable = TRUE;
1130                                 } else if (!strcmp(name, "UInt16")) {
1131                                         t = MONO_TYPE_U2;
1132                                         class->blittable = TRUE;
1133                                 } else if (!strcmp(name, "UInt64")) {
1134                                         t = MONO_TYPE_U8;
1135                                         class->blittable = TRUE;
1136                                 } else if (!strcmp(name, "UIntPtr")) {
1137                                         t = MONO_TYPE_U;
1138                                         class->blittable = TRUE;
1139                                 }
1140                                 break;
1141                         case 'V':
1142                                 if (!strcmp (name, "Void")) {
1143                                         t = MONO_TYPE_VOID;
1144                                 }
1145                                 break;
1146                         default:
1147                                 break;
1148                         }
1149                 }
1150                 class->this_arg.type = class->byval_arg.type = t;
1151         }
1152 }
1153
1154 void
1155 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
1156 {
1157         gboolean system_namespace;
1158
1159         system_namespace = !strcmp (class->name_space, "System");
1160
1161         /* if root of the hierarchy */
1162         if (system_namespace && !strcmp (class->name, "Object")) {
1163                 class->parent = NULL;
1164                 class->instance_size = sizeof (MonoObject);
1165                 return;
1166         }
1167         if (!strcmp (class->name, "<Module>")) {
1168                 class->parent = NULL;
1169                 class->instance_size = 0;
1170                 return;
1171         }
1172
1173         if (!(class->flags & TYPE_ATTRIBUTE_INTERFACE)) {
1174                 int rnum = 0;
1175                 class->parent = parent;
1176
1177                 if (!parent)
1178                         g_assert_not_reached (); /* FIXME */
1179
1180                 class->marshalbyref = parent->marshalbyref;
1181                 class->contextbound  = parent->contextbound;
1182                 class->delegate  = parent->delegate;
1183                 
1184                 if (system_namespace) {
1185                         if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
1186                                 class->marshalbyref = 1;
1187
1188                         if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject")) 
1189                                 class->contextbound  = 1;
1190
1191                         if (*class->name == 'D' && !strcmp (class->name, "Delegate")) 
1192                                 class->delegate  = 1;
1193                 }
1194
1195                 if (class->parent->enumtype || ((strcmp (class->parent->name, "ValueType") == 0) && 
1196                                                 (strcmp (class->parent->name_space, "System") == 0)))
1197                         class->valuetype = 1;
1198                 if (((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
1199                         class->valuetype = class->enumtype = 1;
1200                 }
1201                 /*class->enumtype = class->parent->enumtype; */
1202                 class->parent->subclasses = g_list_prepend (class->parent->subclasses, class);
1203                 mono_compute_relative_numbering (mono_defaults.object_class, &rnum);
1204                 mono_class_setup_supertypes (class);
1205         } else {
1206                 class->parent = NULL;
1207         }
1208
1209 }
1210
1211 void
1212 mono_class_setup_supertypes (MonoClass *class)
1213 {
1214         MonoClass *k;
1215         int ms, i;
1216
1217         if (class->supertypes)
1218                 return;
1219
1220         class->idepth = 0;
1221         for (k = class; k ; k = k->parent) {
1222                 class->idepth++;
1223         }
1224
1225         ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
1226         class->supertypes = g_new0 (MonoClass *, ms);
1227
1228         if (class->parent) {
1229                 for (i = class->idepth, k = class; k ; k = k->parent)
1230                         class->supertypes [--i] = k;
1231         } else {
1232                 class->supertypes [0] = class;
1233         }
1234 }       
1235
1236 /**
1237  * @image: context where the image is created
1238  * @type_token:  typedef token
1239  */
1240 static MonoClass *
1241 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
1242 {
1243         MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
1244         MonoClass *class, *parent = NULL;
1245         guint32 cols [MONO_TYPEDEF_SIZE];
1246         guint32 cols_next [MONO_TYPEDEF_SIZE];
1247         guint tidx = mono_metadata_token_index (type_token);
1248         const char *name, *nspace;
1249         guint icount = 0; 
1250         MonoClass **interfaces;
1251
1252         if ((class = g_hash_table_lookup (image->class_cache, GUINT_TO_POINTER (type_token)))) 
1253                 return class;
1254
1255         g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
1256         
1257         mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
1258         
1259         name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1260         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1261
1262         if (cols [MONO_TYPEDEF_EXTENDS])
1263                 parent = mono_class_get (image, mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]));
1264         interfaces = mono_metadata_interfaces_from_typedef (image, type_token, &icount);
1265
1266         class = g_malloc0 (sizeof (MonoClass));
1267                            
1268         g_hash_table_insert (image->class_cache, GUINT_TO_POINTER (type_token), class);
1269
1270         class->interfaces = interfaces;
1271         class->interface_count = icount;
1272
1273         class->name = name;
1274         class->name_space = nspace;
1275
1276         class->image = image;
1277         class->type_token = type_token;
1278         class->flags = cols [MONO_TYPEDEF_FLAGS];
1279
1280         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
1281                 class->unicode = 1;
1282         /* fixme: maybe we must set this on windows 
1283         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
1284                 class->unicode = 1;
1285         */
1286
1287         class->cast_class = class->element_class = class;
1288
1289         /*g_print ("Init class %s\n", name);*/
1290
1291         mono_class_setup_parent (class, parent);
1292
1293         mono_class_setup_mono_type (class);
1294
1295         /*
1296          * Compute the field and method lists
1297          */
1298         class->field.first  = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
1299         class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
1300
1301         if (tt->rows > tidx){           
1302                 mono_metadata_decode_row (tt, tidx, cols_next, CSIZE (cols_next));
1303                 class->field.last  = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1304                 class->method.last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1305         } else {
1306                 class->field.last  = image->tables [MONO_TABLE_FIELD].rows;
1307                 class->method.last = image->tables [MONO_TABLE_METHOD].rows;
1308         }
1309
1310         if (cols [MONO_TYPEDEF_FIELD_LIST] && 
1311             cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
1312                 class->field.count = class->field.last - class->field.first;
1313         else
1314                 class->field.count = 0;
1315
1316         if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
1317                 class->method.count = class->method.last - class->method.first;
1318         else
1319                 class->method.count = 0;
1320
1321         /* reserve space to store vector pointer in arrays */
1322         if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
1323                 class->instance_size += 2 * sizeof (gpointer);
1324                 g_assert (class->field.count == 0);
1325         }
1326
1327         if (class->enumtype)
1328                 class_compute_field_layout (class);
1329
1330         if ((type_token = mono_metadata_nested_in_typedef (image, type_token)))
1331                 class->nested_in = mono_class_create_from_typedef (image, type_token);
1332
1333         return class;
1334 }
1335
1336 MonoClass *
1337 mono_ptr_class_get (MonoType *type)
1338 {
1339         MonoClass *result;
1340         MonoClass *el_class;
1341         static GHashTable *ptr_hash = NULL;
1342
1343         if (!ptr_hash)
1344                 ptr_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
1345         el_class = mono_class_from_mono_type (type);
1346         if ((result = g_hash_table_lookup (ptr_hash, el_class)))
1347                 return result;
1348         result = g_new0 (MonoClass, 1);
1349
1350         result->parent = NULL; /* no parent for PTR types */
1351         result->name = "System";
1352         result->name_space = "MonoPtrFakeClass";
1353         result->image = el_class->image;
1354         result->inited = TRUE;
1355         result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
1356         /* Can pointers get boxed? */
1357         result->instance_size = sizeof (gpointer);
1358         /*
1359          * baseval, diffval: need them to allow casting ?
1360          */
1361         result->cast_class = result->element_class = el_class;
1362         result->enum_basetype = &result->element_class->byval_arg;
1363
1364         result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
1365         result->this_arg.data.type = result->byval_arg.data.type = result->enum_basetype;
1366         result->this_arg.byref = TRUE;
1367
1368         g_hash_table_insert (ptr_hash, el_class, result);
1369
1370         return result;
1371 }
1372
1373 static MonoClass *
1374 mono_fnptr_class_get (MonoMethodSignature *sig)
1375 {
1376         MonoClass *result;
1377         static GHashTable *ptr_hash = NULL;
1378
1379         if (!ptr_hash)
1380                 ptr_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
1381         
1382         if ((result = g_hash_table_lookup (ptr_hash, sig)))
1383                 return result;
1384         result = g_new0 (MonoClass, 1);
1385
1386         result->parent = NULL; /* no parent for PTR types */
1387         result->name = "System";
1388         result->name_space = "MonoFNPtrFakeClass";
1389         result->image = NULL; /* need to fix... */
1390         result->inited = TRUE;
1391         result->flags = TYPE_ATTRIBUTE_CLASS; // | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
1392         /* Can pointers get boxed? */
1393         result->instance_size = sizeof (gpointer);
1394         /*
1395          * baseval, diffval: need them to allow casting ?
1396          */
1397         result->cast_class = result->element_class = result;
1398
1399         result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
1400         result->this_arg.data.method = result->byval_arg.data.method = sig;
1401         result->this_arg.byref = TRUE;
1402         result->enum_basetype = &result->element_class->byval_arg;
1403
1404         g_hash_table_insert (ptr_hash, sig, result);
1405
1406         return result;
1407 }
1408
1409 MonoClass *
1410 mono_class_from_mono_type (MonoType *type)
1411 {
1412         switch (type->type) {
1413         case MONO_TYPE_OBJECT:
1414                 return mono_defaults.object_class;
1415         case MONO_TYPE_VOID:
1416                 return mono_defaults.void_class;
1417         case MONO_TYPE_BOOLEAN:
1418                 return mono_defaults.boolean_class;
1419         case MONO_TYPE_CHAR:
1420                 return mono_defaults.char_class;
1421         case MONO_TYPE_I1:
1422                 return mono_defaults.sbyte_class;
1423         case MONO_TYPE_U1:
1424                 return mono_defaults.byte_class;
1425         case MONO_TYPE_I2:
1426                 return mono_defaults.int16_class;
1427         case MONO_TYPE_U2:
1428                 return mono_defaults.uint16_class;
1429         case MONO_TYPE_I4:
1430                 return mono_defaults.int32_class;
1431         case MONO_TYPE_U4:
1432                 return mono_defaults.uint32_class;
1433         case MONO_TYPE_I:
1434                 return mono_defaults.int_class;
1435         case MONO_TYPE_U:
1436                 return mono_defaults.uint_class;
1437         case MONO_TYPE_I8:
1438                 return mono_defaults.int64_class;
1439         case MONO_TYPE_U8:
1440                 return mono_defaults.uint64_class;
1441         case MONO_TYPE_R4:
1442                 return mono_defaults.single_class;
1443         case MONO_TYPE_R8:
1444                 return mono_defaults.double_class;
1445         case MONO_TYPE_STRING:
1446                 return mono_defaults.string_class;
1447         case MONO_TYPE_TYPEDBYREF:
1448                 return mono_defaults.typed_reference_class;
1449         case MONO_TYPE_ARRAY:
1450                 return mono_array_class_get (type->data.array->type, type->data.array->rank);
1451         case MONO_TYPE_PTR:
1452                 return mono_ptr_class_get (type->data.type);
1453         case MONO_TYPE_FNPTR:
1454                 return mono_fnptr_class_get (type->data.method);
1455         case MONO_TYPE_SZARRAY:
1456                 return mono_array_class_get (type->data.type, 1);
1457         case MONO_TYPE_CLASS:
1458         case MONO_TYPE_VALUETYPE:
1459                 return type->data.klass;
1460                 
1461         case MONO_TYPE_GENERICINST:
1462                 g_warning ("mono_class_from_type: implement me MONO_TYPE_GENERICINST");
1463                 g_assert_not_reached ();
1464                 
1465         case MONO_TYPE_VAR:
1466                 g_warning ("mono_class_from_type: implement me MONO_TYPE_VAR");
1467                 g_assert_not_reached ();
1468
1469         case MONO_TYPE_MVAR:
1470                 g_warning ("mono_class_from_type: implement me MONO_TYPE_MVAR");
1471                 g_assert_not_reached ();
1472                 
1473         default:
1474                 g_warning ("implement me 0x%02x\n", type->type);
1475                 g_assert_not_reached ();
1476         }
1477         
1478         return NULL;
1479 }
1480
1481 /**
1482  * @image: context where the image is created
1483  * @type_spec:  typespec token
1484  */
1485 static MonoClass *
1486 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec)
1487 {
1488         MonoType *type;
1489         MonoClass *class;
1490
1491         type = mono_type_create_from_typespec (image, type_spec);
1492
1493         switch (type->type) {
1494         case MONO_TYPE_ARRAY:
1495                 class = mono_array_class_get (type->data.array->type, type->data.array->rank);
1496                 break;
1497         case MONO_TYPE_SZARRAY:
1498                 class = mono_array_class_get (type->data.type, 1);
1499                 break;
1500         case MONO_TYPE_PTR:
1501                 class = mono_class_from_mono_type (type->data.type);
1502                 break;
1503         default:
1504                 /* it seems any type can be stored in TypeSpec as well */
1505                 class = mono_class_from_mono_type (type);
1506                 break;
1507         }
1508
1509         mono_metadata_free_type (type);
1510         
1511         return class;
1512 }
1513
1514 /**
1515  * mono_array_class_get:
1516  * @element_type: element type 
1517  * @rank: the dimension of the array class
1518  *
1519  * Returns: a class object describing the array with element type @element_type and 
1520  * dimension @rank. 
1521  */
1522 MonoClass *
1523 mono_array_class_get (MonoType *element_type, guint32 rank)
1524 {
1525         MonoClass *eclass;
1526         MonoImage *image;
1527         MonoClass *class;
1528         MonoClass *parent = NULL;
1529         GSList *list;
1530         int rnum = 0, nsize;
1531         char *name;
1532
1533         eclass = mono_class_from_mono_type (element_type);
1534         g_assert (rank <= 255);
1535
1536         parent = mono_defaults.array_class;
1537
1538         if (!parent->inited)
1539                 mono_class_init (parent);
1540
1541         image = eclass->image;
1542
1543         if ((list = g_hash_table_lookup (image->array_cache, element_type))) {
1544                 for (; list; list = list->next) {
1545                         class = list->data;
1546                         if (class->rank == rank)
1547                                 return class;
1548                 }
1549         }
1550         
1551         class = g_malloc0 (sizeof (MonoClass) + parent->vtable_size * sizeof (gpointer));
1552
1553         class->image = image;
1554         class->name_space = eclass->name_space;
1555         nsize = strlen (eclass->name);
1556         name = g_malloc (nsize + 2 + rank);
1557         memcpy (name, eclass->name, nsize);
1558         name [nsize] = '[';
1559         if (rank > 1)
1560                 memset (name + nsize + 1, ',', rank - 1);
1561         name [nsize + rank] = ']';
1562         name [nsize + rank + 1] = 0;
1563         class->name = name;
1564         class->type_token = 0;
1565         class->flags = TYPE_ATTRIBUTE_CLASS | (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
1566         class->parent = parent;
1567         class->instance_size = mono_class_instance_size (class->parent);
1568         class->class_size = 0;
1569         class->vtable_size = parent->vtable_size;
1570         class->parent->subclasses = g_list_prepend (class->parent->subclasses, class);
1571         mono_compute_relative_numbering (mono_defaults.object_class, &rnum);
1572         mono_class_setup_supertypes (class);
1573
1574         class->rank = rank;
1575         
1576         if (eclass->enumtype)
1577                 class->cast_class = eclass->element_class;
1578         else
1579                 class->cast_class = eclass;
1580
1581         class->element_class = eclass;
1582
1583         if (rank > 1) {
1584                 MonoArrayType *at = g_new0 (MonoArrayType, 1);
1585                 class->byval_arg.type = MONO_TYPE_ARRAY;
1586                 class->byval_arg.data.array = at;
1587                 at->type = &eclass->byval_arg;
1588                 at->rank = rank;
1589                 /* FIXME: complete.... */
1590         } else {
1591                 /* FIXME: this is not correct. the lbound could be >0 */
1592                 class->byval_arg.type = MONO_TYPE_SZARRAY;
1593                 class->byval_arg.data.type = &eclass->byval_arg;
1594         }
1595         class->this_arg = class->byval_arg;
1596         class->this_arg.byref = 1;
1597
1598         list = g_slist_append (list, class);
1599         g_hash_table_insert (image->array_cache, &class->element_class->byval_arg, list);
1600         return class;
1601 }
1602
1603 /**
1604  * mono_class_instance_size:
1605  * @klass: a class 
1606  * 
1607  * Returns: the size of an object instance
1608  */
1609 gint32
1610 mono_class_instance_size (MonoClass *klass)
1611 {
1612         
1613         if (!klass->size_inited)
1614                 mono_class_init (klass);
1615
1616         return klass->instance_size;
1617 }
1618
1619 /**
1620  * mono_class_native_size:
1621  * @klass: a class 
1622  * 
1623  * Returns: the native size of an object instance (when marshaled 
1624  * to unmanaged code) 
1625  */
1626 gint32
1627 mono_class_native_size (MonoClass *klass, guint32 *align)
1628 {
1629         
1630         if (!klass->marshal_info)
1631                 mono_marshal_load_type_info (klass);
1632
1633         if (align)
1634                 *align = klass->min_align;
1635
1636         return klass->marshal_info->native_size;
1637 }
1638
1639 /**
1640  * mono_class_min_align:
1641  * @klass: a class 
1642  * 
1643  * Returns: minimm alignment requirements 
1644  */
1645 gint32
1646 mono_class_min_align (MonoClass *klass)
1647 {
1648         
1649         if (!klass->size_inited)
1650                 mono_class_init (klass);
1651
1652         return klass->min_align;
1653 }
1654
1655 /**
1656  * mono_class_value_size:
1657  * @klass: a class 
1658  *
1659  * This function is used for value types, and return the
1660  * space and the alignment to store that kind of value object.
1661  *
1662  * Returns: the size of a value of kind @klass
1663  */
1664 gint32
1665 mono_class_value_size      (MonoClass *klass, guint32 *align)
1666 {
1667         gint32 size;
1668
1669         /* fixme: check disable, because we still have external revereces to
1670          * mscorlib and Dummy Objects 
1671          */
1672         /*g_assert (klass->valuetype);*/
1673
1674         size = mono_class_instance_size (klass) - sizeof (MonoObject);
1675
1676         if (align)
1677                 *align = klass->min_align;
1678
1679         return size;
1680 }
1681
1682 /**
1683  * mono_class_data_size:
1684  * @klass: a class 
1685  * 
1686  * Returns: the size of the static class data
1687  */
1688 gint32
1689 mono_class_data_size (MonoClass *klass)
1690 {
1691         
1692         if (!klass->inited)
1693                 mono_class_init (klass);
1694
1695         return klass->class_size;
1696 }
1697
1698 /*
1699  * Auxiliary routine to mono_class_get_field
1700  *
1701  * Takes a field index instead of a field token.
1702  */
1703 static MonoClassField *
1704 mono_class_get_field_idx (MonoClass *class, int idx)
1705 {
1706         if (class->field.count){
1707                 if ((idx >= class->field.first) && (idx < class->field.last)){
1708                         return &class->fields [idx - class->field.first];
1709                 }
1710         }
1711
1712         if (!class->parent)
1713                 return NULL;
1714         
1715         return mono_class_get_field_idx (class->parent, idx);
1716 }
1717
1718 /**
1719  * mono_class_get_field:
1720  * @class: the class to lookup the field.
1721  * @field_token: the field token
1722  *
1723  * Returns: A MonoClassField representing the type and offset of
1724  * the field, or a NULL value if the field does not belong to this
1725  * class.
1726  */
1727 MonoClassField *
1728 mono_class_get_field (MonoClass *class, guint32 field_token)
1729 {
1730         int idx = mono_metadata_token_index (field_token);
1731
1732         g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
1733
1734         return mono_class_get_field_idx (class, idx - 1);
1735 }
1736
1737 MonoClassField *
1738 mono_class_get_field_from_name (MonoClass *klass, const char *name)
1739 {
1740         int i;
1741
1742         while (klass) {
1743                 for (i = 0; i < klass->field.count; ++i) {
1744                         if (strcmp (name, klass->fields [i].name) == 0)
1745                                 return &klass->fields [i];
1746                 }
1747                 klass = klass->parent;
1748         }
1749         return NULL;
1750 }
1751
1752 MonoProperty*
1753 mono_class_get_property_from_name (MonoClass *klass, const char *name)
1754 {
1755         int i;
1756
1757         while (klass) {
1758                 for (i = 0; i < klass->property.count; ++i) {
1759                         if (strcmp (name, klass->properties [i].name) == 0)
1760                                 return &klass->properties [i];
1761                 }
1762                 klass = klass->parent;
1763         }
1764         return NULL;
1765 }
1766
1767 /**
1768  * mono_class_get:
1769  * @image: the image where the class resides
1770  * @type_token: the token for the class
1771  * @at: an optional pointer to return the array element type
1772  *
1773  * Returns: the MonoClass that represents @type_token in @image
1774  */
1775 MonoClass *
1776 mono_class_get (MonoImage *image, guint32 type_token)
1777 {
1778         MonoClass *class;
1779
1780         if (image->assembly->dynamic)
1781                 return mono_lookup_dynamic_token (image, type_token);
1782
1783         switch (type_token & 0xff000000){
1784         case MONO_TOKEN_TYPE_DEF:
1785                 class = mono_class_create_from_typedef (image, type_token);
1786                 break;          
1787         case MONO_TOKEN_TYPE_REF:
1788                 class = mono_class_from_typeref (image, type_token);
1789                 break;
1790         case MONO_TOKEN_TYPE_SPEC:
1791                 class = mono_class_create_from_typespec (image, type_token);
1792                 break;
1793         default:
1794                 g_warning ("unknown token type %x", type_token & 0xff000000);
1795                 g_assert_not_reached ();
1796         }
1797
1798         if (!class)
1799                 g_warning ("Could not load class from token 0x%08x in %s", type_token, image->name);
1800
1801         return class;
1802 }
1803
1804 MonoClass *
1805 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
1806 {
1807         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
1808         guint32 cols [MONO_TYPEDEF_SIZE];
1809         const char *n;
1810         const char *nspace;
1811         guint32 i, visib;
1812
1813         /* add a cache if needed */
1814         for (i = 1; i <= t->rows; ++i) {
1815                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
1816                 /* nested types are accessed from the nesting name */
1817                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
1818                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
1819                         continue;
1820                 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1821                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1822                 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
1823                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
1824         }
1825         return NULL;
1826 }
1827
1828 static MonoImage*
1829 load_file_for_image (MonoImage *image, int fileidx)
1830 {
1831         char *base_dir, *name;
1832         MonoImage *res;
1833         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1834         const char *fname;
1835         guint32 fname_id;
1836
1837         if (fileidx < 1 || fileidx > t->rows)
1838                 return NULL;
1839         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1840         fname = mono_metadata_string_heap (image, fname_id);
1841         base_dir = g_path_get_dirname (image->name);
1842         name = g_build_filename (base_dir, fname, NULL);
1843         res = mono_image_open (name, NULL);
1844         if (res) {
1845                 int i;
1846                 t = &res->tables [MONO_TABLE_MODULEREF];
1847                 //g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly);
1848                 res->assembly = image->assembly;
1849                 for (i = 0; i < t->rows; ++i) {
1850                         if (res->modules [i] && !res->modules [i]->assembly)
1851                                 res->modules [i]->assembly = image->assembly;
1852                 }
1853                 mono_image_load_references (image, NULL);
1854         }
1855         g_free (name);
1856         g_free (base_dir);
1857         return res;
1858 }
1859
1860 static MonoClass*
1861 return_nested_in (MonoClass *class, char *nested) {
1862         MonoClass *found;
1863         char *s = strchr (nested, '/');
1864         GList *tmp;
1865
1866         if (s) {
1867                 *s = 0;
1868                 s++;
1869         }
1870         for (tmp = class->nested_classes; tmp; tmp = tmp->next) {
1871                 found = tmp->data;
1872                 if (strcmp (found->name, nested) == 0) {
1873                         if (s)
1874                                 return return_nested_in (found, s);
1875                         return found;
1876                 }
1877         }
1878         return NULL;
1879 }
1880
1881 MonoClass *
1882 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
1883 {
1884         GHashTable *nspace_table;
1885         MonoImage *loaded_image;
1886         guint32 token;
1887         MonoClass *class;
1888         char *nested;
1889         char buf [1024];
1890
1891         if ((nested = strchr (name, '/'))) {
1892                 int pos = nested - name;
1893                 int len = strlen (name);
1894                 if (len > 1023)
1895                         return NULL;
1896                 memcpy (buf, name, len + 1);
1897                 buf [pos] = 0;
1898                 nested = buf + pos + 1;
1899                 name = buf;
1900         }
1901
1902         nspace_table = g_hash_table_lookup (image->name_cache, name_space);
1903         
1904         if (!nspace_table || !(token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name)))) {
1905                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
1906                 guint32 cols [MONO_EXP_TYPE_SIZE];
1907                 int i;
1908
1909                 for (i = 0; i < t->rows; ++i) {
1910                         const char *ename, *enspace;
1911                         mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
1912                         ename = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
1913                         enspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
1914
1915                         if (strcmp (name, ename) == 0 && strcmp (name_space, enspace) == 0) {
1916                                 guint32 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
1917                                 if ((impl & IMPLEMENTATION_MASK) == IMPLEMENTATION_FILE) {
1918                                         loaded_image = load_file_for_image (image, impl >> IMPLEMENTATION_BITS);
1919                                         if (!loaded_image)
1920                                                 return NULL;
1921                                         class = mono_class_from_name (loaded_image, name_space, name);
1922                                         if (nested)
1923                                                 return return_nested_in (class, nested);
1924                                         return class;
1925                                 } else {
1926                                         g_error ("not yet implemented");
1927                                 }
1928                         }
1929                 }
1930                 /*g_warning ("token not found for %s.%s in image %s", name_space, name, image->name);*/
1931                 return NULL;
1932         }
1933
1934         token = MONO_TOKEN_TYPE_DEF | token;
1935
1936         class = mono_class_get (image, token);
1937         if (nested)
1938                 return return_nested_in (class, nested);
1939         return class;
1940 }
1941
1942 gboolean
1943 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc, 
1944                                                    gboolean check_interfaces)
1945 {
1946         if (check_interfaces && (klassc->flags & TYPE_ATTRIBUTE_INTERFACE) && !(klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
1947                 if ((klassc->interface_id <= klass->max_interface_id) &&
1948                         (klass->interface_offsets [klassc->interface_id] >= 0))
1949                         return TRUE;
1950         } else if (check_interfaces && (klassc->flags & TYPE_ATTRIBUTE_INTERFACE) && (klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
1951                 int i;
1952
1953                 for (i = 0; i < klass->interface_count; i ++) {
1954                         MonoClass *ic =  klass->interfaces [i];
1955                         if (ic == klassc)
1956                                 return TRUE;
1957                 }
1958         } else {
1959                 /*
1960                  * klass->baseval is 0 for interfaces 
1961                  */
1962                 if (klass->baseval && ((klass->baseval - klassc->baseval) <= klassc->diffval))
1963                         return TRUE;
1964         }
1965         
1966         return FALSE;
1967 }
1968
1969 /*
1970  * Returns the nnumber of bytes an element of type klass
1971  * uses when stored into an array.
1972  */
1973 gint32
1974 mono_class_array_element_size (MonoClass *klass)
1975 {
1976         int t = klass->byval_arg.type;
1977         
1978 handle_enum:
1979         switch (t) {
1980         case MONO_TYPE_I1:
1981         case MONO_TYPE_U1:
1982         case MONO_TYPE_BOOLEAN:
1983                 return 1;
1984         case MONO_TYPE_I2:
1985         case MONO_TYPE_U2:
1986         case MONO_TYPE_CHAR:
1987                 return 2;
1988         case MONO_TYPE_I4:
1989         case MONO_TYPE_U4:
1990         case MONO_TYPE_R4:
1991                 return 4;
1992         case MONO_TYPE_I:
1993         case MONO_TYPE_U:
1994         case MONO_TYPE_PTR:
1995         case MONO_TYPE_CLASS:
1996         case MONO_TYPE_STRING:
1997         case MONO_TYPE_OBJECT:
1998         case MONO_TYPE_SZARRAY:
1999         case MONO_TYPE_ARRAY:    
2000                 return sizeof (gpointer);
2001         case MONO_TYPE_I8:
2002         case MONO_TYPE_U8:
2003         case MONO_TYPE_R8:
2004                 return 8;
2005         case MONO_TYPE_VALUETYPE:
2006                 if (klass->enumtype) {
2007                         t = klass->enum_basetype->type;
2008                         goto handle_enum;
2009                 }
2010                 return mono_class_instance_size (klass) - sizeof (MonoObject);
2011         default:
2012                 g_error ("unknown type 0x%02x in mono_class_array_element_size", t);
2013         }
2014         return -1;
2015 }
2016
2017 /**
2018  * mono_array_element_size:
2019  * @ac: pointer to a #MonoArrayClass
2020  *
2021  * Returns: the size of single array element.
2022  */
2023 gint32
2024 mono_array_element_size (MonoClass *ac)
2025 {
2026         return mono_class_array_element_size (ac->element_class);
2027 }
2028
2029 gpointer
2030 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class)
2031 {
2032         if (image->assembly->dynamic) {
2033                 gpointer obj = mono_lookup_dynamic_token (image, token);
2034
2035                 switch (token & 0xff000000) {
2036                 case MONO_TOKEN_TYPE_DEF:
2037                 case MONO_TOKEN_TYPE_REF:
2038                 case MONO_TOKEN_TYPE_SPEC:
2039                         if (handle_class)
2040                                 *handle_class = mono_defaults.typehandle_class;
2041                         return &((MonoClass*)obj)->byval_arg;
2042                 case MONO_TOKEN_METHOD_DEF:
2043                         if (handle_class)
2044                                 *handle_class = mono_defaults.methodhandle_class;
2045                         return obj;
2046                 case MONO_TOKEN_FIELD_DEF:
2047                         if (handle_class)
2048                                 *handle_class = mono_defaults.fieldhandle_class;
2049                         return obj;
2050                 default:
2051                         g_assert_not_reached ();
2052                 }
2053         }
2054
2055         switch (token & 0xff000000) {
2056         case MONO_TOKEN_TYPE_DEF:
2057         case MONO_TOKEN_TYPE_REF: {
2058                 MonoClass *class;
2059                 if (handle_class)
2060                         *handle_class = mono_defaults.typehandle_class;
2061                 class = mono_class_get (image, token);
2062                 mono_class_init (class);
2063                 /* We return a MonoType* as handle */
2064                 return &class->byval_arg;
2065         }
2066         case MONO_TOKEN_TYPE_SPEC: {
2067                 MonoClass *class;
2068                 if (handle_class)
2069                         *handle_class = mono_defaults.typehandle_class;
2070                 class = mono_class_create_from_typespec (image, token);
2071                 mono_class_init (class);
2072                 return &class->byval_arg;
2073         }
2074         case MONO_TOKEN_FIELD_DEF: {
2075                 MonoClass *class;
2076                 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
2077                 class = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
2078                 mono_class_init (class);
2079                 if (handle_class)
2080                                 *handle_class = mono_defaults.fieldhandle_class;
2081                 return mono_class_get_field (class, token);
2082         }
2083         case MONO_TOKEN_METHOD_DEF:
2084         case MONO_TOKEN_MEMBER_REF:
2085         default:
2086                 g_warning ("Unknown token 0x%08x in ldtoken", token);
2087                 break;
2088         }
2089         return NULL;
2090 }
2091
2092 /**
2093  * This function might need to call runtime functions so it can't be part
2094  * of the metadata library.
2095  */
2096 static MonoLookupDynamicToken lookup_dynamic = NULL;
2097
2098 void
2099 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
2100 {
2101         lookup_dynamic = func;
2102 }
2103
2104 gpointer
2105 mono_lookup_dynamic_token (MonoImage *image, guint32 token)
2106 {
2107         return lookup_dynamic (image, token);
2108 }