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