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