2009-05-16 Zoltan Varga <vargaz@gmail.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  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9  */
10 #include <config.h>
11 #ifdef HAVE_ALLOCA_H
12 #include <alloca.h>
13 #endif
14 #include <glib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #if !PLATFORM_WIN32
19 #include <mono/io-layer/atomic.h>
20 #endif
21 #include <mono/metadata/image.h>
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/metadata.h>
24 #include <mono/metadata/metadata-internals.h>
25 #include <mono/metadata/profiler-private.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/tokentype.h>
28 #include <mono/metadata/class-internals.h>
29 #include <mono/metadata/object.h>
30 #include <mono/metadata/appdomain.h>
31 #include <mono/metadata/mono-endian.h>
32 #include <mono/metadata/debug-helpers.h>
33 #include <mono/metadata/reflection.h>
34 #include <mono/metadata/exception.h>
35 #include <mono/metadata/security-manager.h>
36 #include <mono/metadata/security-core-clr.h>
37 #include <mono/metadata/attrdefs.h>
38 #include <mono/metadata/gc-internal.h>
39 #include <mono/metadata/verify-internals.h>
40 #include <mono/metadata/mono-debug.h>
41 #include <mono/utils/mono-counters.h>
42
43 MonoStats mono_stats;
44
45 gboolean mono_print_vtable = FALSE;
46
47 /*
48  * Controls whenever mono_class_init () constructs a generic vtable. This is TRUE by
49  * default to avoid breaking embedding apps, but set to FALSE by the runtime executable
50  * startup code.
51  */
52 gboolean mono_setup_vtable_in_class_init = TRUE;
53
54 /* Statistics */
55 guint32 inflated_classes, inflated_classes_size, inflated_methods_size;
56 guint32 classes_size, class_ext_size;
57
58 /* Function supplied by the runtime to find classes by name using information from the AOT file */
59 static MonoGetClassFromName get_class_from_name = NULL;
60
61 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
62 static gboolean mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res);
63 static gboolean can_access_type (MonoClass *access_klass, MonoClass *member_klass);
64 static MonoMethod* find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags);
65 static int generic_array_methods (MonoClass *class);
66 static void setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos);
67
68 static MonoMethod* mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter);
69
70 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
71 void (*mono_debugger_class_loaded_methods_func) (MonoClass *klass) = NULL;
72
73 /*
74  * mono_class_from_typeref:
75  * @image: a MonoImage
76  * @type_token: a TypeRef token
77  *
78  * Creates the MonoClass* structure representing the type defined by
79  * the typeref token valid inside @image.
80  * Returns: the MonoClass* representing the typeref token, NULL ifcould
81  * not be loaded.
82  */
83 MonoClass *
84 mono_class_from_typeref (MonoImage *image, guint32 type_token)
85 {
86         guint32 cols [MONO_TYPEREF_SIZE];
87         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
88         guint32 idx;
89         const char *name, *nspace;
90         MonoClass *res;
91         MonoImage *module;
92         
93         mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
94
95         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
96         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
97
98         idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
99         switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
100         case MONO_RESOLTION_SCOPE_MODULE:
101                 if (!idx)
102                         g_error ("null ResolutionScope not yet handled");
103                 /* a typedef in disguise */
104                 return mono_class_from_name (image, nspace, name);
105         case MONO_RESOLTION_SCOPE_MODULEREF:
106                 module = mono_image_load_module (image, idx);
107                 if (module)
108                         return mono_class_from_name (module, nspace, name);
109                 else {
110                         char *msg = g_strdup_printf ("%s%s%s", nspace, nspace [0] ? "." : "", name);
111                         char *human_name;
112                         
113                         human_name = mono_stringify_assembly_name (&image->assembly->aname);
114                         mono_loader_set_error_type_load (msg, human_name);
115                         g_free (msg);
116                         g_free (human_name);
117                 
118                         return NULL;
119                 }
120         case MONO_RESOLTION_SCOPE_TYPEREF: {
121                 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
122                 GList *tmp;
123
124                 if (enclosing->nested_classes_inited && enclosing->ext) {
125                         /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
126                         for (tmp = enclosing->ext->nested_classes; tmp; tmp = tmp->next) {
127                                 res = tmp->data;
128                                 if (strcmp (res->name, name) == 0)
129                                         return res;
130                         }
131                 } else {
132                         /* Don't call mono_class_init as we might've been called by it recursively */
133                         int i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, 1);
134                         while (i) {
135                                 guint32 class_nested = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, MONO_NESTED_CLASS_NESTED);
136                                 guint32 string_offset = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_TYPEDEF], class_nested - 1, MONO_TYPEDEF_NAME);
137                                 const char *nname = mono_metadata_string_heap (enclosing->image, string_offset);
138
139                                 if (strcmp (nname, name) == 0)
140                                         return mono_class_create_from_typedef (enclosing->image, MONO_TOKEN_TYPE_DEF | class_nested);
141
142                                 i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, i + 1);
143                         }
144                 }
145                 g_warning ("TypeRef ResolutionScope not yet handled (%d) for %s.%s in image %s", idx, nspace, name, image->name);
146                 return NULL;
147         }
148         case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
149                 break;
150         }
151
152         if (!image->references || !image->references [idx - 1])
153                 mono_assembly_load_reference (image, idx - 1);
154         g_assert (image->references [idx - 1]);
155
156         /* If the assembly did not load, register this as a type load exception */
157         if (image->references [idx - 1] == REFERENCE_MISSING){
158                 MonoAssemblyName aname;
159                 char *human_name;
160                 
161                 mono_assembly_get_assemblyref (image, idx - 1, &aname);
162                 human_name = mono_stringify_assembly_name (&aname);
163                 mono_loader_set_error_assembly_load (human_name, image->assembly->ref_only);
164                 g_free (human_name);
165                 
166                 return NULL;
167         }
168
169         return mono_class_from_name (image->references [idx - 1]->image, nspace, name);
170 }
171
172
173 static void *
174 mono_image_memdup (MonoImage *image, void *data, guint size)
175 {
176         void *res = mono_image_alloc (image, size);
177         memcpy (res, data, size);
178         return res;
179 }
180         
181 /* Copy everything mono_metadata_free_array free. */
182 MonoArrayType *
183 mono_dup_array_type (MonoImage *image, MonoArrayType *a)
184 {
185         if (image) {
186                 a = mono_image_memdup (image, a, sizeof (MonoArrayType));
187                 if (a->sizes)
188                         a->sizes = mono_image_memdup (image, a->sizes, a->numsizes * sizeof (int));
189                 if (a->lobounds)
190                         a->lobounds = mono_image_memdup (image, a->lobounds, a->numlobounds * sizeof (int));
191         } else {
192                 a = g_memdup (a, sizeof (MonoArrayType));
193                 if (a->sizes)
194                         a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
195                 if (a->lobounds)
196                         a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
197         }
198         return a;
199 }
200
201 /* Copy everything mono_metadata_free_method_signature free. */
202 MonoMethodSignature*
203 mono_metadata_signature_deep_dup (MonoImage *image, MonoMethodSignature *sig)
204 {
205         int i;
206         
207         sig = mono_metadata_signature_dup_full (image, sig);
208         
209         sig->ret = mono_metadata_type_dup (image, sig->ret);
210         for (i = 0; i < sig->param_count; ++i)
211                 sig->params [i] = mono_metadata_type_dup (image, sig->params [i]);
212         
213         return sig;
214 }
215
216 static void
217 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
218 {
219         MonoAssembly *ta = klass->image->assembly;
220
221         g_string_append_printf (
222                 str, ", %s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
223                 ta->aname.name,
224                 ta->aname.major, ta->aname.minor, ta->aname.build, ta->aname.revision,
225                 ta->aname.culture && *ta->aname.culture? ta->aname.culture: "neutral",
226                 ta->aname.public_key_token [0] ? (char *)ta->aname.public_key_token : "null",
227                 (ta->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
228 }
229
230 static inline void
231 mono_type_name_check_byref (MonoType *type, GString *str)
232 {
233         if (type->byref)
234                 g_string_append_c (str, '&');
235 }
236
237 static void
238 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
239                             MonoTypeNameFormat format)
240 {
241         MonoClass *klass;
242         
243         switch (type->type) {
244         case MONO_TYPE_ARRAY: {
245                 int i, rank = type->data.array->rank;
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.array->eklass->byval_arg, str, FALSE, nested_format);
253                 g_string_append_c (str, '[');
254                 if (rank == 1)
255                         g_string_append_c (str, '*');
256                 for (i = 1; i < rank; i++)
257                         g_string_append_c (str, ',');
258                 g_string_append_c (str, ']');
259                 
260                 mono_type_name_check_byref (type, str);
261
262                 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
263                         _mono_type_get_assembly_name (type->data.array->eklass, str);
264                 break;
265         }
266         case MONO_TYPE_SZARRAY: {
267                 MonoTypeNameFormat nested_format;
268
269                 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
270                         MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
271
272                 mono_type_get_name_recurse (
273                         &type->data.klass->byval_arg, str, FALSE, nested_format);
274                 g_string_append (str, "[]");
275                 
276                 mono_type_name_check_byref (type, str);
277
278                 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
279                         _mono_type_get_assembly_name (type->data.klass, str);
280                 break;
281         }
282         case MONO_TYPE_PTR: {
283                 MonoTypeNameFormat nested_format;
284
285                 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
286                         MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
287
288                 mono_type_get_name_recurse (
289                         type->data.type, str, FALSE, nested_format);
290                 g_string_append_c (str, '*');
291
292                 mono_type_name_check_byref (type, str);
293
294                 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
295                         _mono_type_get_assembly_name (mono_class_from_mono_type (type->data.type), str);
296                 break;
297         }
298         case MONO_TYPE_VAR:
299         case MONO_TYPE_MVAR:
300                 if (!mono_generic_param_info (type->data.generic_param))
301                         g_string_append_printf (str, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", type->data.generic_param->num);
302                 else
303                         g_string_append (str, mono_generic_param_info (type->data.generic_param)->name);
304
305                 mono_type_name_check_byref (type, str);
306
307                 break;
308         default:
309                 klass = mono_class_from_mono_type (type);
310                 if (klass->nested_in) {
311                         mono_type_get_name_recurse (
312                                 &klass->nested_in->byval_arg, str, TRUE, format);
313                         if (format == MONO_TYPE_NAME_FORMAT_IL)
314                                 g_string_append_c (str, '.');
315                         else
316                                 g_string_append_c (str, '+');
317                 } else if (*klass->name_space) {
318                         g_string_append (str, klass->name_space);
319                         g_string_append_c (str, '.');
320                 }
321                 if (format == MONO_TYPE_NAME_FORMAT_IL) {
322                         char *s = strchr (klass->name, '`');
323                         int len = s ? s - klass->name : strlen (klass->name);
324
325                         g_string_append_len (str, klass->name, len);
326                 } else
327                         g_string_append (str, klass->name);
328                 if (is_recursed)
329                         break;
330                 if (klass->generic_class) {
331                         MonoGenericClass *gclass = klass->generic_class;
332                         MonoGenericInst *inst = gclass->context.class_inst;
333                         MonoTypeNameFormat nested_format;
334                         int i;
335
336                         nested_format = format == MONO_TYPE_NAME_FORMAT_FULL_NAME ?
337                                 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED : format;
338
339                         if (format == MONO_TYPE_NAME_FORMAT_IL)
340                                 g_string_append_c (str, '<');
341                         else
342                                 g_string_append_c (str, '[');
343                         for (i = 0; i < inst->type_argc; i++) {
344                                 MonoType *t = inst->type_argv [i];
345
346                                 if (i)
347                                         g_string_append_c (str, ',');
348                                 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
349                                     (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
350                                         g_string_append_c (str, '[');
351                                 mono_type_get_name_recurse (inst->type_argv [i], str, FALSE, nested_format);
352                                 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
353                                     (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
354                                         g_string_append_c (str, ']');
355                         }
356                         if (format == MONO_TYPE_NAME_FORMAT_IL) 
357                                 g_string_append_c (str, '>');
358                         else
359                                 g_string_append_c (str, ']');
360                 } else if (klass->generic_container &&
361                            (format != MONO_TYPE_NAME_FORMAT_FULL_NAME) &&
362                            (format != MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)) {
363                         int i;
364
365                         if (format == MONO_TYPE_NAME_FORMAT_IL) 
366                                 g_string_append_c (str, '<');
367                         else
368                                 g_string_append_c (str, '[');
369                         for (i = 0; i < klass->generic_container->type_argc; i++) {
370                                 if (i)
371                                         g_string_append_c (str, ',');
372                                 g_string_append (str, mono_generic_container_get_param_info (klass->generic_container, i)->name);
373                         }
374                         if (format == MONO_TYPE_NAME_FORMAT_IL) 
375                                 g_string_append_c (str, '>');
376                         else
377                                 g_string_append_c (str, ']');
378                 }
379
380                 mono_type_name_check_byref (type, str);
381
382                 if ((format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
383                     (type->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
384                         _mono_type_get_assembly_name (klass, str);
385                 break;
386         }
387 }
388
389 /**
390  * mono_type_get_name:
391  * @type: a type
392  * @format: the format for the return string.
393  *
394  * 
395  * Returns: the string representation in a number of formats:
396  *
397  * if format is MONO_TYPE_NAME_FORMAT_REFLECTION, the return string is
398  * returned in the formatrequired by System.Reflection, this is the
399  * inverse of mono_reflection_parse_type ().
400  *
401  * if format is MONO_TYPE_NAME_FORMAT_IL, it returns a syntax that can
402  * be used by the IL assembler.
403  *
404  * if format is MONO_TYPE_NAME_FORMAT_FULL_NAME
405  *
406  * if format is MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED
407  */
408 char*
409 mono_type_get_name_full (MonoType *type, MonoTypeNameFormat format)
410 {
411         GString* result;
412
413         result = g_string_new ("");
414
415         mono_type_get_name_recurse (type, result, FALSE, format);
416
417         return g_string_free (result, FALSE);
418 }
419
420 /**
421  * mono_type_get_full_name:
422  * @class: a class
423  *
424  * Returns: the string representation for type as required by System.Reflection.
425  * The inverse of mono_reflection_parse_type ().
426  */
427 char *
428 mono_type_get_full_name (MonoClass *class)
429 {
430         return mono_type_get_name_full (mono_class_get_type (class), MONO_TYPE_NAME_FORMAT_REFLECTION);
431 }
432
433 /**
434  * mono_type_get_name:
435  * @type: a type
436  *
437  * Returns: the string representation for type as it would be represented in IL code.
438  */
439 char*
440 mono_type_get_name (MonoType *type)
441 {
442         return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_IL);
443 }
444
445 /*
446  * mono_type_get_underlying_type:
447  * @type: a type
448  *
449  * Returns: the MonoType for the underlying integer type if @type
450  * is an enum and byref is false, otherwise the type itself.
451  */
452 MonoType*
453 mono_type_get_underlying_type (MonoType *type)
454 {
455         if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype && !type->byref)
456                 return mono_class_enum_basetype (type->data.klass);
457         if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype && !type->byref)
458                 return mono_class_enum_basetype (type->data.generic_class->container_class);
459         return type;
460 }
461
462 /*
463  * mono_class_is_open_constructed_type:
464  * @type: a type
465  *
466  * Returns TRUE if type represents a generics open constructed type
467  * (not all the type parameters required for the instantiation have
468  * been provided).
469  */
470 gboolean
471 mono_class_is_open_constructed_type (MonoType *t)
472 {
473         switch (t->type) {
474         case MONO_TYPE_VAR:
475         case MONO_TYPE_MVAR:
476                 return TRUE;
477         case MONO_TYPE_SZARRAY:
478                 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
479         case MONO_TYPE_ARRAY:
480                 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
481         case MONO_TYPE_PTR:
482                 return mono_class_is_open_constructed_type (t->data.type);
483         case MONO_TYPE_GENERICINST:
484                 return t->data.generic_class->context.class_inst->is_open;
485         default:
486                 return FALSE;
487         }
488 }
489
490 static MonoType*
491 inflate_generic_type (MonoImage *image, MonoType *type, MonoGenericContext *context)
492 {
493         switch (type->type) {
494         case MONO_TYPE_MVAR: {
495                 MonoType *nt;
496                 int num = mono_type_get_generic_param_num (type);
497                 MonoGenericInst *inst = context->method_inst;
498                 if (!inst || !inst->type_argv)
499                         return NULL;
500                 if (num >= inst->type_argc)
501                         g_error ("MVAR %d (%s) cannot be expanded in this context with %d instantiations",
502                                 num, mono_generic_param_info (type->data.generic_param)->name, inst->type_argc);
503
504                 /*
505                  * Note that the VAR/MVAR cases are different from the rest.  The other cases duplicate @type,
506                  * while the VAR/MVAR duplicates a type from the context.  So, we need to ensure that the
507                  * ->byref and ->attrs from @type are propagated to the returned type.
508                  */
509                 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
510                 nt->byref = type->byref;
511                 nt->attrs = type->attrs;
512                 return nt;
513         }
514         case MONO_TYPE_VAR: {
515                 MonoType *nt;
516                 int num = mono_type_get_generic_param_num (type);
517                 MonoGenericInst *inst = context->class_inst;
518                 if (!inst)
519                         return NULL;
520                 if (num >= inst->type_argc)
521                         g_error ("VAR %d (%s) cannot be expanded in this context with %d instantiations",
522                                 num, mono_generic_param_info (type->data.generic_param)->name, inst->type_argc);
523                 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
524                 nt->byref = type->byref;
525                 nt->attrs = type->attrs;
526                 return nt;
527         }
528         case MONO_TYPE_SZARRAY: {
529                 MonoClass *eclass = type->data.klass;
530                 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context);
531                 if (!inflated)
532                         return NULL;
533                 nt = mono_metadata_type_dup (image, type);
534                 nt->data.klass = mono_class_from_mono_type (inflated);
535                 mono_metadata_free_type (inflated);
536                 return nt;
537         }
538         case MONO_TYPE_ARRAY: {
539                 MonoClass *eclass = type->data.array->eklass;
540                 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context);
541                 if (!inflated)
542                         return NULL;
543                 nt = mono_metadata_type_dup (image, type);
544                 nt->data.array = g_memdup (nt->data.array, sizeof (MonoArrayType));
545                 nt->data.array->eklass = mono_class_from_mono_type (inflated);
546                 mono_metadata_free_type (inflated);
547                 return nt;
548         }
549         case MONO_TYPE_GENERICINST: {
550                 MonoGenericClass *gclass = type->data.generic_class;
551                 MonoGenericInst *inst;
552                 MonoType *nt;
553                 if (!gclass->context.class_inst->is_open)
554                         return NULL;
555
556                 inst = mono_metadata_inflate_generic_inst (gclass->context.class_inst, context);
557                 if (inst != gclass->context.class_inst)
558                         gclass = mono_metadata_lookup_generic_class (gclass->container_class, inst, gclass->is_dynamic);
559
560                 if (gclass == type->data.generic_class)
561                         return NULL;
562
563                 nt = mono_metadata_type_dup (image, type);
564                 nt->data.generic_class = gclass;
565                 return nt;
566         }
567         case MONO_TYPE_CLASS:
568         case MONO_TYPE_VALUETYPE: {
569                 MonoClass *klass = type->data.klass;
570                 MonoGenericContainer *container = klass->generic_container;
571                 MonoGenericInst *inst;
572                 MonoGenericClass *gclass = NULL;
573                 MonoType *nt;
574
575                 if (!container)
576                         return NULL;
577
578                 /* We can't use context->class_inst directly, since it can have more elements */
579                 inst = mono_metadata_inflate_generic_inst (container->context.class_inst, context);
580                 if (inst == container->context.class_inst)
581                         return NULL;
582
583                 gclass = mono_metadata_lookup_generic_class (klass, inst, klass->image->dynamic);
584
585                 nt = mono_metadata_type_dup (image, type);
586                 nt->type = MONO_TYPE_GENERICINST;
587                 nt->data.generic_class = gclass;
588                 return nt;
589         }
590         default:
591                 return NULL;
592         }
593         return NULL;
594 }
595
596 MonoGenericContext *
597 mono_generic_class_get_context (MonoGenericClass *gclass)
598 {
599         return &gclass->context;
600 }
601
602 MonoGenericContext *
603 mono_class_get_context (MonoClass *class)
604 {
605        return class->generic_class ? mono_generic_class_get_context (class->generic_class) : NULL;
606 }
607
608 /*
609  * mono_class_get_generic_container:
610  *
611  *   Return the generic container of KLASS which should be a generic type definition.
612  */
613 MonoGenericContainer*
614 mono_class_get_generic_container (MonoClass *klass)
615 {
616         g_assert (klass->is_generic);
617
618         return klass->generic_container;
619 }
620
621 /*
622  * mono_class_get_generic_class:
623  *
624  *   Return the MonoGenericClass of KLASS, which should be a generic instance.
625  */
626 MonoGenericClass*
627 mono_class_get_generic_class (MonoClass *klass)
628 {
629         g_assert (klass->is_inflated);
630
631         return klass->generic_class;
632 }
633
634 /*
635  * mono_class_inflate_generic_type_with_mempool:
636  * @mempool: a mempool
637  * @type: a type
638  * @context: a generics context
639  *
640  * The same as mono_class_inflate_generic_type, but allocates the MonoType
641  * from mempool if it is non-NULL.  If it is NULL, the MonoType is
642  * allocated on the heap and is owned by the caller.
643  * The returned type can potentially be the same as TYPE, so it should not be
644  * modified by the caller, and it should be freed using mono_metadata_free_type ().
645  */
646 MonoType*
647 mono_class_inflate_generic_type_with_mempool (MonoImage *image, MonoType *type, MonoGenericContext *context)
648 {
649         MonoType *inflated = NULL; 
650
651         if (context)
652                 inflated = inflate_generic_type (image, type, context);
653
654         if (!inflated) {
655                 MonoType *shared = mono_metadata_get_shared_type (type);
656
657                 if (shared) {
658                         return shared;
659                 } else {
660                         return mono_metadata_type_dup (image, type);
661                 }
662         }
663
664         mono_stats.inflated_type_count++;
665         return inflated;
666 }
667
668 /*
669  * mono_class_inflate_generic_type:
670  * @type: a type
671  * @context: a generics context
672  *
673  * If @type is a generic type and @context is not NULL, instantiate it using the 
674  * generics context @context.
675  *
676  * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
677  * on the heap and is owned by the caller.
678  */
679 MonoType*
680 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
681 {
682         return mono_class_inflate_generic_type_with_mempool (NULL, type, context);
683 }
684
685 /*
686  * mono_class_inflate_generic_type_no_copy:
687  *
688  *   Same as inflate_generic_type_with_mempool, but return TYPE if no inflation
689  * was done.
690  */
691 static MonoType*
692 mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context)
693 {
694         MonoType *inflated = NULL; 
695
696         if (context)
697                 inflated = inflate_generic_type (image, type, context);
698
699         if (!inflated)
700                 return type;
701
702         mono_stats.inflated_type_count++;
703         return inflated;
704 }
705
706 /*
707  * mono_class_inflate_generic_class:
708  *
709  *   Inflate the class GKLASS with CONTEXT.
710  */
711 MonoClass*
712 mono_class_inflate_generic_class (MonoClass *gklass, MonoGenericContext *context)
713 {
714         MonoClass *res;
715         MonoType *inflated;
716
717         inflated = mono_class_inflate_generic_type (&gklass->byval_arg, context);
718
719         res = mono_class_from_mono_type (inflated);
720         mono_metadata_free_type (inflated);
721
722         return res;
723 }
724
725 static MonoGenericContext
726 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with)
727 {
728         MonoGenericInst *class_inst = NULL;
729         MonoGenericInst *method_inst = NULL;
730         MonoGenericContext res;
731
732         if (context->class_inst)
733                 class_inst = mono_metadata_inflate_generic_inst (context->class_inst, inflate_with);
734
735         if (context->method_inst)
736                 method_inst = mono_metadata_inflate_generic_inst (context->method_inst, inflate_with);
737
738         res.class_inst = class_inst;
739         res.method_inst = method_inst;
740
741         return res;
742 }
743
744 /*
745  * mono_class_inflate_generic_method:
746  * @method: a generic method
747  * @context: a generics context
748  *
749  * Instantiate the generic method @method using the generics context @context.
750  *
751  * Returns: the new instantiated method
752  */
753 MonoMethod *
754 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
755 {
756         return mono_class_inflate_generic_method_full (method, NULL, context);
757 }
758
759 /**
760  * mono_class_inflate_generic_method:
761  *
762  * Instantiate method @method with the generic context @context.
763  * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
764  *         Use mono_method_signature () and mono_method_get_header () to get the correct values.
765  */
766 MonoMethod*
767 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
768 {
769         MonoMethod *result;
770         MonoMethodInflated *iresult, *cached;
771         MonoMethodSignature *sig;
772         MonoGenericContext tmp_context;
773         gboolean is_mb_open = FALSE;
774
775         /* The `method' has already been instantiated before => we need to peel out the instantiation and create a new context */
776         while (method->is_inflated) {
777                 MonoGenericContext *method_context = mono_method_get_context (method);
778                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
779
780                 tmp_context = inflate_generic_context (method_context, context);
781                 context = &tmp_context;
782
783                 if (mono_metadata_generic_context_equal (method_context, context))
784                         return method;
785
786                 method = imethod->declaring;
787         }
788
789         if (!method->is_generic && !method->klass->generic_container)
790                 return method;
791
792         /*
793          * The reason for this hack is to fix the behavior of inflating generic methods that come from a MethodBuilder.
794          * What happens is that instantiating a generic MethodBuilder with its own arguments should create a diferent object.
795          * This is opposite to the way non-SRE MethodInfos behave.
796          * 
797          * This happens, for example, when we want to emit a recursive generic method. Given the following C# code:
798          * 
799          * void Example<T> () {
800          *    Example<T> ();
801          * }
802          *  
803          * In Example, the method token must be encoded as: "void Example<!!0>()"
804          * 
805          * The reference to the first generic argument, "!!0", must be explicit otherwise it won't be inflated
806          * properly. To get that we need to inflate the MethodBuilder with its own arguments.
807          * 
808          * On the other hand, inflating a non-SRE generic method with its own arguments should
809          * return itself. For example:
810          * 
811          * MethodInfo m = ... //m is a generic method definition
812          * MethodInfo res = m.MakeGenericMethod (m.GetGenericArguments ());
813          * res == m
814          *
815          * To allow such scenarios we must allow inflation of MethodBuilder to happen in a diferent way than
816          * what happens with regular methods.
817          * 
818          * There is one last touch to this madness, once a TypeBuilder is finished, IOW CreateType() is called,
819          * everything should behave like a regular type or method.
820          * 
821          */
822         is_mb_open = method->is_generic &&
823                 method->klass->image->dynamic && !method->klass->wastypebuilder && /* that is a MethodBuilder from an unfinished TypeBuilder */
824                 context->method_inst == mono_method_get_generic_container (method)->context.method_inst; /* and it's been instantiated with its own arguments.  */
825
826         iresult = g_new0 (MonoMethodInflated, 1);
827         iresult->context = *context;
828         iresult->declaring = method;
829         iresult->method.method.is_mb_open = is_mb_open;
830
831         if (!context->method_inst && method->is_generic)
832                 iresult->context.method_inst = mono_method_get_generic_container (method)->context.method_inst;
833
834         if (!context->class_inst) {
835                 g_assert (!iresult->declaring->klass->generic_class);
836                 if (iresult->declaring->klass->generic_container)
837                         iresult->context.class_inst = iresult->declaring->klass->generic_container->context.class_inst;
838                 else if (iresult->declaring->klass->generic_class)
839                         iresult->context.class_inst = iresult->declaring->klass->generic_class->context.class_inst;
840         }
841
842         mono_loader_lock ();
843         cached = mono_method_inflated_lookup (iresult, FALSE);
844         if (cached) {
845                 mono_loader_unlock ();
846                 g_free (iresult);
847                 return (MonoMethod*)cached;
848         }
849
850         mono_stats.inflated_method_count++;
851
852         inflated_methods_size += sizeof (MonoMethodInflated);
853
854         sig = mono_method_signature (method);
855         if (sig->pinvoke) {
856                 memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
857         } else {
858                 memcpy (&iresult->method.normal, method, sizeof (MonoMethodNormal));
859                 iresult->method.normal.header = NULL;
860         }
861
862         result = (MonoMethod *) iresult;
863         result->is_inflated = TRUE;
864         result->is_generic = FALSE;
865         result->signature = NULL;
866         result->is_mb_open = is_mb_open;
867
868         if (!context->method_inst) {
869                 /* Set the generic_container of the result to the generic_container of method */
870                 MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
871
872                 if (generic_container) {
873                         result->is_generic = 1;
874                         mono_method_set_generic_container (result, generic_container);
875                 }
876         }
877
878         if (!klass_hint || !klass_hint->generic_class ||
879             klass_hint->generic_class->container_class != method->klass ||
880             klass_hint->generic_class->context.class_inst != context->class_inst)
881                 klass_hint = NULL;
882
883         if (method->klass->generic_container)
884                 result->klass = klass_hint;
885
886         if (!result->klass) {
887                 MonoType *inflated = inflate_generic_type (NULL, &method->klass->byval_arg, context);
888                 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
889                 if (inflated)
890                         mono_metadata_free_type (inflated);
891         }
892
893         mono_method_inflated_lookup (iresult, TRUE);
894         mono_loader_unlock ();
895         return result;
896 }
897
898 /**
899  * mono_get_inflated_method:
900  *
901  * Obsolete.  We keep it around since it's mentioned in the public API.
902  */
903 MonoMethod*
904 mono_get_inflated_method (MonoMethod *method)
905 {
906         return method;
907 }
908
909 /*
910  * mono_method_get_context_general:
911  * @method: a method
912  * @uninflated: handle uninflated methods?
913  *
914  * Returns the generic context of a method or NULL if it doesn't have
915  * one.  For an inflated method that's the context stored in the
916  * method.  Otherwise it's in the method's generic container or in the
917  * generic container of the method's class.
918  */
919 MonoGenericContext*
920 mono_method_get_context_general (MonoMethod *method, gboolean uninflated)
921 {
922         if (method->is_inflated) {
923                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
924                 return &imethod->context;
925         }
926         if (!uninflated)
927                 return NULL;
928         if (method->is_generic)
929                 return &(mono_method_get_generic_container (method)->context);
930         if (method->klass->generic_container)
931                 return &method->klass->generic_container->context;
932         return NULL;
933 }
934
935 /*
936  * mono_method_get_context:
937  * @method: a method
938  *
939  * Returns the generic context for method if it's inflated, otherwise
940  * NULL.
941  */
942 MonoGenericContext*
943 mono_method_get_context (MonoMethod *method)
944 {
945         return mono_method_get_context_general (method, FALSE);
946 }
947
948 /*
949  * mono_method_get_generic_container:
950  *
951  *   Returns the generic container of METHOD, which should be a generic method definition.
952  * Returns NULL if METHOD is not a generic method definition.
953  * LOCKING: Acquires the loader lock.
954  */
955 MonoGenericContainer*
956 mono_method_get_generic_container (MonoMethod *method)
957 {
958         MonoGenericContainer *container;
959
960         if (!method->is_generic)
961                 return NULL;
962
963         container = mono_image_property_lookup (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER);
964         g_assert (container);
965
966         return container;
967 }
968
969 /*
970  * mono_method_set_generic_container:
971  *
972  *   Sets the generic container of METHOD to CONTAINER.
973  * LOCKING: Acquires the loader lock.
974  */
975 void
976 mono_method_set_generic_container (MonoMethod *method, MonoGenericContainer* container)
977 {
978         g_assert (method->is_generic);
979
980         mono_image_property_insert (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER, container);
981 }
982
983 /** 
984  * mono_class_find_enum_basetype:
985  * @class: The enum class
986  *
987  *   Determine the basetype of an enum by iterating through its fields. We do this
988  * in a separate function since it is cheaper than calling mono_class_setup_fields.
989  */
990 static MonoType*
991 mono_class_find_enum_basetype (MonoClass *class)
992 {
993         MonoImage *m = class->image; 
994         const int top = class->field.count;
995         int i;
996
997         g_assert (class->enumtype);
998
999         /*
1000          * Fetch all the field information.
1001          */
1002         for (i = 0; i < top; i++){
1003                 const char *sig;
1004                 guint32 cols [MONO_FIELD_SIZE];
1005                 int idx = class->field.first + i;
1006                 MonoGenericContainer *container = NULL;
1007                 MonoType *ftype;
1008
1009                 /* class->field.first and idx points into the fieldptr table */
1010                 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1011                 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1012                 mono_metadata_decode_value (sig, &sig);
1013                 /* FIELD signature == 0x06 */
1014                 g_assert (*sig == 0x06);
1015                 if (class->generic_container)
1016                         container = class->generic_container;
1017                 else if (class->generic_class) {
1018                         MonoClass *gklass = class->generic_class->container_class;
1019
1020                         container = gklass->generic_container;
1021                         g_assert (container);
1022                 }
1023                 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1024                 if (!ftype)
1025                         return NULL;
1026                 if (class->generic_class) {
1027                         //FIXME do we leak here?
1028                         ftype = mono_class_inflate_generic_type (ftype, mono_class_get_context (class));
1029                         ftype->attrs = cols [MONO_FIELD_FLAGS];
1030                 }
1031
1032                 if (class->enumtype && !(cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC))
1033                         return ftype;
1034         }
1035
1036         return NULL;
1037 }
1038
1039 /** 
1040  * mono_class_setup_fields:
1041  * @class: The class to initialize
1042  *
1043  * Initializes the class->fields.
1044  * LOCKING: Assumes the loader lock is held.
1045  */
1046 static void
1047 mono_class_setup_fields (MonoClass *class)
1048 {
1049         MonoImage *m = class->image; 
1050         int top = class->field.count;
1051         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1052         int i, blittable = TRUE;
1053         guint32 real_size = 0;
1054         guint32 packing_size = 0;
1055         gboolean explicit_size;
1056         MonoClassField *field;
1057         MonoGenericContainer *container = NULL;
1058         MonoClass *gklass = NULL;
1059
1060         if (class->size_inited)
1061                 return;
1062
1063         if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1064                 /*
1065                  * This happens when a generic instance of an unfinished generic typebuilder
1066                  * is used as an element type for creating an array type. We can't initialize
1067                  * the fields of this class using the fields of gklass, since gklass is not
1068                  * finished yet, fields could be added to it later.
1069                  */
1070                 return;
1071         }
1072
1073         if (class->generic_class) {
1074                 MonoClass *gklass = class->generic_class->container_class;
1075                 mono_class_setup_fields (gklass);
1076                 top = gklass->field.count;
1077                 class->field.first = gklass->field.first;
1078                 class->field.count = gklass->field.count;
1079         }
1080
1081         class->instance_size = 0;
1082         if (!class->rank)
1083                 class->sizes.class_size = 0;
1084
1085         if (class->parent) {
1086                 /* For generic instances, class->parent might not have been initialized */
1087                 mono_class_init (class->parent);
1088                 if (!class->parent->size_inited)
1089                         mono_class_setup_fields (class->parent);
1090                 class->instance_size += class->parent->instance_size;
1091                 class->min_align = class->parent->min_align;
1092                 /* we use |= since it may have been set already */
1093                 class->has_references |= class->parent->has_references;
1094                 blittable = class->parent->blittable;
1095         } else {
1096                 class->instance_size = sizeof (MonoObject);
1097                 class->min_align = 1;
1098         }
1099
1100         if (class->simd_type)
1101                 class->min_align = 16;
1102
1103         /* Get the real size */
1104         explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1105
1106         if (explicit_size) {
1107                 g_assert ((packing_size & 0xfffffff0) == 0);
1108                 class->packing_size = packing_size;
1109                 real_size += class->instance_size;
1110         }
1111
1112         if (!top) {
1113                 if (explicit_size && real_size) {
1114                         class->instance_size = MAX (real_size, class->instance_size);
1115                 }
1116                 class->size_inited = 1;
1117                 class->blittable = blittable;
1118                 return;
1119         }
1120
1121         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1122                 blittable = FALSE;
1123
1124         /* Prevent infinite loops if the class references itself */
1125         class->size_inited = 1;
1126
1127         class->fields = mono_image_alloc0 (class->image, sizeof (MonoClassField) * top);
1128
1129         if (class->generic_container) {
1130                 container = class->generic_container;
1131         } else if (class->generic_class) {
1132                 gklass = class->generic_class->container_class;
1133                 container = gklass->generic_container;
1134                 g_assert (container);
1135
1136                 mono_class_setup_fields (gklass);
1137
1138                 if (gklass->exception_type) {
1139                         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1140                         return;
1141                 }
1142         }
1143
1144         /*
1145          * Fetch all the field information.
1146          */
1147         for (i = 0; i < top; i++){
1148                 int idx = class->field.first + i;
1149                 field = &class->fields [i];
1150
1151                 field->parent = class;
1152
1153                 if (class->generic_class) {
1154                         MonoClassField *gfield = &gklass->fields [i];
1155
1156                         field->name = mono_field_get_name (gfield);
1157                         /*This memory must come from the image mempool as we don't have a chance to free it.*/
1158                         field->type = mono_class_inflate_generic_type_no_copy (class->image, gfield->type, mono_class_get_context (class));
1159                         g_assert (field->type->attrs == gfield->type->attrs);
1160                         if (mono_field_is_deleted (field))
1161                                 continue;
1162                         field->offset = gfield->offset;
1163                 } else {
1164                         const char *sig;
1165                         guint32 cols [MONO_FIELD_SIZE];
1166
1167                         /* class->field.first and idx points into the fieldptr table */
1168                         mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1169                         /* The name is needed for fieldrefs */
1170                         field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
1171                         sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1172                         mono_metadata_decode_value (sig, &sig);
1173                         /* FIELD signature == 0x06 */
1174                         g_assert (*sig == 0x06);
1175                         field->type = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1176                         if (!field->type) {
1177                                 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1178                                 break;
1179                         }
1180                         if (mono_field_is_deleted (field))
1181                                 continue;
1182                         if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1183                                 guint32 offset;
1184                                 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1185                                 field->offset = offset;
1186                                 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1187                                         g_warning ("%s not initialized correctly (missing field layout info for %s)",
1188                                                            class->name, mono_field_get_name (field));
1189                         }
1190                 }
1191
1192                 /* Only do these checks if we still think this type is blittable */
1193                 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1194                         if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1195                                 blittable = FALSE;
1196                         } else {
1197                                 MonoClass *field_class = mono_class_from_mono_type (field->type);
1198                                 if (field_class)
1199                                         mono_class_setup_fields (field_class);
1200                                 if (!field_class || !field_class->blittable)
1201                                         blittable = FALSE;
1202                         }
1203                 }
1204
1205                 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1206                         class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1207                         blittable = class->element_class->blittable;
1208                 }
1209
1210                 /* The def_value of fields is compute lazily during vtable creation */
1211         }
1212
1213         if (class == mono_defaults.string_class)
1214                 blittable = FALSE;
1215
1216         class->blittable = blittable;
1217
1218         if (class->enumtype && !mono_class_enum_basetype (class)) {
1219                 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
1220                         G_BREAKPOINT ();
1221         }
1222         if (explicit_size && real_size) {
1223                 class->instance_size = MAX (real_size, class->instance_size);
1224         }
1225
1226         if (class->exception_type)
1227                 return;
1228         mono_class_layout_fields (class);
1229 }
1230
1231 /** 
1232  * mono_class_setup_fields_locking:
1233  * @class: The class to initialize
1234  *
1235  * Initializes the class->fields array of fields.
1236  * Aquires the loader lock.
1237  */
1238 static void
1239 mono_class_setup_fields_locking (MonoClass *class)
1240 {
1241         mono_loader_lock ();
1242         mono_class_setup_fields (class);
1243         mono_loader_unlock ();
1244 }
1245
1246 /*
1247  * mono_class_has_references:
1248  *
1249  *   Returns whenever @klass->has_references is set, initializing it if needed.
1250  * Aquires the loader lock.
1251  */
1252 static gboolean
1253 mono_class_has_references (MonoClass *klass)
1254 {
1255         if (klass->init_pending) {
1256                 /* Be conservative */
1257                 return TRUE;
1258         } else {
1259                 mono_class_init (klass);
1260
1261                 return klass->has_references;
1262         }
1263 }
1264
1265 /* useful until we keep track of gc-references in corlib etc. */
1266 #ifdef HAVE_SGEN_GC
1267 #define IS_GC_REFERENCE(t) FALSE
1268 #else
1269 #define IS_GC_REFERENCE(t) ((t)->type == MONO_TYPE_U && class->image == mono_defaults.corlib)
1270 #endif
1271
1272 /*
1273  * mono_type_get_basic_type_from_generic:
1274  * @type: a type
1275  *
1276  * Returns a closed type corresponding to the possibly open type
1277  * passed to it.
1278  */
1279 MonoType*
1280 mono_type_get_basic_type_from_generic (MonoType *type)
1281 {
1282         /* When we do generic sharing we let type variables stand for reference types. */
1283         if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1284                 return &mono_defaults.object_class->byval_arg;
1285         return type;
1286 }
1287
1288 /*
1289  * mono_class_layout_fields:
1290  * @class: a class
1291  *
1292  * Compute the placement of fields inside an object or struct, according to
1293  * the layout rules and set the following fields in @class:
1294  *  - has_references (if the class contains instance references firled or structs that contain references)
1295  *  - has_static_refs (same, but for static fields)
1296  *  - instance_size (size of the object in memory)
1297  *  - class_size (size needed for the static fields)
1298  *  - size_inited (flag set when the instance_size is set)
1299  *
1300  * LOCKING: this is supposed to be called with the loader lock held.
1301  */
1302 void
1303 mono_class_layout_fields (MonoClass *class)
1304 {
1305         int i;
1306         const int top = class->field.count;
1307         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1308         guint32 pass, passes, real_size;
1309         gboolean gc_aware_layout = FALSE;
1310         MonoClassField *field;
1311
1312         /*
1313          * When we do generic sharing we need to have layout
1314          * information for open generic classes (either with a generic
1315          * context containing type variables or with a generic
1316          * container), so we don't return in that case anymore.
1317          */
1318
1319         /*
1320          * Enable GC aware auto layout: in this mode, reference
1321          * fields are grouped together inside objects, increasing collector 
1322          * performance.
1323          * Requires that all classes whose layout is known to native code be annotated
1324          * with [StructLayout (LayoutKind.Sequential)]
1325          * Value types have gc_aware_layout disabled by default, as per
1326          * what the default is for other runtimes.
1327          */
1328          /* corlib is missing [StructLayout] directives in many places */
1329         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1330                 if (class->image != mono_defaults.corlib &&
1331                         class->byval_arg.type != MONO_TYPE_VALUETYPE)
1332                         gc_aware_layout = TRUE;
1333                 /* from System.dll, used in metadata/process.h */
1334                 if (strcmp (class->name, "ProcessStartInfo") == 0)
1335                         gc_aware_layout = FALSE;
1336         }
1337
1338         /* Compute klass->has_references */
1339         /* 
1340          * Process non-static fields first, since static fields might recursively
1341          * refer to the class itself.
1342          */
1343         for (i = 0; i < top; i++) {
1344                 MonoType *ftype;
1345
1346                 field = &class->fields [i];
1347
1348                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1349                         ftype = mono_type_get_underlying_type (field->type);
1350                         ftype = mono_type_get_basic_type_from_generic (ftype);
1351                         if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1352                                 class->has_references = TRUE;
1353                 }
1354         }
1355
1356         for (i = 0; i < top; i++) {
1357                 MonoType *ftype;
1358
1359                 field = &class->fields [i];
1360
1361                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1362                         ftype = mono_type_get_underlying_type (field->type);
1363                         ftype = mono_type_get_basic_type_from_generic (ftype);
1364                         if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1365                                 class->has_static_refs = TRUE;
1366                 }
1367         }
1368
1369         for (i = 0; i < top; i++) {
1370                 MonoType *ftype;
1371
1372                 field = &class->fields [i];
1373
1374                 ftype = mono_type_get_underlying_type (field->type);
1375                 ftype = mono_type_get_basic_type_from_generic (ftype);
1376                 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1377                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1378                                 class->has_static_refs = TRUE;
1379                         else
1380                                 class->has_references = TRUE;
1381                 }
1382         }
1383
1384         /*
1385          * Compute field layout and total size (not considering static fields)
1386          */
1387
1388         switch (layout) {
1389         case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1390         case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1391
1392                 if (gc_aware_layout)
1393                         passes = 2;
1394                 else
1395                         passes = 1;
1396
1397                 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1398                         passes = 1;
1399
1400                 if (class->parent)
1401                         real_size = class->parent->instance_size;
1402                 else
1403                         real_size = sizeof (MonoObject);
1404
1405                 for (pass = 0; pass < passes; ++pass) {
1406                         for (i = 0; i < top; i++){
1407                                 gint32 align;
1408                                 guint32 size;
1409                                 MonoType *ftype;
1410
1411                                 field = &class->fields [i];
1412
1413                                 if (mono_field_is_deleted (field))
1414                                         continue;
1415                                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1416                                         continue;
1417
1418                                 ftype = mono_type_get_underlying_type (field->type);
1419                                 ftype = mono_type_get_basic_type_from_generic (ftype);
1420                                 if (gc_aware_layout) {
1421                                         if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1422                                                 if (pass == 1)
1423                                                         continue;
1424                                         } else {
1425                                                 if (pass == 0)
1426                                                         continue;
1427                                         }
1428                                 }
1429
1430                                 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1431                                         (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1432                                         /* This field is a hack inserted by MCS to empty structures */
1433                                         continue;
1434                                 }
1435
1436                                 size = mono_type_size (field->type, &align);
1437                         
1438                                 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1439                                 align = class->packing_size ? MIN (class->packing_size, align): align;
1440                                 /* if the field has managed references, we need to force-align it
1441                                  * see bug #77788
1442                                  */
1443                                 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1444                                         align = MAX (align, sizeof (gpointer));
1445
1446                                 class->min_align = MAX (align, class->min_align);
1447                                 field->offset = real_size;
1448                                 field->offset += align - 1;
1449                                 field->offset &= ~(align - 1);
1450                                 real_size = field->offset + size;
1451                         }
1452
1453                         class->instance_size = MAX (real_size, class->instance_size);
1454        
1455                         if (class->instance_size & (class->min_align - 1)) {
1456                                 class->instance_size += class->min_align - 1;
1457                                 class->instance_size &= ~(class->min_align - 1);
1458                         }
1459                 }
1460                 break;
1461         case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1462                 real_size = 0;
1463                 for (i = 0; i < top; i++) {
1464                         gint32 align;
1465                         guint32 size;
1466                         MonoType *ftype;
1467
1468                         field = &class->fields [i];
1469
1470                         /*
1471                          * There must be info about all the fields in a type if it
1472                          * uses explicit layout.
1473                          */
1474
1475                         if (mono_field_is_deleted (field))
1476                                 continue;
1477                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1478                                 continue;
1479
1480                         size = mono_type_size (field->type, &align);
1481                         class->min_align = MAX (align, class->min_align);
1482
1483                         /*
1484                          * When we get here, field->offset is already set by the
1485                          * loader (for either runtime fields or fields loaded from metadata).
1486                          * The offset is from the start of the object: this works for both
1487                          * classes and valuetypes.
1488                          */
1489                         field->offset += sizeof (MonoObject);
1490                         ftype = mono_type_get_underlying_type (field->type);
1491                         ftype = mono_type_get_basic_type_from_generic (ftype);
1492                         if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1493                                 if (field->offset % sizeof (gpointer)) {
1494                                         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1495                                 }
1496                         }
1497
1498                         /*
1499                          * Calc max size.
1500                          */
1501                         real_size = MAX (real_size, size + field->offset);
1502                 }
1503                 class->instance_size = MAX (real_size, class->instance_size);
1504                 break;
1505         }
1506
1507         if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1508                 /*
1509                  * For small structs, set min_align to at least the struct size to improve
1510                  * performance, and since the JIT memset/memcpy code assumes this and generates 
1511                  * unaligned accesses otherwise. See #78990 for a testcase.
1512                  */
1513                 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1514                         class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1515         }
1516
1517         class->size_inited = 1;
1518
1519         /*
1520          * Compute static field layout and size
1521          */
1522         for (i = 0; i < top; i++){
1523                 gint32 align;
1524                 guint32 size;
1525
1526                 field = &class->fields [i];
1527                         
1528                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1529                         continue;
1530                 if (mono_field_is_deleted (field))
1531                         continue;
1532
1533                 size = mono_type_size (field->type, &align);
1534                 field->offset = class->sizes.class_size;
1535                 field->offset += align - 1;
1536                 field->offset &= ~(align - 1);
1537                 class->sizes.class_size = field->offset + size;
1538         }
1539 }
1540
1541 static MonoMethod*
1542 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1543 {
1544         MonoMethod *method;
1545
1546         method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1547         method->klass = class;
1548         method->flags = METHOD_ATTRIBUTE_PUBLIC;
1549         method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1550         method->signature = sig;
1551         method->name = name;
1552         method->slot = -1;
1553         /* .ctor */
1554         if (name [0] == '.') {
1555                 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1556         } else {
1557                 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1558         }
1559         return method;
1560 }
1561
1562 /*
1563  * mono_class_setup_methods:
1564  * @class: a class
1565  *
1566  *   Initializes the 'methods' array in the klass.
1567  * Calling this method should be avoided if possible since it allocates a lot 
1568  * of long-living MonoMethod structures.
1569  * Methods belonging to an interface are assigned a sequential slot starting
1570  * from 0.
1571  */
1572 void
1573 mono_class_setup_methods (MonoClass *class)
1574 {
1575         int i;
1576         MonoMethod **methods;
1577
1578         if (class->methods)
1579                 return;
1580
1581         mono_loader_lock ();
1582
1583         if (class->methods) {
1584                 mono_loader_unlock ();
1585                 return;
1586         }
1587
1588         if (class->generic_class) {
1589                 MonoClass *gklass = class->generic_class->container_class;
1590
1591                 mono_class_init (gklass);
1592                 mono_class_setup_methods (gklass);
1593
1594                 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1595                 class->method.count = gklass->method.count;
1596                 methods = g_new0 (MonoMethod *, class->method.count + 1);
1597
1598                 for (i = 0; i < class->method.count; i++) {
1599                         methods [i] = mono_class_inflate_generic_method_full (
1600                                 gklass->methods [i], class, mono_class_get_context (class));
1601                 }
1602         } else if (class->rank) {
1603                 MonoMethod *amethod;
1604                 MonoMethodSignature *sig;
1605                 int count_generic = 0, first_generic = 0;
1606                 int method_num = 0;
1607
1608                 class->method.count = 3 + (class->rank > 1? 2: 1);
1609
1610                 mono_class_setup_interfaces (class);
1611
1612                 if (class->interface_count) {
1613                         count_generic = generic_array_methods (class);
1614                         first_generic = class->method.count;
1615                         class->method.count += class->interface_count * count_generic;
1616                 }
1617
1618                 methods = mono_image_alloc0 (class->image, sizeof (MonoMethod*) * class->method.count);
1619
1620                 sig = mono_metadata_signature_alloc (class->image, class->rank);
1621                 sig->ret = &mono_defaults.void_class->byval_arg;
1622                 sig->pinvoke = TRUE;
1623                 sig->hasthis = TRUE;
1624                 for (i = 0; i < class->rank; ++i)
1625                         sig->params [i] = &mono_defaults.int32_class->byval_arg;
1626
1627                 amethod = create_array_method (class, ".ctor", sig);
1628                 methods [method_num++] = amethod;
1629                 if (class->rank > 1) {
1630                         sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1631                         sig->ret = &mono_defaults.void_class->byval_arg;
1632                         sig->pinvoke = TRUE;
1633                         sig->hasthis = TRUE;
1634                         for (i = 0; i < class->rank * 2; ++i)
1635                                 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1636
1637                         amethod = create_array_method (class, ".ctor", sig);
1638                         methods [method_num++] = amethod;
1639                 }
1640                 /* element Get (idx11, [idx2, ...]) */
1641                 sig = mono_metadata_signature_alloc (class->image, class->rank);
1642                 sig->ret = &class->element_class->byval_arg;
1643                 sig->pinvoke = TRUE;
1644                 sig->hasthis = TRUE;
1645                 for (i = 0; i < class->rank; ++i)
1646                         sig->params [i] = &mono_defaults.int32_class->byval_arg;
1647                 amethod = create_array_method (class, "Get", sig);
1648                 methods [method_num++] = amethod;
1649                 /* element& Address (idx11, [idx2, ...]) */
1650                 sig = mono_metadata_signature_alloc (class->image, class->rank);
1651                 sig->ret = &class->element_class->this_arg;
1652                 sig->pinvoke = TRUE;
1653                 sig->hasthis = TRUE;
1654                 for (i = 0; i < class->rank; ++i)
1655                         sig->params [i] = &mono_defaults.int32_class->byval_arg;
1656                 amethod = create_array_method (class, "Address", sig);
1657                 methods [method_num++] = amethod;
1658                 /* void Set (idx11, [idx2, ...], element) */
1659                 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1660                 sig->ret = &mono_defaults.void_class->byval_arg;
1661                 sig->pinvoke = TRUE;
1662                 sig->hasthis = TRUE;
1663                 for (i = 0; i < class->rank; ++i)
1664                         sig->params [i] = &mono_defaults.int32_class->byval_arg;
1665                 sig->params [i] = &class->element_class->byval_arg;
1666                 amethod = create_array_method (class, "Set", sig);
1667                 methods [method_num++] = amethod;
1668
1669                 for (i = 0; i < class->interface_count; i++)
1670                         setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1671         } else {
1672                 methods = mono_image_alloc (class->image, sizeof (MonoMethod*) * class->method.count);
1673                 for (i = 0; i < class->method.count; ++i) {
1674                         int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1675                         methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1676                 }
1677         }
1678
1679         if (MONO_CLASS_IS_INTERFACE (class))
1680                 for (i = 0; i < class->method.count; ++i)
1681                         methods [i]->slot = i;
1682
1683         /* Needed because of the double-checking locking pattern */
1684         mono_memory_barrier ();
1685
1686         class->methods = methods;
1687
1688         if (mono_debugger_class_loaded_methods_func)
1689                 mono_debugger_class_loaded_methods_func (class);
1690
1691         mono_loader_unlock ();
1692 }
1693
1694 /*
1695  * mono_class_get_method_by_index:
1696  *
1697  *   Returns class->methods [index], initializing class->methods if neccesary.
1698  *
1699  * LOCKING: Acquires the loader lock.
1700  */
1701 MonoMethod*
1702 mono_class_get_method_by_index (MonoClass *class, int index)
1703 {
1704         /* Avoid calling setup_methods () if possible */
1705         if (class->generic_class && !class->methods) {
1706                 MonoClass *gklass = class->generic_class->container_class;
1707                 MonoMethod *m;
1708
1709                 m = mono_class_inflate_generic_method_full (
1710                                 gklass->methods [index], class, mono_class_get_context (class));
1711                 /*
1712                  * If setup_methods () is called later for this class, no duplicates are created,
1713                  * since inflate_generic_method guarantees that only one instance of a method
1714                  * is created for each context.
1715                  */
1716                 /*
1717                 mono_class_setup_methods (class);
1718                 g_assert (m == class->methods [index]);
1719                 */
1720                 return m;
1721         } else {
1722                 mono_class_setup_methods (class);
1723                 g_assert (index >= 0 && index < class->method.count);
1724                 return class->methods [index];
1725         }
1726 }       
1727
1728 /*
1729  * mono_class_get_inflated_method:
1730  *
1731  *   Given an inflated class CLASS and a method METHOD which should be a method of
1732  * CLASS's generic definition, return the inflated method corresponding to METHOD.
1733  */
1734 MonoMethod*
1735 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
1736 {
1737         MonoClass *gklass = class->generic_class->container_class;
1738         int i;
1739
1740         mono_class_setup_methods (gklass);
1741         for (i = 0; i < gklass->method.count; ++i) {
1742                 if (gklass->methods [i] == method) {
1743                         if (class->methods)
1744                                 return class->methods [i];
1745                         else
1746                                 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
1747                 }
1748         }
1749
1750         return NULL;
1751 }       
1752
1753 /*
1754  * mono_class_get_vtable_entry:
1755  *
1756  *   Returns class->vtable [offset], computing it if neccesary.
1757  * LOCKING: Acquires the loader lock.
1758  */
1759 MonoMethod*
1760 mono_class_get_vtable_entry (MonoClass *class, int offset)
1761 {
1762         MonoMethod *m;
1763
1764         if (class->rank == 1) {
1765                 /* 
1766                  * szarrays do not overwrite any methods of Array, so we can avoid
1767                  * initializing their vtables in some cases.
1768                  */
1769                 mono_class_setup_vtable (class->parent);
1770                 if (offset < class->parent->vtable_size)
1771                         return class->parent->vtable [offset];
1772         }
1773
1774         if (class->generic_class) {
1775                 MonoClass *gklass = class->generic_class->container_class;
1776                 mono_class_setup_vtable (gklass);
1777                 m = gklass->vtable [offset];
1778
1779                 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
1780         } else {
1781                 mono_class_setup_vtable (class);
1782                 m = class->vtable [offset];
1783         }
1784
1785         return m;
1786 }
1787
1788 static void
1789 mono_class_setup_properties (MonoClass *class)
1790 {
1791         guint startm, endm, i, j;
1792         guint32 cols [MONO_PROPERTY_SIZE];
1793         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1794         MonoProperty *properties;
1795         guint32 last;
1796
1797         if (class->ext && class->ext->properties)
1798                 return;
1799
1800         mono_loader_lock ();
1801
1802         if (class->ext && class->ext->properties) {
1803                 mono_loader_unlock ();
1804                 return;
1805         }
1806
1807         mono_class_alloc_ext (class);
1808
1809         if (class->generic_class) {
1810                 MonoClass *gklass = class->generic_class->container_class;
1811
1812                 mono_class_init (gklass);
1813                 mono_class_setup_properties (gklass);
1814
1815                 class->ext->property = gklass->ext->property;
1816
1817                 properties = g_new0 (MonoProperty, class->ext->property.count + 1);
1818
1819                 for (i = 0; i < class->ext->property.count; i++) {
1820                         MonoProperty *prop = &properties [i];
1821
1822                         *prop = gklass->ext->properties [i];
1823
1824                         if (prop->get)
1825                                 prop->get = mono_class_inflate_generic_method_full (
1826                                         prop->get, class, mono_class_get_context (class));
1827                         if (prop->set)
1828                                 prop->set = mono_class_inflate_generic_method_full (
1829                                         prop->set, class, mono_class_get_context (class));
1830
1831                         prop->parent = class;
1832                 }
1833         } else {
1834                 class->ext->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1835                 class->ext->property.count = last - class->ext->property.first;
1836
1837                 if (class->ext->property.count)
1838                         mono_class_setup_methods (class);
1839
1840                 properties = mono_image_alloc0 (class->image, sizeof (MonoProperty) * class->ext->property.count);
1841                 for (i = class->ext->property.first; i < last; ++i) {
1842                         mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
1843                         properties [i - class->ext->property.first].parent = class;
1844                         properties [i - class->ext->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
1845                         properties [i - class->ext->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
1846
1847                         startm = mono_metadata_methods_from_property (class->image, i, &endm);
1848                         for (j = startm; j < endm; ++j) {
1849                                 MonoMethod *method;
1850
1851                                 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1852
1853                                 if (class->image->uncompressed_metadata)
1854                                         /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1855                                         method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1856                                 else
1857                                         method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1858
1859                                 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1860                                 case METHOD_SEMANTIC_SETTER:
1861                                         properties [i - class->ext->property.first].set = method;
1862                                         break;
1863                                 case METHOD_SEMANTIC_GETTER:
1864                                         properties [i - class->ext->property.first].get = method;
1865                                         break;
1866                                 default:
1867                                         break;
1868                                 }
1869                         }
1870                 }
1871         }
1872         /*Flush any pending writes as we do double checked locking on class->properties */
1873         mono_memory_barrier ();
1874
1875         /* Leave this assignment as the last op in the function */
1876         class->ext->properties = properties;
1877
1878         mono_loader_unlock ();
1879 }
1880
1881 static MonoMethod**
1882 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
1883 {
1884         MonoMethod **om, **retval;
1885         int count;
1886
1887         for (om = methods, count = 0; *om; ++om, ++count)
1888                 ;
1889
1890         retval = g_new0 (MonoMethod*, count + 1);
1891         count = 0;
1892         for (om = methods, count = 0; *om; ++om, ++count)
1893                 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
1894
1895         return retval;
1896 }
1897
1898 static void
1899 mono_class_setup_events (MonoClass *class)
1900 {
1901         guint startm, endm, i, j;
1902         guint32 cols [MONO_EVENT_SIZE];
1903         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1904         guint32 last;
1905         MonoEvent *events;
1906
1907         if (class->ext && class->ext->events)
1908                 return;
1909
1910         mono_loader_lock ();
1911
1912         if (class->ext && class->ext->events) {
1913                 mono_loader_unlock ();
1914                 return;
1915         }
1916
1917         mono_class_alloc_ext (class);
1918
1919         if (class->generic_class) {
1920                 MonoClass *gklass = class->generic_class->container_class;
1921                 MonoGenericContext *context;
1922
1923                 mono_class_setup_events (gklass);
1924                 class->ext->event = gklass->ext->event;
1925
1926                 class->ext->events = g_new0 (MonoEvent, class->ext->event.count);
1927
1928                 if (class->ext->event.count)
1929                         context = mono_class_get_context (class);
1930
1931                 for (i = 0; i < class->ext->event.count; i++) {
1932                         MonoEvent *event = &class->ext->events [i];
1933                         MonoEvent *gevent = &gklass->ext->events [i];
1934
1935                         event->parent = class;
1936                         event->name = gevent->name;
1937                         event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
1938                         event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
1939                         event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
1940                         event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
1941                         event->attrs = gevent->attrs;
1942                 }
1943
1944                 mono_loader_unlock ();
1945                 return;
1946         }
1947
1948         class->ext->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1949         class->ext->event.count = last - class->ext->event.first;
1950
1951         if (class->ext->event.count)
1952                 mono_class_setup_methods (class);
1953
1954         events = mono_image_alloc0 (class->image, sizeof (MonoEvent) * class->ext->event.count);
1955         for (i = class->ext->event.first; i < last; ++i) {
1956                 MonoEvent *event = &events [i - class->ext->event.first];
1957
1958                 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
1959                 event->parent = class;
1960                 event->attrs = cols [MONO_EVENT_FLAGS];
1961                 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
1962
1963                 startm = mono_metadata_methods_from_event (class->image, i, &endm);
1964                 for (j = startm; j < endm; ++j) {
1965                         MonoMethod *method;
1966
1967                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1968
1969                         if (class->image->uncompressed_metadata)
1970                                 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1971                                 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1972                         else
1973                                 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1974
1975                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1976                         case METHOD_SEMANTIC_ADD_ON:
1977                                 event->add = method;
1978                                 break;
1979                         case METHOD_SEMANTIC_REMOVE_ON:
1980                                 event->remove = method;
1981                                 break;
1982                         case METHOD_SEMANTIC_FIRE:
1983                                 event->raise = method;
1984                                 break;
1985                         case METHOD_SEMANTIC_OTHER: {
1986                                 int n = 0;
1987
1988                                 if (event->other == NULL) {
1989                                         event->other = g_new0 (MonoMethod*, 2);
1990                                 } else {
1991                                         while (event->other [n])
1992                                                 n++;
1993                                         event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
1994                                 }
1995                                 event->other [n] = method;
1996                                 /* NULL terminated */
1997                                 event->other [n + 1] = NULL;
1998                                 break;
1999                         }
2000                         default:
2001                                 break;
2002                         }
2003                 }
2004         }
2005         /*Flush any pending writes as we do double checked locking on class->properties */
2006         mono_memory_barrier ();
2007
2008         /* Leave this assignment as the last op in the function */
2009         class->ext->events = events;
2010
2011         mono_loader_unlock ();
2012 }
2013
2014 /*
2015  * Global pool of interface IDs, represented as a bitset.
2016  * LOCKING: this is supposed to be accessed with the loader lock held.
2017  */
2018 static MonoBitSet *global_interface_bitset = NULL;
2019
2020 /*
2021  * mono_unload_interface_ids:
2022  * @bitset: bit set of interface IDs
2023  *
2024  * When an image is unloaded, the interface IDs associated with
2025  * the image are put back in the global pool of IDs so the numbers
2026  * can be reused.
2027  */
2028 void
2029 mono_unload_interface_ids (MonoBitSet *bitset)
2030 {
2031         mono_loader_lock ();
2032         mono_bitset_sub (global_interface_bitset, bitset);
2033         mono_loader_unlock ();
2034 }
2035
2036 /*
2037  * mono_get_unique_iid:
2038  * @class: interface
2039  *
2040  * Assign a unique integer ID to the interface represented by @class.
2041  * The ID will positive and as small as possible.
2042  * LOCKING: this is supposed to be called with the loader lock held.
2043  * Returns: the new ID.
2044  */
2045 static guint
2046 mono_get_unique_iid (MonoClass *class)
2047 {
2048         int iid;
2049         
2050         g_assert (MONO_CLASS_IS_INTERFACE (class));
2051
2052         if (!global_interface_bitset) {
2053                 global_interface_bitset = mono_bitset_new (128, 0);
2054         }
2055
2056         iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2057         if (iid < 0) {
2058                 int old_size = mono_bitset_size (global_interface_bitset);
2059                 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2060                 mono_bitset_free (global_interface_bitset);
2061                 global_interface_bitset = new_set;
2062                 iid = old_size;
2063         }
2064         mono_bitset_set (global_interface_bitset, iid);
2065         /* set the bit also in the per-image set */
2066         if (class->image->interface_bitset) {
2067                 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2068                         MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2069                         mono_bitset_free (class->image->interface_bitset);
2070                         class->image->interface_bitset = new_set;
2071                 }
2072         } else {
2073                 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2074         }
2075         mono_bitset_set (class->image->interface_bitset, iid);
2076
2077         if (mono_print_vtable) {
2078                 int generic_id;
2079                 char *type_name = mono_type_full_name (&class->byval_arg);
2080                 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2081                         generic_id = class->generic_class->context.class_inst->id;
2082                         g_assert (generic_id != 0);
2083                 } else {
2084                         generic_id = 0;
2085                 }
2086                 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2087                 g_free (type_name);
2088         }
2089
2090         g_assert (iid <= 65535);
2091         return iid;
2092 }
2093
2094 static void
2095 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
2096 {
2097         int i;
2098         MonoClass *ic;
2099
2100         mono_class_setup_interfaces (klass);
2101         
2102         for (i = 0; i < klass->interface_count; i++) {
2103                 ic = klass->interfaces [i];
2104
2105                 if (*res == NULL)
2106                         *res = g_ptr_array_new ();
2107                 g_ptr_array_add (*res, ic);
2108                 mono_class_init (ic);
2109
2110                 collect_implemented_interfaces_aux (ic, res);
2111         }
2112 }
2113
2114 GPtrArray*
2115 mono_class_get_implemented_interfaces (MonoClass *klass)
2116 {
2117         GPtrArray *res = NULL;
2118
2119         collect_implemented_interfaces_aux (klass, &res);
2120         return res;
2121 }
2122
2123 static int
2124 compare_interface_ids (const void *p_key, const void *p_element) {
2125         const MonoClass *key = p_key;
2126         const MonoClass *element = *(MonoClass**) p_element;
2127         
2128         return (key->interface_id - element->interface_id);
2129 }
2130
2131 int
2132 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2133         MonoClass **result = bsearch (
2134                         itf,
2135                         klass->interfaces_packed,
2136                         klass->interface_offsets_count,
2137                         sizeof (MonoClass *),
2138                         compare_interface_ids);
2139         if (result) {
2140                 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2141         } else {
2142                 return -1;
2143         }
2144 }
2145
2146 static void
2147 print_implemented_interfaces (MonoClass *klass) {
2148         GPtrArray *ifaces = NULL;
2149         int i;
2150         int ancestor_level = 0;
2151         
2152         printf ("Packed interface table for class %s has size %d\n", klass->name, klass->interface_offsets_count);
2153         for (i = 0; i < klass->interface_offsets_count; i++)
2154                 printf ("  [%03d][UUID %03d][SLOT %03d][SIZE  %03d] interface %s.%s\n", i,
2155                                 klass->interfaces_packed [i]->interface_id,
2156                                 klass->interface_offsets_packed [i],
2157                                 klass->interfaces_packed [i]->method.count,
2158                                 klass->interfaces_packed [i]->name_space,
2159                                 klass->interfaces_packed [i]->name );
2160         printf ("Interface flags: ");
2161         for (i = 0; i <= klass->max_interface_id; i++)
2162                 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2163                         printf ("(%d,T)", i);
2164                 else
2165                         printf ("(%d,F)", i);
2166         printf ("\n");
2167         printf ("Dump interface flags:");
2168         for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2169                 printf (" %02X", klass->interface_bitmap [i]);
2170         printf ("\n");
2171         while (klass != NULL) {
2172                 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2173                 ifaces = mono_class_get_implemented_interfaces (klass);
2174                 if (ifaces) {
2175                         for (i = 0; i < ifaces->len; i++) {
2176                                 MonoClass *ic = g_ptr_array_index (ifaces, i);
2177                                 printf ("  [UIID %d] interface %s\n", ic->interface_id, ic->name);
2178                                 printf ("  [%03d][UUID %03d][SLOT %03d][SIZE  %03d] interface %s.%s\n", i,
2179                                                 ic->interface_id,
2180                                                 mono_class_interface_offset (klass, ic),
2181                                                 ic->method.count,
2182                                                 ic->name_space,
2183                                                 ic->name );
2184                         }
2185                         g_ptr_array_free (ifaces, TRUE);
2186                 }
2187                 ancestor_level ++;
2188                 klass = klass->parent;
2189         }
2190 }
2191
2192 static MonoClass*
2193 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2194 {
2195         MonoType *args [1];
2196         args [0] = &arg0->byval_arg;
2197
2198         return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2199 }
2200
2201 static MonoClass*
2202 array_class_get_if_rank (MonoClass *class, guint rank)
2203 {
2204         return rank ? mono_array_class_get (class, rank) :  class;
2205 }
2206
2207 static void
2208 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2209 {
2210         valuetype_types [0] = eclass;
2211         if (eclass == mono_defaults.int16_class)
2212                 valuetype_types [1] = mono_defaults.uint16_class;
2213         else if (eclass == mono_defaults.uint16_class)
2214                 valuetype_types [1] = mono_defaults.int16_class;
2215         else if (eclass == mono_defaults.int32_class)
2216                 valuetype_types [1] = mono_defaults.uint32_class;
2217         else if (eclass == mono_defaults.uint32_class)
2218                 valuetype_types [1] = mono_defaults.int32_class;
2219         else if (eclass == mono_defaults.int64_class)
2220                 valuetype_types [1] = mono_defaults.uint64_class;
2221         else if (eclass == mono_defaults.uint64_class)
2222                 valuetype_types [1] = mono_defaults.int64_class;
2223         else if (eclass == mono_defaults.byte_class)
2224                 valuetype_types [1] = mono_defaults.sbyte_class;
2225         else if (eclass == mono_defaults.sbyte_class)
2226                 valuetype_types [1] = mono_defaults.byte_class;
2227         else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2228                 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2229 }
2230
2231 /* this won't be needed once bug #325495 is completely fixed
2232  * though we'll need something similar to know which interfaces to allow
2233  * in arrays when they'll be lazyly created
2234  * 
2235  * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2236  * MS returns diferrent types based on which instance is called. For example:
2237  *      object obj = new byte[10][];
2238  *      Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2239  *      Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2240  *      a != b ==> true
2241  * 
2242  * Fixing this should kill quite some code, save some bits and improve compatbility.
2243  */
2244 static MonoClass**
2245 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2246 {
2247         MonoClass *eclass = class->element_class;
2248         static MonoClass* generic_icollection_class = NULL;
2249         static MonoClass* generic_ienumerable_class = NULL;
2250         static MonoClass* generic_ienumerator_class = NULL;
2251         MonoClass *valuetype_types[2] = { NULL, NULL };
2252         MonoClass **interfaces = NULL;
2253         int i, interface_count, real_count, original_rank;
2254         int all_interfaces;
2255         gboolean internal_enumerator;
2256         gboolean eclass_is_valuetype;
2257
2258         if (!mono_defaults.generic_ilist_class) {
2259                 *num = 0;
2260                 return NULL;
2261         }
2262         internal_enumerator = FALSE;
2263         eclass_is_valuetype = FALSE;
2264         original_rank = eclass->rank;
2265         if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2266                 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0)  {
2267                         /*
2268                          * For a Enumerator<T[]> we need to get the list of interfaces for T.
2269                          */
2270                         eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2271                         original_rank = eclass->rank;
2272                         eclass = eclass->element_class;
2273                         internal_enumerator = TRUE;
2274                         *is_enumerator = TRUE;
2275                 } else {
2276                         *num = 0;
2277                         return NULL;
2278                 }
2279         }
2280
2281         /* 
2282          * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2283          * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2284          */
2285         all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2286
2287         if (!generic_icollection_class) {
2288                 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2289                         "System.Collections.Generic", "ICollection`1");
2290                 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2291                         "System.Collections.Generic", "IEnumerable`1");
2292                 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2293                         "System.Collections.Generic", "IEnumerator`1");
2294         }
2295
2296         mono_class_init (eclass);
2297
2298         /*
2299          * Arrays in 2.0 need to implement a number of generic interfaces
2300          * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2301          * on the element class). We collect the types needed to build the
2302          * instantiations in interfaces at intervals of 3, because 3 are
2303          * the generic interfaces needed to implement.
2304          */
2305         if (eclass->valuetype) {
2306                 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2307
2308                 /* IList, ICollection, IEnumerable */
2309                 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2310                 if (internal_enumerator) {
2311                         ++real_count;
2312                         if (valuetype_types [1])
2313                                 ++real_count;
2314                 }
2315
2316                 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2317                 interfaces [0] = valuetype_types [0];
2318                 if (valuetype_types [1])
2319                         interfaces [3] = valuetype_types [1];
2320
2321                 eclass_is_valuetype = TRUE;
2322         } else {
2323                 int j;
2324                 int idepth = eclass->idepth;
2325                 if (!internal_enumerator)
2326                         idepth--;
2327                 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2328                 /* we add object for interfaces and the supertypes for the other
2329                  * types. The last of the supertypes is the element class itself which we
2330                  * already created the explicit interfaces for (so we include it for IEnumerator
2331                  * and exclude it for arrays).
2332                  */
2333                 if (MONO_CLASS_IS_INTERFACE (eclass))
2334                         interface_count++;
2335                 else
2336                         interface_count += idepth;
2337                 if (eclass->rank && eclass->element_class->valuetype) {
2338                         fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2339                         if (valuetype_types [1])
2340                                 ++interface_count;
2341                 }
2342                 /* IList, ICollection, IEnumerable */
2343                 interface_count *= 3;
2344                 real_count = interface_count;
2345                 if (internal_enumerator) {
2346                         real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2347                         if (valuetype_types [1])
2348                                 ++real_count;
2349                 }
2350                 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2351                 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2352                         interfaces [0] = mono_defaults.object_class;
2353                         j = 3;
2354                 } else {
2355                         j = 0;
2356                         for (i = 0; i < idepth; i++) {
2357                                 mono_class_init (eclass->supertypes [i]);
2358                                 interfaces [j] = eclass->supertypes [i];
2359                                 j += 3;
2360                         }
2361                 }
2362                 if (all_interfaces) {
2363                         for (i = 0; i < eclass->interface_offsets_count; i++) {
2364                                 interfaces [j] = eclass->interfaces_packed [i];
2365                                 j += 3;
2366                         }
2367                 } else {
2368                         for (i = 0; i < eclass->interface_count; i++) {
2369                                 interfaces [j] = eclass->interfaces [i];
2370                                 j += 3;
2371                         }
2372                 }
2373                 if (valuetype_types [1]) {
2374                         interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2375                         j += 3;
2376                 }
2377         }
2378
2379         /* instantiate the generic interfaces */
2380         for (i = 0; i < interface_count; i += 3) {
2381                 MonoClass *iface = interfaces [i];
2382
2383                 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2384                 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2385                 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2386         }
2387         if (internal_enumerator) {
2388                 int j;
2389                 /* instantiate IEnumerator<iface> */
2390                 for (i = 0; i < interface_count; i++) {
2391                         interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2392                 }
2393                 j = interface_count;
2394                 if (!eclass_is_valuetype) {
2395                         if (MONO_CLASS_IS_INTERFACE (eclass)) {
2396                                 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2397                                 j ++;
2398                         } else {
2399                                 for (i = 0; i < eclass->idepth; i++) {
2400                                         interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2401                                         j ++;
2402                                 }
2403                         }
2404                         for (i = 0; i < eclass->interface_offsets_count; i++) {
2405                                 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2406                                 j ++;
2407                         }
2408                 } else {
2409                         interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2410                 }
2411                 if (valuetype_types [1])
2412                         interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2413         }
2414 #if 0
2415         {
2416         char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2417         for (i = 0; i  < real_count; ++i) {
2418                 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2419                 g_print ("%s implements %s\n", type_name, name);
2420                 g_free (name);
2421         }
2422         g_free (type_name);
2423         }
2424 #endif
2425         *num = real_count;
2426         return interfaces;
2427 }
2428
2429 static int
2430 find_array_interface (MonoClass *klass, const char *name)
2431 {
2432         int i;
2433         for (i = 0; i < klass->interface_count; ++i) {
2434                 if (strcmp (klass->interfaces [i]->name, name) == 0)
2435                         return i;
2436         }
2437         return -1;
2438 }
2439
2440 /*
2441  * LOCKING: this is supposed to be called with the loader lock held.
2442  */
2443 static int
2444 setup_interface_offsets (MonoClass *class, int cur_slot)
2445 {
2446         MonoClass *k, *ic;
2447         int i, max_iid;
2448         MonoClass **interfaces_full;
2449         int *interface_offsets_full;
2450         GPtrArray *ifaces;
2451         int interface_offsets_count;
2452         MonoClass **array_interfaces;
2453         int num_array_interfaces;
2454         int is_enumerator = FALSE;
2455
2456         /* 
2457          * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
2458          * implicit interfaces have the property that they are assigned the same slot in the
2459          * vtables for compatible interfaces
2460          */
2461         array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
2462
2463         /* compute maximum number of slots and maximum interface id */
2464         max_iid = 0;
2465         for (k = class; k ; k = k->parent) {
2466                 for (i = 0; i < k->interface_count; i++) {
2467                         ic = k->interfaces [i];
2468
2469                         if (!ic->inited)
2470                                 mono_class_init (ic);
2471
2472                         if (max_iid < ic->interface_id)
2473                                 max_iid = ic->interface_id;
2474                 }
2475                 ifaces = mono_class_get_implemented_interfaces (k);
2476                 if (ifaces) {
2477                         for (i = 0; i < ifaces->len; ++i) {
2478                                 ic = g_ptr_array_index (ifaces, i);
2479                                 if (max_iid < ic->interface_id)
2480                                         max_iid = ic->interface_id;
2481                         }
2482                         g_ptr_array_free (ifaces, TRUE);
2483                 }
2484         }
2485         for (i = 0; i < num_array_interfaces; ++i) {
2486                 ic = array_interfaces [i];
2487                 mono_class_init (ic);
2488                 if (max_iid < ic->interface_id)
2489                         max_iid = ic->interface_id;
2490         }
2491
2492         if (MONO_CLASS_IS_INTERFACE (class)) {
2493                 if (max_iid < class->interface_id)
2494                         max_iid = class->interface_id;
2495         }
2496         class->max_interface_id = max_iid;
2497         /* compute vtable offset for interfaces */
2498         interfaces_full = g_malloc (sizeof (MonoClass*) * (max_iid + 1));
2499         interface_offsets_full = g_malloc (sizeof (int) * (max_iid + 1));
2500
2501         for (i = 0; i <= max_iid; i++) {
2502                 interfaces_full [i] = NULL;
2503                 interface_offsets_full [i] = -1;
2504         }
2505
2506         ifaces = mono_class_get_implemented_interfaces (class);
2507         if (ifaces) {
2508                 for (i = 0; i < ifaces->len; ++i) {
2509                         ic = g_ptr_array_index (ifaces, i);
2510                         interfaces_full [ic->interface_id] = ic;
2511                         interface_offsets_full [ic->interface_id] = cur_slot;
2512                         cur_slot += ic->method.count;
2513                 }
2514                 g_ptr_array_free (ifaces, TRUE);
2515         }
2516
2517         for (k = class->parent; k ; k = k->parent) {
2518                 ifaces = mono_class_get_implemented_interfaces (k);
2519                 if (ifaces) {
2520                         for (i = 0; i < ifaces->len; ++i) {
2521                                 ic = g_ptr_array_index (ifaces, i);
2522
2523                                 if (interface_offsets_full [ic->interface_id] == -1) {
2524                                         int io = mono_class_interface_offset (k, ic);
2525
2526                                         g_assert (io >= 0);
2527
2528                                         interfaces_full [ic->interface_id] = ic;
2529                                         interface_offsets_full [ic->interface_id] = io;
2530                                 }
2531                         }
2532                         g_ptr_array_free (ifaces, TRUE);
2533                 }
2534         }
2535
2536         if (MONO_CLASS_IS_INTERFACE (class)) {
2537                 interfaces_full [class->interface_id] = class;
2538                 interface_offsets_full [class->interface_id] = cur_slot;
2539         }
2540
2541         if (num_array_interfaces) {
2542                 if (is_enumerator) {
2543                         int ienumerator_offset;
2544                         int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
2545                         ienumerator_offset = interface_offsets_full [class->interfaces [ienumerator_idx]->interface_id];
2546                         for (i = 0; i < num_array_interfaces; ++i) {
2547                                 ic = array_interfaces [i];
2548                                 interfaces_full [ic->interface_id] = ic;
2549                                 if (strcmp (ic->name, "IEnumerator`1") == 0)
2550                                         interface_offsets_full [ic->interface_id] = ienumerator_offset;
2551                                 else
2552                                         g_assert_not_reached ();
2553                                 /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, interface_offsets_full [ic->interface_id], class->interfaces [0]->name);*/
2554                         }
2555                 } else {
2556                         int ilist_offset, icollection_offset, ienumerable_offset;
2557                         int ilist_iface_idx = find_array_interface (class, "IList`1");
2558                         int icollection_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "ICollection`1");
2559                         int ienumerable_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "IEnumerable`1");
2560                         ilist_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interface_id];
2561                         icollection_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [icollection_iface_idx]->interface_id];
2562                         ienumerable_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [ienumerable_iface_idx]->interface_id];
2563                         g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
2564                         for (i = 0; i < num_array_interfaces; ++i) {
2565                                 ic = array_interfaces [i];
2566                                 interfaces_full [ic->interface_id] = ic;
2567                                 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
2568                                         interface_offsets_full [ic->interface_id] = ilist_offset;
2569                                 else if (strcmp (ic->name, "ICollection`1") == 0)
2570                                         interface_offsets_full [ic->interface_id] = icollection_offset;
2571                                 else if (strcmp (ic->name, "IEnumerable`1") == 0)
2572                                         interface_offsets_full [ic->interface_id] = ienumerable_offset;
2573                                 else
2574                                         g_assert_not_reached ();
2575                                 /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, interface_offsets_full [ic->interface_id], class->interfaces [0]->name);*/
2576                         }
2577                 }
2578         }
2579
2580         for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2581                 if (interface_offsets_full [i] != -1) {
2582                         interface_offsets_count ++;
2583                 }
2584         }
2585
2586         /*
2587          * We might get called twice: once from mono_class_init () then once from 
2588          * mono_class_setup_vtable ().
2589          */
2590         if (class->interfaces_packed) {
2591                 g_assert (class->interface_offsets_count == interface_offsets_count);
2592         } else {
2593                 class->interface_offsets_count = interface_offsets_count;
2594                 class->interfaces_packed = mono_image_alloc (class->image, sizeof (MonoClass*) * interface_offsets_count);
2595                 class->interface_offsets_packed = mono_image_alloc (class->image, sizeof (guint16) * interface_offsets_count);
2596                 class->interface_bitmap = mono_image_alloc0 (class->image, (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0));
2597                 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2598                         if (interface_offsets_full [i] != -1) {
2599                                 class->interface_bitmap [i >> 3] |= (1 << (i & 7));
2600                                 class->interfaces_packed [interface_offsets_count] = interfaces_full [i];
2601                                 class->interface_offsets_packed [interface_offsets_count] = interface_offsets_full [i];
2602                                 /*if (num_array_interfaces)
2603                                   g_print ("type %s has %s offset at %d\n", mono_type_get_name_full (&class->byval_arg, 0), mono_type_get_name_full (&interfaces_full [i]->byval_arg, 0), interface_offsets_full [i]);*/
2604                                 interface_offsets_count ++;
2605                         }
2606                 }
2607         }
2608         
2609         g_free (interfaces_full);
2610         g_free (interface_offsets_full);
2611         g_free (array_interfaces);
2612         
2613         //printf ("JUST DONE: ");
2614         //print_implemented_interfaces (class);
2615  
2616         return cur_slot;
2617 }
2618
2619 /*
2620  * Setup interface offsets for interfaces. 
2621  * Initializes:
2622  * - class->max_interface_id
2623  * - class->interface_offsets_count
2624  * - class->interfaces_packed
2625  * - class->interface_offsets_packed
2626  * - class->interface_bitmap
2627  */
2628 void
2629 mono_class_setup_interface_offsets (MonoClass *class)
2630 {
2631         mono_loader_lock ();
2632
2633         setup_interface_offsets (class, 0);
2634
2635         mono_loader_unlock ();
2636 }
2637  
2638 /*
2639  * mono_class_setup_vtable:
2640  *
2641  *   Creates the generic vtable of CLASS.
2642  * Initializes the following fields in MonoClass:
2643  * - vtable
2644  * - vtable_size
2645  * Plus all the fields initialized by setup_interface_offsets ().
2646  * If there is an error during vtable construction, class->exception_type is set.
2647  *
2648  * LOCKING: Acquires the loader lock.
2649  */
2650 void
2651 mono_class_setup_vtable (MonoClass *class)
2652 {
2653         MonoMethod **overrides;
2654         MonoGenericContext *context;
2655         guint32 type_token;
2656         int onum = 0;
2657         int i;
2658         gboolean ok = TRUE;
2659
2660         if (class->vtable)
2661                 return;
2662
2663         if (mono_debug_using_mono_debugger ())
2664                 /* The debugger currently depends on this */
2665                 mono_class_setup_methods (class);
2666
2667         if (MONO_CLASS_IS_INTERFACE (class)) {
2668                 /* This sets method->slot for all methods if this is an interface */
2669                 mono_class_setup_methods (class);
2670                 return;
2671         }
2672
2673         mono_loader_lock ();
2674
2675         if (class->vtable) {
2676                 mono_loader_unlock ();
2677                 return;
2678         }
2679
2680         mono_stats.generic_vtable_count ++;
2681
2682         if (class->generic_class) {
2683                 context = mono_class_get_context (class);
2684                 type_token = class->generic_class->container_class->type_token;
2685         } else {
2686                 context = (MonoGenericContext *) class->generic_container;              
2687                 type_token = class->type_token;
2688         }
2689
2690         if (class->image->dynamic) {
2691                 if (class->generic_class) {
2692                         MonoClass *gklass = class->generic_class->container_class;
2693
2694                         mono_reflection_get_dynamic_overrides (gklass, &overrides, &onum);
2695                         for (i = 0; i < onum; ++i) {
2696                                 MonoMethod *override = overrides [(i * 2) + 1];
2697                                 MonoMethod *inflated = NULL;
2698                                 int j;
2699
2700                                 for (j = 0; j < class->method.count; ++j) {
2701                                         if (gklass->methods [j] == override) {
2702                                                 inflated = class->methods [j];
2703                                                 break;
2704                                         }
2705                                 }
2706                                 g_assert (inflated);
2707                                                 
2708                                 overrides [(i * 2) + 1] = inflated;
2709                         }
2710                 } else {
2711                         mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
2712                 }
2713         } else {
2714                 /* The following call fails if there are missing methods in the type */
2715                 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
2716         }
2717
2718         if (ok)
2719                 mono_class_setup_vtable_general (class, overrides, onum);
2720                 
2721         g_free (overrides);
2722
2723         mono_loader_unlock ();
2724
2725         return;
2726 }
2727
2728 #define DEBUG_INTERFACE_VTABLE_CODE 0
2729 #define TRACE_INTERFACE_VTABLE_CODE 0
2730 #define VERIFY_INTERFACE_VTABLE_CODE 0
2731
2732 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2733 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
2734         stmt;\
2735 } while (0)
2736 #else
2737 #define DEBUG_INTERFACE_VTABLE(stmt)
2738 #endif
2739
2740 #if TRACE_INTERFACE_VTABLE_CODE
2741 #define TRACE_INTERFACE_VTABLE(stmt) do {\
2742         stmt;\
2743 } while (0)
2744 #else
2745 #define TRACE_INTERFACE_VTABLE(stmt)
2746 #endif
2747
2748 #if VERIFY_INTERFACE_VTABLE_CODE
2749 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
2750         stmt;\
2751 } while (0)
2752 #else
2753 #define VERIFY_INTERFACE_VTABLE(stmt)
2754 #endif
2755
2756
2757 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2758 static char*
2759 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
2760 {
2761         int i;
2762         char *result;
2763         GString *res = g_string_new ("");
2764         
2765         g_string_append_c (res, '(');
2766         for (i = 0; i < sig->param_count; ++i) {
2767                 if (i > 0)
2768                         g_string_append_c (res, ',');
2769                 mono_type_get_desc (res, sig->params [i], include_namespace);
2770         }
2771         g_string_append (res, ")=>");
2772         if (sig->ret != NULL) {
2773                 mono_type_get_desc (res, sig->ret, include_namespace);
2774         } else {
2775                 g_string_append (res, "NULL");
2776         }
2777         result = res->str;
2778         g_string_free (res, FALSE);
2779         return result;
2780 }
2781 static void
2782 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
2783         char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
2784         char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
2785         printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
2786         g_free (im_sig);
2787         g_free (cm_sig);
2788         
2789 }
2790
2791 #endif
2792 static gboolean
2793 check_interface_method_override (MonoClass *class, MonoMethod *im, MonoMethod *cm, gboolean require_newslot, gboolean interface_is_explicitly_implemented_by_class, gboolean slot_is_empty, gboolean security_enabled) {
2794         if (strcmp (im->name, cm->name) == 0) {
2795                 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
2796                         TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
2797                         return FALSE;
2798                 }
2799                 if (! slot_is_empty) {
2800                         if (require_newslot) {
2801                                 if (! interface_is_explicitly_implemented_by_class) {
2802                                         TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
2803                                         return FALSE;
2804                                 }
2805                                 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
2806                                         TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
2807                                         return FALSE;
2808                                 }
2809                         } else {
2810                                 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
2811                         }
2812                 }
2813                 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2814                         TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED  "));
2815                         TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2816                         TRACE_INTERFACE_VTABLE (printf ("]"));
2817                         return FALSE;
2818                 }
2819                 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
2820                 /* CAS - SecurityAction.InheritanceDemand on interface */
2821                 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2822                         mono_secman_inheritancedemand_method (cm, im);
2823                 }
2824
2825                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
2826                         mono_security_core_clr_check_override (class, cm, im);
2827                 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
2828                 return TRUE;
2829         } else {
2830                 MonoClass *ic = im->klass;
2831                 const char *ic_name_space = ic->name_space;
2832                 const char *ic_name = ic->name;
2833                 char *subname;
2834                 
2835                 if (! require_newslot) {
2836                         TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
2837                         return FALSE;
2838                 }
2839                 if (cm->klass->rank == 0) {
2840                         TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
2841                         return FALSE;
2842                 }
2843                 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2844                         TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED  "));
2845                         TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2846                         TRACE_INTERFACE_VTABLE (printf ("]"));
2847                         return FALSE;
2848                 }
2849                 if (mono_class_get_image (ic) != mono_defaults.corlib) {
2850                         TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
2851                         return FALSE;
2852                 }
2853                 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
2854                         TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
2855                         return FALSE;
2856                 }
2857                 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
2858                         TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
2859                         return FALSE;
2860                 }
2861                 
2862                 subname = strstr (cm->name, ic_name_space);
2863                 if (subname != cm->name) {
2864                         TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
2865                         return FALSE;
2866                 }
2867                 subname += strlen (ic_name_space);
2868                 if (subname [0] != '.') {
2869                         TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
2870                         return FALSE;
2871                 }
2872                 subname ++;
2873                 if (strstr (subname, ic_name) != subname) {
2874                         TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
2875                         return FALSE;
2876                 }
2877                 subname += strlen (ic_name);
2878                 if (subname [0] != '.') {
2879                         TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
2880                         return FALSE;
2881                 }
2882                 subname ++;
2883                 if (strcmp (subname, im->name) != 0) {
2884                         TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
2885                         return FALSE;
2886                 }
2887                 
2888                 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
2889                 /* CAS - SecurityAction.InheritanceDemand on interface */
2890                 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2891                         mono_secman_inheritancedemand_method (cm, im);
2892                 }
2893
2894                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
2895                         mono_security_core_clr_check_override (class, cm, im);
2896                 
2897                 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
2898                 return TRUE;
2899         }
2900 }
2901
2902 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2903 static void
2904 foreach_override (gpointer key, gpointer value, gpointer user_data) {
2905         MonoMethod *method = key;
2906         MonoMethod *override = value;
2907         MonoClass *method_class = mono_method_get_class (method);
2908         MonoClass *override_class = mono_method_get_class (override);
2909         
2910         printf ("  Method '%s.%s:%s' has override '%s.%s:%s'\n",
2911                         mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
2912                         mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
2913 }
2914 static void
2915 print_overrides (GHashTable *override_map, const char *message) {
2916         if (override_map) {
2917                 printf ("Override map \"%s\" START:\n", message);
2918                 g_hash_table_foreach (override_map, foreach_override, NULL);
2919                 printf ("Override map \"%s\" END.\n", message);
2920         } else {
2921                 printf ("Override map \"%s\" EMPTY.\n", message);
2922         }
2923 }
2924 static void
2925 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
2926         char *full_name = mono_type_full_name (&class->byval_arg);
2927         int i;
2928         int parent_size;
2929         
2930         printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
2931         
2932         if (print_interfaces) {
2933                 print_implemented_interfaces (class);
2934                 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
2935         }
2936         
2937         if (class->parent) {
2938                 parent_size = class->parent->vtable_size;
2939         } else {
2940                 parent_size = 0;
2941         }
2942         for (i = 0; i < size; ++i) {
2943                 MonoMethod *cm = vtable [i];
2944                 if (cm) {
2945                         char *cm_name = mono_method_full_name (cm, TRUE);
2946                         char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
2947                         printf ("  [%c][%03d][INDEX %03d] %s\n", newness, i, cm->slot, cm_name);
2948                         g_free (cm_name);
2949                 }
2950         }
2951
2952         g_free (full_name);
2953 }
2954 #endif
2955
2956 #if VERIFY_INTERFACE_VTABLE_CODE
2957 static int
2958 mono_method_try_get_vtable_index (MonoMethod *method)
2959 {
2960         if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2961                 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
2962                 if (imethod->declaring->is_generic)
2963                         return imethod->declaring->slot;
2964         }
2965         return method->slot;
2966 }
2967
2968 static void
2969 mono_class_verify_vtable (MonoClass *class)
2970 {
2971         int i;
2972         char *full_name = mono_type_full_name (&class->byval_arg);
2973
2974         printf ("*** Verifying VTable of class '%s' \n", full_name);
2975         g_free (full_name);
2976         full_name = NULL;
2977         
2978         if (!class->methods)
2979                 return;
2980
2981         for (i = 0; i < class->method.count; ++i) {
2982                 MonoMethod *cm = class->methods [i];
2983                 int slot;
2984
2985                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
2986                         continue;
2987
2988                 g_free (full_name);
2989                 full_name = mono_method_full_name (cm, TRUE);
2990
2991                 slot = mono_method_try_get_vtable_index (cm);
2992                 if (slot >= 0) {
2993                         if (slot >= class->vtable_size) {
2994                                 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
2995                                 continue;
2996                         }
2997
2998                         if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
2999                                 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3000                                 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3001                                 g_free (other_name);
3002                         }
3003                 } else
3004                         printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3005         }
3006         g_free (full_name);
3007 }
3008 #endif
3009
3010 static void
3011 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3012         int index;
3013         char *method_signature;
3014         
3015         for (index = 0; index < onum; ++index) {
3016                 g_print (" at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name, 
3017                          overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3018         }
3019         method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3020         printf ("no implementation for interface method %s::%s(%s) in class %s.%s\n",
3021                 mono_type_get_name (&ic->byval_arg), im->name, method_signature, class->name_space, class->name);
3022         g_free (method_signature);
3023         mono_class_setup_methods (class);
3024         for (index = 0; index < class->method.count; ++index) {
3025                 MonoMethod *cm = class->methods [index];
3026                 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3027
3028                 printf ("METHOD %s(%s)\n", cm->name, method_signature);
3029                 g_free (method_signature);
3030         }
3031 }
3032
3033 /*
3034  * LOCKING: this is supposed to be called with the loader lock held.
3035  */
3036 void
3037 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
3038 {
3039         MonoClass *k, *ic;
3040         MonoMethod **vtable;
3041         int i, max_vtsize = 0, max_iid, cur_slot = 0;
3042         GPtrArray *ifaces = NULL;
3043         GHashTable *override_map = NULL;
3044         gboolean security_enabled = mono_is_security_manager_active ();
3045         MonoMethod *cm;
3046         gpointer class_iter;
3047 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3048         int first_non_interface_slot;
3049 #endif
3050
3051         if (class->vtable)
3052                 return;
3053
3054         ifaces = mono_class_get_implemented_interfaces (class);
3055         if (ifaces) {
3056                 for (i = 0; i < ifaces->len; i++) {
3057                         MonoClass *ic = g_ptr_array_index (ifaces, i);
3058                         max_vtsize += ic->method.count;
3059                 }
3060                 g_ptr_array_free (ifaces, TRUE);
3061                 ifaces = NULL;
3062         }
3063         
3064         if (class->parent) {
3065                 mono_class_init (class->parent);
3066                 mono_class_setup_vtable (class->parent);
3067                 max_vtsize += class->parent->vtable_size;
3068                 cur_slot = class->parent->vtable_size;
3069         }
3070
3071         max_vtsize += class->method.count;
3072
3073         vtable = alloca (sizeof (gpointer) * max_vtsize);
3074         memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3075
3076         /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3077
3078         cur_slot = setup_interface_offsets (class, cur_slot);
3079         max_iid = class->max_interface_id;
3080         DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3081
3082         /* Optimized version for generic instances */
3083         if (class->generic_class) {
3084                 MonoClass *gklass = class->generic_class->container_class;
3085                 MonoMethod **tmp;
3086
3087                 mono_class_setup_vtable (gklass);
3088
3089                 tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * gklass->vtable_size);
3090                 class->vtable_size = gklass->vtable_size;
3091                 for (i = 0; i < gklass->vtable_size; ++i)
3092                         if (gklass->vtable [i]) {
3093                                 tmp [i] = mono_class_inflate_generic_method_full (gklass->vtable [i], class, mono_class_get_context (class));
3094                                 tmp [i]->slot = gklass->vtable [i]->slot;
3095                         }
3096                 mono_memory_barrier ();
3097                 class->vtable = tmp;
3098
3099                 /* Have to set method->slot for abstract virtual methods */
3100                 if (class->methods && gklass->methods) {
3101                         for (i = 0; i < class->method.count; ++i)
3102                                 if (class->methods [i]->slot == -1)
3103                                         class->methods [i]->slot = gklass->methods [i]->slot;
3104                 }
3105
3106                 return;
3107         }
3108
3109         if (class->parent && class->parent->vtable_size) {
3110                 MonoClass *parent = class->parent;
3111                 int i;
3112                 
3113                 memcpy (vtable, parent->vtable,  sizeof (gpointer) * parent->vtable_size);
3114                 
3115                 // Also inherit parent interface vtables, just as a starting point.
3116                 // This is needed otherwise bug-77127.exe fails when the property methods
3117                 // have different names in the iterface and the class, because for child
3118                 // classes the ".override" information is not used anymore.
3119                 for (i = 0; i < parent->interface_offsets_count; i++) {
3120                         MonoClass *parent_interface = parent->interfaces_packed [i];
3121                         int interface_offset = mono_class_interface_offset (class, parent_interface);
3122                         
3123                         if (interface_offset >= parent->vtable_size) {
3124                                 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
3125                                 int j;
3126                                 
3127                                 mono_class_setup_methods (parent_interface);
3128                                 TRACE_INTERFACE_VTABLE (printf ("    +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
3129                                 for (j = 0; j < parent_interface->method.count; j++) {
3130                                         vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
3131                                         TRACE_INTERFACE_VTABLE (printf ("    --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
3132                                                         parent_interface_offset + j, parent_interface_offset, j,
3133                                                         interface_offset + j, interface_offset, j));
3134                                 }
3135                         }
3136                         
3137                 }
3138         }
3139
3140         TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
3141         /* override interface methods */
3142         for (i = 0; i < onum; i++) {
3143                 MonoMethod *decl = overrides [i*2];
3144                 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
3145                         int dslot;
3146                         dslot = mono_method_get_vtable_slot (decl) + mono_class_interface_offset (class, decl->klass);
3147                         vtable [dslot] = overrides [i*2 + 1];
3148                         vtable [dslot]->slot = dslot;
3149                         if (!override_map)
3150                                 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3151
3152                         g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
3153
3154                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3155                                 mono_security_core_clr_check_override (class, vtable [dslot], decl);
3156                 }
3157         }
3158         TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
3159         TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
3160
3161         // Loop on all implemented interfaces...
3162         for (i = 0; i < class->interface_offsets_count; i++) {
3163                 MonoClass *parent = class->parent;
3164                 int ic_offset;
3165                 gboolean interface_is_explicitly_implemented_by_class;
3166                 int im_index;
3167                 
3168                 ic = class->interfaces_packed [i];
3169                 ic_offset = mono_class_interface_offset (class, ic);
3170
3171                 mono_class_setup_methods (ic);
3172                 
3173                 // Check if this interface is explicitly implemented (instead of just inherited)
3174                 if (parent != NULL) {
3175                         int implemented_interfaces_index;
3176                         interface_is_explicitly_implemented_by_class = FALSE;
3177                         for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
3178                                 if (ic == class->interfaces [implemented_interfaces_index]) {
3179                                         interface_is_explicitly_implemented_by_class = TRUE;
3180                                         break;
3181                                 }
3182                         }
3183                 } else {
3184                         interface_is_explicitly_implemented_by_class = TRUE;
3185                 }
3186                 
3187                 // Loop on all interface methods...
3188                 for (im_index = 0; im_index < ic->method.count; im_index++) {
3189                         MonoMethod *im = ic->methods [im_index];
3190                         int im_slot = ic_offset + im->slot;
3191                         MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
3192                         
3193                         if (im->flags & METHOD_ATTRIBUTE_STATIC)
3194                                 continue;
3195
3196                         // If there is an explicit implementation, just use it right away,
3197                         // otherwise look for a matching method
3198                         if (override_im == NULL) {
3199                                 int cm_index;
3200                                 gpointer iter;
3201                                 MonoMethod *cm;
3202
3203                                 // First look for a suitable method among the class methods
3204                                 iter = NULL;
3205                                 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
3206                                         TRACE_INTERFACE_VTABLE (printf ("    For slot %d ('%s'.'%s':'%s'), trying method '%s'.'%s':'%s'... [EXPLICIT IMPLEMENTATION = %d][SLOT IS NULL = %d]", im_slot, ic->name_space, ic->name, im->name, cm->klass->name_space, cm->klass->name, cm->name, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL)));
3207                                         if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
3208                                                 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
3209                                                 vtable [im_slot] = cm;
3210                                                 /* Why do we need this? */
3211                                                 if (cm->slot < 0) {
3212                                                         cm->slot = im_slot;
3213                                                 }
3214                                         }
3215                                         TRACE_INTERFACE_VTABLE (printf ("\n"));
3216                                 }
3217                                 
3218                                 // If the slot is still empty, look in all the inherited virtual methods...
3219                                 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
3220                                         MonoClass *parent = class->parent;
3221                                         // Reverse order, so that last added methods are preferred
3222                                         for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
3223                                                 MonoMethod *cm = parent->vtable [cm_index];
3224                                                 
3225                                                 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("    For slot %d ('%s'.'%s':'%s'), trying (ancestor) method '%s'.'%s':'%s'... ", im_slot, ic->name_space, ic->name, im->name, cm->klass->name_space, cm->klass->name, cm->name));
3226                                                 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
3227                                                         TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
3228                                                         vtable [im_slot] = cm;
3229                                                         /* Why do we need this? */
3230                                                         if (cm->slot < 0) {
3231                                                                 cm->slot = im_slot;
3232                                                         }
3233                                                         break;
3234                                                 }
3235                                                 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
3236                                         }
3237                                 }
3238                         } else {
3239                                 g_assert (vtable [im_slot] == override_im);
3240                         }
3241                 }
3242         }
3243         
3244         // If the class is not abstract, check that all its interface slots are full.
3245         // The check is done here and not directly at the end of the loop above because
3246         // it can happen (for injected generic array interfaces) that the same slot is
3247         // processed multiple times (those interfaces have overlapping slots), and it
3248         // will not always be the first pass the one that fills the slot.
3249         if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3250                 for (i = 0; i < class->interface_offsets_count; i++) {
3251                         int ic_offset;
3252                         int im_index;
3253                         
3254                         ic = class->interfaces_packed [i];
3255                         ic_offset = mono_class_interface_offset (class, ic);
3256                         
3257                         for (im_index = 0; im_index < ic->method.count; im_index++) {
3258                                 MonoMethod *im = ic->methods [im_index];
3259                                 int im_slot = ic_offset + im->slot;
3260                                 
3261                                 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3262                                         continue;
3263
3264                                 TRACE_INTERFACE_VTABLE (printf ("      [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
3265                                                 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
3266                                 if (vtable [im_slot] == NULL) {
3267                                         print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
3268                                         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3269                                         if (override_map)
3270                                                 g_hash_table_destroy (override_map);
3271                                         return;
3272                                 }
3273                         }
3274                 }
3275         }
3276
3277         TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
3278         class_iter = NULL;
3279         while ((cm = mono_class_get_virtual_methods (class, &class_iter))) {
3280                 /*
3281                  * If the method is REUSE_SLOT, we must check in the
3282                  * base class for a method to override.
3283                  */
3284                 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3285                         int slot = -1;
3286                         for (k = class->parent; k ; k = k->parent) {
3287                                 gpointer k_iter;
3288                                 MonoMethod *m1;
3289
3290                                 k_iter = NULL;
3291                                 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
3292                                         MonoMethodSignature *cmsig, *m1sig;
3293
3294                                         cmsig = mono_method_signature (cm);
3295                                         m1sig = mono_method_signature (m1);
3296
3297                                         if (!cmsig || !m1sig) {
3298                                                 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3299                                                 return;
3300                                         }
3301
3302                                         if (!strcmp(cm->name, m1->name) && 
3303                                             mono_metadata_signature_equal (cmsig, m1sig)) {
3304
3305                                                 /* CAS - SecurityAction.InheritanceDemand */
3306                                                 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3307                                                         mono_secman_inheritancedemand_method (cm, m1);
3308                                                 }
3309
3310                                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3311                                                         mono_security_core_clr_check_override (class, cm, m1);
3312
3313                                                 slot = mono_method_get_vtable_slot (m1);
3314                                                 g_assert (cm->slot < max_vtsize);
3315                                                 if (!override_map)
3316                                                         override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3317                                                 g_hash_table_insert (override_map, m1, cm);
3318                                                 break;
3319                                         }
3320                                 }
3321                                 if (slot >= 0) 
3322                                         break;
3323                         }
3324                         if (slot >= 0)
3325                                 cm->slot = slot;
3326                 }
3327
3328                 if (cm->slot < 0)
3329                         cm->slot = cur_slot++;
3330
3331                 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
3332                         vtable [cm->slot] = cm;
3333         }
3334
3335         /* override non interface methods */
3336         for (i = 0; i < onum; i++) {
3337                 MonoMethod *decl = overrides [i*2];
3338                 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
3339                         g_assert (decl->slot != -1);
3340                         vtable [decl->slot] = overrides [i*2 + 1];
3341                         overrides [i * 2 + 1]->slot = decl->slot;
3342                         if (!override_map)
3343                                 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3344                         g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
3345
3346                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3347                                 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
3348                 }
3349         }
3350
3351         /*
3352          * If a method occupies more than one place in the vtable, and it is
3353          * overriden, then change the other occurances too.
3354          */
3355         if (override_map) {
3356                 for (i = 0; i < max_vtsize; ++i)
3357                         if (vtable [i]) {
3358                                 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
3359                                 if (cm)
3360                                         vtable [i] = cm;
3361                         }
3362
3363                 g_hash_table_destroy (override_map);
3364         }
3365
3366         if (class->generic_class) {
3367                 MonoClass *gklass = class->generic_class->container_class;
3368
3369                 mono_class_init (gklass);
3370
3371                 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
3372         } else {
3373                 /* Check that the vtable_size value computed in mono_class_init () is correct */
3374                 if (class->vtable_size)
3375                         g_assert (cur_slot == class->vtable_size);
3376                 class->vtable_size = cur_slot;
3377         }
3378
3379         /* Try to share the vtable with our parent. */
3380         if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
3381                 mono_memory_barrier ();
3382                 class->vtable = class->parent->vtable;
3383         } else {
3384                 MonoMethod **tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * class->vtable_size);
3385                 memcpy (tmp, vtable,  sizeof (gpointer) * class->vtable_size);
3386                 mono_memory_barrier ();
3387                 class->vtable = tmp;
3388         }
3389
3390         DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
3391         if (mono_print_vtable) {
3392                 int icount = 0;
3393
3394                 print_implemented_interfaces (class);
3395                 
3396                 for (i = 0; i <= max_iid; i++)
3397                         if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
3398                                 icount++;
3399
3400                 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg), 
3401                         class->vtable_size, icount); 
3402
3403                 for (i = 0; i < class->vtable_size; ++i) {
3404                         MonoMethod *cm;
3405                
3406                         cm = vtable [i];
3407                         if (cm) {
3408                                 printf ("  slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
3409                                         mono_method_full_name (cm, TRUE));
3410                         }
3411                 }
3412
3413
3414                 if (icount) {
3415                         printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space, 
3416                                 class->name, max_iid);
3417         
3418                         for (i = 0; i < class->interface_count; i++) {
3419                                 ic = class->interfaces [i];
3420                                 printf ("  slot offset: %03d, method count: %03d, iid: %03d %s\n",  
3421                                         mono_class_interface_offset (class, ic),
3422                                         ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
3423                         }
3424
3425                         for (k = class->parent; k ; k = k->parent) {
3426                                 for (i = 0; i < k->interface_count; i++) {
3427                                         ic = k->interfaces [i]; 
3428                                         printf ("  slot offset: %03d, method count: %03d, iid: %03d %s\n",  
3429                                                 mono_class_interface_offset (class, ic),
3430                                                 ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
3431                                 }
3432                         }
3433                 }
3434         }
3435
3436         VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
3437 }
3438
3439 /*
3440  * mono_method_get_vtable_slot:
3441  *
3442  *   Returns method->slot, computing it if neccesary.
3443  * LOCKING: Acquires the loader lock.
3444  */
3445 int
3446 mono_method_get_vtable_slot (MonoMethod *method)
3447 {
3448         if (method->slot == -1) {
3449                 mono_class_setup_vtable (method->klass);
3450                 g_assert (method->slot != -1);
3451         }
3452         return method->slot;
3453 }
3454
3455 /**
3456  * mono_method_get_vtable_index:
3457  * @method: a method
3458  *
3459  * Returns the index into the runtime vtable to access the method or,
3460  * in the case of a virtual generic method, the virtual generic method
3461  * thunk.
3462  */
3463 int
3464 mono_method_get_vtable_index (MonoMethod *method)
3465 {
3466         if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3467                 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3468                 if (imethod->declaring->is_generic)
3469                         return mono_method_get_vtable_slot (imethod->declaring);
3470         }
3471         return mono_method_get_vtable_slot (method);
3472 }
3473
3474 static MonoMethod *default_ghc = NULL;
3475 static MonoMethod *default_finalize = NULL;
3476 static int finalize_slot = -1;
3477 static int ghc_slot = -1;
3478
3479 static void
3480 initialize_object_slots (MonoClass *class)
3481 {
3482         int i;
3483         if (default_ghc)
3484                 return;
3485         if (class == mono_defaults.object_class) { 
3486                 mono_class_setup_vtable (class);                       
3487                 for (i = 0; i < class->vtable_size; ++i) {
3488                         MonoMethod *cm = class->vtable [i];
3489        
3490                         if (!strcmp (cm->name, "GetHashCode"))
3491                                 ghc_slot = i;
3492                         else if (!strcmp (cm->name, "Finalize"))
3493                                 finalize_slot = i;
3494                 }
3495
3496                 g_assert (ghc_slot > 0);
3497                 default_ghc = class->vtable [ghc_slot];
3498
3499                 g_assert (finalize_slot > 0);
3500                 default_finalize = class->vtable [finalize_slot];
3501         }
3502 }
3503
3504 typedef struct {
3505         MonoMethod *array_method;
3506         char *name;
3507 } GenericArrayMethodInfo;
3508
3509 static int generic_array_method_num = 0;
3510 static GenericArrayMethodInfo *generic_array_method_info = NULL;
3511
3512 static int
3513 generic_array_methods (MonoClass *class)
3514 {
3515         int i, count_generic = 0;
3516         GList *list = NULL, *tmp;
3517         if (generic_array_method_num)
3518                 return generic_array_method_num;
3519         mono_class_setup_methods (class->parent);
3520         for (i = 0; i < class->parent->method.count; i++) {
3521                 MonoMethod *m = class->parent->methods [i];
3522                 if (!strncmp (m->name, "InternalArray__", 15)) {
3523                         count_generic++;
3524                         list = g_list_prepend (list, m);
3525                 }
3526         }
3527         list = g_list_reverse (list);
3528         generic_array_method_info = g_malloc (sizeof (GenericArrayMethodInfo) * count_generic);
3529         i = 0;
3530         for (tmp = list; tmp; tmp = tmp->next) {
3531                 const char *mname, *iname;
3532                 gchar *name;
3533                 MonoMethod *m = tmp->data;
3534                 generic_array_method_info [i].array_method = m;
3535                 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
3536                         iname = "System.Collections.Generic.ICollection`1.";
3537                         mname = m->name + 27;
3538                 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
3539                         iname = "System.Collections.Generic.IEnumerable`1.";
3540                         mname = m->name + 27;
3541                 } else if (!strncmp (m->name, "InternalArray__", 15)) {
3542                         iname = "System.Collections.Generic.IList`1.";
3543                         mname = m->name + 15;
3544                 } else {
3545                         g_assert_not_reached ();
3546                 }
3547
3548                 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
3549                 strcpy (name, iname);
3550                 strcpy (name + strlen (iname), mname);
3551                 generic_array_method_info [i].name = name;
3552                 i++;
3553         }
3554         /*g_print ("array generic methods: %d\n", count_generic);*/
3555
3556         generic_array_method_num = count_generic;
3557         g_list_free (list);
3558         return generic_array_method_num;
3559 }
3560
3561 static void
3562 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
3563 {
3564         MonoGenericContext tmp_context;
3565         int i;
3566
3567         tmp_context.class_inst = NULL;
3568         tmp_context.method_inst = iface->generic_class->context.class_inst;
3569         //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
3570
3571         for (i = 0; i < generic_array_method_num; i++) {
3572                 MonoMethod *m = generic_array_method_info [i].array_method;
3573                 MonoMethod *inflated;
3574
3575                 inflated = mono_class_inflate_generic_method (m, &tmp_context);
3576                 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
3577         }
3578 }
3579
3580 static char*
3581 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
3582 {
3583         int len = strlen (s1) + strlen (s2) + 2;
3584         char *s = mono_image_alloc (image, len);
3585         int result;
3586
3587         result = g_snprintf (s, len, "%s%c%s", s1, '\0', s2);
3588         g_assert (result == len - 1);
3589
3590         return s;
3591 }
3592
3593 static void
3594 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
3595 {
3596         gpointer exception_data = NULL;
3597
3598         switch (error->exception_type) {
3599         case MONO_EXCEPTION_TYPE_LOAD:
3600                 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
3601                 break;
3602
3603         case MONO_EXCEPTION_MISSING_METHOD:
3604                 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
3605                 break;
3606
3607         case MONO_EXCEPTION_MISSING_FIELD: {
3608                 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
3609                 const char *class_name;
3610
3611                 if (name_space)
3612                         class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
3613                 else
3614                         class_name = error->klass->name;
3615
3616                 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
3617                 
3618                 if (name_space)
3619                         g_free ((void*)class_name);
3620                 break;
3621         }
3622
3623         case MONO_EXCEPTION_FILE_NOT_FOUND: {
3624                 const char *msg;
3625
3626                 if (error->ref_only)
3627                         msg = "Cannot resolve dependency to assembly '%s' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.";
3628                 else
3629                         msg = "Could not load file or assembly '%s' or one of its dependencies.";
3630
3631                 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
3632                 break;
3633         }
3634
3635         case MONO_EXCEPTION_BAD_IMAGE:
3636                 exception_data = error->msg;
3637                 break;
3638
3639         default :
3640                 g_assert_not_reached ();
3641         }
3642
3643         mono_class_set_failure (class, error->exception_type, exception_data);
3644 }
3645
3646 /**
3647  * mono_class_init:
3648  * @class: the class to initialize
3649  *
3650  *   Compute the instance_size, class_size and other infos that cannot be 
3651  * computed at mono_class_get() time. Also compute vtable_size if possible. 
3652  * Returns TRUE on success or FALSE if there was a problem in loading
3653  * the type (incorrect assemblies, missing assemblies, methods, etc). 
3654  *
3655  * LOCKING: Acquires the loader lock.
3656  */
3657 gboolean
3658 mono_class_init (MonoClass *class)
3659 {
3660         int i;
3661         MonoCachedClassInfo cached_info;
3662         gboolean has_cached_info;
3663         int class_init_ok = TRUE;
3664         
3665         g_assert (class);
3666
3667         /* Double-checking locking pattern */
3668         if (class->inited)
3669                 return class->exception_type == MONO_EXCEPTION_NONE;
3670
3671         /*g_print ("Init class %s\n", class->name);*/
3672
3673         /* We do everything inside the lock to prevent races */
3674         mono_loader_lock ();
3675
3676         if (class->inited) {
3677                 mono_loader_unlock ();
3678                 /* Somebody might have gotten in before us */
3679                 return class->exception_type == MONO_EXCEPTION_NONE;
3680         }
3681
3682         if (class->init_pending) {
3683                 mono_loader_unlock ();
3684                 /* this indicates a cyclic dependency */
3685                 g_error ("pending init %s.%s\n", class->name_space, class->name);
3686         }
3687
3688         class->init_pending = 1;
3689
3690         /* CAS - SecurityAction.InheritanceDemand */
3691         if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
3692                 mono_secman_inheritancedemand_class (class, class->parent);
3693         }
3694
3695         if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3696                 mono_security_core_clr_check_inheritance (class);
3697
3698         mono_stats.initialized_class_count++;
3699
3700         if (class->generic_class && !class->generic_class->is_dynamic) {
3701                 MonoClass *gklass = class->generic_class->container_class;
3702
3703                 mono_stats.generic_class_count++;
3704
3705                 class->method = gklass->method;
3706                 class->field = gklass->field;
3707
3708                 mono_class_init (gklass);
3709                 // FIXME: Why is this needed ?
3710                 mono_class_setup_methods (gklass);
3711
3712                 if (MONO_CLASS_IS_INTERFACE (class))
3713                         class->interface_id = mono_get_unique_iid (class);
3714         }
3715
3716         if (class->parent && !class->parent->inited)
3717                 mono_class_init (class->parent);
3718
3719         has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
3720
3721         if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
3722                 class->nested_classes_inited = TRUE;
3723
3724         /*
3725          * Computes the size used by the fields, and their locations
3726          */
3727         if (has_cached_info) {
3728                 class->instance_size = cached_info.instance_size;
3729                 class->sizes.class_size = cached_info.class_size;
3730                 class->packing_size = cached_info.packing_size;
3731                 class->min_align = cached_info.min_align;
3732                 class->blittable = cached_info.blittable;
3733                 class->has_references = cached_info.has_references;
3734                 class->has_static_refs = cached_info.has_static_refs;
3735                 class->no_special_static_fields = cached_info.no_special_static_fields;
3736         }
3737         else
3738                 if (!class->size_inited){
3739                         mono_class_setup_fields (class);
3740                         if (class->exception_type || mono_loader_get_last_error ()){
3741                                 class_init_ok = FALSE;
3742                                 goto leave;
3743                         }
3744                 }
3745                                 
3746         /* Initialize arrays */
3747         if (class->rank) {
3748                 class->method.count = 3 + (class->rank > 1? 2: 1);
3749
3750                 if (class->interface_count) {
3751                         int count_generic = generic_array_methods (class);
3752                         class->method.count += class->interface_count * count_generic;
3753                 }
3754         }
3755
3756         mono_class_setup_supertypes (class);
3757
3758         if (!default_ghc)
3759                 initialize_object_slots (class);
3760
3761         /* 
3762          * Initialize the rest of the data without creating a generic vtable if possible.
3763          * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
3764          * also avoid computing a generic vtable.
3765          */
3766         if (has_cached_info) {
3767                 /* AOT case */
3768                 class->vtable_size = cached_info.vtable_size;
3769                 class->has_finalize = cached_info.has_finalize;
3770                 class->ghcimpl = cached_info.ghcimpl;
3771                 class->has_cctor = cached_info.has_cctor;
3772         } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
3773                 static int szarray_vtable_size = 0;
3774
3775                 /* SZARRAY case */
3776                 if (!szarray_vtable_size) {
3777                         mono_class_setup_vtable (class);
3778                         szarray_vtable_size = class->vtable_size;
3779                 } else {
3780                         class->vtable_size = szarray_vtable_size;
3781                 }
3782         } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
3783                 MonoClass *gklass = class->generic_class->container_class;
3784
3785                 /* Generic instance case */
3786                 class->ghcimpl = gklass->ghcimpl;
3787                 class->has_finalize = gklass->has_finalize;
3788                 class->has_cctor = gklass->has_cctor;
3789
3790                 mono_class_setup_vtable (gklass);
3791                 if (gklass->exception_type)
3792                         goto fail;
3793
3794                 class->vtable_size = gklass->vtable_size;
3795         } else {
3796                 /* General case */
3797
3798                 /* ghcimpl is not currently used
3799                 class->ghcimpl = 1;
3800                 if (class->parent) { 
3801                         MonoMethod *cmethod = class->vtable [ghc_slot];
3802                         if (cmethod->is_inflated)
3803                                 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
3804                         if (cmethod == default_ghc) {
3805                                 class->ghcimpl = 0;
3806                         }
3807                 }
3808                 */
3809
3810                 /* Interfaces and valuetypes are not supposed to have finalizers */
3811                 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
3812                         MonoMethod *cmethod = NULL;
3813
3814                         if (class->parent && class->parent->has_finalize) {
3815                                 class->has_finalize = 1;
3816                         } else {
3817                                 if (class->type_token) {
3818                                         cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
3819                                 } else if (class->parent) {
3820                                         /* FIXME: Optimize this */
3821                                         mono_class_setup_vtable (class);
3822                                         if (class->exception_type || mono_loader_get_last_error ())
3823                                                 goto fail;
3824                                         cmethod = class->vtable [finalize_slot];
3825                                 }
3826
3827                                 if (cmethod) {
3828                                         /* Check that this is really the finalizer method */
3829                                         mono_class_setup_vtable (class);
3830                                         if (class->exception_type || mono_loader_get_last_error ())
3831                                         goto fail;
3832
3833                                         class->has_finalize = 0;
3834                                         if (class->parent) { 
3835                                                 cmethod = class->vtable [finalize_slot];
3836                                                 if (cmethod->is_inflated)
3837                                                         cmethod = ((MonoMethodInflated*)cmethod)->declaring;
3838                                                 if (cmethod != default_finalize) {
3839                                                         class->has_finalize = 1;
3840                                                 }
3841                                         }
3842                                 }
3843                         }
3844                 }
3845
3846                 /* C# doesn't allow interfaces to have cctors */
3847                 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
3848                         MonoMethod *cmethod = NULL;
3849
3850                         if (class->type_token) {
3851                                 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
3852                                 /* The find_method function ignores the 'flags' argument */
3853                                 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
3854                                         class->has_cctor = 1;
3855                         } else {
3856                                 mono_class_setup_methods (class);
3857
3858                                 for (i = 0; i < class->method.count; ++i) {
3859                                         MonoMethod *method = class->methods [i];
3860                                         if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
3861                                                 (strcmp (".cctor", method->name) == 0)) {
3862                                                 class->has_cctor = 1;
3863                                                 break;
3864                                         }
3865                                 }
3866                         }
3867                 }
3868         }
3869
3870         if (!mono_setup_vtable_in_class_init) {
3871                 /*
3872                  * This is an embedding API break, since the caller might assume that 
3873                  * mono_class_init () constructs a generic vtable, so vtable construction errors
3874                  * are visible right after the mono_class_init (), and not after 
3875                  * mono_class_vtable ().
3876                  */
3877                 if (class->parent) {
3878                         /* This will compute class->parent->vtable_size for some classes */
3879                         mono_class_init (class->parent);
3880                         if (class->parent->exception_type || mono_loader_get_last_error ())
3881                                 goto fail;
3882                         if (!class->parent->vtable_size) {
3883                                 /* FIXME: Get rid of this somehow */
3884                                 mono_class_setup_vtable (class->parent);
3885                                 if (class->parent->exception_type || mono_loader_get_last_error ())
3886                                         goto fail;
3887                         }
3888                         setup_interface_offsets (class, class->parent->vtable_size);
3889                 } else {
3890                         setup_interface_offsets (class, 0);
3891                 }
3892         } else {
3893                 mono_class_setup_vtable (class);
3894
3895                 if (MONO_CLASS_IS_INTERFACE (class))
3896                         setup_interface_offsets (class, 0);
3897         }
3898
3899         if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
3900                 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
3901                 class_init_ok = FALSE;
3902         }
3903
3904         goto leave;
3905
3906  fail:
3907         class_init_ok = FALSE;
3908
3909  leave:
3910         /* Because of the double-checking locking pattern */
3911         mono_memory_barrier ();
3912         class->inited = 1;
3913         class->init_pending = 0;
3914
3915         if (mono_loader_get_last_error ()) {
3916                 if (class->exception_type == MONO_EXCEPTION_NONE)
3917                         set_failure_from_loader_error (class, mono_loader_get_last_error ());
3918
3919                 mono_loader_clear_error ();
3920         }
3921
3922         mono_loader_unlock ();
3923
3924         if (mono_debugger_class_init_func)
3925                 mono_debugger_class_init_func (class);
3926
3927         return class_init_ok;
3928 }
3929
3930 static gboolean
3931 is_corlib_image (MonoImage *image)
3932 {
3933         /* FIXME: allow the dynamic case for our compilers and with full trust */
3934         if (image->dynamic)
3935                 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
3936         else
3937                 return image == mono_defaults.corlib;
3938 }
3939
3940 /*
3941  * LOCKING: this assumes the loader lock is held
3942  */
3943 void
3944 mono_class_setup_mono_type (MonoClass *class)
3945 {
3946         const char *name = class->name;
3947         const char *nspace = class->name_space;
3948         gboolean is_corlib = is_corlib_image (class->image);
3949
3950         class->this_arg.byref = 1;
3951         class->this_arg.data.klass = class;
3952         class->this_arg.type = MONO_TYPE_CLASS;
3953         class->byval_arg.data.klass = class;
3954         class->byval_arg.type = MONO_TYPE_CLASS;
3955
3956         if (is_corlib && !strcmp (nspace, "System")) {
3957                 if (!strcmp (name, "ValueType")) {
3958                         /*
3959                          * do not set the valuetype bit for System.ValueType.
3960                          * class->valuetype = 1;
3961                          */
3962                         class->blittable = TRUE;
3963                 } else if (!strcmp (name, "Enum")) {
3964                         /*
3965                          * do not set the valuetype bit for System.Enum.
3966                          * class->valuetype = 1;
3967                          */
3968                         class->valuetype = 0;
3969                         class->enumtype = 0;
3970                 } else if (!strcmp (name, "Object")) {
3971                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
3972                 } else if (!strcmp (name, "String")) {
3973                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
3974                 } else if (!strcmp (name, "TypedReference")) {
3975                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
3976                 }
3977         }
3978
3979         if (class->valuetype) {
3980                 int t = MONO_TYPE_VALUETYPE;
3981
3982                 if (is_corlib && !strcmp (nspace, "System")) {
3983                         switch (*name) {
3984                         case 'B':
3985                                 if (!strcmp (name, "Boolean")) {
3986                                         t = MONO_TYPE_BOOLEAN;
3987                                 } else if (!strcmp(name, "Byte")) {
3988                                         t = MONO_TYPE_U1;
3989                                         class->blittable = TRUE;                                                
3990                                 }
3991                                 break;
3992                         case 'C':
3993                                 if (!strcmp (name, "Char")) {
3994                                         t = MONO_TYPE_CHAR;
3995                                 }
3996                                 break;
3997                         case 'D':
3998                                 if (!strcmp (name, "Double")) {
3999                                         t = MONO_TYPE_R8;
4000                                         class->blittable = TRUE;                                                
4001                                 }
4002                                 break;
4003                         case 'I':
4004                                 if (!strcmp (name, "Int32")) {
4005                                         t = MONO_TYPE_I4;
4006                                         class->blittable = TRUE;
4007                                 } else if (!strcmp(name, "Int16")) {
4008                                         t = MONO_TYPE_I2;
4009                                         class->blittable = TRUE;
4010                                 } else if (!strcmp(name, "Int64")) {
4011                                         t = MONO_TYPE_I8;
4012                                         class->blittable = TRUE;
4013                                 } else if (!strcmp(name, "IntPtr")) {
4014                                         t = MONO_TYPE_I;
4015                                         class->blittable = TRUE;
4016                                 }
4017                                 break;
4018                         case 'S':
4019                                 if (!strcmp (name, "Single")) {
4020                                         t = MONO_TYPE_R4;
4021                                         class->blittable = TRUE;                                                
4022                                 } else if (!strcmp(name, "SByte")) {
4023                                         t = MONO_TYPE_I1;
4024                                         class->blittable = TRUE;
4025                                 }
4026                                 break;
4027                         case 'U':
4028                                 if (!strcmp (name, "UInt32")) {
4029                                         t = MONO_TYPE_U4;
4030                                         class->blittable = TRUE;
4031                                 } else if (!strcmp(name, "UInt16")) {
4032                                         t = MONO_TYPE_U2;
4033                                         class->blittable = TRUE;
4034                                 } else if (!strcmp(name, "UInt64")) {
4035                                         t = MONO_TYPE_U8;
4036                                         class->blittable = TRUE;
4037                                 } else if (!strcmp(name, "UIntPtr")) {
4038                                         t = MONO_TYPE_U;
4039                                         class->blittable = TRUE;
4040                                 }
4041                                 break;
4042                         case 'T':
4043                                 if (!strcmp (name, "TypedReference")) {
4044                                         t = MONO_TYPE_TYPEDBYREF;
4045                                         class->blittable = TRUE;
4046                                 }
4047                                 break;
4048                         case 'V':
4049                                 if (!strcmp (name, "Void")) {
4050                                         t = MONO_TYPE_VOID;
4051                                 }
4052                                 break;
4053                         default:
4054                                 break;
4055                         }
4056                 }
4057                 class->this_arg.type = class->byval_arg.type = t;
4058         }
4059
4060         if (MONO_CLASS_IS_INTERFACE (class))
4061                 class->interface_id = mono_get_unique_iid (class);
4062
4063 }
4064
4065 /*
4066  * LOCKING: this assumes the loader lock is held
4067  */
4068 void
4069 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
4070 {
4071         gboolean system_namespace;
4072         gboolean is_corlib = is_corlib_image (class->image);
4073
4074         system_namespace = !strcmp (class->name_space, "System") && is_corlib;
4075
4076         /* if root of the hierarchy */
4077         if (system_namespace && !strcmp (class->name, "Object")) {
4078                 class->parent = NULL;
4079                 class->instance_size = sizeof (MonoObject);
4080                 return;
4081         }
4082         if (!strcmp (class->name, "<Module>")) {
4083                 class->parent = NULL;
4084                 class->instance_size = 0;
4085                 return;
4086         }
4087
4088         if (!MONO_CLASS_IS_INTERFACE (class)) {
4089                 /* Imported COM Objects always derive from __ComObject. */
4090                 if (MONO_CLASS_IS_IMPORT (class)) {
4091                         mono_init_com_types ();
4092                         if (parent == mono_defaults.object_class)
4093                                 parent = mono_defaults.com_object_class;
4094                 }
4095                 if (!parent) {
4096                         /* set the parent to something useful and safe, but mark the type as broken */
4097                         parent = mono_defaults.object_class;
4098                         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4099                 }
4100
4101                 class->parent = parent;
4102
4103                 if (parent->generic_class && !parent->name) {
4104                         /*
4105                          * If the parent is a generic instance, we may get
4106                          * called before it is fully initialized, especially
4107                          * before it has its name.
4108                          */
4109                         return;
4110                 }
4111
4112                 class->marshalbyref = parent->marshalbyref;
4113                 class->contextbound  = parent->contextbound;
4114                 class->delegate  = parent->delegate;
4115                 if (MONO_CLASS_IS_IMPORT (class))
4116                         class->is_com_object = 1;
4117                 else
4118                         class->is_com_object = parent->is_com_object;
4119                 
4120                 if (system_namespace) {
4121                         if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
4122                                 class->marshalbyref = 1;
4123
4124                         if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject")) 
4125                                 class->contextbound  = 1;
4126
4127                         if (*class->name == 'D' && !strcmp (class->name, "Delegate")) 
4128                                 class->delegate  = 1;
4129                 }
4130
4131                 if (class->parent->enumtype || (is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) && 
4132                                                 (strcmp (class->parent->name_space, "System") == 0)))
4133                         class->valuetype = 1;
4134                 if (is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
4135                         class->valuetype = class->enumtype = 1;
4136                 }
4137                 /*class->enumtype = class->parent->enumtype; */
4138                 mono_class_setup_supertypes (class);
4139         } else {
4140                 /* initialize com types if COM interfaces are present */
4141                 if (MONO_CLASS_IS_IMPORT (class))
4142                         mono_init_com_types ();
4143                 class->parent = NULL;
4144         }
4145
4146 }
4147
4148 /*
4149  * mono_class_setup_supertypes:
4150  * @class: a class
4151  *
4152  * Build the data structure needed to make fast type checks work.
4153  * This currently sets two fields in @class:
4154  *  - idepth: distance between @class and System.Object in the type
4155  *    hierarchy + 1
4156  *  - supertypes: array of classes: each element has a class in the hierarchy
4157  *    starting from @class up to System.Object
4158  * 
4159  * LOCKING: this assumes the loader lock is held
4160  */
4161 void
4162 mono_class_setup_supertypes (MonoClass *class)
4163 {
4164         int ms;
4165
4166         if (class->supertypes)
4167                 return;
4168
4169         if (class->parent && !class->parent->supertypes)
4170                 mono_class_setup_supertypes (class->parent);
4171         if (class->parent)
4172                 class->idepth = class->parent->idepth + 1;
4173         else
4174                 class->idepth = 1;
4175
4176         ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
4177         class->supertypes = mono_image_alloc0 (class->image, sizeof (MonoClass *) * ms);
4178
4179         if (class->parent) {
4180                 class->supertypes [class->idepth - 1] = class;
4181                 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
4182         } else {
4183                 class->supertypes [0] = class;
4184         }
4185 }
4186
4187 /**
4188  * mono_class_create_from_typedef:
4189  * @image: image where the token is valid
4190  * @type_token:  typedef token
4191  *
4192  * Create the MonoClass* representing the specified type token.
4193  * @type_token must be a TypeDef token.
4194  */
4195 static MonoClass *
4196 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
4197 {
4198         MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
4199         MonoClass *class, *parent = NULL;
4200         guint32 cols [MONO_TYPEDEF_SIZE];
4201         guint32 cols_next [MONO_TYPEDEF_SIZE];
4202         guint tidx = mono_metadata_token_index (type_token);
4203         MonoGenericContext *context = NULL;
4204         const char *name, *nspace;
4205         guint icount = 0; 
4206         MonoClass **interfaces;
4207         guint32 field_last, method_last;
4208         guint32 nesting_tokeen;
4209
4210         mono_loader_lock ();
4211
4212         if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
4213                 mono_loader_unlock ();
4214                 return class;
4215         }
4216
4217         g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
4218
4219         mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
4220         
4221         name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
4222         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
4223
4224         class = mono_image_alloc0 (image, sizeof (MonoClass));
4225
4226         class->name = name;
4227         class->name_space = nspace;
4228
4229         mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4230
4231         class->image = image;
4232         class->type_token = type_token;
4233         class->flags = cols [MONO_TYPEDEF_FLAGS];
4234
4235         mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
4236
4237         classes_size += sizeof (MonoClass);
4238
4239         /*
4240          * Check whether we're a generic type definition.
4241          */
4242         class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
4243         if (class->generic_container) {
4244                 class->is_generic = 1;
4245                 class->generic_container->owner.klass = class;
4246                 context = &class->generic_container->context;
4247         }
4248
4249         if (cols [MONO_TYPEDEF_EXTENDS]) {
4250                 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
4251
4252                 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
4253                         /*WARNING: this must satisfy mono_metadata_type_hash*/
4254                         class->this_arg.byref = 1;
4255                         class->this_arg.data.klass = class;
4256                         class->this_arg.type = MONO_TYPE_CLASS;
4257                         class->byval_arg.data.klass = class;
4258                         class->byval_arg.type = MONO_TYPE_CLASS;
4259                 }
4260                 parent = mono_class_get_full (image, parent_token, context);
4261
4262                 if (parent == NULL){
4263                         mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
4264                         mono_loader_unlock ();
4265                         mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4266                         return NULL;
4267                 }
4268         }
4269
4270         /* do this early so it's available for interfaces in setup_mono_type () */
4271         if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token)))
4272                 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
4273
4274         mono_class_setup_parent (class, parent);
4275
4276         /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
4277         mono_class_setup_mono_type (class);
4278
4279         if (!class->enumtype) {
4280                 if (!mono_metadata_interfaces_from_typedef_full (
4281                             image, type_token, &interfaces, &icount, context)){
4282                         mono_loader_unlock ();
4283                         mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4284                         return NULL;
4285                 }
4286
4287                 class->interfaces = interfaces;
4288                 class->interface_count = icount;
4289                 class->interfaces_inited = 1;
4290         }
4291
4292         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
4293                 class->unicode = 1;
4294
4295 #if PLATFORM_WIN32
4296         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
4297                 class->unicode = 1;
4298 #endif
4299
4300         class->cast_class = class->element_class = class;
4301
4302         /*g_print ("Load class %s\n", name);*/
4303
4304         /*
4305          * Compute the field and method lists
4306          */
4307         class->field.first  = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
4308         class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
4309
4310         if (tt->rows > tidx){           
4311                 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
4312                 field_last  = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
4313                 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
4314         } else {
4315                 field_last  = image->tables [MONO_TABLE_FIELD].rows;
4316                 method_last = image->tables [MONO_TABLE_METHOD].rows;
4317         }
4318
4319         if (cols [MONO_TYPEDEF_FIELD_LIST] && 
4320             cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
4321                 class->field.count = field_last - class->field.first;
4322         else
4323                 class->field.count = 0;
4324
4325         if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
4326                 class->method.count = method_last - class->method.first;
4327         else
4328                 class->method.count = 0;
4329
4330         /* reserve space to store vector pointer in arrays */
4331         if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
4332                 class->instance_size += 2 * sizeof (gpointer);
4333                 g_assert (class->field.count == 0);
4334         }
4335
4336         if (class->enumtype) {
4337                 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
4338                 if (!enum_basetype) {
4339                         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4340                         mono_loader_unlock ();
4341                         return NULL;
4342                 }
4343                 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
4344         }
4345
4346         /*
4347          * If we're a generic type definition, load the constraints.
4348          * We must do this after the class has been constructed to make certain recursive scenarios
4349          * work.
4350          */
4351         if (class->generic_container)
4352                 mono_metadata_load_generic_param_constraints (
4353                         image, type_token, class->generic_container);
4354
4355         if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
4356                 if (!strncmp (name, "Vector", 6))
4357                         class->simd_type = !strcmp (name + 6, "2d") || !strcmp (name + 6, "2ul") || !strcmp (name + 6, "2l") || !strcmp (name + 6, "4f") || !strcmp (name + 6, "4ui") || !strcmp (name + 6, "4i") || !strcmp (name + 6, "8s") || !strcmp (name + 6, "8us") || !strcmp (name + 6, "16b") || !strcmp (name + 6, "16sb");
4358         }
4359
4360         mono_loader_unlock ();
4361
4362         mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4363
4364         return class;
4365 }
4366
4367 /** is klass Nullable<T>? */
4368 gboolean
4369 mono_class_is_nullable (MonoClass *klass)
4370 {
4371        return klass->generic_class != NULL &&
4372                klass->generic_class->container_class == mono_defaults.generic_nullable_class;
4373 }
4374
4375
4376 /** if klass is T? return T */
4377 MonoClass*
4378 mono_class_get_nullable_param (MonoClass *klass)
4379 {
4380        g_assert (mono_class_is_nullable (klass));
4381        return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4382 }
4383
4384 /*
4385  * Create the `MonoClass' for an instantiation of a generic type.
4386  * We only do this if we actually need it.
4387  */
4388 MonoClass*
4389 mono_generic_class_get_class (MonoGenericClass *gclass)
4390 {
4391         MonoClass *klass, *gklass;
4392
4393         mono_loader_lock ();
4394         if (gclass->cached_class) {
4395                 mono_loader_unlock ();
4396                 return gclass->cached_class;
4397         }
4398
4399         gclass->cached_class = g_malloc0 (sizeof (MonoClass));
4400         klass = gclass->cached_class;
4401
4402         gklass = gclass->container_class;
4403
4404         if (gklass->nested_in) {
4405                 /* 
4406                  * FIXME: the nested type context should include everything the
4407                  * nesting context should have, but it may also have additional
4408                  * generic parameters...
4409                  */
4410                 klass->nested_in = mono_class_inflate_generic_class (gklass->nested_in,
4411                                                                                                                          mono_generic_class_get_context (gclass));
4412         }
4413
4414         klass->name = gklass->name;
4415         klass->name_space = gklass->name_space;
4416         
4417         mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4418         
4419         klass->image = gklass->image;
4420         klass->flags = gklass->flags;
4421         klass->type_token = gklass->type_token;
4422         klass->field.count = gklass->field.count;
4423
4424         klass->is_inflated = 1;
4425         klass->generic_class = gclass;
4426
4427         klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
4428         klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
4429         klass->this_arg.byref = TRUE;
4430         klass->enumtype = gklass->enumtype;
4431         klass->valuetype = gklass->valuetype;
4432
4433         klass->cast_class = klass->element_class = klass;
4434
4435         if (mono_class_is_nullable (klass))
4436                 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
4437
4438         /*
4439          * We're not interested in the nested classes of a generic instance.
4440          * We use the generic type definition to look for nested classes.
4441          */
4442
4443         if (gklass->parent) {
4444                 klass->parent = mono_class_inflate_generic_class (gklass->parent, mono_generic_class_get_context (gclass));
4445         }
4446
4447         if (klass->parent)
4448                 mono_class_setup_parent (klass, klass->parent);
4449
4450         if (klass->enumtype) {
4451                 klass->cast_class = gklass->cast_class;
4452                 klass->element_class = gklass->element_class;
4453         }
4454
4455         if (gclass->is_dynamic) {
4456                 klass->inited = 1;
4457
4458                 mono_class_setup_supertypes (klass);
4459
4460                 if (klass->enumtype) {
4461                         /*
4462                          * For enums, gklass->fields might not been set, but instance_size etc. is 
4463                          * already set in mono_reflection_create_internal_class (). For non-enums,
4464                          * these will be computed normally in mono_class_layout_fields ().
4465                          */
4466                         klass->instance_size = gklass->instance_size;
4467                         klass->sizes.class_size = gklass->sizes.class_size;
4468                         klass->size_inited = 1;
4469                 }
4470         }
4471
4472         mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4473
4474         inflated_classes ++;
4475         inflated_classes_size += sizeof (MonoClass);
4476         
4477         mono_loader_unlock ();
4478
4479         return klass;
4480 }
4481
4482 static MonoClass*
4483 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
4484 {
4485         MonoClass *klass, **ptr;
4486         int count, pos, i;
4487
4488         if (!image)
4489                 /* FIXME: */
4490                 image = mono_defaults.corlib;
4491
4492         klass = mono_image_alloc0 (image, sizeof (MonoClass));
4493         classes_size += sizeof (MonoClass);
4494
4495         if (pinfo) {
4496                 klass->name = pinfo->name;
4497         } else {
4498                 int n = mono_generic_param_num (param);
4499                 klass->name = mono_image_alloc0 (image, 16);
4500                 sprintf ((char*)klass->name, "%d", n);
4501         }
4502
4503         klass->name_space = "";
4504         mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4505
4506         count = 0;
4507         if (pinfo)
4508                 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
4509                         ;
4510
4511         pos = 0;
4512         if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
4513                 klass->parent = pinfo->constraints [0];
4514                 pos++;
4515         } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
4516                 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
4517         else
4518                 klass->parent = mono_defaults.object_class;
4519
4520
4521         if (count - pos > 0) {
4522                 klass->interface_count = count - pos;
4523                 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
4524                 for (i = pos; i < count; i++)
4525                         klass->interfaces [i - pos] = pinfo->constraints [i];
4526         }
4527
4528         klass->image = image;
4529
4530         klass->inited = TRUE;
4531         klass->cast_class = klass->element_class = klass;
4532         klass->flags = TYPE_ATTRIBUTE_PUBLIC;
4533
4534         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
4535         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
4536         klass->this_arg.byref = TRUE;
4537
4538         /* FIXME: shouldn't this be ->type_token? */
4539         klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
4540
4541         mono_class_setup_supertypes (klass);
4542
4543         return klass;
4544 }
4545
4546 #define FAST_CACHE_SIZE 1024
4547 static MonoClass *var_cache_fast [FAST_CACHE_SIZE];
4548 static MonoClass *mvar_cache_fast [FAST_CACHE_SIZE];
4549 static GHashTable *var_cache_slow;
4550 static GHashTable *mvar_cache_slow;
4551
4552 static MonoClass *
4553 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
4554 {
4555         int n = mono_generic_param_num (param);
4556         GHashTable *ht;
4557
4558         if (n < FAST_CACHE_SIZE)
4559                 return (is_mvar ? mvar_cache_fast : var_cache_fast) [n];
4560         ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4561         return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
4562 }
4563
4564 static void
4565 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
4566 {
4567         int n = mono_generic_param_num (param);
4568         GHashTable *ht;
4569
4570         if (n < FAST_CACHE_SIZE) {
4571                 (is_mvar ? mvar_cache_fast : var_cache_fast) [n] = klass;
4572                 return;
4573         }
4574         ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4575         if (!ht) {
4576                 ht = g_hash_table_new (NULL, NULL);
4577                 if (is_mvar)
4578                         mvar_cache_slow = ht;
4579                 else
4580                         var_cache_slow = ht;
4581         }
4582
4583         g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
4584 }
4585
4586 /*
4587  * LOCKING: Acquires the loader lock.
4588  */
4589 MonoClass *
4590 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
4591 {
4592         MonoGenericContainer *container = mono_generic_param_owner (param);
4593         MonoGenericParamInfo *pinfo;
4594         MonoClass *klass;
4595
4596         mono_loader_lock ();
4597
4598         if (container) {
4599                 pinfo = mono_generic_param_info (param);
4600                 if (pinfo->pklass) {
4601                         mono_loader_unlock ();
4602                         return pinfo->pklass;
4603                 }
4604         } else {
4605                 pinfo = NULL;
4606                 image = NULL;
4607
4608                 klass = get_anon_gparam_class (param, is_mvar);
4609                 if (klass) {
4610                         mono_loader_unlock ();
4611                         return klass;
4612                 }
4613         }
4614
4615         if (!image && container) {
4616                 if (is_mvar) {
4617                         MonoMethod *method = container->owner.method;
4618                         image = (method && method->klass) ? method->klass->image : NULL;
4619                 } else {
4620                         MonoClass *klass = container->owner.klass;
4621                         // FIXME: 'klass' should not be null
4622                         //        But, monodis creates GenericContainers without associating a owner to it
4623                         image = klass ? klass->image : NULL;
4624                 }
4625         }
4626
4627         klass = make_generic_param_class (param, image, is_mvar, pinfo);
4628
4629         mono_memory_barrier ();
4630
4631         if (container)
4632                 pinfo->pklass = klass;
4633         else
4634                 set_anon_gparam_class (param, is_mvar, klass);
4635
4636         mono_loader_unlock ();
4637
4638         /* FIXME: Should this go inside 'make_generic_param_klass'? */
4639         mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4640
4641         return klass;
4642 }
4643
4644 MonoClass *
4645 mono_ptr_class_get (MonoType *type)
4646 {
4647         MonoClass *result;
4648         MonoClass *el_class;
4649         MonoImage *image;
4650         char *name;
4651
4652         el_class = mono_class_from_mono_type (type);
4653         image = el_class->image;
4654
4655         mono_loader_lock ();
4656
4657         if (!image->ptr_cache)
4658                 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4659
4660         if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
4661                 mono_loader_unlock ();
4662                 return result;
4663         }
4664         result = mono_image_alloc0 (image, sizeof (MonoClass));
4665
4666         classes_size += sizeof (MonoClass);
4667
4668         result->parent = NULL; /* no parent for PTR types */
4669         result->name_space = el_class->name_space;
4670         name = g_strdup_printf ("%s*", el_class->name);
4671         result->name = mono_image_strdup (image, name);
4672         g_free (name);
4673
4674         mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4675
4676         result->image = el_class->image;
4677         result->inited = TRUE;
4678         result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4679         /* Can pointers get boxed? */
4680         result->instance_size = sizeof (gpointer);
4681         result->cast_class = result->element_class = el_class;
4682         result->blittable = TRUE;
4683
4684         result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
4685         result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
4686         result->this_arg.byref = TRUE;
4687
4688         mono_class_setup_supertypes (result);
4689
4690         g_hash_table_insert (image->ptr_cache, el_class, result);
4691
4692         mono_loader_unlock ();
4693
4694         mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4695
4696         return result;
4697 }
4698
4699 static MonoClass *
4700 mono_fnptr_class_get (MonoMethodSignature *sig)
4701 {
4702         MonoClass *result;
4703         static GHashTable *ptr_hash = NULL;
4704
4705         /* FIXME: These should be allocate from a mempool as well, but which one ? */
4706
4707         mono_loader_lock ();
4708
4709         if (!ptr_hash)
4710                 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
4711         
4712         if ((result = g_hash_table_lookup (ptr_hash, sig))) {
4713                 mono_loader_unlock ();
4714                 return result;
4715         }
4716         result = g_new0 (MonoClass, 1);
4717
4718         result->parent = NULL; /* no parent for PTR types */
4719         result->name_space = "System";
4720         result->name = "MonoFNPtrFakeClass";
4721
4722         mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4723
4724         result->image = mono_defaults.corlib; /* need to fix... */
4725         result->inited = TRUE;
4726         result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
4727         /* Can pointers get boxed? */
4728         result->instance_size = sizeof (gpointer);
4729         result->cast_class = result->element_class = result;
4730         result->blittable = TRUE;
4731
4732         result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
4733         result->this_arg.data.method = result->byval_arg.data.method = sig;
4734         result->this_arg.byref = TRUE;
4735         result->blittable = TRUE;
4736
4737         mono_class_setup_supertypes (result);
4738
4739         g_hash_table_insert (ptr_hash, sig, result);
4740
4741         mono_loader_unlock ();
4742
4743         mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4744
4745         return result;
4746 }
4747
4748 MonoClass *
4749 mono_class_from_mono_type (MonoType *type)
4750 {
4751         switch (type->type) {
4752         case MONO_TYPE_OBJECT:
4753                 return type->data.klass? type->data.klass: mono_defaults.object_class;
4754         case MONO_TYPE_VOID:
4755                 return type->data.klass? type->data.klass: mono_defaults.void_class;
4756         case MONO_TYPE_BOOLEAN:
4757                 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
4758         case MONO_TYPE_CHAR:
4759                 return type->data.klass? type->data.klass: mono_defaults.char_class;
4760         case MONO_TYPE_I1:
4761                 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
4762         case MONO_TYPE_U1:
4763                 return type->data.klass? type->data.klass: mono_defaults.byte_class;
4764         case MONO_TYPE_I2:
4765                 return type->data.klass? type->data.klass: mono_defaults.int16_class;
4766         case MONO_TYPE_U2:
4767                 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
4768         case MONO_TYPE_I4:
4769                 return type->data.klass? type->data.klass: mono_defaults.int32_class;
4770         case MONO_TYPE_U4:
4771                 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
4772         case MONO_TYPE_I:
4773                 return type->data.klass? type->data.klass: mono_defaults.int_class;
4774         case MONO_TYPE_U:
4775                 return type->data.klass? type->data.klass: mono_defaults.uint_class;
4776         case MONO_TYPE_I8:
4777                 return type->data.klass? type->data.klass: mono_defaults.int64_class;
4778         case MONO_TYPE_U8:
4779                 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
4780         case MONO_TYPE_R4:
4781                 return type->data.klass? type->data.klass: mono_defaults.single_class;
4782         case MONO_TYPE_R8:
4783                 return type->data.klass? type->data.klass: mono_defaults.double_class;
4784         case MONO_TYPE_STRING:
4785                 return type->data.klass? type->data.klass: mono_defaults.string_class;
4786         case MONO_TYPE_TYPEDBYREF:
4787                 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
4788         case MONO_TYPE_ARRAY:
4789                 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
4790         case MONO_TYPE_PTR:
4791                 return mono_ptr_class_get (type->data.type);
4792         case MONO_TYPE_FNPTR:
4793                 return mono_fnptr_class_get (type->data.method);
4794         case MONO_TYPE_SZARRAY:
4795                 return mono_array_class_get (type->data.klass, 1);
4796         case MONO_TYPE_CLASS:
4797         case MONO_TYPE_VALUETYPE:
4798                 return type->data.klass;
4799         case MONO_TYPE_GENERICINST:
4800                 return mono_generic_class_get_class (type->data.generic_class);
4801         case MONO_TYPE_VAR:
4802                 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
4803         case MONO_TYPE_MVAR:
4804                 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
4805         default:
4806                 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
4807                 g_assert_not_reached ();
4808         }
4809         
4810         return NULL;
4811 }
4812
4813 /**
4814  * mono_type_retrieve_from_typespec
4815  * @image: context where the image is created
4816  * @type_spec:  typespec token
4817  * @context: the generic context used to evaluate generic instantiations in
4818  */
4819 static MonoType *
4820 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate)
4821 {
4822         MonoType *t = mono_type_create_from_typespec (image, type_spec);
4823         if (!t)
4824                 return NULL;
4825         if (context && (context->class_inst || context->method_inst)) {
4826                 MonoType *inflated = inflate_generic_type (NULL, t, context);
4827                 if (inflated) {
4828                         t = inflated;
4829                         *did_inflate = TRUE;
4830                 }
4831         }
4832         return t;
4833 }
4834
4835 /**
4836  * mono_class_create_from_typespec
4837  * @image: context where the image is created
4838  * @type_spec:  typespec token
4839  * @context: the generic context used to evaluate generic instantiations in
4840  */
4841 static MonoClass *
4842 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
4843 {
4844         MonoClass *ret;
4845         gboolean inflated = FALSE;
4846         MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated);
4847         if (!t)
4848                 return NULL;
4849         ret = mono_class_from_mono_type (t);
4850         if (inflated)
4851                 mono_metadata_free_type (t);
4852         return ret;
4853 }
4854
4855 /**
4856  * mono_bounded_array_class_get:
4857  * @element_class: element class 
4858  * @rank: the dimension of the array class
4859  * @bounded: whenever the array has non-zero bounds
4860  *
4861  * Returns: a class object describing the array with element type @element_type and 
4862  * dimension @rank. 
4863  */
4864 MonoClass *
4865 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
4866 {
4867         MonoImage *image;
4868         MonoClass *class;
4869         MonoClass *parent = NULL;
4870         GSList *list, *rootlist;
4871         int nsize;
4872         char *name;
4873         gboolean corlib_type = FALSE;
4874
4875         g_assert (rank <= 255);
4876
4877         if (rank > 1)
4878                 /* bounded only matters for one-dimensional arrays */
4879                 bounded = FALSE;
4880
4881         image = eclass->image;
4882
4883         if (rank == 1 && !bounded) {
4884                 /* 
4885                  * This case is very frequent not just during compilation because of calls 
4886                  * from mono_class_from_mono_type (), mono_array_new (), 
4887                  * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
4888                  */
4889                 EnterCriticalSection (&image->szarray_cache_lock);
4890                 if (!image->szarray_cache)
4891                         image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4892                 class = g_hash_table_lookup (image->szarray_cache, eclass);
4893                 LeaveCriticalSection (&image->szarray_cache_lock);
4894                 if (class)
4895                         return class;
4896
4897                 mono_loader_lock ();
4898         } else {
4899                 mono_loader_lock ();
4900
4901                 if (!image->array_cache)
4902                         image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4903
4904                 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
4905                         for (; list; list = list->next) {
4906                                 class = list->data;
4907                                 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
4908                                         mono_loader_unlock ();
4909                                         return class;
4910                                 }
4911                         }
4912                 }
4913         }
4914
4915         /* for the building corlib use System.Array from it */
4916         if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
4917                 parent = mono_class_from_name (image, "System", "Array");
4918                 corlib_type = TRUE;
4919         } else {
4920                 parent = mono_defaults.array_class;
4921                 if (!parent->inited)
4922                         mono_class_init (parent);
4923         }
4924
4925         class = mono_image_alloc0 (image, sizeof (MonoClass));
4926
4927         class->image = image;
4928         class->name_space = eclass->name_space;
4929         nsize = strlen (eclass->name);
4930         name = g_malloc (nsize + 2 + rank + 1);
4931         memcpy (name, eclass->name, nsize);
4932         name [nsize] = '[';
4933         if (rank > 1)
4934                 memset (name + nsize + 1, ',', rank - 1);
4935         if (bounded)
4936                 name [nsize + rank] = '*';
4937         name [nsize + rank + bounded] = ']';
4938         name [nsize + rank + bounded + 1] = 0;
4939         class->name = mono_image_strdup (image, name);
4940         g_free (name);
4941
4942         mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4943
4944         classes_size += sizeof (MonoClass);
4945
4946         class->type_token = 0;
4947         /* all arrays are marked serializable and sealed, bug #42779 */
4948         class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
4949                 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4950         class->parent = parent;
4951         class->instance_size = mono_class_instance_size (class->parent);
4952
4953         if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
4954                 if (!eclass->reflection_info || eclass->wastypebuilder) {
4955                         g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
4956                         g_assert (eclass->reflection_info && !eclass->wastypebuilder);
4957                 }
4958                 /* element_size -1 is ok as this is not an instantitable type*/
4959                 class->sizes.element_size = -1;
4960         } else
4961                 class->sizes.element_size = mono_class_array_element_size (eclass);
4962
4963         mono_class_setup_supertypes (class);
4964
4965         if (eclass->generic_class)
4966                 mono_class_init (eclass);
4967         if (!eclass->size_inited)
4968                 mono_class_setup_fields (eclass);
4969         class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
4970
4971         class->rank = rank;
4972         
4973         if (eclass->enumtype)
4974                 class->cast_class = eclass->element_class;
4975         else
4976                 class->cast_class = eclass;
4977
4978         class->element_class = eclass;
4979
4980         if ((rank > 1) || bounded) {
4981                 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
4982                 class->byval_arg.type = MONO_TYPE_ARRAY;
4983                 class->byval_arg.data.array = at;
4984                 at->eklass = eclass;
4985                 at->rank = rank;
4986                 /* FIXME: complete.... */
4987         } else {
4988                 class->byval_arg.type = MONO_TYPE_SZARRAY;
4989                 class->byval_arg.data.klass = eclass;
4990         }
4991         class->this_arg = class->byval_arg;
4992         class->this_arg.byref = 1;
4993         if (corlib_type) {
4994                 class->inited = 1;
4995         }
4996
4997         class->generic_container = eclass->generic_container;
4998
4999         if (rank == 1 && !bounded) {
5000                 MonoClass *prev_class;
5001
5002                 EnterCriticalSection (&image->szarray_cache_lock);
5003                 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
5004                 if (prev_class)
5005                         /* Someone got in before us */
5006                         class = prev_class;
5007                 else
5008                         g_hash_table_insert (image->szarray_cache, eclass, class);
5009                 LeaveCriticalSection (&image->szarray_cache_lock);
5010         } else {
5011                 list = g_slist_append (rootlist, class);
5012                 g_hash_table_insert (image->array_cache, eclass, list);
5013         }
5014
5015         mono_loader_unlock ();
5016
5017         mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5018
5019         return class;
5020 }
5021
5022 /**
5023  * mono_array_class_get:
5024  * @element_class: element class 
5025  * @rank: the dimension of the array class
5026  *
5027  * Returns: a class object describing the array with element type @element_type and 
5028  * dimension @rank. 
5029  */
5030 MonoClass *
5031 mono_array_class_get (MonoClass *eclass, guint32 rank)
5032 {
5033         return mono_bounded_array_class_get (eclass, rank, FALSE);
5034 }
5035
5036 /**
5037  * mono_class_instance_size:
5038  * @klass: a class 
5039  * 
5040  * Returns: the size of an object instance
5041  */
5042 gint32
5043 mono_class_instance_size (MonoClass *klass)
5044 {       
5045         if (!klass->size_inited)
5046                 mono_class_init (klass);
5047
5048         return klass->instance_size;
5049 }
5050
5051 /**
5052  * mono_class_min_align:
5053  * @klass: a class 
5054  * 
5055  * Returns: minimm alignment requirements 
5056  */
5057 gint32
5058 mono_class_min_align (MonoClass *klass)
5059 {       
5060         if (!klass->size_inited)
5061                 mono_class_init (klass);
5062
5063         return klass->min_align;
5064 }
5065
5066 /**
5067  * mono_class_value_size:
5068  * @klass: a class 
5069  *
5070  * This function is used for value types, and return the
5071  * space and the alignment to store that kind of value object.
5072  *
5073  * Returns: the size of a value of kind @klass
5074  */
5075 gint32
5076 mono_class_value_size      (MonoClass *klass, guint32 *align)
5077 {
5078         gint32 size;
5079
5080         /* fixme: check disable, because we still have external revereces to
5081          * mscorlib and Dummy Objects 
5082          */
5083         /*g_assert (klass->valuetype);*/
5084
5085         size = mono_class_instance_size (klass) - sizeof (MonoObject);
5086
5087         if (align)
5088                 *align = klass->min_align;
5089
5090         return size;
5091 }
5092
5093 /**
5094  * mono_class_data_size:
5095  * @klass: a class 
5096  * 
5097  * Returns: the size of the static class data
5098  */
5099 gint32
5100 mono_class_data_size (MonoClass *klass)
5101 {       
5102         if (!klass->inited)
5103                 mono_class_init (klass);
5104
5105         /* in arrays, sizes.class_size is unioned with element_size
5106          * and arrays have no static fields
5107          */
5108         if (klass->rank)
5109                 return 0;
5110         return klass->sizes.class_size;
5111 }
5112
5113 /*
5114  * Auxiliary routine to mono_class_get_field
5115  *
5116  * Takes a field index instead of a field token.
5117  */
5118 static MonoClassField *
5119 mono_class_get_field_idx (MonoClass *class, int idx)
5120 {
5121         mono_class_setup_fields_locking (class);
5122
5123         while (class) {
5124                 if (class->image->uncompressed_metadata) {
5125                         /* 
5126                          * class->field.first points to the FieldPtr table, while idx points into the
5127                          * Field table, so we have to do a search.
5128                          */
5129                         const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
5130                         int i;
5131
5132                         for (i = 0; i < class->field.count; ++i)
5133                                 if (mono_field_get_name (&class->fields [i]) == name)
5134                                         return &class->fields [i];
5135                         g_assert_not_reached ();
5136                 } else {                        
5137                         if (class->field.count) {
5138                                 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
5139                                         return &class->fields [idx - class->field.first];
5140                                 }
5141                         }
5142                 }
5143                 class = class->parent;
5144         }
5145         return NULL;
5146 }
5147
5148 /**
5149  * mono_class_get_field:
5150  * @class: the class to lookup the field.
5151  * @field_token: the field token
5152  *
5153  * Returns: A MonoClassField representing the type and offset of
5154  * the field, or a NULL value if the field does not belong to this
5155  * class.
5156  */
5157 MonoClassField *
5158 mono_class_get_field (MonoClass *class, guint32 field_token)
5159 {
5160         int idx = mono_metadata_token_index (field_token);
5161
5162         g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
5163
5164         return mono_class_get_field_idx (class, idx - 1);
5165 }
5166
5167 /**
5168  * mono_class_get_field_from_name:
5169  * @klass: the class to lookup the field.
5170  * @name: the field name
5171  *
5172  * Search the class @klass and it's parents for a field with the name @name.
5173  * 
5174  * Returns: the MonoClassField pointer of the named field or NULL
5175  */
5176 MonoClassField *
5177 mono_class_get_field_from_name (MonoClass *klass, const char *name)
5178 {
5179         int i;
5180
5181         mono_class_setup_fields_locking (klass);
5182         while (klass) {
5183                 for (i = 0; i < klass->field.count; ++i) {
5184                         if (strcmp (name, mono_field_get_name (&klass->fields [i])) == 0)
5185                                 return &klass->fields [i];
5186                 }
5187                 klass = klass->parent;
5188         }
5189         return NULL;
5190 }
5191
5192 /**
5193  * mono_class_get_field_token:
5194  * @field: the field we need the token of
5195  *
5196  * Get the token of a field. Note that the tokesn is only valid for the image
5197  * the field was loaded from. Don't use this function for fields in dynamic types.
5198  * 
5199  * Returns: the token representing the field in the image it was loaded from.
5200  */
5201 guint32
5202 mono_class_get_field_token (MonoClassField *field)
5203 {
5204         MonoClass *klass = field->parent;
5205         int i;
5206
5207         mono_class_setup_fields_locking (klass);
5208         while (klass) {
5209                 for (i = 0; i < klass->field.count; ++i) {
5210                         if (&klass->fields [i] == field) {
5211                                 int idx = klass->field.first + i + 1;
5212
5213                                 if (klass->image->uncompressed_metadata)
5214                                         idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
5215                                 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
5216                         }
5217                 }
5218                 klass = klass->parent;
5219         }
5220
5221         g_assert_not_reached ();
5222         return 0;
5223 }
5224
5225 static int
5226 mono_field_get_index (MonoClassField *field)
5227 {
5228         int index = field - field->parent->fields;
5229
5230         g_assert (index >= 0 && index < field->parent->field.count);
5231
5232         return index;
5233 }
5234
5235 /*
5236  * mono_class_get_field_default_value:
5237  *
5238  * Return the default value of the field as a pointer into the metadata blob.
5239  */
5240 const char*
5241 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
5242 {
5243         guint32 cindex;
5244         guint32 constant_cols [MONO_CONSTANT_SIZE];
5245         int field_index;
5246         MonoClass *klass = field->parent;
5247
5248         g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
5249
5250         if (!klass->ext || !klass->ext->field_def_values) {
5251                 mono_loader_lock ();
5252                 mono_class_alloc_ext (klass);
5253                 if (!klass->ext->field_def_values)
5254                         klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
5255                 mono_loader_unlock ();
5256         }
5257
5258         field_index = mono_field_get_index (field);
5259                 
5260         if (!klass->ext->field_def_values [field_index].data) {
5261                 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
5262                 g_assert (cindex);
5263                 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
5264
5265                 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
5266                 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
5267                 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
5268         }
5269
5270         *def_type = klass->ext->field_def_values [field_index].def_type;
5271         return klass->ext->field_def_values [field_index].data;
5272 }
5273
5274 guint32
5275 mono_class_get_event_token (MonoEvent *event)
5276 {
5277         MonoClass *klass = event->parent;
5278         int i;
5279
5280         while (klass) {
5281                 if (klass->ext) {
5282                         for (i = 0; i < klass->ext->event.count; ++i) {
5283                                 if (&klass->ext->events [i] == event)
5284                                         return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
5285                         }
5286                 }
5287                 klass = klass->parent;
5288         }
5289
5290         g_assert_not_reached ();
5291         return 0;
5292 }
5293
5294 MonoProperty*
5295 mono_class_get_property_from_name (MonoClass *klass, const char *name)
5296 {
5297         while (klass) {
5298                 MonoProperty* p;
5299                 gpointer iter = NULL;
5300                 while ((p = mono_class_get_properties (klass, &iter))) {
5301                         if (! strcmp (name, p->name))
5302                                 return p;
5303                 }
5304                 klass = klass->parent;
5305         }
5306         return NULL;
5307 }
5308
5309 guint32
5310 mono_class_get_property_token (MonoProperty *prop)
5311 {
5312         MonoClass *klass = prop->parent;
5313         while (klass) {
5314                 MonoProperty* p;
5315                 int i = 0;
5316                 gpointer iter = NULL;
5317                 while ((p = mono_class_get_properties (klass, &iter))) {
5318                         if (&klass->ext->properties [i] == prop)
5319                                 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
5320                         
5321                         i ++;
5322                 }
5323                 klass = klass->parent;
5324         }
5325
5326         g_assert_not_reached ();
5327         return 0;
5328 }
5329
5330 char *
5331 mono_class_name_from_token (MonoImage *image, guint32 type_token)
5332 {
5333         const char *name, *nspace;
5334         if (image->dynamic)
5335                 return g_strdup_printf ("DynamicType 0x%08x", type_token);
5336         
5337         switch (type_token & 0xff000000){
5338         case MONO_TOKEN_TYPE_DEF: {
5339                 guint32 cols [MONO_TYPEDEF_SIZE];
5340                 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5341                 guint tidx = mono_metadata_token_index (type_token);
5342
5343                 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5344                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5345                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5346                 if (strlen (nspace) == 0)
5347                         return g_strdup_printf ("%s", name);
5348                 else
5349                         return g_strdup_printf ("%s.%s", nspace, name);
5350         }
5351
5352         case MONO_TOKEN_TYPE_REF: {
5353                 guint32 cols [MONO_TYPEREF_SIZE];
5354                 MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
5355
5356                 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5357                 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
5358                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
5359                 if (strlen (nspace) == 0)
5360                         return g_strdup_printf ("%s", name);
5361                 else
5362                         return g_strdup_printf ("%s.%s", nspace, name);
5363         }
5364                 
5365         case MONO_TOKEN_TYPE_SPEC:
5366                 return g_strdup_printf ("Typespec 0x%08x", type_token);
5367         default:
5368                 g_assert_not_reached ();
5369         }
5370
5371         return NULL;
5372 }
5373
5374 static char *
5375 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
5376 {
5377         if (image->dynamic)
5378                 return g_strdup_printf ("DynamicAssembly %s", image->name);
5379         
5380         switch (type_token & 0xff000000){
5381         case MONO_TOKEN_TYPE_DEF:
5382                 return mono_stringify_assembly_name (&image->assembly->aname);
5383                 break;
5384         case MONO_TOKEN_TYPE_REF: {
5385                 MonoAssemblyName aname;
5386                 guint32 cols [MONO_TYPEREF_SIZE];
5387                 MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
5388                 guint32 idx;
5389         
5390                 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5391
5392                 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
5393                 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
5394                 case MONO_RESOLTION_SCOPE_MODULE:
5395                         /* FIXME: */
5396                         return g_strdup ("");
5397                 case MONO_RESOLTION_SCOPE_MODULEREF:
5398                         /* FIXME: */
5399                         return g_strdup ("");
5400                 case MONO_RESOLTION_SCOPE_TYPEREF:
5401                         /* FIXME: */
5402                         return g_strdup ("");
5403                 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
5404                         mono_assembly_get_assemblyref (image, idx - 1, &aname);
5405                         return mono_stringify_assembly_name (&aname);
5406                 default:
5407                         g_assert_not_reached ();
5408                 }
5409                 break;
5410         }
5411         case MONO_TOKEN_TYPE_SPEC:
5412                 /* FIXME: */
5413                 return g_strdup ("");
5414         default:
5415                 g_assert_not_reached ();
5416         }
5417
5418         return NULL;
5419 }
5420
5421 /**
5422  * mono_class_get_full:
5423  * @image: the image where the class resides
5424  * @type_token: the token for the class
5425  * @context: the generic context used to evaluate generic instantiations in
5426  *
5427  * Returns: the MonoClass that represents @type_token in @image
5428  */
5429 MonoClass *
5430 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5431 {
5432         MonoClass *class = NULL;
5433
5434         if (image->dynamic) {
5435                 int table = mono_metadata_token_table (type_token);
5436
5437                 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
5438                         mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
5439                         return NULL;
5440                 }
5441                 return mono_lookup_dynamic_token (image, type_token, context);
5442         }
5443
5444         switch (type_token & 0xff000000){
5445         case MONO_TOKEN_TYPE_DEF:
5446                 class = mono_class_create_from_typedef (image, type_token);
5447                 break;          
5448         case MONO_TOKEN_TYPE_REF:
5449                 class = mono_class_from_typeref (image, type_token);
5450                 break;
5451         case MONO_TOKEN_TYPE_SPEC:
5452                 class = mono_class_create_from_typespec (image, type_token, context);
5453                 break;
5454         default:
5455                 g_warning ("unknown token type %x", type_token & 0xff000000);
5456                 g_assert_not_reached ();
5457         }
5458
5459         if (!class){
5460                 char *name = mono_class_name_from_token (image, type_token);
5461                 char *assembly = mono_assembly_name_from_token (image, type_token);
5462                 mono_loader_set_error_type_load (name, assembly);
5463         }
5464
5465         return class;
5466 }
5467
5468
5469 /**
5470  * mono_type_get_full:
5471  * @image: the image where the type resides
5472  * @type_token: the token for the type
5473  * @context: the generic context used to evaluate generic instantiations in
5474  *
5475  * This functions exists to fullfill the fact that sometimes it's desirable to have access to the 
5476  * 
5477  * Returns: the MonoType that represents @type_token in @image
5478  */
5479 MonoType *
5480 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5481 {
5482         MonoType *type = NULL;
5483         gboolean inflated = FALSE;
5484
5485         //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
5486         if (image->dynamic)
5487                 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
5488
5489         if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
5490                 MonoClass *class = mono_class_get_full (image, type_token, context);
5491                 return class ? mono_class_get_type (class) : NULL;
5492         }
5493
5494         type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated);
5495
5496         if (!type) {
5497                 char *name = mono_class_name_from_token (image, type_token);
5498                 char *assembly = mono_assembly_name_from_token (image, type_token);
5499                 if (inflated)
5500                         mono_metadata_free_type (type);
5501                 mono_loader_set_error_type_load (name, assembly);
5502         }
5503
5504         if (inflated) {
5505                 MonoType *tmp = type;
5506                 type = mono_class_get_type (mono_class_from_mono_type (type));
5507                 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
5508                  * A MonoClass::byval_arg of a generic type definion has type CLASS.
5509                  * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
5510                  *
5511                  * The long term solution is to chaise this places and make then set MonoType::type correctly.
5512                  * */
5513                 if (type->type != tmp->type)
5514                         type = tmp;
5515                 else
5516                         mono_metadata_free_type (tmp);
5517         }
5518         return type;
5519 }
5520
5521
5522 MonoClass *
5523 mono_class_get (MonoImage *image, guint32 type_token)
5524 {
5525         return mono_class_get_full (image, type_token, NULL);
5526 }
5527
5528 /**
5529  * mono_image_init_name_cache:
5530  *
5531  *  Initializes the class name cache stored in image->name_cache.
5532  *
5533  * LOCKING: Acquires the loader lock.
5534  */
5535 void
5536 mono_image_init_name_cache (MonoImage *image)
5537 {
5538         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
5539         guint32 cols [MONO_TYPEDEF_SIZE];
5540         const char *name;
5541         const char *nspace;
5542         guint32 i, visib, nspace_index;
5543         GHashTable *name_cache2, *nspace_table;
5544
5545         mono_loader_lock ();
5546
5547         image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
5548
5549         if (image->dynamic) {
5550                 mono_loader_unlock ();
5551                 return;
5552         }
5553
5554         /* Temporary hash table to avoid lookups in the nspace_table */
5555         name_cache2 = g_hash_table_new (NULL, NULL);
5556
5557         for (i = 1; i <= t->rows; ++i) {
5558                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5559                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5560                 /*
5561                  * Nested types are accessed from the nesting name.  We use the fact that nested types use different visibility flags
5562                  * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5563                  */
5564                 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5565                         continue;
5566                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5567                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5568
5569                 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
5570                 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5571                 if (!nspace_table) {
5572                         nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5573                         g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5574                         g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5575                                                                  nspace_table);
5576                 }
5577                 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
5578         }
5579
5580         /* Load type names from EXPORTEDTYPES table */
5581         {
5582                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5583                 guint32 cols [MONO_EXP_TYPE_SIZE];
5584                 int i;
5585
5586                 for (i = 0; i < t->rows; ++i) {
5587                         mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
5588                         name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
5589                         nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
5590
5591                         nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
5592                         nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5593                         if (!nspace_table) {
5594                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5595                                 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5596                                 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5597                                                                          nspace_table);
5598                         }
5599                         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
5600                 }
5601         }
5602
5603         g_hash_table_destroy (name_cache2);
5604
5605         mono_loader_unlock ();
5606 }
5607
5608 void
5609 mono_image_add_to_name_cache (MonoImage *image, const char *nspace, 
5610                                                           const char *name, guint32 index)
5611 {
5612         GHashTable *nspace_table;
5613         GHashTable *name_cache;
5614
5615         mono_loader_lock ();
5616
5617         if (!image->name_cache)
5618                 mono_image_init_name_cache (image);
5619
5620         name_cache = image->name_cache;
5621         if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
5622                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5623                 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
5624         }
5625         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
5626
5627         mono_loader_unlock ();
5628 }
5629
5630 typedef struct {
5631         gconstpointer key;
5632         gpointer value;
5633 } FindUserData;
5634
5635 static void
5636 find_nocase (gpointer key, gpointer value, gpointer user_data)
5637 {
5638         char *name = (char*)key;
5639         FindUserData *data = (FindUserData*)user_data;
5640
5641         if (!data->value && (g_strcasecmp (name, (char*)data->key) == 0))
5642                 data->value = value;
5643 }
5644
5645 /**
5646  * mono_class_from_name_case:
5647  * @image: The MonoImage where the type is looked up in
5648  * @name_space: the type namespace
5649  * @name: the type short name.
5650  *
5651  * Obtains a MonoClass with a given namespace and a given name which
5652  * is located in the given MonoImage.   The namespace and name
5653  * lookups are case insensitive.
5654  */
5655 MonoClass *
5656 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
5657 {
5658         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
5659         guint32 cols [MONO_TYPEDEF_SIZE];
5660         const char *n;
5661         const char *nspace;
5662         guint32 i, visib;
5663
5664         if (image->dynamic) {
5665                 guint32 token = 0;
5666                 FindUserData user_data;
5667
5668                 mono_loader_lock ();
5669
5670                 if (!image->name_cache)
5671                         mono_image_init_name_cache (image);
5672
5673                 user_data.key = name_space;
5674                 user_data.value = NULL;
5675                 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
5676
5677                 if (user_data.value) {
5678                         GHashTable *nspace_table = (GHashTable*)user_data.value;
5679
5680                         user_data.key = name;
5681                         user_data.value = NULL;
5682
5683                         g_hash_table_foreach (nspace_table, find_nocase, &user_data);
5684                         
5685                         if (user_data.value)
5686                                 token = GPOINTER_TO_UINT (user_data.value);
5687                 }
5688
5689                 mono_loader_unlock ();
5690                 
5691                 if (token)
5692                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
5693                 else
5694                         return NULL;
5695
5696         }
5697
5698         /* add a cache if needed */
5699         for (i = 1; i <= t->rows; ++i) {
5700                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5701                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5702                 /*
5703                  * Nested types are accessed from the nesting name.  We use the fact that nested types use different visibility flags
5704                  * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5705                  */
5706                 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5707                         continue;
5708                 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5709                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5710                 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
5711                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
5712         }
5713         return NULL;
5714 }
5715
5716 static MonoClass*
5717 return_nested_in (MonoClass *class, char *nested)
5718 {
5719         MonoClass *found;
5720         char *s = strchr (nested, '/');
5721         gpointer iter = NULL;
5722
5723         if (s) {
5724                 *s = 0;
5725                 s++;
5726         }
5727
5728         while ((found = mono_class_get_nested_types (class, &iter))) {
5729                 if (strcmp (found->name, nested) == 0) {
5730                         if (s)
5731                                 return return_nested_in (found, s);
5732                         return found;
5733                 }
5734         }
5735         return NULL;
5736 }
5737
5738 static MonoClass*
5739 search_modules (MonoImage *image, const char *name_space, const char *name)
5740 {
5741         MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
5742         MonoImage *file_image;
5743         MonoClass *class;
5744         int i;
5745
5746         /* 
5747          * The EXPORTEDTYPES table only contains public types, so have to search the
5748          * modules as well.
5749          * Note: image->modules contains the contents of the MODULEREF table, while
5750          * the real module list is in the FILE table.
5751          */
5752         for (i = 0; i < file_table->rows; i++) {
5753                 guint32 cols [MONO_FILE_SIZE];
5754                 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
5755                 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
5756                         continue;
5757
5758                 file_image = mono_image_load_file_for_image (image, i + 1);
5759                 if (file_image) {
5760                         class = mono_class_from_name (file_image, name_space, name);
5761                         if (class)
5762                                 return class;
5763                 }
5764         }
5765
5766         return NULL;
5767 }
5768
5769 /**
5770  * mono_class_from_name:
5771  * @image: The MonoImage where the type is looked up in
5772  * @name_space: the type namespace
5773  * @name: the type short name.
5774  *
5775  * Obtains a MonoClass with a given namespace and a given name which
5776  * is located in the given MonoImage.   
5777  */
5778 MonoClass *
5779 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
5780 {
5781         GHashTable *nspace_table;
5782         MonoImage *loaded_image;
5783         guint32 token = 0;
5784         int i;
5785         MonoClass *class;
5786         char *nested;
5787         char buf [1024];
5788
5789         if ((nested = strchr (name, '/'))) {
5790                 int pos = nested - name;
5791                 int len = strlen (name);
5792                 if (len > 1023)
5793                         return NULL;
5794                 memcpy (buf, name, len + 1);
5795                 buf [pos] = 0;
5796                 nested = buf + pos + 1;
5797                 name = buf;
5798         }
5799
5800         if (get_class_from_name) {
5801                 gboolean res = get_class_from_name (image, name_space, name, &class);
5802                 if (res) {
5803                         if (!class)
5804                                 class = search_modules (image, name_space, name);
5805                         if (nested)
5806                                 return class ? return_nested_in (class, nested) : NULL;
5807                         else
5808                                 return class;
5809                 }
5810         }
5811
5812         mono_loader_lock ();
5813
5814         if (!image->name_cache)
5815                 mono_image_init_name_cache (image);
5816
5817         nspace_table = g_hash_table_lookup (image->name_cache, name_space);
5818
5819         if (nspace_table)
5820                 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
5821
5822         mono_loader_unlock ();
5823
5824         if (!token && image->dynamic && image->modules) {
5825                 /* Search modules as well */
5826                 for (i = 0; i < image->module_count; ++i) {
5827                         MonoImage *module = image->modules [i];
5828
5829                         class = mono_class_from_name (module, name_space, name);
5830                         if (class)
5831                                 return class;
5832                 }
5833         }
5834
5835         if (!token) {
5836                 class = search_modules (image, name_space, name);
5837                 if (class)
5838                         return class;
5839         }
5840
5841         if (!token)
5842                 return NULL;
5843
5844         if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
5845                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5846                 guint32 cols [MONO_EXP_TYPE_SIZE];
5847                 guint32 idx, impl;
5848
5849                 idx = mono_metadata_token_index (token);
5850
5851                 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
5852
5853                 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
5854                 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
5855                         loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
5856                         if (!loaded_image)
5857                                 return NULL;
5858                         class = mono_class_from_name (loaded_image, name_space, name);
5859                         if (nested)
5860                                 return return_nested_in (class, nested);
5861                         return class;
5862                 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
5863                         MonoAssembly **references = image->references;
5864                         guint32 assembly_idx;
5865
5866                         assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
5867
5868                         if (!references [assembly_idx - 1])
5869                                 mono_assembly_load_reference (image, assembly_idx - 1);
5870                         g_assert (references == image->references);
5871                         g_assert (references [assembly_idx - 1]);
5872                         if (references [assembly_idx - 1] == (gpointer)-1)
5873                                 return NULL;                    
5874                         else
5875                                 /* FIXME: Cycle detection */
5876                                 return mono_class_from_name (references [assembly_idx - 1]->image, name_space, name);
5877                 } else {
5878                         g_error ("not yet implemented");
5879                 }
5880         }
5881
5882         token = MONO_TOKEN_TYPE_DEF | token;
5883
5884         class = mono_class_get (image, token);
5885         if (nested)
5886                 return return_nested_in (class, nested);
5887         return class;
5888 }
5889
5890 gboolean
5891 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc, 
5892                            gboolean check_interfaces)
5893 {
5894         g_assert (klassc->idepth > 0);
5895         if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
5896                 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
5897                         return TRUE;
5898         } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
5899                 int i;
5900
5901                 for (i = 0; i < klass->interface_count; i ++) {
5902                         MonoClass *ic =  klass->interfaces [i];
5903                         if (ic == klassc)
5904                                 return TRUE;
5905                 }
5906         } else {
5907                 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
5908                         return TRUE;
5909         }
5910
5911         /* 
5912          * MS.NET thinks interfaces are a subclass of Object, so we think it as
5913          * well.
5914          */
5915         if (klassc == mono_defaults.object_class)
5916                 return TRUE;
5917
5918         return FALSE;
5919 }
5920
5921 static gboolean
5922 mono_class_has_variant_generic_params (MonoClass *klass)
5923 {
5924         int i;
5925         MonoGenericContainer *container;
5926
5927         if (!klass->generic_class)
5928                 return FALSE;
5929
5930         container = klass->generic_class->container_class->generic_container;
5931
5932         for (i = 0; i < container->type_argc; ++i)
5933                 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
5934                         return TRUE;
5935
5936         return FALSE;
5937 }
5938
5939 /**
5940  * mono_class_is_assignable_from:
5941  * @klass: the class to be assigned to
5942  * @oklass: the source class
5943  *
5944  * Return: true if an instance of object oklass can be assigned to an
5945  * instance of object @klass
5946  */
5947 gboolean
5948 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
5949 {
5950         if (!klass->inited)
5951                 mono_class_init (klass);
5952
5953         if (!oklass->inited)
5954                 mono_class_init (oklass);
5955
5956         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
5957                 return klass == oklass;
5958
5959         if (MONO_CLASS_IS_INTERFACE (klass)) {
5960                 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
5961                         return FALSE;
5962
5963                 /* interface_offsets might not be set for dynamic classes */
5964                 if (oklass->reflection_info && !oklass->interface_bitmap)
5965                         /* 
5966                          * oklass might be a generic type parameter but they have 
5967                          * interface_offsets set.
5968                          */
5969                         return mono_reflection_call_is_assignable_to (oklass, klass);
5970                 if (!oklass->interface_bitmap)
5971                         /* Happens with generic instances of not-yet created dynamic types */
5972                         return FALSE;
5973                 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
5974                         return TRUE;
5975
5976                 if (mono_class_has_variant_generic_params (klass)) {
5977                         if (oklass->generic_class) {
5978                                 int i;
5979                                 gboolean match = FALSE;
5980                                 MonoClass *container_class1 = klass->generic_class->container_class;
5981                                 MonoClass *container_class2 = oklass->generic_class->container_class;
5982
5983                                 /* 
5984                                  * Check whenever the generic definition of oklass implements the 
5985                                  * generic definition of klass. The IMPLEMENTS_INTERFACE stuff is not usable
5986                                  * here since the relevant tables are not set up.
5987                                  */
5988                                 for (i = 0; i < container_class2->interface_offsets_count; ++i)
5989                                         if ((container_class2->interfaces_packed [i] == container_class1) || (container_class2->interfaces_packed [i]->generic_class && (container_class2->interfaces_packed [i]->generic_class->container_class == container_class1)))
5990                                                 match = TRUE;
5991
5992                                 if (match) {
5993                                         MonoGenericContainer *container;
5994
5995                                         container = klass->generic_class->container_class->generic_container;
5996
5997                                         match = TRUE;
5998                                         for (i = 0; i < container->type_argc; ++i) {
5999                                                 MonoClass *param1_class = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [i]);
6000                                                 MonoClass *param2_class = mono_class_from_mono_type (oklass->generic_class->context.class_inst->type_argv [i]);
6001
6002                                                 if (param1_class->valuetype != param2_class->valuetype) {
6003                                                         match = FALSE;
6004                                                         break;
6005                                                 }
6006                                                 /*
6007                                                  * The _VARIANT and _COVARIANT constants should read _COVARIANT and
6008                                                  * _CONTRAVARIANT, but they are in a public header so we can't fix it.
6009                                                  */
6010                                                 if (param1_class != param2_class) {
6011                                                         if ((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_VARIANT) && mono_class_is_assignable_from (param1_class, param2_class))
6012                                                                 ;
6013                                                         else if (((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_COVARIANT) && mono_class_is_assignable_from (param2_class, param1_class)))
6014                                                                 ;
6015                                                         else {
6016                                                                 match = FALSE;
6017                                                                 break;
6018                                                         }
6019                                                 }
6020                                         }
6021
6022                                         if (match)
6023                                                 return TRUE;
6024                                 }
6025                         }
6026                 }
6027         } else if (klass->rank) {
6028                 MonoClass *eclass, *eoclass;
6029
6030                 if (oklass->rank != klass->rank)
6031                         return FALSE;
6032
6033                 /* vectors vs. one dimensional arrays */
6034                 if (oklass->byval_arg.type != klass->byval_arg.type)
6035                         return FALSE;
6036
6037                 eclass = klass->cast_class;
6038                 eoclass = oklass->cast_class;
6039
6040                 /* 
6041                  * a is b does not imply a[] is b[] when a is a valuetype, and
6042                  * b is a reference type.
6043                  */
6044
6045                 if (eoclass->valuetype) {
6046                         if ((eclass == mono_defaults.enum_class) || 
6047                                 (eclass == mono_defaults.enum_class->parent) ||
6048                                 (eclass == mono_defaults.object_class))
6049                                 return FALSE;
6050                 }
6051
6052                 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6053         } else if (mono_class_is_nullable (klass)) {
6054                 if (mono_class_is_nullable (oklass))
6055                         return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6056                 else
6057                         return mono_class_is_assignable_from (klass->cast_class, oklass);
6058         } else if (klass == mono_defaults.object_class)
6059                 return TRUE;
6060
6061         return mono_class_has_parent (oklass, klass);
6062 }       
6063
6064 /**
6065  * mono_class_get_cctor:
6066  * @klass: A MonoClass pointer
6067  *
6068  * Returns: the static constructor of @klass if it exists, NULL otherwise.
6069  */
6070 MonoMethod*
6071 mono_class_get_cctor (MonoClass *klass)
6072 {
6073         MonoCachedClassInfo cached_info;
6074
6075         if (!klass->has_cctor)
6076                 return NULL;
6077
6078         if (mono_class_get_cached_class_info (klass, &cached_info))
6079                 return mono_get_method (klass->image, cached_info.cctor_token, klass);
6080
6081         if (klass->generic_class && !klass->methods)
6082                 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
6083
6084         return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
6085 }
6086
6087 /**
6088  * mono_class_get_finalizer:
6089  * @klass: The MonoClass pointer
6090  *
6091  * Returns: the finalizer method of @klass if it exists, NULL otherwise.
6092  */
6093 MonoMethod*
6094 mono_class_get_finalizer (MonoClass *klass)
6095 {
6096         MonoCachedClassInfo cached_info;
6097
6098         if (!klass->inited)
6099                 mono_class_init (klass);
6100         if (!klass->has_finalize)
6101                 return NULL;
6102
6103         if (mono_class_get_cached_class_info (klass, &cached_info))
6104                 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
6105         else {
6106                 mono_class_setup_vtable (klass);
6107                 return klass->vtable [finalize_slot];
6108         }
6109 }
6110
6111 /**
6112  * mono_class_needs_cctor_run:
6113  * @klass: the MonoClass pointer
6114  * @caller: a MonoMethod describing the caller
6115  *
6116  * Determines whenever the class has a static constructor and whenever it
6117  * needs to be called when executing CALLER.
6118  */
6119 gboolean
6120 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
6121 {
6122         MonoMethod *method;
6123
6124         method = mono_class_get_cctor (klass);
6125         if (method)
6126                 return (method == caller) ? FALSE : TRUE;
6127         else
6128                 return TRUE;
6129 }
6130
6131 /**
6132  * mono_class_array_element_size:
6133  * @klass: 
6134  *
6135  * Returns: the number of bytes an element of type @klass
6136  * uses when stored into an array.
6137  */
6138 gint32
6139 mono_class_array_element_size (MonoClass *klass)
6140 {
6141         MonoType *type = &klass->byval_arg;
6142         
6143 handle_enum:
6144         switch (type->type) {
6145         case MONO_TYPE_I1:
6146         case MONO_TYPE_U1:
6147         case MONO_TYPE_BOOLEAN:
6148                 return 1;
6149         case MONO_TYPE_I2:
6150         case MONO_TYPE_U2:
6151         case MONO_TYPE_CHAR:
6152                 return 2;
6153         case MONO_TYPE_I4:
6154         case MONO_TYPE_U4:
6155         case MONO_TYPE_R4:
6156                 return 4;
6157         case MONO_TYPE_I:
6158         case MONO_TYPE_U:
6159         case MONO_TYPE_PTR:
6160         case MONO_TYPE_CLASS:
6161         case MONO_TYPE_STRING:
6162         case MONO_TYPE_OBJECT:
6163         case MONO_TYPE_SZARRAY:
6164         case MONO_TYPE_ARRAY: 
6165         case MONO_TYPE_VAR:
6166         case MONO_TYPE_MVAR:   
6167                 return sizeof (gpointer);
6168         case MONO_TYPE_I8:
6169         case MONO_TYPE_U8:
6170         case MONO_TYPE_R8:
6171                 return 8;
6172         case MONO_TYPE_VALUETYPE:
6173                 if (type->data.klass->enumtype) {
6174                         type = mono_class_enum_basetype (type->data.klass);
6175                         klass = klass->element_class;
6176                         goto handle_enum;
6177                 }
6178                 return mono_class_instance_size (klass) - sizeof (MonoObject);
6179         case MONO_TYPE_GENERICINST:
6180                 type = &type->data.generic_class->container_class->byval_arg;
6181                 goto handle_enum;
6182         default:
6183                 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
6184         }
6185         return -1;
6186 }
6187
6188 /**
6189  * mono_array_element_size:
6190  * @ac: pointer to a #MonoArrayClass
6191  *
6192  * Returns: the size of single array element.
6193  */
6194 gint32
6195 mono_array_element_size (MonoClass *ac)
6196 {
6197         g_assert (ac->rank);
6198         return ac->sizes.element_size;
6199 }
6200
6201 gpointer
6202 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
6203               MonoGenericContext *context)
6204 {
6205         if (image->dynamic) {
6206                 MonoClass *tmp_handle_class;
6207                 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
6208
6209                 g_assert (tmp_handle_class);
6210                 if (handle_class)
6211                         *handle_class = tmp_handle_class;
6212
6213                 if (tmp_handle_class == mono_defaults.typehandle_class)
6214                         return &((MonoClass*)obj)->byval_arg;
6215                 else
6216                         return obj;
6217         }
6218
6219         switch (token & 0xff000000) {
6220         case MONO_TOKEN_TYPE_DEF:
6221         case MONO_TOKEN_TYPE_REF:
6222         case MONO_TOKEN_TYPE_SPEC: {
6223                 MonoType *type;
6224                 if (handle_class)
6225                         *handle_class = mono_defaults.typehandle_class;
6226                 type = mono_type_get_full (image, token, context);
6227                 if (!type)
6228                         return NULL;
6229                 mono_class_init (mono_class_from_mono_type (type));
6230                 /* We return a MonoType* as handle */
6231                 return type;
6232         }
6233         case MONO_TOKEN_FIELD_DEF: {
6234                 MonoClass *class;
6235                 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
6236                 if (handle_class)
6237                         *handle_class = mono_defaults.fieldhandle_class;
6238                 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
6239                 if (!class)
6240                         return NULL;
6241                 mono_class_init (class);
6242                 return mono_class_get_field (class, token);
6243         }
6244         case MONO_TOKEN_METHOD_DEF:
6245         case MONO_TOKEN_METHOD_SPEC: {
6246                 MonoMethod *meth;
6247                 meth = mono_get_method_full (image, token, NULL, context);
6248                 if (handle_class)
6249                         *handle_class = mono_defaults.methodhandle_class;
6250                 return meth;
6251         }
6252         case MONO_TOKEN_MEMBER_REF: {
6253                 guint32 cols [MONO_MEMBERREF_SIZE];
6254                 const char *sig;
6255                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
6256                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6257                 mono_metadata_decode_blob_size (sig, &sig);
6258                 if (*sig == 0x6) { /* it's a field */
6259                         MonoClass *klass;
6260                         MonoClassField *field;
6261                         field = mono_field_from_token (image, token, &klass, context);
6262                         if (handle_class)
6263                                 *handle_class = mono_defaults.fieldhandle_class;
6264                         return field;
6265                 } else {
6266                         MonoMethod *meth;
6267                         meth = mono_get_method_full (image, token, NULL, context);
6268                         if (handle_class)
6269                                 *handle_class = mono_defaults.methodhandle_class;
6270                         return meth;
6271                 }
6272         }
6273         default:
6274                 g_warning ("Unknown token 0x%08x in ldtoken", token);
6275                 break;
6276         }
6277         return NULL;
6278 }
6279
6280 /**
6281  * This function might need to call runtime functions so it can't be part
6282  * of the metadata library.
6283  */
6284 static MonoLookupDynamicToken lookup_dynamic = NULL;
6285
6286 void
6287 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
6288 {
6289         lookup_dynamic = func;
6290 }
6291
6292 gpointer
6293 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
6294 {
6295         MonoClass *handle_class;
6296
6297         return lookup_dynamic (image, token, TRUE, &handle_class, context);
6298 }
6299
6300 gpointer
6301 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
6302 {
6303         return lookup_dynamic (image, token, valid_token, handle_class, context);
6304 }
6305
6306 static MonoGetCachedClassInfo get_cached_class_info = NULL;
6307
6308 void
6309 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
6310 {
6311         get_cached_class_info = func;
6312 }
6313
6314 static gboolean
6315 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
6316 {
6317         if (!get_cached_class_info)
6318                 return FALSE;
6319         else
6320                 return get_cached_class_info (klass, res);
6321 }
6322
6323 void
6324 mono_install_get_class_from_name (MonoGetClassFromName func)
6325 {
6326         get_class_from_name = func;
6327 }
6328
6329 MonoImage*
6330 mono_class_get_image (MonoClass *klass)
6331 {
6332         return klass->image;
6333 }
6334
6335 /**
6336  * mono_class_get_element_class:
6337  * @klass: the MonoClass to act on
6338  *
6339  * Returns: the element class of an array or an enumeration.
6340  */
6341 MonoClass*
6342 mono_class_get_element_class (MonoClass *klass)
6343 {
6344         return klass->element_class;
6345 }
6346
6347 /**
6348  * mono_class_is_valuetype:
6349  * @klass: the MonoClass to act on
6350  *
6351  * Returns: true if the MonoClass represents a ValueType.
6352  */
6353 gboolean
6354 mono_class_is_valuetype (MonoClass *klass)
6355 {
6356         return klass->valuetype;
6357 }
6358
6359 /**
6360  * mono_class_is_enum:
6361  * @klass: the MonoClass to act on
6362  *
6363  * Returns: true if the MonoClass represents an enumeration.
6364  */
6365 gboolean
6366 mono_class_is_enum (MonoClass *klass)
6367 {
6368         return klass->enumtype;
6369 }
6370
6371 /**
6372  * mono_class_enum_basetype:
6373  * @klass: the MonoClass to act on
6374  *
6375  * Returns: the underlying type representation for an enumeration.
6376  */
6377 MonoType*
6378 mono_class_enum_basetype (MonoClass *klass)
6379 {
6380         if (klass->element_class == klass)
6381                 /* SRE */
6382                 return NULL;
6383         else
6384                 return &klass->element_class->byval_arg;
6385 }
6386
6387 /**
6388  * mono_class_get_parent
6389  * @klass: the MonoClass to act on
6390  *
6391  * Returns: the parent class for this class.
6392  */
6393 MonoClass*
6394 mono_class_get_parent (MonoClass *klass)
6395 {
6396         return klass->parent;
6397 }
6398
6399 /**
6400  * mono_class_get_nesting_type;
6401  * @klass: the MonoClass to act on
6402  *
6403  * Returns: the container type where this type is nested or NULL if this type is not a nested type.
6404  */
6405 MonoClass*
6406 mono_class_get_nesting_type (MonoClass *klass)
6407 {
6408         return klass->nested_in;
6409 }
6410
6411 /**
6412  * mono_class_get_rank:
6413  * @klass: the MonoClass to act on
6414  *
6415  * Returns: the rank for the array (the number of dimensions).
6416  */
6417 int
6418 mono_class_get_rank (MonoClass *klass)
6419 {
6420         return klass->rank;
6421 }
6422
6423 /**
6424  * mono_class_get_flags:
6425  * @klass: the MonoClass to act on
6426  *
6427  * The type flags from the TypeDef table from the metadata.
6428  * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
6429  * different values.
6430  *
6431  * Returns: the flags from the TypeDef table.
6432  */
6433 guint32
6434 mono_class_get_flags (MonoClass *klass)
6435 {
6436         return klass->flags;
6437 }
6438
6439 /**
6440  * mono_class_get_name
6441  * @klass: the MonoClass to act on
6442  *
6443  * Returns: the name of the class.
6444  */
6445 const char*
6446 mono_class_get_name (MonoClass *klass)
6447 {
6448         return klass->name;
6449 }
6450
6451 /**
6452  * mono_class_get_namespace:
6453  * @klass: the MonoClass to act on
6454  *
6455  * Returns: the namespace of the class.
6456  */
6457 const char*
6458 mono_class_get_namespace (MonoClass *klass)
6459 {
6460         return klass->name_space;
6461 }
6462
6463 /**
6464  * mono_class_get_type:
6465  * @klass: the MonoClass to act on
6466  *
6467  * This method returns the internal Type representation for the class.
6468  *
6469  * Returns: the MonoType from the class.
6470  */
6471 MonoType*
6472 mono_class_get_type (MonoClass *klass)
6473 {
6474         return &klass->byval_arg;
6475 }
6476
6477 /**
6478  * mono_class_get_type_token
6479  * @klass: the MonoClass to act on
6480  *
6481  * This method returns type token for the class.
6482  *
6483  * Returns: the type token for the class.
6484  */
6485 guint32
6486 mono_class_get_type_token (MonoClass *klass)
6487 {
6488   return klass->type_token;
6489 }
6490
6491 /**
6492  * mono_class_get_byref_type:
6493  * @klass: the MonoClass to act on
6494  *
6495  * 
6496  */
6497 MonoType*
6498 mono_class_get_byref_type (MonoClass *klass)
6499 {
6500         return &klass->this_arg;
6501 }
6502
6503 /**
6504  * mono_class_num_fields:
6505  * @klass: the MonoClass to act on
6506  *
6507  * Returns: the number of static and instance fields in the class.
6508  */
6509 int
6510 mono_class_num_fields (MonoClass *klass)
6511 {
6512         return klass->field.count;
6513 }
6514
6515 /**
6516  * mono_class_num_methods:
6517  * @klass: the MonoClass to act on
6518  *
6519  * Returns: the number of methods in the class.
6520  */
6521 int
6522 mono_class_num_methods (MonoClass *klass)
6523 {
6524         return klass->method.count;
6525 }
6526
6527 /**
6528  * mono_class_num_properties
6529  * @klass: the MonoClass to act on
6530  *
6531  * Returns: the number of properties in the class.
6532  */
6533 int
6534 mono_class_num_properties (MonoClass *klass)
6535 {
6536         mono_class_setup_properties (klass);
6537
6538         return klass->ext->property.count;
6539 }
6540
6541 /**
6542  * mono_class_num_events:
6543  * @klass: the MonoClass to act on
6544  *
6545  * Returns: the number of events in the class.
6546  */
6547 int
6548 mono_class_num_events (MonoClass *klass)
6549 {
6550         mono_class_setup_events (klass);
6551
6552         return klass->ext->event.count;
6553 }
6554
6555 /**
6556  * mono_class_get_fields:
6557  * @klass: the MonoClass to act on
6558  *
6559  * This routine is an iterator routine for retrieving the fields in a class.
6560  *
6561  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6562  * iterate over all of the elements.  When no more values are
6563  * available, the return value is NULL.
6564  *
6565  * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
6566  */
6567 MonoClassField*
6568 mono_class_get_fields (MonoClass* klass, gpointer *iter)
6569 {
6570         MonoClassField* field;
6571         if (!iter)
6572                 return NULL;
6573         if (!*iter) {
6574                 mono_class_setup_fields_locking (klass);
6575                 if (klass->exception_type)
6576                         return NULL;
6577                 /* start from the first */
6578                 if (klass->field.count) {
6579                         return *iter = &klass->fields [0];
6580                 } else {
6581                         /* no fields */
6582                         return NULL;
6583                 }
6584         }
6585         field = *iter;
6586         field++;
6587         if (field < &klass->fields [klass->field.count]) {
6588                 return *iter = field;
6589         }
6590         return NULL;
6591 }
6592
6593 /**
6594  * mono_class_get_methods
6595  * @klass: the MonoClass to act on
6596  *
6597  * This routine is an iterator routine for retrieving the fields in a class.
6598  *
6599  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6600  * iterate over all of the elements.  When no more values are
6601  * available, the return value is NULL.
6602  *
6603  * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
6604  */
6605 MonoMethod*
6606 mono_class_get_methods (MonoClass* klass, gpointer *iter)
6607 {
6608         MonoMethod** method;
6609         if (!iter)
6610                 return NULL;
6611         if (!klass->inited)
6612                 mono_class_init (klass);
6613         if (!*iter) {
6614                 mono_class_setup_methods (klass);
6615                 /* start from the first */
6616                 if (klass->method.count) {
6617                         *iter = &klass->methods [0];
6618                         return klass->methods [0];
6619                 } else {
6620                         /* no method */
6621                         return NULL;
6622                 }
6623         }
6624         method = *iter;
6625         method++;
6626         if (method < &klass->methods [klass->method.count]) {
6627                 *iter = method;
6628                 return *method;
6629         }
6630         return NULL;
6631 }
6632
6633 /*
6634  * mono_class_get_virtual_methods:
6635  *
6636  *   Iterate over the virtual methods of KLASS.
6637  *
6638  * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
6639  */
6640 static MonoMethod*
6641 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
6642 {
6643         MonoMethod** method;
6644         if (!iter)
6645                 return NULL;
6646         if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
6647                 if (!*iter) {
6648                         mono_class_setup_methods (klass);
6649                         /* start from the first */
6650                         method = &klass->methods [0];
6651                 } else {
6652                         method = *iter;
6653                         method++;
6654                 }
6655                 while (method < &klass->methods [klass->method.count]) {
6656                         if (((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
6657                                 break;
6658                         method ++;
6659                 }
6660                 if (method < &klass->methods [klass->method.count]) {
6661                         *iter = method;
6662                         return *method;
6663                 } else {
6664                         return NULL;
6665                 }
6666         } else {
6667                 /* Search directly in metadata to avoid calling setup_methods () */
6668                 MonoMethod *res = NULL;
6669                 int i, start_index;
6670
6671                 if (!*iter) {
6672                         start_index = 0;
6673                 } else {
6674                         start_index = GPOINTER_TO_UINT (*iter);
6675                 }
6676
6677                 for (i = start_index; i < klass->method.count; ++i) {
6678                         guint32 cols [MONO_METHOD_SIZE];
6679
6680                         /* class->method.first points into the methodptr table */
6681                         mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
6682
6683                         if (cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_VIRTUAL)
6684                                 break;
6685                 }
6686
6687                 if (i < klass->method.count) {
6688                         res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
6689                         /* Add 1 here so the if (*iter) check fails */
6690                         *iter = GUINT_TO_POINTER (i + 1);
6691                         return res;
6692                 } else {
6693                         return NULL;
6694                 }
6695         }
6696 }
6697
6698 /**
6699  * mono_class_get_properties:
6700  * @klass: the MonoClass to act on
6701  *
6702  * This routine is an iterator routine for retrieving the properties in a class.
6703  *
6704  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6705  * iterate over all of the elements.  When no more values are
6706  * available, the return value is NULL.
6707  *
6708  * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
6709  */
6710 MonoProperty*
6711 mono_class_get_properties (MonoClass* klass, gpointer *iter)
6712 {
6713         MonoProperty* property;
6714         if (!iter)
6715                 return NULL;
6716         if (!klass->inited)
6717                 mono_class_init (klass);
6718         if (!*iter) {
6719                 mono_class_setup_properties (klass);
6720                 /* start from the first */
6721                 if (klass->ext->property.count) {
6722                         return *iter = &klass->ext->properties [0];
6723                 } else {
6724                         /* no fields */
6725                         return NULL;
6726                 }
6727         }
6728         property = *iter;
6729         property++;
6730         if (property < &klass->ext->properties [klass->ext->property.count]) {
6731                 return *iter = property;
6732         }
6733         return NULL;
6734 }
6735
6736 /**
6737  * mono_class_get_events:
6738  * @klass: the MonoClass to act on
6739  *
6740  * This routine is an iterator routine for retrieving the properties in a class.
6741  *
6742  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6743  * iterate over all of the elements.  When no more values are
6744  * available, the return value is NULL.
6745  *
6746  * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
6747  */
6748 MonoEvent*
6749 mono_class_get_events (MonoClass* klass, gpointer *iter)
6750 {
6751         MonoEvent* event;
6752         if (!iter)
6753                 return NULL;
6754         if (!klass->inited)
6755                 mono_class_init (klass);
6756         if (!*iter) {
6757                 mono_class_setup_events (klass);
6758                 /* start from the first */
6759                 if (klass->ext->event.count) {
6760                         return *iter = &klass->ext->events [0];
6761                 } else {
6762                         /* no fields */
6763                         return NULL;
6764                 }
6765         }
6766         event = *iter;
6767         event++;
6768         if (event < &klass->ext->events [klass->ext->event.count]) {
6769                 return *iter = event;
6770         }
6771         return NULL;
6772 }
6773
6774 /**
6775  * mono_class_get_interfaces
6776  * @klass: the MonoClass to act on
6777  *
6778  * This routine is an iterator routine for retrieving the interfaces implemented by this class.
6779  *
6780  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6781  * iterate over all of the elements.  When no more values are
6782  * available, the return value is NULL.
6783  *
6784  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
6785  */
6786 MonoClass*
6787 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
6788 {
6789         MonoClass** iface;
6790         if (!iter)
6791                 return NULL;
6792         if (!*iter) {
6793                 if (!klass->inited)
6794                         mono_class_init (klass);
6795                 if (!klass->interfaces_inited)
6796                         mono_class_setup_interfaces (klass);
6797                 /* start from the first */
6798                 if (klass->interface_count) {
6799                         *iter = &klass->interfaces [0];
6800                         return klass->interfaces [0];
6801                 } else {
6802                         /* no interface */
6803                         return NULL;
6804                 }
6805         }
6806         iface = *iter;
6807         iface++;
6808         if (iface < &klass->interfaces [klass->interface_count]) {
6809                 *iter = iface;
6810                 return *iface;
6811         }
6812         return NULL;
6813 }
6814
6815 /**
6816  * mono_class_get_nested_types
6817  * @klass: the MonoClass to act on
6818  *
6819  * This routine is an iterator routine for retrieving the nested types of a class.
6820  * This works only if @klass is non-generic, or a generic type definition.
6821  *
6822  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6823  * iterate over all of the elements.  When no more values are
6824  * available, the return value is NULL.
6825  *
6826  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
6827  */
6828 MonoClass*
6829 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
6830 {
6831         GList *item;
6832         int i;
6833
6834         if (!iter)
6835                 return NULL;
6836         if (!klass->inited)
6837                 mono_class_init (klass);
6838         if (!klass->nested_classes_inited) {
6839                 if (!klass->type_token)
6840                         klass->nested_classes_inited = TRUE;
6841                 mono_loader_lock ();
6842                 if (!klass->nested_classes_inited) {
6843                         i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
6844                         while (i) {
6845                                 MonoClass* nclass;
6846                                 guint32 cols [MONO_NESTED_CLASS_SIZE];
6847                                 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
6848                                 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
6849                                 mono_class_alloc_ext (klass);
6850                                 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
6851
6852                                 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
6853                         }
6854                 }
6855                 mono_memory_barrier ();
6856                 klass->nested_classes_inited = TRUE;
6857                 mono_loader_unlock ();
6858         }
6859
6860         if (!*iter) {
6861                 /* start from the first */
6862                 if (klass->ext && klass->ext->nested_classes) {
6863                         *iter = klass->ext->nested_classes;
6864                         return klass->ext->nested_classes->data;
6865                 } else {
6866                         /* no nested types */
6867                         return NULL;
6868                 }
6869         }
6870         item = *iter;
6871         item = item->next;
6872         if (item) {
6873                 *iter = item;
6874                 return item->data;
6875         }
6876         return NULL;
6877 }
6878
6879 /**
6880  * mono_field_get_name:
6881  * @field: the MonoClassField to act on
6882  *
6883  * Returns: the name of the field.
6884  */
6885 const char*
6886 mono_field_get_name (MonoClassField *field)
6887 {
6888         return field->name;
6889 }
6890
6891 /**
6892  * mono_field_get_type:
6893  * @field: the MonoClassField to act on
6894  *
6895  * Returns: MonoType of the field.
6896  */
6897 MonoType*
6898 mono_field_get_type (MonoClassField *field)
6899 {
6900         return field->type;
6901 }
6902
6903 /**
6904  * mono_field_get_type:
6905  * @field: the MonoClassField to act on
6906  *
6907  * Returns: MonoClass where the field was defined.
6908  */
6909 MonoClass*
6910 mono_field_get_parent (MonoClassField *field)
6911 {
6912         return field->parent;
6913 }
6914
6915 /**
6916  * mono_field_get_flags;
6917  * @field: the MonoClassField to act on
6918  *
6919  * The metadata flags for a field are encoded using the
6920  * FIELD_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
6921  *
6922  * Returns: the flags for the field.
6923  */
6924 guint32
6925 mono_field_get_flags (MonoClassField *field)
6926 {
6927         return field->type->attrs;
6928 }
6929
6930 /**
6931  * mono_field_get_offset;
6932  * @field: the MonoClassField to act on
6933  *
6934  * Returns: the field offset.
6935  */
6936 guint32
6937 mono_field_get_offset (MonoClassField *field)
6938 {
6939         return field->offset;
6940 }
6941
6942 static const char *
6943 mono_field_get_rva (MonoClassField *field)
6944 {
6945         guint32 rva;
6946         int field_index;
6947         MonoClass *klass = field->parent;
6948
6949         g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
6950
6951         if (!klass->ext || !klass->ext->field_def_values) {
6952                 mono_loader_lock ();
6953                 mono_class_alloc_ext (klass);
6954                 if (!klass->ext->field_def_values)
6955                         klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
6956                 mono_loader_unlock ();
6957         }
6958
6959         field_index = mono_field_get_index (field);
6960                 
6961         if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
6962                 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
6963                 if (!rva)
6964                         g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
6965                 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
6966         }
6967
6968         return klass->ext->field_def_values [field_index].data;
6969 }
6970
6971 /**
6972  * mono_field_get_data;
6973  * @field: the MonoClassField to act on
6974  *
6975  * Returns: pointer to the metadata constant value or to the field
6976  * data if it has an RVA flag.
6977  */
6978 const char *
6979 mono_field_get_data (MonoClassField *field)
6980 {
6981         if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
6982                 MonoTypeEnum def_type;
6983
6984                 return mono_class_get_field_default_value (field, &def_type);
6985         } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
6986                 return mono_field_get_rva (field);
6987         } else {
6988                 return NULL;
6989         }
6990 }
6991
6992 /**
6993  * mono_property_get_name: 
6994  * @prop: the MonoProperty to act on
6995  *
6996  * Returns: the name of the property
6997  */
6998 const char*
6999 mono_property_get_name (MonoProperty *prop)
7000 {
7001         return prop->name;
7002 }
7003
7004 /**
7005  * mono_property_get_set_method
7006  * @prop: the MonoProperty to act on.
7007  *
7008  * Returns: the setter method of the property (A MonoMethod)
7009  */
7010 MonoMethod*
7011 mono_property_get_set_method (MonoProperty *prop)
7012 {
7013         return prop->set;
7014 }
7015
7016 /**
7017  * mono_property_get_get_method
7018  * @prop: the MonoProperty to act on.
7019  *
7020  * Returns: the setter method of the property (A MonoMethod)
7021  */
7022 MonoMethod*
7023 mono_property_get_get_method (MonoProperty *prop)
7024 {
7025         return prop->get;
7026 }
7027
7028 /**
7029  * mono_property_get_parent:
7030  * @prop: the MonoProperty to act on.
7031  *
7032  * Returns: the MonoClass where the property was defined.
7033  */
7034 MonoClass*
7035 mono_property_get_parent (MonoProperty *prop)
7036 {
7037         return prop->parent;
7038 }
7039
7040 /**
7041  * mono_property_get_flags:
7042  * @prop: the MonoProperty to act on.
7043  *
7044  * The metadata flags for a property are encoded using the
7045  * PROPERTY_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
7046  *
7047  * Returns: the flags for the property.
7048  */
7049 guint32
7050 mono_property_get_flags (MonoProperty *prop)
7051 {
7052         return prop->attrs;
7053 }
7054
7055 /**
7056  * mono_event_get_name:
7057  * @event: the MonoEvent to act on
7058  *
7059  * Returns: the name of the event.
7060  */
7061 const char*
7062 mono_event_get_name (MonoEvent *event)
7063 {
7064         return event->name;
7065 }
7066
7067 /**
7068  * mono_event_get_add_method:
7069  * @event: The MonoEvent to act on.
7070  *
7071  * Returns: the @add' method for the event (a MonoMethod).
7072  */
7073 MonoMethod*
7074 mono_event_get_add_method (MonoEvent *event)
7075 {
7076         return event->add;
7077 }
7078
7079 /**
7080  * mono_event_get_remove_method:
7081  * @event: The MonoEvent to act on.
7082  *
7083  * Returns: the @remove method for the event (a MonoMethod).
7084  */
7085 MonoMethod*
7086 mono_event_get_remove_method (MonoEvent *event)
7087 {
7088         return event->remove;
7089 }
7090
7091 /**
7092  * mono_event_get_raise_method:
7093  * @event: The MonoEvent to act on.
7094  *
7095  * Returns: the @raise method for the event (a MonoMethod).
7096  */
7097 MonoMethod*
7098 mono_event_get_raise_method (MonoEvent *event)
7099 {
7100         return event->raise;
7101 }
7102
7103 /**
7104  * mono_event_get_parent:
7105  * @event: the MonoEvent to act on.
7106  *
7107  * Returns: the MonoClass where the event is defined.
7108  */
7109 MonoClass*
7110 mono_event_get_parent (MonoEvent *event)
7111 {
7112         return event->parent;
7113 }
7114
7115 /**
7116  * mono_event_get_flags
7117  * @event: the MonoEvent to act on.
7118  *
7119  * The metadata flags for an event are encoded using the
7120  * EVENT_* constants.  See the tabledefs.h file for details.
7121  *
7122  * Returns: the flags for the event.
7123  */
7124 guint32
7125 mono_event_get_flags (MonoEvent *event)
7126 {
7127         return event->attrs;
7128 }
7129
7130 /**
7131  * mono_class_get_method_from_name:
7132  * @klass: where to look for the method
7133  * @name_space: name of the method
7134  * @param_count: number of parameters. -1 for any number.
7135  *
7136  * Obtains a MonoMethod with a given name and number of parameters.
7137  * It only works if there are no multiple signatures for any given method name.
7138  */
7139 MonoMethod *
7140 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
7141 {
7142         return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
7143 }
7144
7145 static MonoMethod*
7146 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
7147 {
7148         MonoMethod *res = NULL;
7149         int i;
7150
7151         /* Search directly in the metadata to avoid calling setup_methods () */
7152         for (i = 0; i < klass->method.count; ++i) {
7153                 guint32 cols [MONO_METHOD_SIZE];
7154                 MonoMethod *method;
7155
7156                 /* class->method.first points into the methodptr table */
7157                 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
7158
7159                 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
7160                         method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7161                         if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
7162                                 res = method;
7163                                 break;
7164                         }
7165                 }
7166         }
7167
7168         return res;
7169 }
7170
7171 /**
7172  * mono_class_get_method_from_name_flags:
7173  * @klass: where to look for the method
7174  * @name_space: name of the method
7175  * @param_count: number of parameters. -1 for any number.
7176  * @flags: flags which must be set in the method
7177  *
7178  * Obtains a MonoMethod with a given name and number of parameters.
7179  * It only works if there are no multiple signatures for any given method name.
7180  */
7181 MonoMethod *
7182 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
7183 {
7184         MonoMethod *res = NULL;
7185         int i;
7186
7187         mono_class_init (klass);
7188
7189         if (klass->generic_class && !klass->methods) {
7190                 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
7191                 if (res)
7192                         res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
7193                 return res;
7194         }
7195
7196         if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
7197                 mono_class_setup_methods (klass);
7198                 for (i = 0; i < klass->method.count; ++i) {
7199                         MonoMethod *method = klass->methods [i];
7200
7201                         if (method->name[0] == name [0] && 
7202                                 !strcmp (name, method->name) &&
7203                                 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
7204                                 ((method->flags & flags) == flags)) {
7205                                 res = method;
7206                                 break;
7207                         }
7208                 }
7209         }
7210         else {
7211             res = find_method_in_metadata (klass, name, param_count, flags);
7212         }
7213
7214         return res;
7215 }
7216
7217 /**
7218  * mono_class_set_failure:
7219  * @klass: class in which the failure was detected
7220  * @ex_type: the kind of exception/error to be thrown (later)
7221  * @ex_data: exception data (specific to each type of exception/error)
7222  *
7223  * Keep a detected failure informations in the class for later processing.
7224  * Note that only the first failure is kept.
7225  *
7226  * LOCKING: Acquires the loader lock.
7227  */
7228 gboolean
7229 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
7230 {
7231         if (klass->exception_type)
7232                 return FALSE;
7233
7234         mono_loader_lock ();
7235         klass->exception_type = ex_type;
7236         if (ex_data)
7237                 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
7238         mono_loader_unlock ();
7239
7240         return TRUE;
7241 }
7242
7243 /*
7244  * mono_class_get_exception_data:
7245  *
7246  *   Return the exception_data property of KLASS.
7247  *
7248  * LOCKING: Acquires the loader lock.
7249  */
7250 gpointer
7251 mono_class_get_exception_data (MonoClass *klass)
7252 {
7253         return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
7254 }
7255
7256 /**
7257  * mono_classes_init:
7258  *
7259  * Initialize the resources used by this module.
7260  */
7261 void
7262 mono_classes_init (void)
7263 {
7264         mono_counters_register ("Inflated methods size",
7265                                                         MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
7266         mono_counters_register ("Inflated classes",
7267                                                         MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
7268         mono_counters_register ("Inflated classes size",
7269                                                         MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
7270         mono_counters_register ("MonoClass size",
7271                                                         MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
7272         mono_counters_register ("MonoClassExt size",
7273                                                         MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
7274 }
7275
7276 /**
7277  * mono_classes_cleanup:
7278  *
7279  * Free the resources used by this module.
7280  */
7281 void
7282 mono_classes_cleanup (void)
7283 {
7284         if (global_interface_bitset)
7285                 mono_bitset_free (global_interface_bitset);
7286 }
7287
7288 /**
7289  * mono_class_get_exception_for_failure:
7290  * @klass: class in which the failure was detected
7291  *
7292  * Return a constructed MonoException than the caller can then throw
7293  * using mono_raise_exception - or NULL if no failure is present (or
7294  * doesn't result in an exception).
7295  */
7296 MonoException*
7297 mono_class_get_exception_for_failure (MonoClass *klass)
7298 {
7299         gpointer exception_data = mono_class_get_exception_data (klass);
7300
7301         switch (klass->exception_type) {
7302         case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
7303                 MonoDomain *domain = mono_domain_get ();
7304                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
7305                 MonoMethod *method = exception_data;
7306                 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
7307                 MonoObject *exc = NULL;
7308                 gpointer args [4];
7309
7310                 args [0] = &error;
7311                 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
7312                 args [2] = mono_type_get_object (domain, &klass->byval_arg);
7313                 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
7314
7315                 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
7316                 return (MonoException*) exc;
7317         }
7318         case MONO_EXCEPTION_TYPE_LOAD: {
7319                 MonoString *name;
7320                 MonoException *ex;
7321                 char *str = mono_type_get_full_name (klass);
7322                 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
7323                 name = mono_string_new (mono_domain_get (), str);
7324                 g_free (str);
7325                 ex = mono_get_exception_type_load (name, astr);
7326                 g_free (astr);
7327                 return ex;
7328         }
7329         case MONO_EXCEPTION_MISSING_METHOD: {
7330                 char *class_name = exception_data;
7331                 char *assembly_name = class_name + strlen (class_name) + 1;
7332
7333                 return mono_get_exception_missing_method (class_name, assembly_name);
7334         }
7335         case MONO_EXCEPTION_MISSING_FIELD: {
7336                 char *class_name = exception_data;
7337                 char *member_name = class_name + strlen (class_name) + 1;
7338
7339                 return mono_get_exception_missing_field (class_name, member_name);
7340         }
7341         case MONO_EXCEPTION_FILE_NOT_FOUND: {
7342                 char *msg_format = exception_data;
7343                 char *assembly_name = msg_format + strlen (msg_format) + 1;
7344                 char *msg = g_strdup_printf (msg_format, assembly_name);
7345                 MonoException *ex;
7346
7347                 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
7348
7349                 g_free (msg);
7350
7351                 return ex;
7352         }
7353         case MONO_EXCEPTION_BAD_IMAGE: {
7354                 return mono_get_exception_bad_image_format (exception_data);
7355         }
7356         default: {
7357                 MonoLoaderError *error;
7358                 MonoException *ex;
7359                 
7360                 error = mono_loader_get_last_error ();
7361                 if (error != NULL){
7362                         ex = mono_loader_error_prepare_exception (error);
7363                         return ex;
7364                 }
7365                 
7366                 /* TODO - handle other class related failures */
7367                 return NULL;
7368         }
7369         }
7370 }
7371
7372 static gboolean
7373 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
7374  {
7375         outer_klass = mono_class_get_generic_type_definition (outer_klass);
7376         inner_klass = mono_class_get_generic_type_definition (inner_klass);
7377         do {
7378                 if (outer_klass == inner_klass)
7379                         return TRUE;
7380                 inner_klass = inner_klass->nested_in;
7381         } while (inner_klass);
7382         return FALSE;
7383 }
7384
7385 MonoClass *
7386 mono_class_get_generic_type_definition (MonoClass *klass)
7387 {
7388         return klass->generic_class ? klass->generic_class->container_class : klass;
7389 }
7390
7391 /*
7392  * Check if @klass is a subtype of @parent ignoring generic instantiations.
7393  * 
7394  * Generic instantiations are ignored for all super types of @klass.
7395  * 
7396  * Visibility checks ignoring generic instantiations.  
7397  */
7398 gboolean
7399 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
7400 {
7401         int i;
7402         klass = mono_class_get_generic_type_definition (klass);
7403         parent = mono_class_get_generic_type_definition (parent);
7404         
7405         for (i = 0; i < klass->idepth; ++i) {
7406                 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
7407                         return TRUE;
7408         }
7409         return FALSE;
7410 }
7411 /*
7412  * Subtype can only access parent members with family protection if the site object
7413  * is subclass of Subtype. For example:
7414  * class A { protected int x; }
7415  * class B : A {
7416  *      void valid_access () {
7417  *              B b;
7418  *              b.x = 0;
7419  *  }
7420  *  void invalid_access () {
7421  *              A a;
7422  *              a.x = 0;
7423  *  }
7424  * }
7425  * */
7426 static gboolean
7427 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
7428 {
7429         if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
7430                 return FALSE;
7431
7432         if (context_klass == NULL)
7433                 return TRUE;
7434         /*if access_klass is not member_klass context_klass must be type compat*/
7435         if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
7436                 return FALSE;
7437         return TRUE;
7438 }
7439
7440 static gboolean
7441 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
7442 {
7443         GSList *tmp;
7444         if (accessing == accessed)
7445                 return TRUE;
7446         if (!accessed || !accessing)
7447                 return FALSE;
7448         mono_assembly_load_friends (accessed);
7449         for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
7450                 MonoAssemblyName *friend = tmp->data;
7451                 /* Be conservative with checks */
7452                 if (!friend->name)
7453                         continue;
7454                 if (strcmp (accessing->aname.name, friend->name))
7455                         continue;
7456                 if (friend->public_key_token [0]) {
7457                         if (!accessing->aname.public_key_token [0])
7458                                 continue;
7459                         if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
7460                                 continue;
7461                 }
7462                 return TRUE;
7463         }
7464         return FALSE;
7465 }
7466
7467 /*
7468  * If klass is a generic type or if it is derived from a generic type, return the
7469  * MonoClass of the generic definition
7470  * Returns NULL if not found
7471  */
7472 static MonoClass*
7473 get_generic_definition_class (MonoClass *klass)
7474 {
7475         while (klass) {
7476                 if (klass->generic_class && klass->generic_class->container_class)
7477                         return klass->generic_class->container_class;
7478                 klass = klass->parent;
7479         }
7480         return NULL;
7481 }
7482
7483 static gboolean
7484 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
7485 {
7486         int i;
7487         for (i = 0; i < ginst->type_argc; ++i) {
7488                 MonoType *type = ginst->type_argv[i];
7489                 switch (type->type) {
7490                 case MONO_TYPE_SZARRAY:
7491                         if (!can_access_type (access_klass, type->data.klass))
7492                                 return FALSE;
7493                         break;
7494                 case MONO_TYPE_ARRAY:
7495                         if (!can_access_type (access_klass, type->data.array->eklass))
7496                                 return FALSE;
7497                         break;
7498                 case MONO_TYPE_PTR:
7499                         if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
7500                                 return FALSE;
7501                         break;
7502                 case MONO_TYPE_CLASS:
7503                 case MONO_TYPE_VALUETYPE:
7504                 case MONO_TYPE_GENERICINST:
7505                         if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
7506                                 return FALSE;
7507                 }
7508         }
7509         return TRUE;
7510 }
7511
7512 static gboolean
7513 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
7514 {
7515         int access_level;
7516
7517         if (access_klass->element_class && !access_klass->enumtype)
7518                 access_klass = access_klass->element_class;
7519
7520         if (member_klass->element_class && !member_klass->enumtype)
7521                 member_klass = member_klass->element_class;
7522
7523         access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
7524
7525         if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
7526                 return TRUE;
7527
7528         if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
7529                 return FALSE;
7530
7531         if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
7532                 return TRUE;
7533
7534         if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
7535                 return FALSE;
7536
7537         switch (access_level) {
7538         case TYPE_ATTRIBUTE_NOT_PUBLIC:
7539                 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7540
7541         case TYPE_ATTRIBUTE_PUBLIC:
7542                 return TRUE;
7543
7544         case TYPE_ATTRIBUTE_NESTED_PUBLIC:
7545                 return TRUE;
7546
7547         case TYPE_ATTRIBUTE_NESTED_PRIVATE:
7548                 return is_nesting_type (member_klass, access_klass);
7549
7550         case TYPE_ATTRIBUTE_NESTED_FAMILY:
7551                 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in); 
7552
7553         case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
7554                 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7555
7556         case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
7557                 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
7558                         mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7559
7560         case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
7561                 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
7562                         mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7563         }
7564         return FALSE;
7565 }
7566
7567 /* FIXME: check visibility of type, too */
7568 static gboolean
7569 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
7570 {
7571         MonoClass *member_generic_def;
7572         if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
7573                                         access_klass->generic_container) && 
7574                         (member_generic_def = get_generic_definition_class (member_klass))) {
7575                 MonoClass *access_container;
7576
7577                 if (access_klass->generic_container)
7578                         access_container = access_klass;
7579                 else
7580                         access_container = access_klass->generic_class->container_class;
7581
7582                 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
7583                         return TRUE;
7584         }
7585
7586         /* Partition I 8.5.3.2 */
7587         /* the access level values are the same for fields and methods */
7588         switch (access_level) {
7589         case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
7590                 /* same compilation unit */
7591                 return access_klass->image == member_klass->image;
7592         case FIELD_ATTRIBUTE_PRIVATE:
7593                 return access_klass == member_klass;
7594         case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
7595                 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
7596                     can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
7597                         return TRUE;
7598                 return FALSE;
7599         case FIELD_ATTRIBUTE_ASSEMBLY:
7600                 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7601         case FIELD_ATTRIBUTE_FAMILY:
7602                 if (is_valid_family_access (access_klass, member_klass, context_klass))
7603                         return TRUE;
7604                 return FALSE;
7605         case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
7606                 if (is_valid_family_access (access_klass, member_klass, context_klass))
7607                         return TRUE;
7608                 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7609         case FIELD_ATTRIBUTE_PUBLIC:
7610                 return TRUE;
7611         }
7612         return FALSE;
7613 }
7614
7615 gboolean
7616 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
7617 {
7618         /* FIXME: check all overlapping fields */
7619         int can = can_access_member (method->klass, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7620         if (!can) {
7621                 MonoClass *nested = method->klass->nested_in;
7622                 while (nested) {
7623                         can = can_access_member (nested, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7624                         if (can)
7625                                 return TRUE;
7626                         nested = nested->nested_in;
7627                 }
7628         }
7629         return can;
7630 }
7631
7632 gboolean
7633 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
7634 {
7635         int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7636         if (!can) {
7637                 MonoClass *nested = method->klass->nested_in;
7638                 while (nested) {
7639                         can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7640                         if (can)
7641                                 return TRUE;
7642                         nested = nested->nested_in;
7643                 }
7644         }
7645         /* 
7646          * FIXME:
7647          * with generics calls to explicit interface implementations can be expressed
7648          * directly: the method is private, but we must allow it. This may be opening
7649          * a hole or the generics code should handle this differently.
7650          * Maybe just ensure the interface type is public.
7651          */
7652         if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
7653                 return TRUE;
7654         return can;
7655 }
7656
7657 /*
7658  * mono_method_can_access_method_full:
7659  * @method: The caller method 
7660  * @called: The called method 
7661  * @context_klass: The static type on stack of the owner @called object used
7662  * 
7663  * This function must be used with instance calls, as they have more strict family accessibility.
7664  * It can be used with static methods, but context_klass should be NULL.
7665  * 
7666  * Returns: TRUE if caller have proper visibility and acessibility to @called
7667  */
7668 gboolean
7669 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
7670 {
7671         MonoClass *access_class = method->klass;
7672         MonoClass *member_class = called->klass;
7673         int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7674         if (!can) {
7675                 MonoClass *nested = access_class->nested_in;
7676                 while (nested) {
7677                         can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7678                         if (can)
7679                                 break;
7680                         nested = nested->nested_in;
7681                 }
7682         }
7683
7684         if (!can)
7685                 return FALSE;
7686
7687         if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
7688                 return FALSE;
7689
7690         if (called->is_inflated) {
7691                 MonoMethodInflated * infl = (MonoMethodInflated*)called;
7692                 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
7693                         return FALSE;
7694         }
7695                 
7696         return TRUE;
7697 }
7698
7699
7700 /*
7701  * mono_method_can_access_method_with_context:
7702  * @method: The caller method 
7703  * @field: The accessed field
7704  * @context_klass: The static type on stack of the owner @field object used
7705  * 
7706  * This function must be used with instance fields, as they have more strict family accessibility.
7707  * It can be used with static fields, but context_klass should be NULL.
7708  * 
7709  * Returns: TRUE if caller have proper visibility and acessibility to @field
7710  */
7711 gboolean
7712 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
7713 {
7714         MonoClass *access_class = method->klass;
7715         MonoClass *member_class = field->parent;
7716         /* FIXME: check all overlapping fields */
7717         int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7718         if (!can) {
7719                 MonoClass *nested = access_class->nested_in;
7720                 while (nested) {
7721                         can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7722                         if (can)
7723                                 break;
7724                         nested = nested->nested_in;
7725                 }
7726         }
7727
7728         if (!can)
7729                 return FALSE;
7730
7731         if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
7732                 return FALSE;
7733         return TRUE;
7734 }
7735
7736 /**
7737  * mono_type_is_valid_enum_basetype:
7738  * @type: The MonoType to check
7739  *
7740  * Returns: TRUE if the type can be used as the basetype of an enum
7741  */
7742 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
7743         switch (type->type) {
7744         case MONO_TYPE_I1:
7745         case MONO_TYPE_U1:
7746         case MONO_TYPE_BOOLEAN:
7747         case MONO_TYPE_I2:
7748         case MONO_TYPE_U2:
7749         case MONO_TYPE_CHAR:
7750         case MONO_TYPE_I4:
7751         case MONO_TYPE_U4:
7752         case MONO_TYPE_I8:
7753         case MONO_TYPE_U8:
7754         case MONO_TYPE_I:
7755         case MONO_TYPE_U:
7756                 return TRUE;
7757         }
7758         return FALSE;
7759 }
7760
7761 /**
7762  * mono_class_is_valid_enum:
7763  * @klass: An enum class to be validated
7764  *
7765  * This method verify the required properties an enum should have.
7766  *  
7767  * Returns: TRUE if the informed enum class is valid 
7768  *
7769  * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
7770  * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
7771  * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
7772  */
7773 gboolean mono_class_is_valid_enum (MonoClass *klass) {
7774         MonoClassField * field;
7775         gpointer iter = NULL;
7776         gboolean found_base_field = FALSE;
7777
7778         g_assert (klass->enumtype);
7779         /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
7780         if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
7781                 return FALSE;
7782         }
7783
7784         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
7785                 return FALSE;
7786
7787         while ((field = mono_class_get_fields (klass, &iter))) {
7788                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
7789                         if (found_base_field)
7790                                 return FALSE;
7791                         found_base_field = TRUE;
7792                         if (!mono_type_is_valid_enum_basetype (field->type))
7793                                 return FALSE;
7794                 }
7795         }
7796
7797         if (!found_base_field)
7798                 return FALSE;
7799
7800         if (klass->method.count > 0) 
7801                 return FALSE;
7802
7803         return TRUE;
7804 }
7805
7806 gboolean
7807 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
7808 {
7809         return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
7810 }
7811
7812 static gboolean gshared_supported;
7813
7814 void
7815 mono_set_generic_sharing_supported (gboolean supported)
7816 {
7817         gshared_supported = supported;
7818 }
7819
7820 /*
7821  * mono_class_generic_sharing_enabled:
7822  * @class: a class
7823  *
7824  * Returns whether generic sharing is enabled for class.
7825  *
7826  * This is a stop-gap measure to slowly introduce generic sharing
7827  * until we have all the issues sorted out, at which time this
7828  * function will disappear and generic sharing will always be enabled.
7829  */
7830 gboolean
7831 mono_class_generic_sharing_enabled (MonoClass *class)
7832 {
7833         static int generic_sharing = MONO_GENERIC_SHARING_NONE;
7834         static gboolean inited = FALSE;
7835
7836         if (!inited) {
7837                 const char *option;
7838
7839                 if (gshared_supported)
7840                         generic_sharing = MONO_GENERIC_SHARING_ALL;
7841                 else
7842                         generic_sharing = MONO_GENERIC_SHARING_NONE;
7843
7844                 if ((option = g_getenv ("MONO_GENERIC_SHARING"))) {
7845                         if (strcmp (option, "corlib") == 0)
7846                                 generic_sharing = MONO_GENERIC_SHARING_CORLIB;
7847                         else if (strcmp (option, "collections") == 0)
7848                                 generic_sharing = MONO_GENERIC_SHARING_COLLECTIONS;
7849                         else if (strcmp (option, "all") == 0)
7850                                 generic_sharing = MONO_GENERIC_SHARING_ALL;
7851                         else if (strcmp (option, "none") == 0)
7852                                 generic_sharing = MONO_GENERIC_SHARING_NONE;
7853                         else
7854                                 g_warning ("Unknown generic sharing option `%s'.", option);
7855                 }
7856
7857                 if (!gshared_supported)
7858                         generic_sharing = MONO_GENERIC_SHARING_NONE;
7859
7860                 inited = TRUE;
7861         }
7862
7863         switch (generic_sharing) {
7864         case MONO_GENERIC_SHARING_NONE:
7865                 return FALSE;
7866         case MONO_GENERIC_SHARING_ALL:
7867                 return TRUE;
7868         case MONO_GENERIC_SHARING_CORLIB :
7869                 return class->image == mono_defaults.corlib;
7870         case MONO_GENERIC_SHARING_COLLECTIONS:
7871                 if (class->image != mono_defaults.corlib)
7872                         return FALSE;
7873                 while (class->nested_in)
7874                         class = class->nested_in;
7875                 return g_str_has_prefix (class->name_space, "System.Collections.Generic");
7876         default:
7877                 g_assert_not_reached ();
7878         }
7879 }
7880
7881 /*
7882  * mono_class_setup_interface_id:
7883  *
7884  * Initializes MonoClass::interface_id if required.
7885  *
7886  * LOCKING: Acquires the loader lock.
7887  */
7888 void
7889 mono_class_setup_interface_id (MonoClass *class)
7890 {
7891         mono_loader_lock ();
7892         if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
7893                 class->interface_id = mono_get_unique_iid (class);
7894         mono_loader_unlock ();
7895 }
7896
7897 /*
7898  * mono_class_alloc_ext:
7899  *
7900  *   Allocate klass->ext if not already done.
7901  * LOCKING: Assumes the loader lock is held.
7902  */
7903 void
7904 mono_class_alloc_ext (MonoClass *klass)
7905 {
7906         if (!klass->ext) {
7907                 if (klass->generic_class) {
7908                         klass->ext = g_new0 (MonoClassExt, 1);
7909                 } else {
7910                         klass->ext = mono_image_alloc0 (klass->image, sizeof (MonoClassExt));
7911                 }
7912                 class_ext_size += sizeof (MonoClassExt);
7913         }
7914 }
7915
7916 /*
7917  * mono_class_setup_interfaces:
7918  *
7919  *   Initialize class->interfaces/interfaces_count.
7920  * LOCKING: Acquires the loader lock.
7921  */
7922 void
7923 mono_class_setup_interfaces (MonoClass *klass)
7924 {
7925         int i;
7926
7927         if (klass->interfaces_inited)
7928                 return;
7929
7930         mono_loader_lock ();
7931
7932         if (klass->interfaces_inited) {
7933                 mono_loader_unlock ();
7934                 return;
7935         }
7936
7937         if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
7938                 MonoType *args [1];
7939
7940                 /* generic IList, ICollection, IEnumerable */
7941                 klass->interface_count = 1;
7942                 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
7943
7944                 args [0] = &klass->element_class->byval_arg;
7945                 klass->interfaces [0] = mono_class_bind_generic_parameters (
7946                         mono_defaults.generic_ilist_class, 1, args, FALSE);
7947         } else if (klass->generic_class) {
7948                 MonoClass *gklass = klass->generic_class->container_class;
7949
7950                 klass->interface_count = gklass->interface_count;
7951                 klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
7952                 for (i = 0; i < klass->interface_count; i++)
7953                         klass->interfaces [i] = mono_class_inflate_generic_class (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class));
7954         }
7955
7956         mono_memory_barrier ();
7957
7958         klass->interfaces_inited = TRUE;
7959
7960         mono_loader_unlock ();
7961 }