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