In mono/metadata:
[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/metadata-internals.h>
27 #include <mono/metadata/tabledefs.h>
28 #include <mono/metadata/tokentype.h>
29 #include <mono/metadata/class-internals.h>
30 #include <mono/metadata/object.h>
31 #include <mono/metadata/appdomain.h>
32 #include <mono/metadata/mono-endian.h>
33 #include <mono/metadata/debug-helpers.h>
34 #include <mono/metadata/reflection.h>
35 #include <mono/metadata/mono-debug-debugger.h>
36 #include <mono/os/gc_wrapper.h>
37
38 MonoStats mono_stats;
39
40 gboolean mono_print_vtable = FALSE;
41
42 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
43 static void mono_class_create_generic_2 (MonoGenericClass *gclass);
44
45 void (*mono_debugger_start_class_init_func) (MonoClass *klass) = NULL;
46 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
47
48 MonoClass *
49 mono_class_from_typeref (MonoImage *image, guint32 type_token)
50 {
51         guint32 cols [MONO_TYPEREF_SIZE];
52         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
53         guint32 idx;
54         const char *name, *nspace;
55         MonoClass *res;
56         MonoAssembly **references;
57         
58         mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
59
60         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
61         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
62
63         idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
64         switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
65         case MONO_RESOLTION_SCOPE_MODULE:
66                 if (!idx)
67                         g_error ("null ResolutionScope not yet handled");
68                 /* a typedef in disguise */
69                 return mono_class_from_name (image, nspace, name);
70         case MONO_RESOLTION_SCOPE_MODULEREF:
71                 return mono_class_from_name (image->modules [idx - 1], nspace, name);
72         case MONO_RESOLTION_SCOPE_TYPEREF: {
73                 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
74                 GList *tmp;
75                 mono_class_init (enclosing);
76                 for (tmp = enclosing->nested_classes; tmp; tmp = tmp->next) {
77                         res = tmp->data;
78                         if (strcmp (res->name, name) == 0)
79                                 return res;
80                 }
81                 g_warning ("TypeRef ResolutionScope not yet handled (%d)", idx);
82                 return NULL;
83         }
84         case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
85                 break;
86         }
87
88         references = image->references;
89         if (!references [idx-1])
90                 mono_assembly_load_reference (image, idx - 1);
91         if (references [idx - 1] == (gpointer)-1)
92                 return NULL;
93
94         image = references [idx-1]->image;
95
96         return mono_class_from_name (image, nspace, name);
97 }
98
99 static MonoType*
100 dup_type (MonoType* t, const MonoType *original)
101 {
102         MonoType *r = g_new0 (MonoType, 1);
103         *r = *t;
104         r->attrs = original->attrs;
105         r->byref = original->byref;
106         mono_stats.generics_metadata_size += sizeof (MonoType);
107         return r;
108 }
109
110 static void
111 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
112                             gboolean include_ns, gboolean include_arity)
113 {
114         MonoClass *klass;
115         
116         switch (type->type) {
117         case MONO_TYPE_ARRAY: {
118                 int i, rank = type->data.array->rank;
119
120                 mono_type_get_name_recurse (
121                         &type->data.array->eklass->byval_arg, str,
122                         FALSE, include_ns, include_arity);
123                 g_string_append_c (str, '[');
124                 for (i = 1; i < rank; i++)
125                         g_string_append_c (str, ',');
126                 g_string_append_c (str, ']');
127                 break;
128         }
129         case MONO_TYPE_SZARRAY:
130                 mono_type_get_name_recurse (
131                         &type->data.klass->byval_arg, str, FALSE, include_ns, include_arity);
132                 g_string_append (str, "[]");
133                 break;
134         case MONO_TYPE_PTR:
135                 mono_type_get_name_recurse (type->data.type, str, FALSE, include_ns, include_arity);
136                 g_string_append_c (str, '*');
137                 break;
138         default:
139                 klass = mono_class_from_mono_type (type);
140                 if (klass->nested_in) {
141                         mono_type_get_name_recurse (
142                                 &klass->nested_in->byval_arg, str, TRUE, include_ns, include_arity);
143                         g_string_append_c (str, '+');
144                 }
145                 if (include_ns && *klass->name_space) {
146                         g_string_append (str, klass->name_space);
147                         g_string_append_c (str, '.');
148                 }
149                 if (!include_arity) {
150                         char *s = strchr (klass->name, '`');
151                         int len = s ? s - klass->name : strlen (klass->name);
152
153                         g_string_append_len (str, klass->name, len);
154                 } else
155                         g_string_append (str, klass->name);
156                 if (is_recursed)
157                         break;
158                 if (klass->generic_class) {
159                         MonoGenericClass *gclass = klass->generic_class;
160                         int i;
161
162                         g_string_append_c (str, '[');
163                         for (i = 0; i < gclass->inst->type_argc; i++) {
164                                 if (i)
165                                         g_string_append_c (str, ',');
166                                 mono_type_get_name_recurse (
167                                         gclass->inst->type_argv [i], str, FALSE, include_ns, include_arity);
168                         }
169                         g_string_append_c (str, ']');
170                 } else if (klass->generic_container) {
171                         int i;
172
173                         g_string_append_c (str, '[');
174                         for (i = 0; i < klass->generic_container->type_argc; i++) {
175                                 if (i)
176                                         g_string_append_c (str, ',');
177                                 g_string_append (str, klass->generic_container->type_params [i].name);
178                         }
179                         g_string_append_c (str, ']');
180                 }
181                 break;
182         }
183 }
184
185 /**
186  * mono_type_get_name:
187  * @type: a type
188  *
189  * Returns: the string representation for type as required by System.Reflection.
190  * The inverse of mono_reflection_parse_type ().
191  */
192 static char*
193 _mono_type_get_name (MonoType *type, gboolean is_recursed, gboolean include_ns,
194                      gboolean include_arity)
195 {
196         GString* result = g_string_new ("");
197         mono_type_get_name_recurse (type, result, is_recursed, include_ns, include_arity);
198
199         if (type->byref)
200                 g_string_append_c (result, '&');
201
202         return g_string_free (result, FALSE);
203 }
204
205 char*
206 mono_type_get_name (MonoType *type)
207 {
208         return _mono_type_get_name (type, TRUE, TRUE, TRUE);
209 }
210
211 char*
212 mono_type_get_full_name (MonoType *type)
213 {
214         return _mono_type_get_name (type, FALSE, TRUE, TRUE);
215 }
216
217 MonoType*
218 mono_type_get_underlying_type (MonoType *type)
219 {
220         switch (type->type) {
221         case MONO_TYPE_VALUETYPE:
222                 if (type->data.klass->enumtype)
223                         return type->data.klass->enum_basetype;
224                 break;
225         case MONO_TYPE_GENERICINST:
226                 return mono_type_get_underlying_type (&type->data.generic_class->container_class->byval_arg);
227         default:
228                 break;
229         }
230
231         return type;
232 }
233
234 gboolean
235 mono_class_is_open_constructed_type (MonoType *t)
236 {
237         switch (t->type) {
238         case MONO_TYPE_VAR:
239         case MONO_TYPE_MVAR:
240                 return TRUE;
241         case MONO_TYPE_SZARRAY:
242                 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
243         case MONO_TYPE_ARRAY:
244                 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
245         case MONO_TYPE_PTR:
246                 return mono_class_is_open_constructed_type (t->data.type);
247         case MONO_TYPE_GENERICINST: {
248                 MonoGenericClass *gclass = t->data.generic_class;
249                 int i;
250
251                 if (mono_class_is_open_constructed_type (&gclass->container_class->byval_arg))
252                         return TRUE;
253                 for (i = 0; i < gclass->inst->type_argc; i++)
254                         if (mono_class_is_open_constructed_type (gclass->inst->type_argv [i]))
255                                 return TRUE;
256                 return FALSE;
257         }
258         default:
259                 return FALSE;
260         }
261 }
262
263 static MonoGenericClass *
264 inflate_generic_class (MonoGenericClass *ogclass, MonoGenericContext *context)
265 {
266         MonoGenericClass *ngclass, *cached;
267
268         if (ogclass->is_dynamic) {
269                 MonoDynamicGenericClass *dgclass = g_new0 (MonoDynamicGenericClass, 1);
270                 ngclass = &dgclass->generic_class;
271                 ngclass->is_dynamic = 1;
272         } else
273                 ngclass = g_new0 (MonoGenericClass, 1);
274
275         *ngclass = *ogclass;
276
277         ngclass->inst = mono_metadata_inflate_generic_inst (ogclass->inst, context);
278
279         ngclass->klass = NULL;
280
281         ngclass->context = g_new0 (MonoGenericContext, 1);
282         ngclass->context->container = context->container;
283         ngclass->context->gclass = ngclass;
284
285         mono_loader_lock ();
286         cached = mono_metadata_lookup_generic_class (ngclass);
287         mono_loader_unlock ();
288         if (cached) {
289                 g_free (ngclass);
290                 return cached;
291         }
292
293         mono_class_create_generic (ngclass);
294
295         return ngclass;
296 }
297
298 static MonoType*
299 inflate_generic_type (MonoType *type, MonoGenericContext *context)
300 {
301         switch (type->type) {
302         case MONO_TYPE_MVAR:
303                 if (context->gmethod && context->gmethod->inst->type_argv)
304                         return dup_type (
305                                 context->gmethod->inst->type_argv [type->data.generic_param->num],
306                                 type);
307                 else
308                         return NULL;
309         case MONO_TYPE_VAR:
310                 if (context->gclass)
311                         return dup_type (
312                                 context->gclass->inst->type_argv [type->data.generic_param->num],
313                                 type);
314                 else
315                         return NULL;
316         case MONO_TYPE_SZARRAY: {
317                 MonoClass *eclass = type->data.klass;
318                 MonoType *nt, *inflated = inflate_generic_type (&eclass->byval_arg, context);
319                 if (!inflated)
320                         return NULL;
321                 nt = dup_type (type, type);
322                 nt->data.klass = mono_class_from_mono_type (inflated);
323                 return nt;
324         }
325         case MONO_TYPE_GENERICINST: {
326                 MonoGenericClass *ngclass = inflate_generic_class (type->data.generic_class, context);
327                 MonoType *nt = dup_type (type, type);
328                 nt->data.generic_class = ngclass;
329                 return nt;
330         }
331         case MONO_TYPE_CLASS:
332         case MONO_TYPE_VALUETYPE: {
333                 MonoClass *klass = type->data.klass;
334                 MonoGenericClass *gclass;
335                 MonoType *nt;
336
337                 if (!klass->generic_container)
338                         return NULL;
339
340                 gclass = inflate_generic_class (klass->generic_container->context.gclass, context);
341
342                 nt = dup_type (type, type);
343                 nt->type = MONO_TYPE_GENERICINST;
344                 nt->data.generic_class = gclass;
345                 return nt;
346         }
347         default:
348                 return NULL;
349         }
350         return NULL;
351 }
352
353 MonoType*
354 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
355 {
356         MonoType *inflated = inflate_generic_type (type, context);
357
358         if (!inflated)
359                 return dup_type (type, type);
360
361         mono_stats.inflated_type_count++;
362         return inflated;
363 }
364
365 MonoMethodSignature*
366 mono_class_inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context)
367 {
368         MonoMethodSignature *res;
369         gboolean is_open;
370         int i;
371
372         if (!context)
373                 return sig;
374
375         res = mono_metadata_signature_alloc (image, sig->param_count);
376         res->ret = mono_class_inflate_generic_type (sig->ret, context);
377         is_open = mono_class_is_open_constructed_type (res->ret);
378         for (i = 0; i < sig->param_count; ++i) {
379                 res->params [i] = mono_class_inflate_generic_type (sig->params [i], context);
380                 if (!is_open)
381                         is_open = mono_class_is_open_constructed_type (res->params [i]);
382         }
383         res->hasthis = sig->hasthis;
384         res->explicit_this = sig->explicit_this;
385         res->call_convention = sig->call_convention;
386         res->generic_param_count = sig->generic_param_count;
387         res->sentinelpos = sig->sentinelpos;
388         res->has_type_parameters = is_open;
389         res->is_inflated = 1;
390         return res;
391 }
392
393 static MonoMethodHeader*
394 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
395 {
396         MonoMethodHeader *res;
397         int i;
398         res = g_malloc0 (sizeof (MonoMethodHeader) + sizeof (gpointer) * header->num_locals);
399         res->code = header->code;
400         res->code_size = header->code_size;
401         res->max_stack = header->max_stack;
402         res->num_clauses = header->num_clauses;
403         res->init_locals = header->init_locals;
404         res->num_locals = header->num_locals;
405         res->clauses = header->clauses;
406         for (i = 0; i < header->num_locals; ++i)
407                 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
408         return res;
409 }
410
411 static MonoGenericContext *
412 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with)
413 {
414         MonoGenericContext *res = g_new0 (MonoGenericContext, 1);
415
416         res->container = context->container;
417
418         if (context->gclass)
419                 res->gclass = inflate_generic_class (context->gclass, inflate_with);
420
421         if (context->gmethod) {
422                 res->gmethod = g_new0 (MonoGenericMethod, 1);
423
424                 res->gmethod->container = context->gmethod->container;
425                 res->gmethod->inst = mono_metadata_inflate_generic_inst (context->gmethod->inst, inflate_with);
426         } else
427                 res->gmethod = inflate_with->gmethod;
428
429         return res;
430 }
431
432 MonoMethod*
433 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context,
434                                    MonoClass *klass)
435 {
436         MonoMethodInflated *result;
437
438         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
439             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
440                 return method;
441
442         if (method->is_inflated || mono_method_signature (method)->is_inflated) {
443                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
444
445                 context = inflate_generic_context (imethod->context, context);
446                 method = imethod->declaring;
447         }
448
449         mono_stats.inflated_method_count++;
450
451         result = g_new0 (MonoMethodInflated, 1);
452         result->nmethod = *(MonoMethodNormal*)method;
453         result->nmethod.method.is_inflated = 1;
454         result->context = context;
455         result->declaring = method;
456
457         if (result->nmethod.method.klass->generic_class)
458                 result->nmethod.method.klass = result->nmethod.method.klass->generic_class->container_class;
459
460         return (MonoMethod *) result;
461 }
462
463 MonoMethod *
464 mono_get_inflated_method (MonoMethod *method)
465 {
466         MonoMethodInflated *imethod, *res;
467         MonoMethodHeader *mh;
468         MonoType *dtype;
469         MonoClass *rklass;
470
471         if (!method->is_inflated)
472                 return method;
473
474         imethod = (MonoMethodInflated *) method;
475         if (imethod->inflated)
476                 return (MonoMethod *) imethod->inflated;
477
478         mono_stats.inflated_method_count_2++;
479         mono_stats.generics_metadata_size +=
480                 sizeof (MonoMethodInflated) - sizeof (MonoMethodNormal);
481
482         res = g_new0 (MonoMethodInflated, 1);
483         *res = *imethod;
484         res->inflated = imethod->inflated = res;
485
486         mh = mono_method_get_header (method);
487         if (mh)
488                 res->nmethod.header = inflate_generic_header (mh, imethod->context);
489
490         dtype = mono_class_inflate_generic_type (&method->klass->byval_arg, imethod->context);
491         rklass = res->nmethod.method.klass = mono_class_from_mono_type (dtype);
492
493         res->nmethod.method.signature = mono_class_inflate_generic_signature (
494                 method->klass->image, mono_method_signature (method), imethod->context);
495
496         return (MonoMethod *) res;
497 }
498
499 /** 
500  * class_compute_field_layout:
501  * @m: pointer to the metadata.
502  * @class: The class to initialize
503  *
504  * Initializes the class->fields.
505  *
506  * Currently we only support AUTO_LAYOUT, and do not even try to do
507  * a good job at it.  This is temporary to get the code for Paolo.
508  */
509 static void
510 class_compute_field_layout (MonoClass *class)
511 {
512         MonoImage *m = class->image; 
513         const int top = class->field.count;
514         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
515         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
516         int i, blittable = TRUE, real_size = 0;
517         guint32 rva;
518         guint32 packing_size = 0;
519         gboolean explicit_size;
520         MonoClassField *field;
521
522         if (class->size_inited)
523                 return;
524
525         if (class->parent) {
526                 if (!class->parent->size_inited)
527                         class_compute_field_layout (class->parent);
528                 class->instance_size += class->parent->instance_size;
529                 class->min_align = class->parent->min_align;
530                 blittable = class->parent->blittable;
531         } else {
532                 class->instance_size = sizeof (MonoObject);
533                 class->min_align = 1;
534         }
535
536         /* Get the real size */
537         explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
538
539         if (explicit_size) {
540                 g_assert ((packing_size & 0xfffffff0) == 0);
541                 class->packing_size = packing_size;
542                 real_size += class->instance_size;
543         }
544
545         if (!top) {
546                 if (explicit_size && real_size) {
547                         class->instance_size = MAX (real_size, class->instance_size);
548                 }
549                 class->size_inited = 1;
550                 class->blittable = blittable;
551                 return;
552         }
553
554         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
555                 blittable = FALSE;
556
557         class->fields = g_new0 (MonoClassField, top);
558
559         /*
560          * Fetch all the field information.
561          */
562         for (i = 0; i < top; i++){
563                 const char *sig;
564                 guint32 cols [MONO_FIELD_SIZE];
565                 int idx = class->field.first + i;
566                 MonoGenericContainer *container = NULL;
567
568                 field = &class->fields [i];
569                 mono_metadata_decode_row (t, idx, cols, MONO_FIELD_SIZE);
570                 /* The name is needed for fieldrefs */
571                 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
572                 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
573                 mono_metadata_decode_value (sig, &sig);
574                 /* FIELD signature == 0x06 */
575                 g_assert (*sig == 0x06);
576                 if (class->generic_container)
577                         container = class->generic_container;
578                 else if (class->generic_class) {
579                         container = class->generic_class->container_class->generic_container;
580                         g_assert (container);
581                 }
582                 field->type = mono_metadata_parse_type_full (
583                         m, (MonoGenericContext *) container, MONO_PARSE_FIELD,
584                         cols [MONO_FIELD_FLAGS], sig + 1, &sig);
585                 if (mono_field_is_deleted (field))
586                         continue;
587                 if (class->generic_class) {
588                         field->type = mono_class_inflate_generic_type (
589                                 field->type, class->generic_class->context);
590                         field->type->attrs = cols [MONO_FIELD_FLAGS];
591                 }
592
593                 field->parent = class;
594
595                 /* Only do these checks if we still think this type is blittable */
596                 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
597                         if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
598                                 blittable = FALSE;
599                         } else {
600                                 MonoClass *field_class = mono_class_from_mono_type (field->type);
601                                 if (!field_class || !field_class->blittable)
602                                         blittable = FALSE;
603                         }
604                 }
605
606                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
607                         mono_metadata_field_info (m, idx, &field->offset, NULL, NULL);
608                         if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
609                                 g_warning ("%s not initialized correctly (missing field layout info for %s)", class->name, field->name);
610                 }
611
612                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
613                         mono_metadata_field_info (m, idx, NULL, &rva, NULL);
614                         if (!rva)
615                                 g_warning ("field %s in %s should have RVA data, but hasn't", field->name, class->name);
616                         field->data = mono_image_rva_map (class->image, rva);
617                 }
618
619                 if (class->enumtype && !(cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC)) {
620                         class->enum_basetype = field->type;
621                         class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
622                         blittable = class->element_class->blittable;
623                 }
624
625                 /* The def_value of fields is compute lazily during vtable creation */
626         }
627
628         if (class == mono_defaults.string_class)
629                 blittable = FALSE;
630
631         class->blittable = blittable;
632
633         if (class->enumtype && !class->enum_basetype) {
634                 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
635                         G_BREAKPOINT ();
636         }
637         if (explicit_size && real_size) {
638                 class->instance_size = MAX (real_size, class->instance_size);
639         }
640
641         if (class->generic_container ||
642             (class->generic_class && class->generic_class->inst->is_open))
643                 return;
644
645         mono_class_layout_fields (class);
646 }
647
648 void
649 mono_class_layout_fields (MonoClass *class)
650 {
651         int i;
652         const int top = class->field.count;
653         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
654         guint32 pass, passes, real_size;
655         gboolean gc_aware_layout = FALSE;
656         MonoClassField *field;
657
658         /*
659          * Enable GC aware auto layout: in this mode, reference
660          * fields are grouped together inside objects, increasing collector 
661          * performance.
662          * Requires that all classes whose layout is known to native code be annotated
663          * with [StructLayout (LayoutKind.Sequential)]
664          * Value types have gc_aware_layout disabled by default, as per
665          * what the default is for other runtimes.
666          */
667          /* corlib is missing [StructLayout] directives in many places */
668         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
669                 if (class->image != mono_defaults.corlib &&
670                         class->byval_arg.type != MONO_TYPE_VALUETYPE)
671                         gc_aware_layout = TRUE;
672         }
673
674         /*
675          * Compute field layout and total size (not considering static fields)
676          */
677
678         switch (layout) {
679         case TYPE_ATTRIBUTE_AUTO_LAYOUT:
680         case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
681
682                 if (gc_aware_layout)
683                         passes = 2;
684                 else
685                         passes = 1;
686
687                 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
688                         passes = 1;
689
690                 if (class->parent)
691                         real_size = class->parent->instance_size;
692                 else
693                         real_size = sizeof (MonoObject);
694
695                 for (pass = 0; pass < passes; ++pass) {
696                         for (i = 0; i < top; i++){
697                                 int size, align;
698                                 field = &class->fields [i];
699
700                                 if (mono_field_is_deleted (field))
701                                         continue;
702                                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
703                                         continue;
704
705                                 if (gc_aware_layout) {
706                                         /* 
707                                          * We process fields with reference type in the first pass,
708                                          * and fields with non-reference type in the second pass.
709                                          * We use IS_POINTER instead of IS_REFERENCE because in
710                                          * some internal structures, we store GC_MALLOCed memory
711                                          * in IntPtr fields...
712                                          */
713                                         if (MONO_TYPE_IS_POINTER (field->type)) {
714                                                 if (pass == 1)
715                                                         continue;
716                                         } else {
717                                                 if (pass == 0)
718                                                         continue;
719                                         }
720                                 }
721
722                                 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
723                                         (strcmp (field->name, "$PRIVATE$") == 0)) {
724                                         /* This field is a hack inserted by MCS to empty structures */
725                                         continue;
726                                 }
727
728                                 size = mono_type_size (field->type, &align);
729                         
730                                 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
731                                 align = class->packing_size ? MIN (class->packing_size, align): align;
732                                 class->min_align = MAX (align, class->min_align);
733                                 field->offset = real_size;
734                                 field->offset += align - 1;
735                                 field->offset &= ~(align - 1);
736                                 real_size = field->offset + size;
737                         }
738
739                         class->instance_size = MAX (real_size, class->instance_size);
740        
741                         if (class->instance_size & (class->min_align - 1)) {
742                                 class->instance_size += class->min_align - 1;
743                                 class->instance_size &= ~(class->min_align - 1);
744                         }
745                 }
746                 break;
747         case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
748                 real_size = 0;
749                 for (i = 0; i < top; i++) {
750                         int size, align;
751                         field = &class->fields [i];
752
753                         /*
754                          * There must be info about all the fields in a type if it
755                          * uses explicit layout.
756                          */
757
758                         if (mono_field_is_deleted (field))
759                                 continue;
760                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
761                                 continue;
762
763                         size = mono_type_size (field->type, &align);
764                         
765                         /*
766                          * When we get here, field->offset is already set by the
767                          * loader (for either runtime fields or fields loaded from metadata).
768                          * The offset is from the start of the object: this works for both
769                          * classes and valuetypes.
770                          */
771                         field->offset += sizeof (MonoObject);
772
773                         /*
774                          * Calc max size.
775                          */
776                         real_size = MAX (real_size, size + field->offset);
777                 }
778                 class->instance_size = MAX (real_size, class->instance_size);
779                 break;
780         }
781
782         class->size_inited = 1;
783
784         /*
785          * Compute static field layout and size
786          */
787         for (i = 0; i < top; i++){
788                 int size, align;
789                 field = &class->fields [i];
790                         
791                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
792                         continue;
793                 if (mono_field_is_deleted (field))
794                         continue;
795                         
796                 size = mono_type_size (field->type, &align);
797                 field->offset = class->class_size;
798                 field->offset += align - 1;
799                 field->offset &= ~(align - 1);
800                 class->class_size = field->offset + size;
801         }
802 }
803
804 static void
805 init_properties (MonoClass *class)
806 {
807         guint startm, endm, i, j;
808         guint32 cols [MONO_PROPERTY_SIZE];
809         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_PROPERTY];
810         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
811
812         class->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->property.last);
813         class->property.count = class->property.last - class->property.first;
814
815         class->properties = g_new0 (MonoProperty, class->property.count);
816         for (i = class->property.first; i < class->property.last; ++i) {
817                 mono_metadata_decode_row (pt, i, cols, MONO_PROPERTY_SIZE);
818                 class->properties [i - class->property.first].parent = class;
819                 class->properties [i - class->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
820                 class->properties [i - class->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
821
822                 startm = mono_metadata_methods_from_property (class->image, i, &endm);
823                 for (j = startm; j < endm; ++j) {
824                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
825                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
826                         case METHOD_SEMANTIC_SETTER:
827                                 class->properties [i - class->property.first].set = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
828                                 break;
829                         case METHOD_SEMANTIC_GETTER:
830                                 class->properties [i - class->property.first].get = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
831                                 break;
832                         default:
833                                 break;
834                         }
835                 }
836         }
837 }
838
839 static void
840 init_events (MonoClass *class)
841 {
842         guint startm, endm, i, j;
843         guint32 cols [MONO_EVENT_SIZE];
844         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_EVENT];
845         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
846
847         class->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &class->event.last);
848         class->event.count = class->event.last - class->event.first;
849
850         class->events = g_new0 (MonoEvent, class->event.count);
851         for (i = class->event.first; i < class->event.last; ++i) {
852                 MonoEvent *event = &class->events [i - class->event.first];
853                         
854                 mono_metadata_decode_row (pt, i, cols, MONO_EVENT_SIZE);
855                 event->parent = class;
856                 event->attrs = cols [MONO_EVENT_FLAGS];
857                 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
858
859                 startm = mono_metadata_methods_from_event (class->image, i, &endm);
860                 for (j = startm; j < endm; ++j) {
861                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
862                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
863                         case METHOD_SEMANTIC_ADD_ON:
864                                 event->add = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
865                                 break;
866                         case METHOD_SEMANTIC_REMOVE_ON:
867                                 event->remove = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
868                                 break;
869                         case METHOD_SEMANTIC_FIRE:
870                                 event->raise = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
871                                 break;
872                         case METHOD_SEMANTIC_OTHER: {
873                                 int n = 0;
874
875                                 if (event->other == NULL) {
876                                         event->other = g_new0 (MonoMethod*, 1);
877                                 } else {
878                                         while (event->other [n])
879                                                 n++;
880                                         event->other = g_realloc (event->other, (n + 1) * sizeof (MonoMethod*));
881                                 }
882                                 event->other [n] = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
883                                 break;
884                         }
885                         default:
886                                 break;
887                         }
888                 }
889         }
890 }
891
892 static guint
893 mono_get_unique_iid (MonoClass *class)
894 {
895         static GHashTable *iid_hash = NULL;
896         static guint iid = 0;
897
898         char *str;
899         gpointer value;
900         
901         g_assert (MONO_CLASS_IS_INTERFACE (class));
902
903         mono_loader_lock ();
904
905         if (!iid_hash)
906                 iid_hash = g_hash_table_new (g_str_hash, g_str_equal);
907
908         str = g_strdup_printf ("%s|%s.%s\n", class->image->name, class->name_space, class->name);
909
910         if (g_hash_table_lookup_extended (iid_hash, str, NULL, &value)) {
911                 mono_loader_unlock ();
912                 g_free (str);
913                 return (guint)value;
914         } else {
915                 g_hash_table_insert (iid_hash, str, (gpointer)iid);
916                 ++iid;
917         }
918
919         mono_loader_unlock ();
920
921         g_assert (iid <= 65535);
922         return iid - 1;
923 }
924
925 static void
926 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
927 {
928         int i;
929         MonoClass *ic;
930         
931         for (i = 0; i < klass->interface_count; i++) {
932                 ic = klass->interfaces [i];
933
934                 if (*res == NULL)
935                         *res = g_ptr_array_new ();
936                 g_ptr_array_add (*res, ic);
937                 mono_class_init (ic);
938
939                 collect_implemented_interfaces_aux (ic, res);
940         }
941 }
942
943 GPtrArray*
944 mono_class_get_implemented_interfaces (MonoClass *klass)
945 {
946         GPtrArray *res = NULL;
947
948         collect_implemented_interfaces_aux (klass, &res);
949         return res;
950 }
951
952 static int
953 setup_interface_offsets (MonoClass *class, int cur_slot)
954 {
955         MonoClass *k, *ic;
956         int i, max_iid;
957         GPtrArray *ifaces;
958
959         /* compute maximum number of slots and maximum interface id */
960         max_iid = 0;
961         for (k = class; k ; k = k->parent) {
962                 for (i = 0; i < k->interface_count; i++) {
963                         ic = k->interfaces [i];
964
965                         if (!ic->inited)
966                                 mono_class_init (ic);
967
968                         if (max_iid < ic->interface_id)
969                                 max_iid = ic->interface_id;
970                 }
971         }
972
973         if (MONO_CLASS_IS_INTERFACE (class)) {
974                 if (max_iid < class->interface_id)
975                         max_iid = class->interface_id;
976         }
977         class->max_interface_id = max_iid;
978         /* compute vtable offset for interfaces */
979         class->interface_offsets = g_malloc (sizeof (gpointer) * (max_iid + 1));
980
981         for (i = 0; i <= max_iid; i++)
982                 class->interface_offsets [i] = -1;
983
984         ifaces = mono_class_get_implemented_interfaces (class);
985         if (ifaces) {
986                 for (i = 0; i < ifaces->len; ++i) {
987                         ic = g_ptr_array_index (ifaces, i);
988                         class->interface_offsets [ic->interface_id] = cur_slot;
989                         cur_slot += ic->method.count;
990                 }
991                 g_ptr_array_free (ifaces, TRUE);
992         }
993
994         for (k = class->parent; k ; k = k->parent) {
995                 ifaces = mono_class_get_implemented_interfaces (k);
996                 if (ifaces) {
997                         for (i = 0; i < ifaces->len; ++i) {
998                                 ic = g_ptr_array_index (ifaces, i);
999
1000                                 if (class->interface_offsets [ic->interface_id] == -1) {
1001                                         int io = k->interface_offsets [ic->interface_id];
1002
1003                                         g_assert (io >= 0);
1004
1005                                         class->interface_offsets [ic->interface_id] = io;
1006                                 }
1007                         }
1008                         g_ptr_array_free (ifaces, TRUE);
1009                 }
1010         }
1011
1012         if (MONO_CLASS_IS_INTERFACE (class))
1013                 class->interface_offsets [class->interface_id] = cur_slot;
1014
1015         return cur_slot;
1016 }
1017
1018 void
1019 mono_class_setup_vtable (MonoClass *class, MonoMethod **overrides, int onum)
1020 {
1021         MonoClass *k, *ic;
1022         MonoMethod **vtable;
1023         int i, max_vtsize = 0, max_iid, cur_slot = 0;
1024         GPtrArray *ifaces;
1025         GHashTable *override_map = NULL;
1026
1027         /* setup_vtable() must be called only once on the type */
1028         if (class->interface_offsets) {
1029                 g_warning ("vtable already computed in %s.%s", class->name_space, class->name);
1030                 return;
1031         }
1032
1033         ifaces = mono_class_get_implemented_interfaces (class);
1034         if (ifaces) {
1035                 for (i = 0; i < ifaces->len; i++) {
1036                         MonoClass *ic = g_ptr_array_index (ifaces, i);
1037                         max_vtsize += ic->method.count;
1038                 }
1039                 g_ptr_array_free (ifaces, TRUE);
1040         }
1041         
1042         if (class->parent) {
1043                 mono_class_init (class->parent);
1044                 max_vtsize += class->parent->vtable_size;
1045                 cur_slot = class->parent->vtable_size;
1046         }
1047
1048         max_vtsize += class->method.count;
1049
1050         vtable = alloca (sizeof (gpointer) * max_vtsize);
1051         memset (vtable, 0, sizeof (gpointer) * max_vtsize);
1052
1053         /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
1054
1055         cur_slot = setup_interface_offsets (class, cur_slot);
1056         max_iid = class->max_interface_id;
1057
1058         if (class->parent && class->parent->vtable_size)
1059                 memcpy (vtable, class->parent->vtable,  sizeof (gpointer) * class->parent->vtable_size);
1060
1061         /* override interface methods */
1062         for (i = 0; i < onum; i++) {
1063                 MonoMethod *decl = overrides [i*2];
1064                 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
1065                         int dslot;
1066                         g_assert (decl->slot != -1);
1067                         dslot = decl->slot + class->interface_offsets [decl->klass->interface_id];
1068                         vtable [dslot] = overrides [i*2 + 1];
1069                         vtable [dslot]->slot = dslot;
1070                         if (!override_map)
1071                                 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
1072
1073                         g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
1074                 }
1075         }
1076
1077         for (k = class; k ; k = k->parent) {
1078                 int nifaces = 0;
1079                 ifaces = mono_class_get_implemented_interfaces (k);
1080                 if (ifaces)
1081                         nifaces = ifaces->len;
1082                 for (i = 0; i < nifaces; i++) {
1083                         int j, l, io;
1084
1085                         ic = g_ptr_array_index (ifaces, i);
1086                         io = k->interface_offsets [ic->interface_id];
1087
1088                         g_assert (io >= 0);
1089                         g_assert (io <= max_vtsize);
1090
1091                         if (k == class) {
1092                                 for (l = 0; l < ic->method.count; l++) {
1093                                         MonoMethod *im = ic->methods [l];                                               
1094
1095                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1096                                                 continue;
1097
1098                                         for (j = 0; j < class->method.count; ++j) {
1099                                                 MonoMethod *cm = class->methods [j];
1100                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
1101                                                     !((cm->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) ||
1102                                                     !(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT))
1103                                                         continue;
1104                                                 if (!strcmp(cm->name, im->name) && 
1105                                                     mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
1106                                                         g_assert (io + l <= max_vtsize);
1107                                                         vtable [io + l] = cm;
1108                                                 }
1109                                         }
1110                                 }
1111                         } else {
1112                                 /* already implemented */
1113                                 if (io >= k->vtable_size)
1114                                         continue;
1115                         }
1116                                 
1117                         for (l = 0; l < ic->method.count; l++) {
1118                                 MonoMethod *im = ic->methods [l];                                               
1119                                 MonoClass *k1;
1120
1121                                 g_assert (io + l <= max_vtsize);
1122
1123                                 if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1124                                         continue;
1125                                         
1126                                 for (k1 = class; k1; k1 = k1->parent) {
1127                                         for (j = 0; j < k1->method.count; ++j) {
1128                                                 MonoMethod *cm = k1->methods [j];
1129
1130                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
1131                                                     !(cm->flags & METHOD_ATTRIBUTE_PUBLIC))
1132                                                         continue;
1133                                                 
1134                                                 if (!strcmp(cm->name, im->name) && 
1135                                                     mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
1136                                                         g_assert (io + l <= max_vtsize);
1137                                                         vtable [io + l] = cm;
1138                                                         break;
1139                                                 }
1140                                                 
1141                                         }
1142                                         g_assert (io + l <= max_vtsize);
1143                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1144                                                 break;
1145                                 }
1146                         }
1147
1148                         for (l = 0; l < ic->method.count; l++) {
1149                                 MonoMethod *im = ic->methods [l];                                               
1150                                 char *qname, *fqname, *cname, *the_cname;
1151                                 MonoClass *k1;
1152                                 
1153                                 if (vtable [io + l])
1154                                         continue;
1155
1156                                 if (ic->generic_class) {
1157                                         MonoClass *the_ic = ic->generic_class->container_class;
1158                                         the_cname = _mono_type_get_name (&the_ic->byval_arg, TRUE, FALSE, TRUE);
1159                                         cname = the_cname;
1160                                 } else {
1161                                         the_cname = NULL;
1162                                         cname = (char*)ic->name;
1163                                 }
1164                                         
1165                                 qname = g_strconcat (cname, ".", im->name, NULL);
1166                                 if (ic->name_space && ic->name_space [0])
1167                                         fqname = g_strconcat (ic->name_space, ".", cname, ".", im->name, NULL);
1168                                 else
1169                                         fqname = NULL;
1170
1171                                 for (k1 = class; k1; k1 = k1->parent) {
1172                                         for (j = 0; j < k1->method.count; ++j) {
1173                                                 MonoMethod *cm = k1->methods [j];
1174
1175                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
1176                                                         continue;
1177                                         
1178                                                 if (((fqname && !strcmp (cm->name, fqname)) || !strcmp (cm->name, qname)) &&
1179                                                     mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
1180                                                         g_assert (io + l <= max_vtsize);
1181                                                         vtable [io + l] = cm;
1182                                                         break;
1183                                                 }
1184                                         }
1185                                 }
1186                                 g_free (the_cname);
1187                                 g_free (qname);
1188                                 g_free (fqname);
1189                         }
1190
1191                         
1192                         if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
1193                                 for (l = 0; l < ic->method.count; l++) {
1194                                         char *msig;
1195                                         MonoMethod *im = ic->methods [l];
1196                                         if (im->flags & METHOD_ATTRIBUTE_STATIC)
1197                                                         continue;
1198                                         g_assert (io + l <= max_vtsize);
1199
1200                                         /* 
1201                                          * If one of our parents already implements this interface
1202                                          * we can inherit the implementation.
1203                                          */
1204                                         if (!(vtable [io + l])) {
1205                                                 MonoClass *parent = class->parent;
1206
1207                                                 if ((ic->interface_id <= parent->max_interface_id) && 
1208                                                         (parent->interface_offsets [ic->interface_id]) &&
1209                                                         parent->vtable)
1210                                                         vtable [io + l] = parent->vtable [parent->interface_offsets [ic->interface_id] + l];
1211                                         }
1212
1213                                         if (!(vtable [io + l])) {
1214                                                 for (j = 0; j < onum; ++j) {
1215                                                         g_print (" at slot %d: %s (%d) overrides %s (%d)\n", io+l, overrides [j*2+1]->name, 
1216                                                                  overrides [j*2+1]->slot, overrides [j*2]->name, overrides [j*2]->slot);
1217                                                 }
1218                                                 msig = mono_signature_get_desc (mono_method_signature (im), FALSE);
1219                                                 printf ("no implementation for interface method %s.%s::%s(%s) in class %s.%s\n",
1220                                                         ic->name_space, ic->name, im->name, msig, class->name_space, class->name);
1221                                                 g_free (msig);
1222                                                 for (j = 0; j < class->method.count; ++j) {
1223                                                         MonoMethod *cm = class->methods [j];
1224                                                         msig = mono_signature_get_desc (mono_method_signature (cm), FALSE);
1225                                                         
1226                                                         printf ("METHOD %s(%s)\n", cm->name, msig);
1227                                                         g_free (msig);
1228                                                 }
1229                                                 g_assert_not_reached ();
1230                                         }
1231                                 }
1232                         }
1233                 
1234                         for (l = 0; l < ic->method.count; l++) {
1235                                 MonoMethod *im = vtable [io + l];
1236
1237                                 if (im) {
1238                                         g_assert (io + l <= max_vtsize);
1239                                         if (im->slot < 0) {
1240                                                 /* FIXME: why do we need this ? */
1241                                                 im->slot = io + l;
1242                                                 /* g_assert_not_reached (); */
1243                                         }
1244                                 }
1245                         }
1246                 }
1247                 if (ifaces)
1248                         g_ptr_array_free (ifaces, TRUE);
1249         } 
1250
1251         for (i = 0; i < class->method.count; ++i) {
1252                 MonoMethod *cm;
1253                
1254                 cm = class->methods [i];
1255                 
1256                 /*
1257                  * Non-virtual method have no place in the vtable.
1258                  * This also catches static methods (since they are not virtual).
1259                  */
1260                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
1261                         continue;
1262                 
1263                 /*
1264                  * If the method is REUSE_SLOT, we must check in the
1265                  * base class for a method to override.
1266                  */
1267                 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
1268                         int slot = -1;
1269                         for (k = class->parent; k ; k = k->parent) {
1270                                 int j;
1271                                 for (j = 0; j < k->method.count; ++j) {
1272                                         MonoMethod *m1 = k->methods [j];
1273                                         if (!(m1->flags & METHOD_ATTRIBUTE_VIRTUAL))
1274                                                 continue;
1275                                         if (!strcmp(cm->name, m1->name) && 
1276                                             mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (m1))) {
1277                                                 slot = k->methods [j]->slot;
1278                                                 g_assert (cm->slot < max_vtsize);
1279                                                 if (!override_map)
1280                                                         override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
1281                                                 g_hash_table_insert (override_map, m1, cm);
1282                                                 break;
1283                                         }
1284                                 }
1285                                 if (slot >= 0) 
1286                                         break;
1287                         }
1288                         if (slot >= 0)
1289                                 cm->slot = slot;
1290                 }
1291
1292                 if (cm->slot < 0)
1293                         cm->slot = cur_slot++;
1294
1295                 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT) && ! mono_method_signature (cm)->generic_param_count)
1296                         vtable [cm->slot] = cm;
1297         }
1298
1299         /* override non interface methods */
1300         for (i = 0; i < onum; i++) {
1301                 MonoMethod *decl = overrides [i*2];
1302                 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
1303                         g_assert (decl->slot != -1);
1304                         vtable [decl->slot] = overrides [i*2 + 1];
1305                         overrides [i * 2 + 1]->slot = decl->slot;
1306                         if (!override_map)
1307                                 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
1308                         g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
1309                 }
1310         }
1311
1312         /*
1313          * If a method occupies more than one place in the vtable, and it is
1314          * overriden, then change the other occurances too.
1315          */
1316         if (override_map) {
1317                 for (i = 0; i < max_vtsize; ++i)
1318                         if (vtable [i]) {
1319                                 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
1320                                 if (cm)
1321                                         vtable [i] = cm;
1322                         }
1323
1324                 g_hash_table_destroy (override_map);
1325         }
1326
1327         if (class->generic_class) {
1328                 MonoClass *gklass = class->generic_class->container_class;
1329
1330                 mono_class_init (gklass);
1331                 class->vtable_size = gklass->vtable_size;
1332         } else       
1333                 class->vtable_size = cur_slot;
1334
1335         class->vtable = g_malloc0 (sizeof (gpointer) * class->vtable_size);
1336         memcpy (class->vtable, vtable,  sizeof (gpointer) * class->vtable_size);
1337
1338         if (mono_print_vtable) {
1339                 int icount = 0;
1340
1341                 for (i = 0; i <= max_iid; i++)
1342                         if (class->interface_offsets [i] != -1)
1343                                 icount++;
1344
1345                 printf ("VTable %s.%s (size = %d, interfaces = %d)\n", class->name_space, 
1346                         class->name, class->vtable_size, icount); 
1347
1348                 for (i = 0; i < class->vtable_size; ++i) {
1349                         MonoMethod *cm;
1350                
1351                         cm = vtable [i];
1352                         if (cm) {
1353                                 printf ("  slot %03d(%03d) %s.%s:%s\n", i, cm->slot,
1354                                         cm->klass->name_space, cm->klass->name,
1355                                         cm->name);
1356                         }
1357                 }
1358
1359
1360                 if (icount) {
1361                         printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space, 
1362                                 class->name, max_iid);
1363         
1364                         for (i = 0; i < class->interface_count; i++) {
1365                                 ic = class->interfaces [i];
1366                                 printf ("  slot %03d(%03d) %s.%s\n",  
1367                                         class->interface_offsets [ic->interface_id],
1368                                         ic->method.count, ic->name_space, ic->name);
1369                         }
1370
1371                         for (k = class->parent; k ; k = k->parent) {
1372                                 for (i = 0; i < k->interface_count; i++) {
1373                                         ic = k->interfaces [i]; 
1374                                         printf ("  slot %03d(%03d) %s.%s\n", 
1375                                                 class->interface_offsets [ic->interface_id],
1376                                                 ic->method.count, ic->name_space, ic->name);
1377                                 }
1378                         }
1379                 }
1380         }
1381 }
1382
1383 /**
1384  * mono_class_init:
1385  * @class: the class to initialize
1386  *
1387  * compute the instance_size, class_size and other infos that cannot be 
1388  * computed at mono_class_get() time. Also compute a generic vtable and 
1389  * the method slot numbers. We use this infos later to create a domain
1390  * specific vtable.  
1391  */
1392 void
1393 mono_class_init (MonoClass *class)
1394 {
1395         int i;
1396         static MonoMethod *default_ghc = NULL;
1397         static MonoMethod *default_finalize = NULL;
1398         static int finalize_slot = -1;
1399         static int ghc_slot = -1;
1400         MonoMethod **overrides;
1401         int onum = 0;
1402
1403         g_assert (class);
1404
1405         if (class->inited)
1406                 return;
1407
1408         /*g_print ("Init class %s\n", class->name);*/
1409
1410         /* We do everything inside the lock to prevent races */
1411         mono_loader_lock ();
1412
1413         if (class->inited) {
1414                 mono_loader_unlock ();
1415                 /* Somebody might have gotten in before us */
1416                 return;
1417         }
1418
1419         if (class->init_pending) {
1420                 /* this indicates a cyclic dependency */
1421                 g_error ("pending init %s.%s\n", class->name_space, class->name);
1422         }
1423
1424         class->init_pending = 1;
1425
1426         if (mono_debugger_start_class_init_func)
1427                 mono_debugger_start_class_init_func (class);
1428
1429         mono_stats.initialized_class_count++;
1430
1431         if (class->generic_class && !class->generic_class->is_dynamic) {
1432                 MonoGenericClass *gclass = class->generic_class;
1433                 MonoClass *gklass = gclass->container_class;
1434
1435                 mono_stats.generic_class_count++;
1436
1437                 class->method = gklass->method;
1438                 class->field = gklass->field;
1439
1440                 mono_class_create_generic_2 (gclass);
1441
1442                 mono_class_init (gklass);
1443
1444                 if (MONO_CLASS_IS_INTERFACE (class))
1445                         class->interface_id = mono_get_unique_iid (class);
1446
1447                 g_assert (class->method.count == gklass->method.count);
1448                 class->methods = g_new0 (MonoMethod *, class->method.count);
1449
1450                 for (i = 0; i < class->method.count; i++) {
1451                         MonoMethod *inflated = mono_class_inflate_generic_method (
1452                                 gklass->methods [i], gclass->context, gclass->klass);
1453
1454                         class->methods [i] = mono_get_inflated_method (inflated);
1455                 }
1456
1457                 g_assert (class->field.count == gklass->field.count);
1458                 class->fields = g_new0 (MonoClassField, class->field.count);
1459
1460                 for (i = 0; i < class->field.count; i++) {
1461                         MonoInflatedField *ifield = g_new0 (MonoInflatedField, 1);
1462                         ifield->generic_type = gklass->fields [i].type;
1463
1464                         class->fields [i] = gklass->fields [i];
1465                         class->fields [i].generic_info = ifield;
1466                         class->fields [i].parent = class;
1467                         class->fields [i].type = mono_class_inflate_generic_type (
1468                                 class->fields [i].type, gclass->context);
1469                 }
1470
1471                 class->property = gklass->property;
1472                 class->properties = g_new0 (MonoProperty, class->property.count);
1473
1474                 for (i = 0; i < class->property.count; i++) {
1475                         MonoProperty *prop = &class->properties [i];
1476
1477                         *prop = gklass->properties [i];
1478
1479                         if (prop->get)
1480                                 prop->get = mono_class_inflate_generic_method (
1481                                         prop->get, gclass->context, gclass->klass);
1482                         if (prop->set)
1483                                 prop->set = mono_class_inflate_generic_method (
1484                                         prop->set, gclass->context, gclass->klass);
1485
1486                         prop->parent = class;
1487                 }
1488
1489                 g_assert (class->interface_count == gklass->interface_count);
1490         }
1491
1492         if (class->parent && !class->parent->inited)
1493                 mono_class_init (class->parent);
1494
1495         /*
1496          * Computes the size used by the fields, and their locations
1497          */
1498         if (!class->size_inited)
1499                 class_compute_field_layout (class);
1500
1501         /* initialize method pointers */
1502         if (class->rank) {
1503                 MonoMethod *ctor;
1504                 MonoMethodSignature *sig;
1505                 class->method.count = class->rank > 1? 2: 1;
1506                 sig = mono_metadata_signature_alloc (class->image, class->rank);
1507                 sig->ret = &mono_defaults.void_class->byval_arg;
1508                 sig->pinvoke = TRUE;
1509                 for (i = 0; i < class->rank; ++i)
1510                         sig->params [i] = &mono_defaults.int32_class->byval_arg;
1511
1512                 ctor = (MonoMethod *) g_new0 (MonoMethodPInvoke, 1);
1513                 ctor->klass = class;
1514                 ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1515                 ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1516                 ctor->signature = sig;
1517                 ctor->name = ".ctor";
1518                 ctor->slot = -1;
1519                 class->methods = g_new (MonoMethod*, class->method.count);
1520                 class->methods [0] = ctor;
1521                 if (class->rank > 1) {
1522                         sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1523                         sig->ret = &mono_defaults.void_class->byval_arg;
1524                         sig->pinvoke = TRUE;
1525                         for (i = 0; i < class->rank * 2; ++i)
1526                                 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1527
1528                         ctor = (MonoMethod *) g_new0 (MonoMethodPInvoke, 1);
1529                         ctor->klass = class;
1530                         ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1531                         ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1532                         ctor->signature = sig;
1533                         ctor->name = ".ctor";
1534                         ctor->slot = -1;
1535                         class->methods [1] = ctor;
1536                 }
1537         } else {
1538                 if (!class->generic_class && !class->methods) {
1539                         class->methods = g_new (MonoMethod*, class->method.count);
1540                         for (i = 0; i < class->method.count; ++i) {
1541                                 class->methods [i] = mono_get_method (class->image,
1542                                                                       MONO_TOKEN_METHOD_DEF | (i + class->method.first + 1), class);
1543                         }
1544                 }
1545         }
1546
1547         if (!class->generic_class) {
1548                 init_properties (class);
1549                 init_events (class);
1550
1551                 i = mono_metadata_nesting_typedef (class->image, class->type_token, 1);
1552                 while (i) {
1553                         MonoClass* nclass;
1554                         guint32 cols [MONO_NESTED_CLASS_SIZE];
1555                         mono_metadata_decode_row (&class->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
1556                         nclass = mono_class_create_from_typedef (class->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
1557                         class->nested_classes = g_list_prepend (class->nested_classes, nclass);
1558
1559                         i = mono_metadata_nesting_typedef (class->image, class->type_token, i + 1);
1560                 }
1561         }
1562
1563         mono_class_setup_supertypes (class);
1564
1565         if (MONO_CLASS_IS_INTERFACE (class)) {
1566                 for (i = 0; i < class->method.count; ++i)
1567                         class->methods [i]->slot = i;
1568                 class->init_pending = 0;
1569                 class->inited = 1;
1570                 /* 
1571                  * class->interface_offsets is needed for the castclass/isinst code, so
1572                  * we have to setup them for interfaces, too.
1573                  */
1574                 setup_interface_offsets (class, 0);
1575                 mono_loader_unlock ();
1576
1577                 if (mono_debugger_class_init_func)
1578                         mono_debugger_class_init_func (class);
1579
1580                 return;
1581         }
1582
1583         overrides = mono_class_get_overrides (class->image, class->type_token, &onum);  
1584         mono_class_setup_vtable (class, overrides, onum);
1585         g_free (overrides);
1586
1587         class->inited = 1;
1588         class->init_pending = 0;
1589
1590         if (!default_ghc) {
1591                 if (class == mono_defaults.object_class) { 
1592                        
1593                         for (i = 0; i < class->vtable_size; ++i) {
1594                                 MonoMethod *cm = class->vtable [i];
1595                
1596                                 if (!strcmp (cm->name, "GetHashCode")) {
1597                                         ghc_slot = i;
1598                                         break;
1599                                 }
1600                         }
1601
1602                         g_assert (ghc_slot > 0);
1603
1604                         default_ghc = class->vtable [ghc_slot];
1605                 }
1606         }
1607         
1608         class->ghcimpl = 1;
1609         if (class->parent) { 
1610
1611                 if (class->vtable [ghc_slot] == default_ghc) {
1612                         class->ghcimpl = 0;
1613                 }
1614         }
1615
1616         if (!default_finalize) {
1617                 if (class == mono_defaults.object_class) { 
1618                        
1619                         for (i = 0; i < class->vtable_size; ++i) {
1620                                 MonoMethod *cm = class->vtable [i];
1621                
1622                                 if (!strcmp (cm->name, "Finalize")) {
1623                                         finalize_slot = i;
1624                                         break;
1625                                 }
1626                         }
1627
1628                         g_assert (finalize_slot > 0);
1629
1630                         default_finalize = class->vtable [finalize_slot];
1631                 }
1632         }
1633
1634         /* Object::Finalize should have empty implemenatation */
1635         class->has_finalize = 0;
1636         if (class->parent) { 
1637                 if (class->vtable [finalize_slot] != default_finalize)
1638                         class->has_finalize = 1;
1639         }
1640
1641         mono_loader_unlock ();
1642
1643         if (mono_debugger_class_init_func)
1644                 mono_debugger_class_init_func (class);
1645 }
1646
1647 void
1648 mono_class_setup_mono_type (MonoClass *class)
1649 {
1650         const char *name = class->name;
1651         const char *nspace = class->name_space;
1652
1653         if (MONO_CLASS_IS_INTERFACE (class))
1654                 class->interface_id = mono_get_unique_iid (class);
1655
1656         class->this_arg.byref = 1;
1657         class->this_arg.data.klass = class;
1658         class->this_arg.type = MONO_TYPE_CLASS;
1659         class->byval_arg.data.klass = class;
1660         class->byval_arg.type = MONO_TYPE_CLASS;
1661
1662         if (!strcmp (nspace, "System")) {
1663                 if (!strcmp (name, "ValueType")) {
1664                         /*
1665                          * do not set the valuetype bit for System.ValueType.
1666                          * class->valuetype = 1;
1667                          */
1668                         class->blittable = TRUE;
1669                 } else if (!strcmp (name, "Enum")) {
1670                         /*
1671                          * do not set the valuetype bit for System.Enum.
1672                          * class->valuetype = 1;
1673                          */
1674                         class->valuetype = 0;
1675                         class->enumtype = 0;
1676                 } else if (!strcmp (name, "Object")) {
1677                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
1678                 } else if (!strcmp (name, "String")) {
1679                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
1680                 } else if (!strcmp (name, "TypedReference")) {
1681                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
1682                 }
1683         }
1684         
1685         if (class->valuetype) {
1686                 int t = MONO_TYPE_VALUETYPE;
1687                 if (!strcmp (nspace, "System")) {
1688                         switch (*name) {
1689                         case 'B':
1690                                 if (!strcmp (name, "Boolean")) {
1691                                         t = MONO_TYPE_BOOLEAN;
1692                                 } else if (!strcmp(name, "Byte")) {
1693                                         t = MONO_TYPE_U1;
1694                                         class->blittable = TRUE;                                                
1695                                 }
1696                                 break;
1697                         case 'C':
1698                                 if (!strcmp (name, "Char")) {
1699                                         t = MONO_TYPE_CHAR;
1700                                 }
1701                                 break;
1702                         case 'D':
1703                                 if (!strcmp (name, "Double")) {
1704                                         t = MONO_TYPE_R8;
1705                                         class->blittable = TRUE;                                                
1706                                 }
1707                                 break;
1708                         case 'I':
1709                                 if (!strcmp (name, "Int32")) {
1710                                         t = MONO_TYPE_I4;
1711                                         class->blittable = TRUE;
1712                                 } else if (!strcmp(name, "Int16")) {
1713                                         t = MONO_TYPE_I2;
1714                                         class->blittable = TRUE;
1715                                 } else if (!strcmp(name, "Int64")) {
1716                                         t = MONO_TYPE_I8;
1717                                         class->blittable = TRUE;
1718                                 } else if (!strcmp(name, "IntPtr")) {
1719                                         t = MONO_TYPE_I;
1720                                         class->blittable = TRUE;
1721                                 }
1722                                 break;
1723                         case 'S':
1724                                 if (!strcmp (name, "Single")) {
1725                                         t = MONO_TYPE_R4;
1726                                         class->blittable = TRUE;                                                
1727                                 } else if (!strcmp(name, "SByte")) {
1728                                         t = MONO_TYPE_I1;
1729                                         class->blittable = TRUE;
1730                                 }
1731                                 break;
1732                         case 'U':
1733                                 if (!strcmp (name, "UInt32")) {
1734                                         t = MONO_TYPE_U4;
1735                                         class->blittable = TRUE;
1736                                 } else if (!strcmp(name, "UInt16")) {
1737                                         t = MONO_TYPE_U2;
1738                                         class->blittable = TRUE;
1739                                 } else if (!strcmp(name, "UInt64")) {
1740                                         t = MONO_TYPE_U8;
1741                                         class->blittable = TRUE;
1742                                 } else if (!strcmp(name, "UIntPtr")) {
1743                                         t = MONO_TYPE_U;
1744                                         class->blittable = TRUE;
1745                                 }
1746                                 break;
1747                         case 'T':
1748                                 if (!strcmp (name, "TypedReference")) {
1749                                         t = MONO_TYPE_TYPEDBYREF;
1750                                         class->blittable = TRUE;
1751                                 }
1752                                 break;
1753                         case 'V':
1754                                 if (!strcmp (name, "Void")) {
1755                                         t = MONO_TYPE_VOID;
1756                                 }
1757                                 break;
1758                         default:
1759                                 break;
1760                         }
1761                 }
1762                 class->this_arg.type = class->byval_arg.type = t;
1763         }
1764 }
1765
1766 void
1767 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
1768 {
1769         gboolean system_namespace;
1770
1771         system_namespace = !strcmp (class->name_space, "System");
1772
1773         /* if root of the hierarchy */
1774         if (system_namespace && !strcmp (class->name, "Object")) {
1775                 class->parent = NULL;
1776                 class->instance_size = sizeof (MonoObject);
1777                 return;
1778         }
1779         if (!strcmp (class->name, "<Module>")) {
1780                 class->parent = NULL;
1781                 class->instance_size = 0;
1782                 return;
1783         }
1784
1785         if (parent && parent->generic_class)
1786                 mono_class_create_generic_2 (parent->generic_class);
1787
1788         if (!MONO_CLASS_IS_INTERFACE (class)) {
1789                 class->parent = parent;
1790
1791                 if (!parent)
1792                         g_assert_not_reached (); /* FIXME */
1793
1794                 if (parent->generic_class && !parent->name) {
1795                         /*
1796                          * If the parent is a generic instance, we may get
1797                          * called before it is fully initialized, especially
1798                          * before it has its name.
1799                          */
1800                         return;
1801                 }
1802
1803                 class->marshalbyref = parent->marshalbyref;
1804                 class->contextbound  = parent->contextbound;
1805                 class->delegate  = parent->delegate;
1806                 
1807                 if (system_namespace) {
1808                         if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
1809                                 class->marshalbyref = 1;
1810
1811                         if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject")) 
1812                                 class->contextbound  = 1;
1813
1814                         if (*class->name == 'D' && !strcmp (class->name, "Delegate")) 
1815                                 class->delegate  = 1;
1816                 }
1817
1818                 if (class->parent->enumtype || ((strcmp (class->parent->name, "ValueType") == 0) && 
1819                                                 (strcmp (class->parent->name_space, "System") == 0)))
1820                         class->valuetype = 1;
1821                 if (((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
1822                         class->valuetype = class->enumtype = 1;
1823                 }
1824                 /*class->enumtype = class->parent->enumtype; */
1825                 mono_class_setup_supertypes (class);
1826         } else {
1827                 class->parent = NULL;
1828         }
1829
1830 }
1831
1832 void
1833 mono_class_setup_supertypes (MonoClass *class)
1834 {
1835         MonoClass *k;
1836         int ms, i;
1837
1838         if (class->supertypes)
1839                 return;
1840
1841         class->idepth = 0;
1842         for (k = class; k ; k = k->parent) {
1843                 class->idepth++;
1844         }
1845
1846         ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
1847         class->supertypes = g_new0 (MonoClass *, ms);
1848
1849         if (class->parent) {
1850                 for (i = class->idepth, k = class; k ; k = k->parent)
1851                         class->supertypes [--i] = k;
1852         } else {
1853                 class->supertypes [0] = class;
1854         }
1855 }       
1856
1857 /*
1858  * If we inherit a type parameter from an outer class, set its owner to that class.
1859  */
1860 static int
1861 set_generic_param_owner (MonoGenericContainer *container, MonoClass *klass, int pos)
1862 {
1863         MonoGenericContainer *gc;
1864         int i;
1865
1866         if (klass->nested_in)
1867                 pos = set_generic_param_owner (container, klass->nested_in, pos);
1868
1869         if (!klass->generic_container)
1870                 return pos;
1871
1872         gc = klass->generic_container;
1873         for (i = pos; i < gc->type_argc; i++)
1874                 container->type_params [i].owner = gc;
1875
1876         return pos + gc->type_argc;
1877 }
1878
1879 static MonoGenericInst *
1880 get_shared_inst (MonoGenericContainer *container)
1881 {
1882         MonoGenericInst *nginst;
1883         int i;
1884
1885         nginst = g_new0 (MonoGenericInst, 1);
1886         nginst->type_argc = container->type_argc;
1887         nginst->type_argv = g_new0 (MonoType *, nginst->type_argc);
1888         nginst->is_reference = 1;
1889         nginst->is_open = 1;
1890
1891         for (i = 0; i < nginst->type_argc; i++) {
1892                 MonoType *t = g_new0 (MonoType, 1);
1893
1894                 t->type = container->is_method ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
1895                 t->data.generic_param = &container->type_params [i];
1896
1897                 nginst->type_argv [i] = t;
1898         }
1899
1900         return mono_metadata_lookup_generic_inst (nginst);
1901 }
1902
1903 MonoGenericClass *
1904 mono_get_shared_generic_class (MonoGenericContainer *container, gboolean is_dynamic)
1905 {
1906         MonoGenericClass *gclass;
1907
1908         if (is_dynamic) {
1909                 MonoDynamicGenericClass *dgclass = g_new0 (MonoDynamicGenericClass, 1);
1910                 gclass = &dgclass->generic_class;
1911                 gclass->is_dynamic = 1;
1912         } else
1913                 gclass = g_new0 (MonoGenericClass, 1);
1914
1915         gclass->context = &container->context;
1916         gclass->container_class = container->klass;
1917         gclass->inst = get_shared_inst (container);
1918
1919         if (!is_dynamic) {
1920                 MonoGenericClass *cached = mono_metadata_lookup_generic_class (gclass);
1921
1922                 if (cached) {
1923                         g_free (gclass);
1924                         return cached;
1925                 }
1926         }
1927
1928         gclass->klass = container->klass;
1929
1930         return gclass;
1931 }
1932
1933 /**
1934  * @image: context where the image is created
1935  * @type_token:  typedef token
1936  */
1937 static MonoClass *
1938 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
1939 {
1940         MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
1941         MonoClass *class, *parent = NULL;
1942         guint32 cols [MONO_TYPEDEF_SIZE];
1943         guint32 cols_next [MONO_TYPEDEF_SIZE];
1944         guint tidx = mono_metadata_token_index (type_token);
1945         MonoGenericContext *context = NULL;
1946         const char *name, *nspace;
1947         guint icount = 0; 
1948         MonoClass **interfaces;
1949
1950         mono_loader_lock ();
1951
1952         if ((class = g_hash_table_lookup (image->class_cache, GUINT_TO_POINTER (type_token)))) {
1953                 mono_loader_unlock ();
1954                 return class;
1955         }
1956
1957         g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
1958
1959         mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
1960         
1961         name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1962         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1963
1964         class = g_malloc0 (sizeof (MonoClass));
1965
1966         class->name = name;
1967         class->name_space = nspace;
1968
1969         class->image = image;
1970         class->type_token = type_token;
1971         class->flags = cols [MONO_TYPEDEF_FLAGS];
1972
1973         g_hash_table_insert (image->class_cache, GUINT_TO_POINTER (type_token), class);
1974
1975         class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
1976         if (class->generic_container) {
1977                 class->generic_container->klass = class;
1978                 context = &class->generic_container->context;
1979
1980                 context->gclass = mono_get_shared_generic_class (context->container, FALSE);
1981         }
1982
1983         if (cols [MONO_TYPEDEF_EXTENDS])
1984                 parent = mono_class_get_full (
1985                         image, mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]), context);
1986
1987         mono_class_setup_parent (class, parent);
1988
1989         mono_class_setup_mono_type (class);
1990
1991         interfaces = mono_metadata_interfaces_from_typedef_full (image, type_token, &icount, context);
1992
1993         class->interfaces = interfaces;
1994         class->interface_count = icount;
1995
1996         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
1997                 class->unicode = 1;
1998         /* fixme: maybe we must set this on windows 
1999         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
2000                 class->unicode = 1;
2001         */
2002
2003         class->cast_class = class->element_class = class;
2004
2005         /*g_print ("Load class %s\n", name);*/
2006
2007         /*
2008          * Compute the field and method lists
2009          */
2010         class->field.first  = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
2011         class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
2012
2013         if (tt->rows > tidx){           
2014                 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
2015                 class->field.last  = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
2016                 class->method.last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
2017         } else {
2018                 class->field.last  = image->tables [MONO_TABLE_FIELD].rows;
2019                 class->method.last = image->tables [MONO_TABLE_METHOD].rows;
2020         }
2021
2022         if (cols [MONO_TYPEDEF_FIELD_LIST] && 
2023             cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
2024                 class->field.count = class->field.last - class->field.first;
2025         else
2026                 class->field.count = 0;
2027
2028         if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
2029                 class->method.count = class->method.last - class->method.first;
2030         else
2031                 class->method.count = 0;
2032
2033         /* reserve space to store vector pointer in arrays */
2034         if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
2035                 class->instance_size += 2 * sizeof (gpointer);
2036                 g_assert (class->field.count == 0);
2037         }
2038
2039         if (class->enumtype)
2040                 class_compute_field_layout (class);
2041
2042         if ((type_token = mono_metadata_nested_in_typedef (image, type_token)))
2043                 class->nested_in = mono_class_create_from_typedef (image, type_token);
2044
2045         if (class->nested_in && class->generic_container)
2046                 set_generic_param_owner (class->generic_container, class->nested_in, 0);
2047
2048         mono_loader_unlock ();
2049
2050         return class;
2051 }
2052
2053 void
2054 mono_class_create_generic (MonoGenericClass *gclass)
2055 {
2056         MonoClass *klass, *gklass;
2057
2058         if (!gclass->klass)
2059                 gclass->klass = g_malloc0 (sizeof (MonoClass));
2060         klass = gclass->klass;
2061
2062         gklass = gclass->container_class;
2063
2064         klass->nested_in = gklass->nested_in;
2065
2066         klass->name = gklass->name;
2067         klass->name_space = gklass->name_space;
2068         klass->image = gklass->image;
2069         klass->flags = gklass->flags;
2070
2071         klass->generic_class = gclass;
2072
2073         klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
2074         klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
2075         klass->this_arg.byref = TRUE;
2076
2077         klass->cast_class = klass->element_class = klass;
2078
2079         if (gclass->is_dynamic) {
2080                 klass->instance_size = gklass->instance_size;
2081                 klass->class_size = gklass->class_size;
2082                 klass->size_inited = 1;
2083                 klass->inited = 1;
2084
2085                 klass->valuetype = gklass->valuetype;
2086
2087                 mono_class_setup_supertypes (klass);
2088         }
2089 }
2090
2091 static void
2092 mono_class_create_generic_2 (MonoGenericClass *gclass)
2093 {
2094         MonoClass *klass, *gklass;
2095         GList *list;
2096         int i;
2097
2098         klass = gclass->klass;
2099         gklass = gclass->container_class;
2100
2101         klass->interface_count = gklass->interface_count;
2102         klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
2103         for (i = 0; i < klass->interface_count; i++) {
2104                 MonoType *it = &gklass->interfaces [i]->byval_arg;
2105                 MonoType *inflated = mono_class_inflate_generic_type (it, gclass->context);
2106                 klass->interfaces [i] = mono_class_from_mono_type (inflated);
2107         }
2108
2109         for (list = gklass->nested_classes; list; list = list->next)
2110                 klass->nested_classes = g_list_append (
2111                         klass->nested_classes, list->data);
2112
2113         if (gclass->parent)
2114                 klass->parent = mono_class_from_mono_type (gclass->parent);
2115         else if (gklass->parent) {
2116                 MonoType *inflated = mono_class_inflate_generic_type (&gklass->parent->byval_arg, gclass->context);
2117
2118                 klass->parent = mono_class_from_mono_type (inflated);
2119         }
2120
2121         if (klass->parent)
2122                 mono_class_setup_parent (klass, klass->parent);
2123 }
2124
2125 MonoClass *
2126 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
2127 {
2128         MonoClass *klass, **ptr;
2129         int count, pos, i;
2130
2131         if (param->pklass)
2132                 return param->pklass;
2133
2134         klass = param->pklass = g_new0 (MonoClass, 1);
2135
2136         for (count = 0, ptr = param->constraints; ptr && *ptr; ptr++, count++)
2137                 ;
2138
2139         pos = 0;
2140         if ((count > 0) && !MONO_CLASS_IS_INTERFACE (param->constraints [0])) {
2141                 klass->parent = param->constraints [0];
2142                 pos++;
2143         }
2144
2145         if (count - pos > 0) {
2146                 klass->interface_count = count - pos;
2147                 klass->interfaces = g_new0 (MonoClass *, count - pos);
2148                 for (i = pos; i < count; i++)
2149                         klass->interfaces [i - pos] = param->constraints [i];
2150         }
2151
2152         g_assert (param->name && param->owner);
2153
2154         klass->name = param->name;
2155         klass->name_space = "";
2156         klass->image = image;
2157         klass->cast_class = klass->element_class = klass;
2158         klass->enum_basetype = &klass->element_class->byval_arg;
2159         klass->flags = TYPE_ATTRIBUTE_PUBLIC;
2160
2161         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
2162         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
2163         klass->this_arg.byref = TRUE;
2164
2165         mono_class_init (klass);
2166
2167         return klass;
2168 }
2169
2170 static MonoClass *
2171 my_mono_class_from_generic_parameter (MonoGenericParam *param, gboolean is_mvar)
2172 {
2173         MonoClass *klass;
2174
2175         if (param->pklass)
2176                 return param->pklass;
2177
2178         g_assert (param->owner);
2179
2180         klass = g_new0 (MonoClass, 1);
2181
2182         if (param->name)
2183                 klass->name = param->name;
2184         else
2185                 klass->name = g_strdup_printf (is_mvar ? "!!%d" : "!%d", param->num);
2186         klass->name_space = "";
2187         klass->image = mono_defaults.corlib;
2188         klass->cast_class = klass->element_class = klass;
2189         klass->enum_basetype = &klass->element_class->byval_arg;
2190         klass->flags = TYPE_ATTRIBUTE_PUBLIC;
2191
2192         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
2193         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
2194         klass->this_arg.byref = TRUE;
2195
2196         mono_class_init (klass);
2197
2198         return klass;
2199 }
2200
2201 MonoClass *
2202 mono_ptr_class_get (MonoType *type)
2203 {
2204         MonoClass *result;
2205         MonoClass *el_class;
2206         static GHashTable *ptr_hash = NULL;
2207
2208         mono_loader_lock ();
2209
2210         if (!ptr_hash)
2211                 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
2212         el_class = mono_class_from_mono_type (type);
2213         if ((result = g_hash_table_lookup (ptr_hash, el_class))) {
2214                 mono_loader_unlock ();
2215                 return result;
2216         }
2217         result = g_new0 (MonoClass, 1);
2218
2219         result->parent = NULL; /* no parent for PTR types */
2220         result->name_space = el_class->name_space;
2221         result->name = g_strdup_printf ("%s*", el_class->name);
2222         result->image = el_class->image;
2223         result->inited = TRUE;
2224         result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
2225         /* Can pointers get boxed? */
2226         result->instance_size = sizeof (gpointer);
2227         result->cast_class = result->element_class = el_class;
2228         result->enum_basetype = &result->element_class->byval_arg;
2229         result->blittable = TRUE;
2230
2231         result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
2232         result->this_arg.data.type = result->byval_arg.data.type = result->enum_basetype;
2233         result->this_arg.byref = TRUE;
2234
2235         mono_class_setup_supertypes (result);
2236
2237         g_hash_table_insert (ptr_hash, el_class, result);
2238
2239         mono_loader_unlock ();
2240
2241         return result;
2242 }
2243
2244 static MonoClass *
2245 mono_fnptr_class_get (MonoMethodSignature *sig)
2246 {
2247         MonoClass *result;
2248         static GHashTable *ptr_hash = NULL;
2249
2250         mono_loader_lock ();
2251
2252         if (!ptr_hash)
2253                 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
2254         
2255         if ((result = g_hash_table_lookup (ptr_hash, sig))) {
2256                 mono_loader_unlock ();
2257                 return result;
2258         }
2259         result = g_new0 (MonoClass, 1);
2260
2261         result->parent = NULL; /* no parent for PTR types */
2262         result->name = "System";
2263         result->name_space = "MonoFNPtrFakeClass";
2264         result->image = NULL; /* need to fix... */
2265         result->inited = TRUE;
2266         result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
2267         /* Can pointers get boxed? */
2268         result->instance_size = sizeof (gpointer);
2269         result->cast_class = result->element_class = result;
2270         result->blittable = TRUE;
2271
2272         result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
2273         result->this_arg.data.method = result->byval_arg.data.method = sig;
2274         result->this_arg.byref = TRUE;
2275         result->enum_basetype = &result->element_class->byval_arg;
2276         result->blittable = TRUE;
2277
2278         mono_class_setup_supertypes (result);
2279
2280         g_hash_table_insert (ptr_hash, sig, result);
2281
2282         mono_loader_unlock ();
2283
2284         return result;
2285 }
2286
2287 MonoClass *
2288 mono_class_from_mono_type (MonoType *type)
2289 {
2290         switch (type->type) {
2291         case MONO_TYPE_OBJECT:
2292                 return type->data.klass? type->data.klass: mono_defaults.object_class;
2293         case MONO_TYPE_VOID:
2294                 return type->data.klass? type->data.klass: mono_defaults.void_class;
2295         case MONO_TYPE_BOOLEAN:
2296                 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
2297         case MONO_TYPE_CHAR:
2298                 return type->data.klass? type->data.klass: mono_defaults.char_class;
2299         case MONO_TYPE_I1:
2300                 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
2301         case MONO_TYPE_U1:
2302                 return type->data.klass? type->data.klass: mono_defaults.byte_class;
2303         case MONO_TYPE_I2:
2304                 return type->data.klass? type->data.klass: mono_defaults.int16_class;
2305         case MONO_TYPE_U2:
2306                 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
2307         case MONO_TYPE_I4:
2308                 return type->data.klass? type->data.klass: mono_defaults.int32_class;
2309         case MONO_TYPE_U4:
2310                 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
2311         case MONO_TYPE_I:
2312                 return type->data.klass? type->data.klass: mono_defaults.int_class;
2313         case MONO_TYPE_U:
2314                 return type->data.klass? type->data.klass: mono_defaults.uint_class;
2315         case MONO_TYPE_I8:
2316                 return type->data.klass? type->data.klass: mono_defaults.int64_class;
2317         case MONO_TYPE_U8:
2318                 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
2319         case MONO_TYPE_R4:
2320                 return type->data.klass? type->data.klass: mono_defaults.single_class;
2321         case MONO_TYPE_R8:
2322                 return type->data.klass? type->data.klass: mono_defaults.double_class;
2323         case MONO_TYPE_STRING:
2324                 return type->data.klass? type->data.klass: mono_defaults.string_class;
2325         case MONO_TYPE_TYPEDBYREF:
2326                 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
2327         case MONO_TYPE_ARRAY:
2328                 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
2329         case MONO_TYPE_PTR:
2330                 return mono_ptr_class_get (type->data.type);
2331         case MONO_TYPE_FNPTR:
2332                 return mono_fnptr_class_get (type->data.method);
2333         case MONO_TYPE_SZARRAY:
2334                 return mono_array_class_get (type->data.klass, 1);
2335         case MONO_TYPE_CLASS:
2336         case MONO_TYPE_VALUETYPE:
2337                 return type->data.klass;
2338         case MONO_TYPE_GENERICINST:
2339                 g_assert (type->data.generic_class->klass);
2340                 return type->data.generic_class->klass;
2341         case MONO_TYPE_VAR:
2342                 return my_mono_class_from_generic_parameter (type->data.generic_param, FALSE);
2343         case MONO_TYPE_MVAR:
2344                 return my_mono_class_from_generic_parameter (type->data.generic_param, TRUE);
2345         default:
2346                 g_warning ("implement me 0x%02x\n", type->type);
2347                 g_assert_not_reached ();
2348         }
2349         
2350         return NULL;
2351 }
2352
2353 /**
2354  * @image: context where the image is created
2355  * @type_spec:  typespec token
2356  */
2357 static MonoClass *
2358 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec,
2359                                  MonoGenericContext *context)
2360 {
2361         MonoType *type, *inflated;
2362         MonoClass *class;
2363
2364         type = mono_type_create_from_typespec_full (image, context, type_spec);
2365
2366         switch (type->type) {
2367         case MONO_TYPE_ARRAY:
2368                 class = mono_array_class_get (type->data.array->eklass, type->data.array->rank);
2369                 break;
2370         case MONO_TYPE_SZARRAY:
2371                 class = mono_array_class_get (type->data.klass, 1);
2372                 break;
2373         case MONO_TYPE_PTR:
2374                 class = mono_ptr_class_get (type->data.type);
2375                 break;
2376         case MONO_TYPE_GENERICINST:
2377                 g_assert (type->data.generic_class->klass);
2378                 class = type->data.generic_class->klass;
2379                 break;
2380         default:
2381                 /* it seems any type can be stored in TypeSpec as well */
2382                 class = mono_class_from_mono_type (type);
2383                 break;
2384         }
2385
2386         if (!class || !context || (!context->gclass && !context->gmethod))
2387                 return class;
2388
2389         inflated = mono_class_inflate_generic_type (&class->byval_arg, context);
2390
2391         return mono_class_from_mono_type (inflated);
2392 }
2393
2394 /**
2395  * mono_bounded_array_class_get:
2396  * @element_class: element class 
2397  * @rank: the dimension of the array class
2398  * @bounded: whenever the array has non-zero bounds
2399  *
2400  * Returns: a class object describing the array with element type @element_type and 
2401  * dimension @rank. 
2402  */
2403 MonoClass *
2404 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
2405 {
2406         MonoImage *image;
2407         MonoClass *class;
2408         MonoClass *parent = NULL;
2409         GSList *list, *rootlist;
2410         int nsize;
2411         char *name;
2412         gboolean corlib_type = FALSE;
2413
2414         g_assert (rank <= 255);
2415
2416         if (rank > 1)
2417                 /* bounded only matters for one-dimensional arrays */
2418                 bounded = FALSE;
2419
2420         image = eclass->image;
2421
2422         mono_loader_lock ();
2423
2424         if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
2425                 for (; list; list = list->next) {
2426                         class = list->data;
2427                         if ((class->rank == rank) && (class->byval_arg.type == (bounded ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
2428                                 mono_loader_unlock ();
2429                                 return class;
2430                         }
2431                 }
2432         }
2433
2434         /* for the building corlib use System.Array from it */
2435         if (image->assembly && image->assembly->dynamic && strcmp (image->assembly_name, "mscorlib") == 0) {
2436                 parent = mono_class_from_name (image, "System", "Array");
2437                 corlib_type = TRUE;
2438         } else {
2439                 parent = mono_defaults.array_class;
2440                 if (!parent->inited)
2441                         mono_class_init (parent);
2442         }
2443
2444         class = g_malloc0 (sizeof (MonoClass));
2445
2446         class->image = image;
2447         class->name_space = eclass->name_space;
2448         nsize = strlen (eclass->name);
2449         name = g_malloc (nsize + 2 + rank);
2450         memcpy (name, eclass->name, nsize);
2451         name [nsize] = '[';
2452         if (rank > 1)
2453                 memset (name + nsize + 1, ',', rank - 1);
2454         name [nsize + rank] = ']';
2455         name [nsize + rank + 1] = 0;
2456         class->name = name;
2457         class->type_token = 0;
2458         /* all arrays are marked serializable and sealed, bug #42779 */
2459         class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
2460                 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
2461         class->parent = parent;
2462         class->instance_size = mono_class_instance_size (class->parent);
2463         class->class_size = 0;
2464         mono_class_setup_supertypes (class);
2465
2466         class->rank = rank;
2467         
2468         if (eclass->enumtype)
2469                 class->cast_class = eclass->element_class;
2470         else
2471                 class->cast_class = eclass;
2472
2473         class->element_class = eclass;
2474
2475         if ((rank > 1) || bounded) {
2476                 MonoArrayType *at = g_new0 (MonoArrayType, 1);
2477                 class->byval_arg.type = MONO_TYPE_ARRAY;
2478                 class->byval_arg.data.array = at;
2479                 at->eklass = eclass;
2480                 at->rank = rank;
2481                 /* FIXME: complete.... */
2482         } else {
2483                 class->byval_arg.type = MONO_TYPE_SZARRAY;
2484                 class->byval_arg.data.klass = eclass;
2485         }
2486         class->this_arg = class->byval_arg;
2487         class->this_arg.byref = 1;
2488         if (corlib_type) {
2489                 class->inited = 1;
2490         }
2491
2492         list = g_slist_append (rootlist, class);
2493         g_hash_table_insert (image->array_cache, eclass, list);
2494
2495         mono_loader_unlock ();
2496
2497         return class;
2498 }
2499
2500 /**
2501  * mono_array_class_get:
2502  * @element_class: element class 
2503  * @rank: the dimension of the array class
2504  *
2505  * Returns: a class object describing the array with element type @element_type and 
2506  * dimension @rank. 
2507  */
2508 MonoClass *
2509 mono_array_class_get (MonoClass *eclass, guint32 rank)
2510 {
2511         return mono_bounded_array_class_get (eclass, rank, FALSE);
2512 }
2513
2514 /**
2515  * mono_class_instance_size:
2516  * @klass: a class 
2517  * 
2518  * Returns: the size of an object instance
2519  */
2520 gint32
2521 mono_class_instance_size (MonoClass *klass)
2522 {       
2523         if (!klass->size_inited)
2524                 mono_class_init (klass);
2525
2526         g_assert (!klass->generic_container &&
2527                   (!klass->generic_class || !klass->generic_class->inst->is_open));
2528         return klass->instance_size;
2529 }
2530
2531 /**
2532  * mono_class_min_align:
2533  * @klass: a class 
2534  * 
2535  * Returns: minimm alignment requirements 
2536  */
2537 gint32
2538 mono_class_min_align (MonoClass *klass)
2539 {       
2540         if (!klass->size_inited)
2541                 mono_class_init (klass);
2542
2543         return klass->min_align;
2544 }
2545
2546 /**
2547  * mono_class_value_size:
2548  * @klass: a class 
2549  *
2550  * This function is used for value types, and return the
2551  * space and the alignment to store that kind of value object.
2552  *
2553  * Returns: the size of a value of kind @klass
2554  */
2555 gint32
2556 mono_class_value_size      (MonoClass *klass, guint32 *align)
2557 {
2558         gint32 size;
2559
2560         /* fixme: check disable, because we still have external revereces to
2561          * mscorlib and Dummy Objects 
2562          */
2563         /*g_assert (klass->valuetype);*/
2564
2565         size = mono_class_instance_size (klass) - sizeof (MonoObject);
2566
2567         if (align)
2568                 *align = klass->min_align;
2569
2570         return size;
2571 }
2572
2573 /**
2574  * mono_class_data_size:
2575  * @klass: a class 
2576  * 
2577  * Returns: the size of the static class data
2578  */
2579 gint32
2580 mono_class_data_size (MonoClass *klass)
2581 {       
2582         if (!klass->inited)
2583                 mono_class_init (klass);
2584
2585         return klass->class_size;
2586 }
2587
2588 /*
2589  * Auxiliary routine to mono_class_get_field
2590  *
2591  * Takes a field index instead of a field token.
2592  */
2593 static MonoClassField *
2594 mono_class_get_field_idx (MonoClass *class, int idx)
2595 {
2596         if (class->field.count){
2597                 if ((idx >= class->field.first) && (idx < class->field.last)){
2598                         return &class->fields [idx - class->field.first];
2599                 }
2600         }
2601
2602         if (!class->parent)
2603                 return NULL;
2604         
2605         return mono_class_get_field_idx (class->parent, idx);
2606 }
2607
2608 /**
2609  * mono_class_get_field:
2610  * @class: the class to lookup the field.
2611  * @field_token: the field token
2612  *
2613  * Returns: A MonoClassField representing the type and offset of
2614  * the field, or a NULL value if the field does not belong to this
2615  * class.
2616  */
2617 MonoClassField *
2618 mono_class_get_field (MonoClass *class, guint32 field_token)
2619 {
2620         int idx = mono_metadata_token_index (field_token);
2621
2622         g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
2623
2624         return mono_class_get_field_idx (class, idx - 1);
2625 }
2626
2627 MonoClassField *
2628 mono_class_get_field_from_name (MonoClass *klass, const char *name)
2629 {
2630         int i;
2631
2632         while (klass) {
2633                 for (i = 0; i < klass->field.count; ++i) {
2634                         if (strcmp (name, klass->fields [i].name) == 0)
2635                                 return &klass->fields [i];
2636                 }
2637                 klass = klass->parent;
2638         }
2639         return NULL;
2640 }
2641
2642 guint32
2643 mono_class_get_field_token (MonoClassField *field)
2644 {
2645         MonoClass *klass = field->parent;
2646         int i;
2647
2648         while (klass) {
2649                 for (i = 0; i < klass->field.count; ++i) {
2650                         if (&klass->fields [i] == field)
2651                                 return mono_metadata_make_token (MONO_TABLE_FIELD, klass->field.first + i + 1);
2652                 }
2653                 klass = klass->parent;
2654         }
2655
2656         g_assert_not_reached ();
2657         return 0;
2658 }
2659
2660 guint32
2661 mono_class_get_event_token (MonoEvent *event)
2662 {
2663         MonoClass *klass = event->parent;
2664         int i;
2665
2666         while (klass) {
2667                 for (i = 0; i < klass->event.count; ++i) {
2668                         if (&klass->events [i] == event)
2669                                 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->event.first + i + 1);
2670                 }
2671                 klass = klass->parent;
2672         }
2673
2674         g_assert_not_reached ();
2675         return 0;
2676 }
2677
2678 void *
2679 mono_vtable_get_static_field_data (MonoVTable *vt)
2680 {
2681         return vt->data;
2682 }
2683
2684 MonoProperty*
2685 mono_class_get_property_from_name (MonoClass *klass, const char *name)
2686 {
2687         int i;
2688
2689         while (klass) {
2690                 for (i = 0; i < klass->property.count; ++i) {
2691                         if (strcmp (name, klass->properties [i].name) == 0)
2692                                 return &klass->properties [i];
2693                 }
2694                 klass = klass->parent;
2695         }
2696         return NULL;
2697 }
2698
2699 guint32
2700 mono_class_get_property_token (MonoProperty *prop)
2701 {
2702         MonoClass *klass = prop->parent;
2703         int i;
2704
2705         while (klass) {
2706                 for (i = 0; i < klass->property.count; ++i) {
2707                         if (&klass->properties [i] == prop)
2708                                 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->property.first + i + 1);
2709                 }
2710                 klass = klass->parent;
2711         }
2712
2713         g_assert_not_reached ();
2714         return 0;
2715 }
2716
2717 static char *
2718 mono_class_name_from_token (MonoImage *image, guint32 type_token, MonoGenericContext *context)
2719 {
2720         const char *name, *nspace;
2721         if (image->dynamic)
2722                 return g_strdup_printf ("DynamicType 0x%08x", type_token);
2723         
2724         switch (type_token & 0xff000000){
2725         case MONO_TOKEN_TYPE_DEF: {
2726                 guint32 cols [MONO_TYPEDEF_SIZE];
2727                 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
2728                 guint tidx = mono_metadata_token_index (type_token);
2729
2730                 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
2731                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2732                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2733                 return g_strdup_printf ("%s.%s", nspace, name);
2734         }
2735
2736         case MONO_TOKEN_TYPE_REF: {
2737                 guint32 cols [MONO_TYPEREF_SIZE];
2738                 MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
2739
2740                 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
2741                 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
2742                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
2743                 return g_strdup_printf ("%s.%s", nspace, name);
2744         }
2745                 
2746         case MONO_TOKEN_TYPE_SPEC:
2747                 return g_strdup_printf ("Typespec 0x%08x", type_token);
2748         }
2749 }
2750
2751 /**
2752  * mono_class_get:
2753  * @image: the image where the class resides
2754  * @type_token: the token for the class
2755  * @at: an optional pointer to return the array element type
2756  *
2757  * Returns: the MonoClass that represents @type_token in @image
2758  */
2759 static MonoClass *
2760 _mono_class_get (MonoImage *image, guint32 type_token, MonoGenericContext *context)
2761 {
2762         MonoClass *class = NULL;
2763
2764         if (image->dynamic)
2765                 return mono_lookup_dynamic_token (image, type_token);
2766
2767         switch (type_token & 0xff000000){
2768         case MONO_TOKEN_TYPE_DEF:
2769                 class = mono_class_create_from_typedef (image, type_token);
2770                 break;          
2771         case MONO_TOKEN_TYPE_REF:
2772                 class = mono_class_from_typeref (image, type_token);
2773                 break;
2774         case MONO_TOKEN_TYPE_SPEC:
2775                 class = mono_class_create_from_typespec (image, type_token, context);
2776                 break;
2777         default:
2778                 g_warning ("unknown token type %x", type_token & 0xff000000);
2779                 g_assert_not_reached ();
2780         }
2781
2782         if (!class){
2783                 char *name = mono_class_name_from_token (image, type_token, context);
2784                 g_warning ("Could not load class from %s (token 0x%08x) in %s", name, type_token, image->name);
2785                 g_free (name);
2786         }
2787
2788         return class;
2789 }
2790
2791 MonoClass *
2792 mono_class_get (MonoImage *image, guint32 type_token)
2793 {
2794         return _mono_class_get (image, type_token, NULL);
2795 }
2796
2797 MonoClass *
2798 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
2799 {
2800         MonoClass *class = _mono_class_get (image, type_token, context);
2801         MonoType *inflated;
2802
2803         if (!class || !context || (!context->gclass && !context->gmethod))
2804                 return class;
2805
2806         switch (class->byval_arg.type) {
2807         case MONO_TYPE_GENERICINST:
2808                 if (!class->generic_class->inst->is_open)
2809                         return class;
2810                 break;
2811         case MONO_TYPE_VAR:
2812         case MONO_TYPE_MVAR:
2813                 break;
2814         default:
2815                 return class;
2816         }
2817
2818         inflated = inflate_generic_type (&class->byval_arg, context);
2819         if (!inflated)
2820                 return class;
2821
2822         return mono_class_from_mono_type (inflated);
2823 }
2824
2825 /**
2826  * mono_class_from_name_case:
2827  * @image: The MonoImage where the type is looked up in, or NULL for looking up in all loaded assemblies
2828  * @name_space: the type namespace
2829  * @name: the type short name.
2830  *
2831  * Obtains a MonoClass with a given namespace and a given name which
2832  * is located in the given MonoImage.   The namespace and name
2833  * lookups are case insensitive.
2834  *
2835  * You can also pass @NULL to the image, and that will lookup for
2836  * a type with the given namespace and name in all of the loaded
2837  * assemblies: notice that since there might be a name clash in this
2838  * case, passing @NULL is not encouraged if you need a precise type.
2839  *
2840  */
2841 MonoClass *
2842 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
2843 {
2844         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
2845         guint32 cols [MONO_TYPEDEF_SIZE];
2846         const char *n;
2847         const char *nspace;
2848         guint32 i, visib;
2849
2850         /* add a cache if needed */
2851         for (i = 1; i <= t->rows; ++i) {
2852                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
2853                 /* nested types are accessed from the nesting name */
2854                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
2855                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
2856                         continue;
2857                 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2858                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2859                 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
2860                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
2861         }
2862         return NULL;
2863 }
2864
2865 static MonoClass*
2866 return_nested_in (MonoClass *class, char *nested) {
2867         MonoClass *found;
2868         char *s = strchr (nested, '/');
2869         GList *tmp;
2870
2871         if (s) {
2872                 *s = 0;
2873                 s++;
2874         }
2875         for (tmp = class->nested_classes; tmp; tmp = tmp->next) {
2876                 found = tmp->data;
2877                 if (strcmp (found->name, nested) == 0) {
2878                         if (s)
2879                                 return return_nested_in (found, s);
2880                         return found;
2881                 }
2882         }
2883         return NULL;
2884 }
2885
2886
2887 /**
2888  * mono_class_from_name_case:
2889  * @image: The MonoImage where the type is looked up in, or NULL for looking up in all loaded assemblies
2890  * @name_space: the type namespace
2891  * @name: the type short name.
2892  *
2893  * Obtains a MonoClass with a given namespace and a given name which
2894  * is located in the given MonoImage.   
2895  *
2896  * You can also pass `NULL' to the image, and that will lookup for
2897  * a type with the given namespace and name in all of the loaded
2898  * assemblies: notice that since there might be a name clash in this
2899  * case, passing NULL is not encouraged if you need a precise type.
2900  *
2901  */
2902 MonoClass *
2903 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
2904 {
2905         GHashTable *nspace_table;
2906         MonoImage *loaded_image;
2907         guint32 token = 0;
2908         MonoClass *class;
2909         char *nested;
2910         char buf [1024];
2911
2912         if ((nested = strchr (name, '/'))) {
2913                 int pos = nested - name;
2914                 int len = strlen (name);
2915                 if (len > 1023)
2916                         return NULL;
2917                 memcpy (buf, name, len + 1);
2918                 buf [pos] = 0;
2919                 nested = buf + pos + 1;
2920                 name = buf;
2921         }
2922
2923         mono_loader_lock ();
2924
2925         nspace_table = g_hash_table_lookup (image->name_cache, name_space);
2926
2927         if (nspace_table)
2928                 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
2929
2930         mono_loader_unlock ();
2931
2932         if (!token)
2933                 return NULL;
2934
2935         if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
2936                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
2937                 guint32 cols [MONO_EXP_TYPE_SIZE];
2938                 guint32 idx, impl;
2939
2940                 idx = mono_metadata_token_index (token);
2941
2942                 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
2943
2944                 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
2945                 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
2946                         loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
2947                         if (!loaded_image)
2948                                 return NULL;
2949                         class = mono_class_from_name (loaded_image, name_space, name);
2950                         if (nested)
2951                                 return return_nested_in (class, nested);
2952                         return class;
2953                 } else {
2954                         g_error ("not yet implemented");
2955                 }
2956         }
2957
2958         token = MONO_TOKEN_TYPE_DEF | token;
2959
2960         class = mono_class_get (image, token);
2961         if (nested)
2962                 return return_nested_in (class, nested);
2963         return class;
2964 }
2965
2966 gboolean
2967 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc, 
2968                            gboolean check_interfaces)
2969 {
2970  again:
2971         g_assert (klassc->idepth > 0);
2972         if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
2973                 if ((klassc->interface_id <= klass->max_interface_id) &&
2974                         (klass->interface_offsets [klassc->interface_id] >= 0))
2975                         return TRUE;
2976         } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
2977                 int i;
2978
2979                 for (i = 0; i < klass->interface_count; i ++) {
2980                         MonoClass *ic =  klass->interfaces [i];
2981                         if (ic == klassc)
2982                                 return TRUE;
2983                 }
2984         } else {
2985                 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
2986                         return TRUE;
2987         }
2988
2989         /* 
2990          * MS.NET thinks interfaces are a subclass of Object, so we think it as
2991          * well.
2992          */
2993         if (klassc == mono_defaults.object_class)
2994                 return TRUE;
2995
2996         if (klass->generic_class) {
2997                 MonoType *parent = klass->generic_class->parent;
2998                 if (!parent)
2999                         return FALSE;
3000
3001                 if (mono_metadata_type_equal (parent, &klassc->byval_arg))
3002                         return TRUE;
3003                 klass = mono_class_from_mono_type (parent);
3004                 goto again;
3005         }
3006         
3007         return FALSE;
3008 }
3009
3010 gboolean
3011 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
3012 {
3013         if (!klass->inited)
3014                 mono_class_init (klass);
3015
3016         if (!oklass->inited)
3017                 mono_class_init (oklass);
3018
3019         if (klass->generic_class)
3020                 klass = klass->generic_class->container_class;
3021
3022         if (MONO_CLASS_IS_INTERFACE (klass)) {
3023                 if ((klass->interface_id <= oklass->max_interface_id) &&
3024                     (oklass->interface_offsets [klass->interface_id] != -1))
3025                         return TRUE;
3026         } else
3027                 if (klass->rank) {
3028                         MonoClass *eclass, *eoclass;
3029
3030                         if (oklass->rank != klass->rank)
3031                                 return FALSE;
3032
3033                         /* vectors vs. one dimensional arrays */
3034                         if (oklass->byval_arg.type != klass->byval_arg.type)
3035                                 return FALSE;
3036
3037                         eclass = klass->cast_class;
3038                         eoclass = oklass->cast_class;
3039
3040
3041                         /* 
3042                          * a is b does not imply a[] is b[] when a is a valuetype, and
3043                          * b is a reference type.
3044                          */
3045
3046                         if (eoclass->valuetype) {
3047                                 if ((eclass == mono_defaults.enum_class) || 
3048                                         (eclass == mono_defaults.enum_class->parent) ||
3049                                         (eclass == mono_defaults.object_class))
3050                                         return FALSE;
3051                         }
3052
3053                         return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
3054                 }
3055         else
3056                 if (klass == mono_defaults.object_class)
3057                         return TRUE;
3058
3059         return mono_class_has_parent (oklass, klass);
3060 }       
3061
3062 /*
3063  * mono_class_needs_cctor_run:
3064  *
3065  *  Determines whenever the class has a static constructor and whenever it
3066  * needs to be called when executing CALLER.
3067  */
3068 gboolean
3069 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
3070 {
3071         int i;
3072         MonoMethod *method;
3073         
3074         for (i = 0; i < klass->method.count; ++i) {
3075                 method = klass->methods [i];
3076                 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
3077                     (strcmp (".cctor", method->name) == 0)) {
3078                         if (caller == method)
3079                                 return FALSE;
3080                         return TRUE;
3081                 }
3082         }
3083         return FALSE;
3084 }
3085
3086 /**
3087  * mono_class_array_element_size:
3088  * @klass: 
3089  *
3090  * Returns: the number of bytes an element of type @klass
3091  * uses when stored into an array.
3092  */
3093 gint32
3094 mono_class_array_element_size (MonoClass *klass)
3095 {
3096         MonoType *type = &klass->byval_arg;
3097         
3098 handle_enum:
3099         switch (type->type) {
3100         case MONO_TYPE_I1:
3101         case MONO_TYPE_U1:
3102         case MONO_TYPE_BOOLEAN:
3103                 return 1;
3104         case MONO_TYPE_I2:
3105         case MONO_TYPE_U2:
3106         case MONO_TYPE_CHAR:
3107                 return 2;
3108         case MONO_TYPE_I4:
3109         case MONO_TYPE_U4:
3110         case MONO_TYPE_R4:
3111                 return 4;
3112         case MONO_TYPE_I:
3113         case MONO_TYPE_U:
3114         case MONO_TYPE_PTR:
3115         case MONO_TYPE_CLASS:
3116         case MONO_TYPE_STRING:
3117         case MONO_TYPE_OBJECT:
3118         case MONO_TYPE_SZARRAY:
3119         case MONO_TYPE_ARRAY: 
3120         case MONO_TYPE_VAR:
3121         case MONO_TYPE_MVAR:   
3122                 return sizeof (gpointer);
3123         case MONO_TYPE_I8:
3124         case MONO_TYPE_U8:
3125         case MONO_TYPE_R8:
3126                 return 8;
3127         case MONO_TYPE_VALUETYPE:
3128                 if (type->data.klass->enumtype) {
3129                         type = type->data.klass->enum_basetype;
3130                         klass = klass->element_class;
3131                         goto handle_enum;
3132                 }
3133                 return mono_class_instance_size (klass) - sizeof (MonoObject);
3134         case MONO_TYPE_GENERICINST:
3135                 type = &type->data.generic_class->container_class->byval_arg;
3136                 goto handle_enum;
3137         default:
3138                 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
3139         }
3140         return -1;
3141 }
3142
3143 /**
3144  * mono_array_element_size:
3145  * @ac: pointer to a #MonoArrayClass
3146  *
3147  * Returns: the size of single array element.
3148  */
3149 gint32
3150 mono_array_element_size (MonoClass *ac)
3151 {
3152         return mono_class_array_element_size (ac->element_class);
3153 }
3154
3155 gpointer
3156 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
3157               MonoGenericContext *context)
3158 {
3159         if (image->dynamic) {
3160                 gpointer obj = mono_lookup_dynamic_token (image, token);
3161
3162                 switch (token & 0xff000000) {
3163                 case MONO_TOKEN_TYPE_DEF:
3164                 case MONO_TOKEN_TYPE_REF:
3165                 case MONO_TOKEN_TYPE_SPEC:
3166                         if (handle_class)
3167                                 *handle_class = mono_defaults.typehandle_class;
3168                         return &((MonoClass*)obj)->byval_arg;
3169                 case MONO_TOKEN_METHOD_DEF:
3170                         if (handle_class)
3171                                 *handle_class = mono_defaults.methodhandle_class;
3172                         return obj;
3173                 case MONO_TOKEN_FIELD_DEF:
3174                         if (handle_class)
3175                                 *handle_class = mono_defaults.fieldhandle_class;
3176                         return obj;
3177                 default:
3178                         g_assert_not_reached ();
3179                 }
3180         }
3181
3182         switch (token & 0xff000000) {
3183         case MONO_TOKEN_TYPE_DEF:
3184         case MONO_TOKEN_TYPE_REF: {
3185                 MonoClass *class;
3186                 if (handle_class)
3187                         *handle_class = mono_defaults.typehandle_class;
3188                 class = mono_class_get_full (image, token, context);
3189                 mono_class_init (class);
3190                 /* We return a MonoType* as handle */
3191                 return &class->byval_arg;
3192         }
3193         case MONO_TOKEN_TYPE_SPEC: {
3194                 MonoClass *class;
3195                 if (handle_class)
3196                         *handle_class = mono_defaults.typehandle_class;
3197                 class = mono_class_create_from_typespec (image, token, context);
3198                 mono_class_init (class);
3199                 return &class->byval_arg;
3200         }
3201         case MONO_TOKEN_FIELD_DEF: {
3202                 MonoClass *class;
3203                 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
3204                 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
3205                 mono_class_init (class);
3206                 if (handle_class)
3207                         *handle_class = mono_defaults.fieldhandle_class;
3208                 return mono_class_get_field (class, token);
3209         }
3210         case MONO_TOKEN_METHOD_DEF: {
3211                 MonoMethod *meth;
3212                 meth = mono_get_method_full (image, token, NULL, context);
3213                 if (handle_class)
3214                         *handle_class = mono_defaults.methodhandle_class;
3215                 return meth;
3216         }
3217         case MONO_TOKEN_MEMBER_REF: {
3218                 guint32 cols [MONO_MEMBERREF_SIZE];
3219                 const char *sig;
3220                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
3221                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
3222                 mono_metadata_decode_blob_size (sig, &sig);
3223                 if (*sig == 0x6) { /* it's a field */
3224                         MonoClass *klass;
3225                         MonoClassField *field;
3226                         field = mono_field_from_token (image, token, &klass, context);
3227                         if (handle_class)
3228                                 *handle_class = mono_defaults.fieldhandle_class;
3229                         return field;
3230                 } else {
3231                         MonoMethod *meth;
3232                         meth = mono_get_method_full (image, token, NULL, context);
3233                         if (handle_class)
3234                                 *handle_class = mono_defaults.methodhandle_class;
3235                         return meth;
3236                 }
3237         }
3238         default:
3239                 g_warning ("Unknown token 0x%08x in ldtoken", token);
3240                 break;
3241         }
3242         return NULL;
3243 }
3244
3245 /**
3246  * This function might need to call runtime functions so it can't be part
3247  * of the metadata library.
3248  */
3249 static MonoLookupDynamicToken lookup_dynamic = NULL;
3250
3251 void
3252 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
3253 {
3254         lookup_dynamic = func;
3255 }
3256
3257 gpointer
3258 mono_lookup_dynamic_token (MonoImage *image, guint32 token)
3259 {
3260         return lookup_dynamic (image, token);
3261 }
3262
3263 MonoImage*
3264 mono_class_get_image (MonoClass *klass)
3265 {
3266         return klass->image;
3267 }
3268
3269 /**
3270  * mono_class_get_element_class:
3271  * @klass: the MonoClass to act on
3272  *
3273  * Returns: the element class of an array or an enumeration.
3274  */
3275 MonoClass*
3276 mono_class_get_element_class (MonoClass *klass)
3277 {
3278         return klass->element_class;
3279 }
3280
3281 /**
3282  * mono_class_is_valuetype:
3283  * @klass: the MonoClass to act on
3284  *
3285  * Returns: true if the MonoClass represents a ValueType.
3286  */
3287 gboolean
3288 mono_class_is_valuetype (MonoClass *klass)
3289 {
3290         return klass->valuetype;
3291 }
3292
3293 /**
3294  * mono_class_is_enum:
3295  * @klass: the MonoClass to act on
3296  *
3297  * Returns: true if the MonoClass represents an enumeration.
3298  */
3299 gboolean
3300 mono_class_is_enum (MonoClass *klass)
3301 {
3302         return klass->enumtype;
3303 }
3304
3305 /**
3306  * mono_class_enum_basetype:
3307  * @klass: the MonoClass to act on
3308  *
3309  * Returns: the underlying type representation for an enumeration.
3310  */
3311 MonoType*
3312 mono_class_enum_basetype (MonoClass *klass)
3313 {
3314         return klass->enum_basetype;
3315 }
3316
3317 /**
3318  * mono_class_get_parent
3319  * @klass: the MonoClass to act on
3320  *
3321  * Returns: the parent class for this class.
3322  */
3323 MonoClass*
3324 mono_class_get_parent (MonoClass *klass)
3325 {
3326         return klass->parent;
3327 }
3328
3329 /**
3330  * mono_class_get_nesting_type;
3331  * @klass: the MonoClass to act on
3332  *
3333  * Returns: the container type where this type is nested or NULL if this type is not a nested type.
3334  */
3335 MonoClass*
3336 mono_class_get_nesting_type (MonoClass *klass)
3337 {
3338         return klass->nested_in;
3339 }
3340
3341 /**
3342  * mono_class_get_rank:
3343  * @klass: the MonoClass to act on
3344  *
3345  * Returns: the rank for the array (the number of dimensions).
3346  */
3347 int
3348 mono_class_get_rank (MonoClass *klass)
3349 {
3350         return klass->rank;
3351 }
3352
3353 /**
3354  * mono_class_get_flags:
3355  * @klass: the MonoClass to act on
3356  *
3357  * The type flags from the TypeDef table from the metadata.
3358  * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
3359  * different values.
3360  *
3361  * Returns: the flags from the TypeDef table.
3362  */
3363 guint32
3364 mono_class_get_flags (MonoClass *klass)
3365 {
3366         return klass->flags;
3367 }
3368
3369 /**
3370  * mono_class_get_name
3371  * @klass: the MonoClass to act on
3372  *
3373  * Returns: the name of the class.
3374  */
3375 const char*
3376 mono_class_get_name (MonoClass *klass)
3377 {
3378         return klass->name;
3379 }
3380
3381 /**
3382  * mono_class_get_namespace:
3383  * @klass: the MonoClass to act on
3384  *
3385  * Returns: the namespace of the class.
3386  */
3387 const char*
3388 mono_class_get_namespace (MonoClass *klass)
3389 {
3390         return klass->name_space;
3391 }
3392
3393 /**
3394  * mono_class_get_type:
3395  * @klass: the MonoClass to act on
3396  *
3397  * This method returns the internal Type representation for the class.
3398  *
3399  * Returns: the MonoType from the class.
3400  */
3401 MonoType*
3402 mono_class_get_type (MonoClass *klass)
3403 {
3404         return &klass->byval_arg;
3405 }
3406
3407 /**
3408  * mono_class_get_byref_type:
3409  * @klass: the MonoClass to act on
3410  *
3411  * 
3412  */
3413 MonoType*
3414 mono_class_get_byref_type (MonoClass *klass)
3415 {
3416         return &klass->this_arg;
3417 }
3418
3419 /**
3420  * mono_class_num_fields:
3421  * @klass: the MonoClass to act on
3422  *
3423  * Returns: the number of static and instance fields in the class.
3424  */
3425 int
3426 mono_class_num_fields (MonoClass *klass)
3427 {
3428         return klass->field.count;
3429 }
3430
3431 /**
3432  * mono_class_num_methods:
3433  * @klass: the MonoClass to act on
3434  *
3435  * Returns: the number of methods in the class.
3436  */
3437 int
3438 mono_class_num_methods (MonoClass *klass)
3439 {
3440         return klass->method.count;
3441 }
3442
3443 /**
3444  * mono_class_num_properties
3445  * @klass: the MonoClass to act on
3446  *
3447  * Returns: the number of properties in the class.
3448  */
3449 int
3450 mono_class_num_properties (MonoClass *klass)
3451 {
3452         return klass->property.count;
3453 }
3454
3455 /**
3456  * mono_class_num_events:
3457  * @klass: the MonoClass to act on
3458  *
3459  * Returns: the number of events in the class.
3460  */
3461 int
3462 mono_class_num_events (MonoClass *klass)
3463 {
3464         return klass->event.count;
3465 }
3466
3467 /**
3468  * mono_class_get_fields:
3469  * @klass: the MonoClass to act on
3470  *
3471  * This routine is an iterator routine for retrieving the fields in a class.
3472  *
3473  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3474  * iterate over all of the elements.  When no more values are
3475  * available, the return value is NULL.
3476  *
3477  * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
3478  */
3479 MonoClassField*
3480 mono_class_get_fields (MonoClass* klass, gpointer *iter)
3481 {
3482         MonoClassField* field;
3483         if (!iter)
3484                 return NULL;
3485         if (!klass->inited)
3486                 mono_class_init (klass);
3487         if (!*iter) {
3488                 /* start from the first */
3489                 if (klass->field.count) {
3490                         return *iter = &klass->fields [0];
3491                 } else {
3492                         /* no fields */
3493                         return NULL;
3494                 }
3495         }
3496         field = *iter;
3497         field++;
3498         if (field < &klass->fields [klass->field.count]) {
3499                 return *iter = field;
3500         }
3501         return NULL;
3502 }
3503
3504 /**
3505  * mono_class_get_methods
3506  * @klass: the MonoClass to act on
3507  *
3508  * This routine is an iterator routine for retrieving the fields in a class.
3509  *
3510  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3511  * iterate over all of the elements.  When no more values are
3512  * available, the return value is NULL.
3513  *
3514  * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
3515  */
3516 MonoMethod*
3517 mono_class_get_methods (MonoClass* klass, gpointer *iter)
3518 {
3519         MonoMethod** method;
3520         if (!iter)
3521                 return NULL;
3522         if (!klass->inited)
3523                 mono_class_init (klass);
3524         if (!*iter) {
3525                 /* start from the first */
3526                 if (klass->method.count) {
3527                         *iter = &klass->methods [0];
3528                         return klass->methods [0];
3529                 } else {
3530                         /* no method */
3531                         return NULL;
3532                 }
3533         }
3534         method = *iter;
3535         method++;
3536         if (method < &klass->methods [klass->method.count]) {
3537                 *iter = method;
3538                 return *method;
3539         }
3540         return NULL;
3541 }
3542
3543 /**
3544  * mono_class_get_properties:
3545  * @klass: the MonoClass to act on
3546  *
3547  * This routine is an iterator routine for retrieving the properties in a class.
3548  *
3549  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3550  * iterate over all of the elements.  When no more values are
3551  * available, the return value is NULL.
3552  *
3553  * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
3554  */
3555 MonoProperty*
3556 mono_class_get_properties (MonoClass* klass, gpointer *iter)
3557 {
3558         MonoProperty* property;
3559         if (!iter)
3560                 return NULL;
3561         if (!klass->inited)
3562                 mono_class_init (klass);
3563         if (!*iter) {
3564                 /* start from the first */
3565                 if (klass->property.count) {
3566                         return *iter = &klass->properties [0];
3567                 } else {
3568                         /* no fields */
3569                         return NULL;
3570                 }
3571         }
3572         property = *iter;
3573         property++;
3574         if (property < &klass->properties [klass->property.count]) {
3575                 return *iter = property;
3576         }
3577         return NULL;
3578 }
3579
3580 /**
3581  * mono_class_get_events:
3582  * @klass: the MonoClass to act on
3583  *
3584  * This routine is an iterator routine for retrieving the properties in a class.
3585  *
3586  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3587  * iterate over all of the elements.  When no more values are
3588  * available, the return value is NULL.
3589  *
3590  * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
3591  */
3592 MonoEvent*
3593 mono_class_get_events (MonoClass* klass, gpointer *iter)
3594 {
3595         MonoEvent* event;
3596         if (!iter)
3597                 return NULL;
3598         if (!klass->inited)
3599                 mono_class_init (klass);
3600         if (!*iter) {
3601                 /* start from the first */
3602                 if (klass->event.count) {
3603                         return *iter = &klass->events [0];
3604                 } else {
3605                         /* no fields */
3606                         return NULL;
3607                 }
3608         }
3609         event = *iter;
3610         event++;
3611         if (event < &klass->events [klass->event.count]) {
3612                 return *iter = event;
3613         }
3614         return NULL;
3615 }
3616
3617 /**
3618  * mono_class_get_interfaces
3619  * @klass: the MonoClass to act on
3620  *
3621  * This routine is an iterator routine for retrieving the interfaces implemented by this class.
3622  *
3623  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3624  * iterate over all of the elements.  When no more values are
3625  * available, the return value is NULL.
3626  *
3627  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
3628  */
3629 MonoClass*
3630 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
3631 {
3632         MonoClass** iface;
3633         if (!iter)
3634                 return NULL;
3635         if (!klass->inited)
3636                 mono_class_init (klass);
3637         if (!*iter) {
3638                 /* start from the first */
3639                 if (klass->interface_count) {
3640                         *iter = &klass->interfaces [0];
3641                         return klass->interfaces [0];
3642                 } else {
3643                         /* no interface */
3644                         return NULL;
3645                 }
3646         }
3647         iface = *iter;
3648         iface++;
3649         if (iface < &klass->interfaces [klass->interface_count]) {
3650                 *iter = iface;
3651                 return *iface;
3652         }
3653         return NULL;
3654 }
3655
3656 /**
3657  * mono_class_get_nested_types
3658  * @klass: the MonoClass to act on
3659  *
3660  * This routine is an iterator routine for retrieving the nested types of a class.
3661  *
3662  * You must pass a gpointer that points to zero and is treated as an opaque handle to
3663  * iterate over all of the elements.  When no more values are
3664  * available, the return value is NULL.
3665  *
3666  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
3667  */
3668 MonoClass*
3669 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
3670 {
3671         GList *item;
3672         if (!iter)
3673                 return NULL;
3674         if (!klass->inited)
3675                 mono_class_init (klass);
3676         if (!*iter) {
3677                 /* start from the first */
3678                 if (klass->nested_classes) {
3679                         *iter = klass->nested_classes;
3680                         return klass->nested_classes->data;
3681                 } else {
3682                         /* no nested types */
3683                         return NULL;
3684                 }
3685         }
3686         item = *iter;
3687         item = item->next;
3688         if (item) {
3689                 *iter = item;
3690                 return item->data;
3691         }
3692         return NULL;
3693 }
3694
3695 /**
3696  * mono_field_get_name:
3697  * @field: the MonoClassField to act on
3698  *
3699  * Returns: the name of the field.
3700  */
3701 const char*
3702 mono_field_get_name (MonoClassField *field)
3703 {
3704         return field->name;
3705 }
3706
3707 /**
3708  * mono_field_get_type:
3709  * @field: the MonoClassField to act on
3710  *
3711  * Returns: MonoType of the field.
3712  */
3713 MonoType*
3714 mono_field_get_type (MonoClassField *field)
3715 {
3716         return field->type;
3717 }
3718
3719 /**
3720  * mono_field_get_type:
3721  * @field: the MonoClassField to act on
3722  *
3723  * Returns: MonoClass where the field was defined.
3724  */
3725 MonoClass*
3726 mono_field_get_parent (MonoClassField *field)
3727 {
3728         return field->parent;
3729 }
3730
3731 /**
3732  * mono_field_get_flags;
3733  * @field: the MonoClassField to act on
3734  *
3735  * The metadata flags for a field are encoded using the
3736  * FIELD_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
3737  *
3738  * Returns: the flags for the field.
3739  */
3740 guint32
3741 mono_field_get_flags (MonoClassField *field)
3742 {
3743         return field->type->attrs;
3744 }
3745
3746 /**
3747  * mono_property_get_name: 
3748  * @prop: the MonoProperty to act on
3749  *
3750  * Returns: the name of the property
3751  */
3752 const char*
3753 mono_property_get_name (MonoProperty *prop)
3754 {
3755         return prop->name;
3756 }
3757
3758 /**
3759  * mono_property_get_set_method
3760  * @prop: the MonoProperty to act on.
3761  *
3762  * Returns: the setter method of the property (A MonoMethod)
3763  */
3764 MonoMethod*
3765 mono_property_get_set_method (MonoProperty *prop)
3766 {
3767         return prop->set;
3768 }
3769
3770 /**
3771  * mono_property_get_get_method
3772  * @prop: the MonoProperty to act on.
3773  *
3774  * Returns: the setter method of the property (A MonoMethod)
3775  */
3776 MonoMethod*
3777 mono_property_get_get_method (MonoProperty *prop)
3778 {
3779         return prop->get;
3780 }
3781
3782 /**
3783  * mono_property_get_parent:
3784  * @prop: the MonoProperty to act on.
3785  *
3786  * Returns: the MonoClass where the property was defined.
3787  */
3788 MonoClass*
3789 mono_property_get_parent (MonoProperty *prop)
3790 {
3791         return prop->parent;
3792 }
3793
3794 /**
3795  * mono_property_get_flags:
3796  * @prop: the MonoProperty to act on.
3797  *
3798  * The metadata flags for a property are encoded using the
3799  * PROPERTY_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
3800  *
3801  * Returns: the flags for the property.
3802  */
3803 guint32
3804 mono_property_get_flags (MonoProperty *prop)
3805 {
3806         return prop->attrs;
3807 }
3808
3809 /**
3810  * mono_event_get_name:
3811  * @event: the MonoEvent to act on
3812  *
3813  * Returns: the name of the event.
3814  */
3815 const char*
3816 mono_event_get_name (MonoEvent *event)
3817 {
3818         return event->name;
3819 }
3820
3821 /**
3822  * mono_event_get_add_method:
3823  * @event: The MonoEvent to act on.
3824  *
3825  * Returns: the @add' method for the event (a MonoMethod).
3826  */
3827 MonoMethod*
3828 mono_event_get_add_method (MonoEvent *event)
3829 {
3830         return event->add;
3831 }
3832
3833 /**
3834  * mono_event_get_remove_method:
3835  * @event: The MonoEvent to act on.
3836  *
3837  * Returns: the @remove method for the event (a MonoMethod).
3838  */
3839 MonoMethod*
3840 mono_event_get_remove_method (MonoEvent *event)
3841 {
3842         return event->remove;
3843 }
3844
3845 /**
3846  * mono_event_get_raise_method:
3847  * @event: The MonoEvent to act on.
3848  *
3849  * Returns: the @raise method for the event (a MonoMethod).
3850  */
3851 MonoMethod*
3852 mono_event_get_raise_method (MonoEvent *event)
3853 {
3854         return event->raise;
3855 }
3856
3857 /**
3858  * mono_event_get_parent:
3859  * @event: the MonoEvent to act on.
3860  *
3861  * Returns: the MonoClass where the event is defined.
3862  */
3863 MonoClass*
3864 mono_event_get_parent (MonoEvent *event)
3865 {
3866         return event->parent;
3867 }
3868
3869 /**
3870  * mono_event_get_flags
3871  * @event: the MonoEvent to act on.
3872  *
3873  * The metadata flags for an event are encoded using the
3874  * EVENT_* constants.  See the tabledefs.h file for details.
3875  *
3876  * Returns: the flags for the event.
3877  */
3878 guint32
3879 mono_event_get_flags (MonoEvent *event)
3880 {
3881         return event->attrs;
3882 }
3883
3884 /**
3885  * mono_find_method_by_name:
3886  * @klass: where to look for the method
3887  * @name_space: name of the method
3888  * @param_count: number of parameters. -1 for any number.
3889  *
3890  * Obtains a MonoMethod with a given name and number of parameters.
3891  * It only works if there are no multiple signatures for any given method name.
3892  */
3893 MonoMethod *
3894 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
3895 {
3896         MonoMethod *res = NULL;
3897         int i;
3898
3899         mono_class_init (klass);
3900
3901         for (i = 0; i < klass->method.count; ++i) {
3902                 if (klass->methods [i]->name[0] == name [0] && 
3903                     !strcmp (name, klass->methods [i]->name) &&
3904                     (param_count == -1 || mono_method_signature (klass->methods [i])->param_count == param_count)) {
3905                         res = klass->methods [i];
3906                         break;
3907                 }
3908         }
3909         return res;
3910 }