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