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