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