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