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