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