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