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