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