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