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