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