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