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