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