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