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