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