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