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