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