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