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