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