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