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