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