2008-05-24 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_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 (guint16) * 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                 class->method.count = 3 + (class->rank > 1? 2: 1);
3597
3598                 if (class->interface_count) {
3599                         int count_generic = generic_array_methods (class);
3600                         class->method.count += class->interface_count * count_generic;
3601                 }
3602         }
3603
3604         mono_class_setup_supertypes (class);
3605
3606         if (!default_ghc)
3607                 initialize_object_slots (class);
3608
3609         /* 
3610          * Initialize the rest of the data without creating a generic vtable if possible.
3611          * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
3612          * also avoid computing a generic vtable.
3613          */
3614         if (has_cached_info) {
3615                 /* AOT case */
3616                 class->vtable_size = cached_info.vtable_size;
3617                 class->has_finalize = cached_info.has_finalize;
3618                 class->ghcimpl = cached_info.ghcimpl;
3619                 class->has_cctor = cached_info.has_cctor;
3620         } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
3621                 static int szarray_vtable_size = 0;
3622
3623                 /* SZARRAY case */
3624                 if (!szarray_vtable_size) {
3625                         mono_class_setup_vtable (class);
3626                         szarray_vtable_size = class->vtable_size;
3627                 } else {
3628                         class->vtable_size = szarray_vtable_size;
3629                 }
3630         } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
3631                 MonoClass *gklass = class->generic_class->container_class;
3632
3633                 /* Generic instance case */
3634                 class->ghcimpl = gklass->ghcimpl;
3635                 class->has_finalize = gklass->has_finalize;
3636                 class->has_cctor = gklass->has_cctor;
3637
3638                 mono_class_setup_vtable (gklass);
3639                 if (gklass->exception_type)
3640                         goto fail;
3641
3642                 class->vtable_size = gklass->vtable_size;
3643         } else {
3644                 /* General case */
3645
3646                 /* ghcimpl is not currently used
3647                 class->ghcimpl = 1;
3648                 if (class->parent) { 
3649                         MonoMethod *cmethod = class->vtable [ghc_slot];
3650                         if (cmethod->is_inflated)
3651                                 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
3652                         if (cmethod == default_ghc) {
3653                                 class->ghcimpl = 0;
3654                         }
3655                 }
3656                 */
3657
3658                 if (!MONO_CLASS_IS_INTERFACE (class)) {
3659                         MonoMethod *cmethod = NULL;
3660
3661                         if (class->type_token) {
3662                                 cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
3663                         } else if (class->parent) {
3664                                 /* FIXME: Optimize this */
3665                                 mono_class_setup_vtable (class);
3666                                 if (class->exception_type || mono_loader_get_last_error ())
3667                                         goto fail;
3668                                 cmethod = class->vtable [finalize_slot];
3669                         }
3670
3671                         if (cmethod) {
3672                                 /* Check that this is really the finalizer method */
3673                                 mono_class_setup_vtable (class);
3674                                 if (class->exception_type || mono_loader_get_last_error ())
3675                                         goto fail;
3676
3677                                 class->has_finalize = 0;
3678                                 if (class->parent) { 
3679                                         cmethod = class->vtable [finalize_slot];
3680                                         if (cmethod->is_inflated)
3681                                                 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
3682                                         if (cmethod != default_finalize) {
3683                                                 class->has_finalize = 1;
3684                                         }
3685                                 }
3686                         }
3687                 }
3688
3689                 /* C# doesn't allow interfaces to have cctors */
3690                 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
3691                         MonoMethod *cmethod = NULL;
3692
3693                         if (class->type_token) {
3694                                 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
3695                                 /* The find_method function ignores the 'flags' argument */
3696                                 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
3697                                         class->has_cctor = 1;
3698                         } else {
3699                                 mono_class_setup_methods (class);
3700
3701                                 for (i = 0; i < class->method.count; ++i) {
3702                                         MonoMethod *method = class->methods [i];
3703                                         if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
3704                                                 (strcmp (".cctor", method->name) == 0)) {
3705                                                 class->has_cctor = 1;
3706                                                 break;
3707                                         }
3708                                 }
3709                         }
3710                 }
3711         }
3712
3713         if (!mono_setup_vtable_in_class_init) {
3714                 /*
3715                  * This is an embedding API break, since the caller might assume that 
3716                  * mono_class_init () constructs a generic vtable, so vtable construction errors
3717                  * are visible right after the mono_class_init (), and not after 
3718                  * mono_class_vtable ().
3719                  */
3720                 if (class->parent) {
3721                         /* This will compute class->parent->vtable_size for some classes */
3722                         mono_class_init (class->parent);
3723                         if (class->parent->exception_type || mono_loader_get_last_error ())
3724                                 goto fail;
3725                         if (!class->parent->vtable_size) {
3726                                 /* FIXME: Get rid of this somehow */
3727                                 mono_class_setup_vtable (class->parent);
3728                                 if (class->parent->exception_type || mono_loader_get_last_error ())
3729                                         goto fail;
3730                         }
3731                         setup_interface_offsets (class, class->parent->vtable_size);
3732                 } else {
3733                         setup_interface_offsets (class, 0);
3734                 }
3735         } else {
3736                 mono_class_setup_vtable (class);
3737
3738                 if (MONO_CLASS_IS_INTERFACE (class))
3739                         setup_interface_offsets (class, 0);
3740         }
3741
3742         if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
3743                 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image->mempool, class->name, class->image->assembly_name));
3744                 class_init_ok = FALSE;
3745         }
3746
3747         goto leave;
3748
3749  fail:
3750         class_init_ok = FALSE;
3751
3752  leave:
3753         /* Because of the double-checking locking pattern */
3754         mono_memory_barrier ();
3755         class->inited = 1;
3756         class->init_pending = 0;
3757
3758         if (mono_loader_get_last_error ()) {
3759                 if (class->exception_type == MONO_EXCEPTION_NONE)
3760                         set_failure_from_loader_error (class, mono_loader_get_last_error ());
3761
3762                 mono_loader_clear_error ();
3763         }
3764
3765         mono_loader_unlock ();
3766
3767         if (mono_debugger_class_init_func)
3768                 mono_debugger_class_init_func (class);
3769
3770         return class_init_ok;
3771 }
3772
3773 static gboolean
3774 is_corlib_image (MonoImage *image)
3775 {
3776         /* FIXME: allow the dynamic case for our compilers and with full trust */
3777         if (image->dynamic)
3778                 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
3779         else
3780                 return image == mono_defaults.corlib;
3781 }
3782
3783 /*
3784  * LOCKING: this assumes the loader lock is held
3785  */
3786 void
3787 mono_class_setup_mono_type (MonoClass *class)
3788 {
3789         const char *name = class->name;
3790         const char *nspace = class->name_space;
3791         gboolean is_corlib = is_corlib_image (class->image);
3792
3793         class->this_arg.byref = 1;
3794         class->this_arg.data.klass = class;
3795         class->this_arg.type = MONO_TYPE_CLASS;
3796         class->byval_arg.data.klass = class;
3797         class->byval_arg.type = MONO_TYPE_CLASS;
3798
3799         if (is_corlib && !strcmp (nspace, "System")) {
3800                 if (!strcmp (name, "ValueType")) {
3801                         /*
3802                          * do not set the valuetype bit for System.ValueType.
3803                          * class->valuetype = 1;
3804                          */
3805                         class->blittable = TRUE;
3806                 } else if (!strcmp (name, "Enum")) {
3807                         /*
3808                          * do not set the valuetype bit for System.Enum.
3809                          * class->valuetype = 1;
3810                          */
3811                         class->valuetype = 0;
3812                         class->enumtype = 0;
3813                 } else if (!strcmp (name, "Object")) {
3814                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
3815                 } else if (!strcmp (name, "String")) {
3816                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
3817                 } else if (!strcmp (name, "TypedReference")) {
3818                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
3819                 }
3820         }
3821
3822         if (class->valuetype) {
3823                 int t = MONO_TYPE_VALUETYPE;
3824
3825                 if (is_corlib && !strcmp (nspace, "System")) {
3826                         switch (*name) {
3827                         case 'B':
3828                                 if (!strcmp (name, "Boolean")) {
3829                                         t = MONO_TYPE_BOOLEAN;
3830                                 } else if (!strcmp(name, "Byte")) {
3831                                         t = MONO_TYPE_U1;
3832                                         class->blittable = TRUE;                                                
3833                                 }
3834                                 break;
3835                         case 'C':
3836                                 if (!strcmp (name, "Char")) {
3837                                         t = MONO_TYPE_CHAR;
3838                                 }
3839                                 break;
3840                         case 'D':
3841                                 if (!strcmp (name, "Double")) {
3842                                         t = MONO_TYPE_R8;
3843                                         class->blittable = TRUE;                                                
3844                                 }
3845                                 break;
3846                         case 'I':
3847                                 if (!strcmp (name, "Int32")) {
3848                                         t = MONO_TYPE_I4;
3849                                         class->blittable = TRUE;
3850                                 } else if (!strcmp(name, "Int16")) {
3851                                         t = MONO_TYPE_I2;
3852                                         class->blittable = TRUE;
3853                                 } else if (!strcmp(name, "Int64")) {
3854                                         t = MONO_TYPE_I8;
3855                                         class->blittable = TRUE;
3856                                 } else if (!strcmp(name, "IntPtr")) {
3857                                         t = MONO_TYPE_I;
3858                                         class->blittable = TRUE;
3859                                 }
3860                                 break;
3861                         case 'S':
3862                                 if (!strcmp (name, "Single")) {
3863                                         t = MONO_TYPE_R4;
3864                                         class->blittable = TRUE;                                                
3865                                 } else if (!strcmp(name, "SByte")) {
3866                                         t = MONO_TYPE_I1;
3867                                         class->blittable = TRUE;
3868                                 }
3869                                 break;
3870                         case 'U':
3871                                 if (!strcmp (name, "UInt32")) {
3872                                         t = MONO_TYPE_U4;
3873                                         class->blittable = TRUE;
3874                                 } else if (!strcmp(name, "UInt16")) {
3875                                         t = MONO_TYPE_U2;
3876                                         class->blittable = TRUE;
3877                                 } else if (!strcmp(name, "UInt64")) {
3878                                         t = MONO_TYPE_U8;
3879                                         class->blittable = TRUE;
3880                                 } else if (!strcmp(name, "UIntPtr")) {
3881                                         t = MONO_TYPE_U;
3882                                         class->blittable = TRUE;
3883                                 }
3884                                 break;
3885                         case 'T':
3886                                 if (!strcmp (name, "TypedReference")) {
3887                                         t = MONO_TYPE_TYPEDBYREF;
3888                                         class->blittable = TRUE;
3889                                 }
3890                                 break;
3891                         case 'V':
3892                                 if (!strcmp (name, "Void")) {
3893                                         t = MONO_TYPE_VOID;
3894                                 }
3895                                 break;
3896                         default:
3897                                 break;
3898                         }
3899                 }
3900                 class->this_arg.type = class->byval_arg.type = t;
3901         }
3902
3903         if (MONO_CLASS_IS_INTERFACE (class))
3904                 class->interface_id = mono_get_unique_iid (class);
3905
3906 }
3907
3908 /*
3909  * LOCKING: this assumes the loader lock is held
3910  */
3911 void
3912 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
3913 {
3914         gboolean system_namespace;
3915         gboolean is_corlib = is_corlib_image (class->image);
3916
3917         system_namespace = !strcmp (class->name_space, "System") && is_corlib;
3918
3919         /* if root of the hierarchy */
3920         if (system_namespace && !strcmp (class->name, "Object")) {
3921                 class->parent = NULL;
3922                 class->instance_size = sizeof (MonoObject);
3923                 return;
3924         }
3925         if (!strcmp (class->name, "<Module>")) {
3926                 class->parent = NULL;
3927                 class->instance_size = 0;
3928                 return;
3929         }
3930
3931         if (!MONO_CLASS_IS_INTERFACE (class)) {
3932                 /* Imported COM Objects always derive from __ComObject. */
3933                 if (MONO_CLASS_IS_IMPORT (class)) {
3934                         mono_init_com_types ();
3935                         if (parent == mono_defaults.object_class)
3936                                 parent = mono_defaults.com_object_class;
3937                 }
3938                 if (!parent) {
3939                         /* set the parent to something useful and safe, but mark the type as broken */
3940                         parent = mono_defaults.object_class;
3941                         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3942                 }
3943
3944                 class->parent = parent;
3945
3946                 if (parent->generic_class && !parent->name) {
3947                         /*
3948                          * If the parent is a generic instance, we may get
3949                          * called before it is fully initialized, especially
3950                          * before it has its name.
3951                          */
3952                         return;
3953                 }
3954
3955                 class->marshalbyref = parent->marshalbyref;
3956                 class->contextbound  = parent->contextbound;
3957                 class->delegate  = parent->delegate;
3958                 if (MONO_CLASS_IS_IMPORT (class))
3959                         class->is_com_object = 1;
3960                 else
3961                         class->is_com_object = parent->is_com_object;
3962                 
3963                 if (system_namespace) {
3964                         if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
3965                                 class->marshalbyref = 1;
3966
3967                         if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject")) 
3968                                 class->contextbound  = 1;
3969
3970                         if (*class->name == 'D' && !strcmp (class->name, "Delegate")) 
3971                                 class->delegate  = 1;
3972                 }
3973
3974                 if (class->parent->enumtype || (is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) && 
3975                                                 (strcmp (class->parent->name_space, "System") == 0)))
3976                         class->valuetype = 1;
3977                 if (is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
3978                         class->valuetype = class->enumtype = 1;
3979                 }
3980                 /*class->enumtype = class->parent->enumtype; */
3981                 mono_class_setup_supertypes (class);
3982         } else {
3983                 /* initialize com types if COM interfaces are present */
3984                 if (MONO_CLASS_IS_IMPORT (class))
3985                         mono_init_com_types ();
3986                 class->parent = NULL;
3987         }
3988
3989 }
3990
3991 /*
3992  * mono_class_setup_supertypes:
3993  * @class: a class
3994  *
3995  * Build the data structure needed to make fast type checks work.
3996  * This currently sets two fields in @class:
3997  *  - idepth: distance between @class and System.Object in the type
3998  *    hierarchy + 1
3999  *  - supertypes: array of classes: each element has a class in the hierarchy
4000  *    starting from @class up to System.Object
4001  * 
4002  * LOCKING: this assumes the loader lock is held
4003  */
4004 void
4005 mono_class_setup_supertypes (MonoClass *class)
4006 {
4007         int ms;
4008
4009         if (class->supertypes)
4010                 return;
4011
4012         if (class->parent && !class->parent->supertypes)
4013                 mono_class_setup_supertypes (class->parent);
4014         if (class->parent)
4015                 class->idepth = class->parent->idepth + 1;
4016         else
4017                 class->idepth = 1;
4018
4019         ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
4020         class->supertypes = mono_mempool_alloc0 (class->image->mempool, sizeof (MonoClass *) * ms);
4021
4022         if (class->parent) {
4023                 class->supertypes [class->idepth - 1] = class;
4024                 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
4025         } else {
4026                 class->supertypes [0] = class;
4027         }
4028 }
4029
4030 /**
4031  * mono_class_create_from_typedef:
4032  * @image: image where the token is valid
4033  * @type_token:  typedef token
4034  *
4035  * Create the MonoClass* representing the specified type token.
4036  * @type_token must be a TypeDef token.
4037  */
4038 static MonoClass *
4039 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
4040 {
4041         MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
4042         MonoClass *class, *parent = NULL;
4043         guint32 cols [MONO_TYPEDEF_SIZE];
4044         guint32 cols_next [MONO_TYPEDEF_SIZE];
4045         guint tidx = mono_metadata_token_index (type_token);
4046         MonoGenericContext *context = NULL;
4047         const char *name, *nspace;
4048         guint icount = 0; 
4049         MonoClass **interfaces;
4050         guint32 field_last, method_last;
4051         guint32 nesting_tokeen;
4052
4053         mono_loader_lock ();
4054
4055         if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
4056                 mono_loader_unlock ();
4057                 return class;
4058         }
4059
4060         g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
4061
4062         mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
4063         
4064         name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
4065         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
4066
4067         class = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
4068
4069         class->name = name;
4070         class->name_space = nspace;
4071
4072         mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4073
4074         class->image = image;
4075         class->type_token = type_token;
4076         class->flags = cols [MONO_TYPEDEF_FLAGS];
4077
4078         mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
4079
4080         /*
4081          * Check whether we're a generic type definition.
4082          */
4083         class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
4084         if (class->generic_container) {
4085                 class->generic_container->owner.klass = class;
4086                 context = &class->generic_container->context;
4087         }
4088
4089         if (cols [MONO_TYPEDEF_EXTENDS]) {
4090                 parent = mono_class_get_full (
4091                         image, mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]), context);
4092                 if (parent == NULL){
4093                         mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
4094                         mono_loader_unlock ();
4095                         mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4096                         return NULL;
4097                 }
4098         }
4099
4100         /* do this early so it's available for interfaces in setup_mono_type () */
4101         if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token)))
4102                 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
4103
4104         mono_class_setup_parent (class, parent);
4105
4106         /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
4107         mono_class_setup_mono_type (class);
4108
4109         if (!class->enumtype) {
4110                 if (!mono_metadata_interfaces_from_typedef_full (
4111                             image, type_token, &interfaces, &icount, context)){
4112                         mono_loader_unlock ();
4113                         mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4114                         return NULL;
4115                 }
4116
4117                 class->interfaces = interfaces;
4118                 class->interface_count = icount;
4119         }
4120
4121         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
4122                 class->unicode = 1;
4123
4124 #if PLATFORM_WIN32
4125         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
4126                 class->unicode = 1;
4127 #endif
4128
4129         class->cast_class = class->element_class = class;
4130
4131         /*g_print ("Load class %s\n", name);*/
4132
4133         /*
4134          * Compute the field and method lists
4135          */
4136         class->field.first  = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
4137         class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
4138
4139         if (tt->rows > tidx){           
4140                 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
4141                 field_last  = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
4142                 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
4143         } else {
4144                 field_last  = image->tables [MONO_TABLE_FIELD].rows;
4145                 method_last = image->tables [MONO_TABLE_METHOD].rows;
4146         }
4147
4148         if (cols [MONO_TYPEDEF_FIELD_LIST] && 
4149             cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
4150                 class->field.count = field_last - class->field.first;
4151         else
4152                 class->field.count = 0;
4153
4154         if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
4155                 class->method.count = method_last - class->method.first;
4156         else
4157                 class->method.count = 0;
4158
4159         /* reserve space to store vector pointer in arrays */
4160         if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
4161                 class->instance_size += 2 * sizeof (gpointer);
4162                 g_assert (class->field.count == 0);
4163         }
4164
4165         if (class->enumtype) {
4166                 class->enum_basetype = mono_class_find_enum_basetype (class);
4167                 if (!class->enum_basetype) {
4168                         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4169                         mono_loader_unlock ();
4170                         return NULL;
4171                 }
4172                 class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
4173         }
4174
4175         /*
4176          * If we're a generic type definition, load the constraints.
4177          * We must do this after the class has been constructed to make certain recursive scenarios
4178          * work.
4179          */
4180         if (class->generic_container)
4181                 mono_metadata_load_generic_param_constraints (
4182                         image, type_token, class->generic_container);
4183
4184         mono_loader_unlock ();
4185
4186         mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4187
4188         return class;
4189 }
4190
4191 /** is klass Nullable<T>? */
4192 gboolean
4193 mono_class_is_nullable (MonoClass *klass)
4194 {
4195        return klass->generic_class != NULL &&
4196                klass->generic_class->container_class == mono_defaults.generic_nullable_class;
4197 }
4198
4199
4200 /** if klass is T? return T */
4201 MonoClass*
4202 mono_class_get_nullable_param (MonoClass *klass)
4203 {
4204        g_assert (mono_class_is_nullable (klass));
4205        return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4206 }
4207
4208 /*
4209  * Create the `MonoClass' for an instantiation of a generic type.
4210  * We only do this if we actually need it.
4211  */
4212 MonoClass*
4213 mono_generic_class_get_class (MonoGenericClass *gclass)
4214 {
4215         MonoClass *klass, *gklass;
4216         int i;
4217
4218         mono_loader_lock ();
4219         if (gclass->cached_class) {
4220                 mono_loader_unlock ();
4221                 return gclass->cached_class;
4222         }
4223
4224         gclass->cached_class = g_malloc0 (sizeof (MonoClass));
4225         klass = gclass->cached_class;
4226
4227         gklass = gclass->container_class;
4228
4229         if (gklass->nested_in) {
4230                 /* 
4231                  * FIXME: the nested type context should include everything the
4232                  * nesting context should have, but it may also have additional
4233                  * generic parameters...
4234                  */
4235                 MonoType *inflated = mono_class_inflate_generic_type (
4236                         &gklass->nested_in->byval_arg, mono_generic_class_get_context (gclass));
4237                 klass->nested_in = mono_class_from_mono_type (inflated);
4238                 mono_metadata_free_type (inflated);
4239         }
4240
4241         klass->name = gklass->name;
4242         klass->name_space = gklass->name_space;
4243         
4244         mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4245         
4246         klass->image = gklass->image;
4247         klass->flags = gklass->flags;
4248         klass->type_token = gklass->type_token;
4249         klass->field.count = gklass->field.count;
4250         klass->property.count = gklass->property.count;
4251
4252         klass->generic_class = gclass;
4253
4254         klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
4255         klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
4256         klass->this_arg.byref = TRUE;
4257         klass->enumtype = gklass->enumtype;
4258         klass->valuetype = gklass->valuetype;
4259
4260         klass->cast_class = klass->element_class = klass;
4261
4262         if (mono_class_is_nullable (klass))
4263                 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
4264
4265         klass->interface_count = gklass->interface_count;
4266         klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
4267         for (i = 0; i < klass->interface_count; i++) {
4268                 MonoType *it = &gklass->interfaces [i]->byval_arg;
4269                 MonoType *inflated = mono_class_inflate_generic_type (it, mono_generic_class_get_context (gclass));
4270                 klass->interfaces [i] = mono_class_from_mono_type (inflated);
4271                 mono_metadata_free_type (inflated);
4272         }
4273
4274         /*
4275          * We're not interested in the nested classes of a generic instance.
4276          * We use the generic type definition to look for nested classes.
4277          */
4278         klass->nested_classes = NULL;
4279
4280         if (gklass->parent) {
4281                 MonoType *inflated = mono_class_inflate_generic_type (
4282                         &gklass->parent->byval_arg, mono_generic_class_get_context (gclass));
4283
4284                 klass->parent = mono_class_from_mono_type (inflated);
4285                 mono_metadata_free_type (inflated);
4286         }
4287
4288         if (klass->parent)
4289                 mono_class_setup_parent (klass, klass->parent);
4290
4291         if (klass->enumtype) {
4292                 klass->enum_basetype = gklass->enum_basetype;
4293                 klass->cast_class = gklass->cast_class;
4294         }
4295
4296         if (gclass->is_dynamic) {
4297                 klass->inited = 1;
4298
4299                 mono_class_setup_supertypes (klass);
4300
4301                 if (klass->enumtype) {
4302                         /*
4303                          * For enums, gklass->fields might not been set, but instance_size etc. is 
4304                          * already set in mono_reflection_create_internal_class (). For non-enums,
4305                          * these will be computed normally in mono_class_layout_fields ().
4306                          */
4307                         klass->instance_size = gklass->instance_size;
4308                         klass->sizes.class_size = gklass->sizes.class_size;
4309                         klass->size_inited = 1;
4310                 }
4311         }
4312
4313         mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4314         
4315         mono_loader_unlock ();
4316
4317         return klass;
4318 }
4319
4320 MonoClass *
4321 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
4322 {
4323         MonoClass *klass, **ptr;
4324         int count, pos, i;
4325
4326         mono_loader_lock ();
4327
4328         if (param->pklass) {
4329                 mono_loader_unlock ();
4330                 return param->pklass;
4331         }
4332
4333         if (!image && param->owner) {
4334                 if (is_mvar) {
4335                         MonoMethod *method = param->owner->owner.method;
4336                         image = (method && method->klass) ? method->klass->image : NULL;
4337                 } else {
4338                         MonoClass *klass = param->owner->owner.klass;
4339                         // FIXME: 'klass' should not be null
4340                         //        But, monodis creates GenericContainers without associating a owner to it
4341                         image = klass ? klass->image : NULL;
4342                 }
4343         }
4344         if (!image)
4345                 /* FIXME: */
4346                 image = mono_defaults.corlib;
4347
4348         klass = param->pklass = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
4349
4350         if (param->name)
4351                 klass->name = param->name;
4352         else {
4353                 klass->name = mono_mempool_alloc0 (image->mempool, 16);
4354                 sprintf ((char*)klass->name, is_mvar ? "!!%d" : "!%d", param->num);
4355         }
4356         klass->name_space = "";
4357         mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4358         
4359         for (count = 0, ptr = param->constraints; ptr && *ptr; ptr++, count++)
4360                 ;
4361
4362         pos = 0;
4363         if ((count > 0) && !MONO_CLASS_IS_INTERFACE (param->constraints [0])) {
4364                 klass->parent = param->constraints [0];
4365                 pos++;
4366         } else if (param->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
4367                 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
4368         else
4369                 klass->parent = mono_defaults.object_class;
4370
4371         if (count - pos > 0) {
4372                 klass->interface_count = count - pos;
4373                 klass->interfaces = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass *) * (count - pos));
4374                 for (i = pos; i < count; i++)
4375                         klass->interfaces [i - pos] = param->constraints [i];
4376         }
4377
4378         if (!image)
4379                 image = mono_defaults.corlib;
4380
4381         klass->image = image;
4382
4383         klass->inited = TRUE;
4384         klass->cast_class = klass->element_class = klass;
4385         klass->enum_basetype = &klass->element_class->byval_arg;
4386         klass->flags = TYPE_ATTRIBUTE_PUBLIC;
4387
4388         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
4389         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
4390         klass->this_arg.byref = TRUE;
4391
4392         if (param->owner) {
4393                 guint32 owner;
4394                 guint32 cols [MONO_GENERICPARAM_SIZE];
4395                 MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
4396                 i = 0;
4397
4398                 if (is_mvar && param->owner->owner.method)
4399                          i = mono_metadata_get_generic_param_row (image, param->owner->owner.method->token, &owner);
4400                 else if (!is_mvar && param->owner->owner.klass)
4401                          i = mono_metadata_get_generic_param_row (image, param->owner->owner.klass->type_token, &owner);
4402
4403                 if (i) {
4404                         mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
4405                         do {
4406                                 if (cols [MONO_GENERICPARAM_NUMBER] == param->num) {
4407                                         klass->sizes.generic_param_token = i | MONO_TOKEN_GENERIC_PARAM;
4408                                         break;
4409                                 }
4410                                 if (++i > tdef->rows)
4411                                         break;
4412                                 mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
4413                         } while (cols [MONO_GENERICPARAM_OWNER] == owner);
4414                 }
4415         }
4416
4417         mono_class_setup_supertypes (klass);
4418
4419         mono_loader_unlock ();
4420
4421         mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4422
4423         return klass;
4424 }
4425
4426 MonoClass *
4427 mono_ptr_class_get (MonoType *type)
4428 {
4429         MonoClass *result;
4430         MonoClass *el_class;
4431         MonoImage *image;
4432         char *name;
4433
4434         el_class = mono_class_from_mono_type (type);
4435         image = el_class->image;
4436
4437         mono_loader_lock ();
4438
4439         if (!image->ptr_cache)
4440                 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4441
4442         if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
4443                 mono_loader_unlock ();
4444                 return result;
4445         }
4446         result = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
4447
4448         result->parent = NULL; /* no parent for PTR types */
4449         result->name_space = el_class->name_space;
4450         name = g_strdup_printf ("%s*", el_class->name);
4451         result->name = mono_mempool_strdup (image->mempool, name);
4452         g_free (name);
4453
4454         mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4455
4456         result->image = el_class->image;
4457         result->inited = TRUE;
4458         result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4459         /* Can pointers get boxed? */
4460         result->instance_size = sizeof (gpointer);
4461         result->cast_class = result->element_class = el_class;
4462         result->enum_basetype = &result->element_class->byval_arg;
4463         result->blittable = TRUE;
4464
4465         result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
4466         result->this_arg.data.type = result->byval_arg.data.type = result->enum_basetype;
4467         result->this_arg.byref = TRUE;
4468
4469         mono_class_setup_supertypes (result);
4470
4471         g_hash_table_insert (image->ptr_cache, el_class, result);
4472
4473         mono_loader_unlock ();
4474
4475         mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4476
4477         return result;
4478 }
4479
4480 static MonoClass *
4481 mono_fnptr_class_get (MonoMethodSignature *sig)
4482 {
4483         MonoClass *result;
4484         static GHashTable *ptr_hash = NULL;
4485
4486         /* FIXME: These should be allocate from a mempool as well, but which one ? */
4487
4488         mono_loader_lock ();
4489
4490         if (!ptr_hash)
4491                 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
4492         
4493         if ((result = g_hash_table_lookup (ptr_hash, sig))) {
4494                 mono_loader_unlock ();
4495                 return result;
4496         }
4497         result = g_new0 (MonoClass, 1);
4498
4499         result->parent = NULL; /* no parent for PTR types */
4500         result->name_space = "System";
4501         result->name = "MonoFNPtrFakeClass";
4502
4503         mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4504
4505         result->image = mono_defaults.corlib; /* need to fix... */
4506         result->inited = TRUE;
4507         result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
4508         /* Can pointers get boxed? */
4509         result->instance_size = sizeof (gpointer);
4510         result->cast_class = result->element_class = result;
4511         result->blittable = TRUE;
4512
4513         result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
4514         result->this_arg.data.method = result->byval_arg.data.method = sig;
4515         result->this_arg.byref = TRUE;
4516         result->enum_basetype = &result->element_class->byval_arg;
4517         result->blittable = TRUE;
4518
4519         mono_class_setup_supertypes (result);
4520
4521         g_hash_table_insert (ptr_hash, sig, result);
4522
4523         mono_loader_unlock ();
4524
4525         mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4526
4527         return result;
4528 }
4529
4530 MonoClass *
4531 mono_class_from_mono_type (MonoType *type)
4532 {
4533         switch (type->type) {
4534         case MONO_TYPE_OBJECT:
4535                 return type->data.klass? type->data.klass: mono_defaults.object_class;
4536         case MONO_TYPE_VOID:
4537                 return type->data.klass? type->data.klass: mono_defaults.void_class;
4538         case MONO_TYPE_BOOLEAN:
4539                 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
4540         case MONO_TYPE_CHAR:
4541                 return type->data.klass? type->data.klass: mono_defaults.char_class;
4542         case MONO_TYPE_I1:
4543                 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
4544         case MONO_TYPE_U1:
4545                 return type->data.klass? type->data.klass: mono_defaults.byte_class;
4546         case MONO_TYPE_I2:
4547                 return type->data.klass? type->data.klass: mono_defaults.int16_class;
4548         case MONO_TYPE_U2:
4549                 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
4550         case MONO_TYPE_I4:
4551                 return type->data.klass? type->data.klass: mono_defaults.int32_class;
4552         case MONO_TYPE_U4:
4553                 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
4554         case MONO_TYPE_I:
4555                 return type->data.klass? type->data.klass: mono_defaults.int_class;
4556         case MONO_TYPE_U:
4557                 return type->data.klass? type->data.klass: mono_defaults.uint_class;
4558         case MONO_TYPE_I8:
4559                 return type->data.klass? type->data.klass: mono_defaults.int64_class;
4560         case MONO_TYPE_U8:
4561                 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
4562         case MONO_TYPE_R4:
4563                 return type->data.klass? type->data.klass: mono_defaults.single_class;
4564         case MONO_TYPE_R8:
4565                 return type->data.klass? type->data.klass: mono_defaults.double_class;
4566         case MONO_TYPE_STRING:
4567                 return type->data.klass? type->data.klass: mono_defaults.string_class;
4568         case MONO_TYPE_TYPEDBYREF:
4569                 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
4570         case MONO_TYPE_ARRAY:
4571                 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
4572         case MONO_TYPE_PTR:
4573                 return mono_ptr_class_get (type->data.type);
4574         case MONO_TYPE_FNPTR:
4575                 return mono_fnptr_class_get (type->data.method);
4576         case MONO_TYPE_SZARRAY:
4577                 return mono_array_class_get (type->data.klass, 1);
4578         case MONO_TYPE_CLASS:
4579         case MONO_TYPE_VALUETYPE:
4580                 return type->data.klass;
4581         case MONO_TYPE_GENERICINST:
4582                 return mono_generic_class_get_class (type->data.generic_class);
4583         case MONO_TYPE_VAR:
4584                 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
4585         case MONO_TYPE_MVAR:
4586                 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
4587         default:
4588                 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
4589                 g_assert_not_reached ();
4590         }
4591         
4592         return NULL;
4593 }
4594
4595 /**
4596  * mono_type_retrieve_from_typespec
4597  * @image: context where the image is created
4598  * @type_spec:  typespec token
4599  * @context: the generic context used to evaluate generic instantiations in
4600  */
4601 static MonoType *
4602 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
4603 {
4604         MonoType *t = mono_type_create_from_typespec (image, type_spec);
4605         if (!t)
4606                 return NULL;
4607         if (context && (context->class_inst || context->method_inst)) {
4608                 MonoType *inflated = inflate_generic_type (t, context);
4609                 if (inflated)
4610                         t = inflated;
4611         }
4612         return t;
4613 }
4614
4615 /**
4616  * mono_class_create_from_typespec
4617  * @image: context where the image is created
4618  * @type_spec:  typespec token
4619  * @context: the generic context used to evaluate generic instantiations in
4620  */
4621 static MonoClass *
4622 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
4623 {
4624         MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context);
4625         if (!t)
4626                 return NULL;
4627         return mono_class_from_mono_type (t);
4628 }
4629
4630 /**
4631  * mono_bounded_array_class_get:
4632  * @element_class: element class 
4633  * @rank: the dimension of the array class
4634  * @bounded: whenever the array has non-zero bounds
4635  *
4636  * Returns: a class object describing the array with element type @element_type and 
4637  * dimension @rank. 
4638  */
4639 MonoClass *
4640 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
4641 {
4642         MonoImage *image;
4643         MonoClass *class;
4644         MonoClass *parent = NULL;
4645         GSList *list, *rootlist;
4646         int nsize;
4647         char *name;
4648         gboolean corlib_type = FALSE;
4649
4650         g_assert (rank <= 255);
4651
4652         if (rank > 1)
4653                 /* bounded only matters for one-dimensional arrays */
4654                 bounded = FALSE;
4655
4656         image = eclass->image;
4657
4658         mono_loader_lock ();
4659
4660         if (!image->array_cache)
4661                 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4662
4663         if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
4664                 for (; list; list = list->next) {
4665                         class = list->data;
4666                         if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
4667                                 mono_loader_unlock ();
4668                                 return class;
4669                         }
4670                 }
4671         }
4672
4673         /* for the building corlib use System.Array from it */
4674         if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
4675                 parent = mono_class_from_name (image, "System", "Array");
4676                 corlib_type = TRUE;
4677         } else {
4678                 parent = mono_defaults.array_class;
4679                 if (!parent->inited)
4680                         mono_class_init (parent);
4681         }
4682
4683         class = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
4684
4685         class->image = image;
4686         class->name_space = eclass->name_space;
4687         nsize = strlen (eclass->name);
4688         name = g_malloc (nsize + 2 + rank + 1);
4689         memcpy (name, eclass->name, nsize);
4690         name [nsize] = '[';
4691         if (rank > 1)
4692                 memset (name + nsize + 1, ',', rank - 1);
4693         if (bounded)
4694                 name [nsize + rank] = '*';
4695         name [nsize + rank + bounded] = ']';
4696         name [nsize + rank + bounded + 1] = 0;
4697         class->name = mono_mempool_strdup (image->mempool, name);
4698         g_free (name);
4699
4700         mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4701
4702         class->type_token = 0;
4703         /* all arrays are marked serializable and sealed, bug #42779 */
4704         class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
4705                 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4706         class->parent = parent;
4707         class->instance_size = mono_class_instance_size (class->parent);
4708
4709         if (eclass->enumtype && !eclass->enum_basetype) {
4710                 if (!eclass->reflection_info || eclass->wastypebuilder) {
4711                         g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
4712                         g_assert (eclass->reflection_info && !eclass->wastypebuilder);
4713                 }
4714                 /* element_size -1 is ok as this is not an instantitable type*/
4715                 class->sizes.element_size = -1;
4716         } else
4717                 class->sizes.element_size = mono_class_array_element_size (eclass);
4718
4719         mono_class_setup_supertypes (class);
4720
4721         if (mono_defaults.generic_ilist_class && !bounded && rank == 1) {
4722                 MonoType *args [1];
4723
4724                 /* generic IList, ICollection, IEnumerable */
4725                 class->interface_count = 1;
4726                 class->interfaces = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass*) * class->interface_count);
4727
4728                 args [0] = &eclass->byval_arg;
4729                 class->interfaces [0] = mono_class_bind_generic_parameters (
4730                         mono_defaults.generic_ilist_class, 1, args, FALSE);
4731         }
4732
4733         if (eclass->generic_class)
4734                 mono_class_init (eclass);
4735         if (!eclass->size_inited)
4736                 mono_class_setup_fields (eclass);
4737         class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
4738
4739         class->rank = rank;
4740         
4741         if (eclass->enumtype)
4742                 class->cast_class = eclass->element_class;
4743         else
4744                 class->cast_class = eclass;
4745
4746         class->element_class = eclass;
4747
4748         if ((rank > 1) || bounded) {
4749                 MonoArrayType *at = mono_mempool_alloc0 (image->mempool, sizeof (MonoArrayType));
4750                 class->byval_arg.type = MONO_TYPE_ARRAY;
4751                 class->byval_arg.data.array = at;
4752                 at->eklass = eclass;
4753                 at->rank = rank;
4754                 /* FIXME: complete.... */
4755         } else {
4756                 class->byval_arg.type = MONO_TYPE_SZARRAY;
4757                 class->byval_arg.data.klass = eclass;
4758         }
4759         class->this_arg = class->byval_arg;
4760         class->this_arg.byref = 1;
4761         if (corlib_type) {
4762                 class->inited = 1;
4763         }
4764
4765         class->generic_container = eclass->generic_container;
4766
4767         list = g_slist_append (rootlist, class);
4768         g_hash_table_insert (image->array_cache, eclass, list);
4769
4770         mono_loader_unlock ();
4771
4772         mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4773
4774         return class;
4775 }
4776
4777 /**
4778  * mono_array_class_get:
4779  * @element_class: element class 
4780  * @rank: the dimension of the array class
4781  *
4782  * Returns: a class object describing the array with element type @element_type and 
4783  * dimension @rank. 
4784  */
4785 MonoClass *
4786 mono_array_class_get (MonoClass *eclass, guint32 rank)
4787 {
4788         return mono_bounded_array_class_get (eclass, rank, FALSE);
4789 }
4790
4791 /**
4792  * mono_class_instance_size:
4793  * @klass: a class 
4794  * 
4795  * Returns: the size of an object instance
4796  */
4797 gint32
4798 mono_class_instance_size (MonoClass *klass)
4799 {       
4800         if (!klass->size_inited)
4801                 mono_class_init (klass);
4802
4803         return klass->instance_size;
4804 }
4805
4806 /**
4807  * mono_class_min_align:
4808  * @klass: a class 
4809  * 
4810  * Returns: minimm alignment requirements 
4811  */
4812 gint32
4813 mono_class_min_align (MonoClass *klass)
4814 {       
4815         if (!klass->size_inited)
4816                 mono_class_init (klass);
4817
4818         return klass->min_align;
4819 }
4820
4821 /**
4822  * mono_class_value_size:
4823  * @klass: a class 
4824  *
4825  * This function is used for value types, and return the
4826  * space and the alignment to store that kind of value object.
4827  *
4828  * Returns: the size of a value of kind @klass
4829  */
4830 gint32
4831 mono_class_value_size      (MonoClass *klass, guint32 *align)
4832 {
4833         gint32 size;
4834
4835         /* fixme: check disable, because we still have external revereces to
4836          * mscorlib and Dummy Objects 
4837          */
4838         /*g_assert (klass->valuetype);*/
4839
4840         size = mono_class_instance_size (klass) - sizeof (MonoObject);
4841
4842         if (align)
4843                 *align = klass->min_align;
4844
4845         return size;
4846 }
4847
4848 /**
4849  * mono_class_data_size:
4850  * @klass: a class 
4851  * 
4852  * Returns: the size of the static class data
4853  */
4854 gint32
4855 mono_class_data_size (MonoClass *klass)
4856 {       
4857         if (!klass->inited)
4858                 mono_class_init (klass);
4859
4860         /* in arrays, sizes.class_size is unioned with element_size
4861          * and arrays have no static fields
4862          */
4863         if (klass->rank)
4864                 return 0;
4865         return klass->sizes.class_size;
4866 }
4867
4868 /*
4869  * Auxiliary routine to mono_class_get_field
4870  *
4871  * Takes a field index instead of a field token.
4872  */
4873 static MonoClassField *
4874 mono_class_get_field_idx (MonoClass *class, int idx)
4875 {
4876         mono_class_setup_fields_locking (class);
4877
4878         while (class) {
4879                 if (class->image->uncompressed_metadata) {
4880                         /* 
4881                          * class->field.first points to the FieldPtr table, while idx points into the
4882                          * Field table, so we have to do a search.
4883                          */
4884                         const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
4885                         int i;
4886
4887                         for (i = 0; i < class->field.count; ++i)
4888                                 if (class->fields [i].name == name)
4889                                         return &class->fields [i];
4890                         g_assert_not_reached ();
4891                 } else {                        
4892                         if (class->field.count) {
4893                                 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
4894                                         return &class->fields [idx - class->field.first];
4895                                 }
4896                         }
4897                 }
4898                 class = class->parent;
4899         }
4900         return NULL;
4901 }
4902
4903 /**
4904  * mono_class_get_field:
4905  * @class: the class to lookup the field.
4906  * @field_token: the field token
4907  *
4908  * Returns: A MonoClassField representing the type and offset of
4909  * the field, or a NULL value if the field does not belong to this
4910  * class.
4911  */
4912 MonoClassField *
4913 mono_class_get_field (MonoClass *class, guint32 field_token)
4914 {
4915         int idx = mono_metadata_token_index (field_token);
4916
4917         g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
4918
4919         return mono_class_get_field_idx (class, idx - 1);
4920 }
4921
4922 /**
4923  * mono_class_get_field_from_name:
4924  * @klass: the class to lookup the field.
4925  * @name: the field name
4926  *
4927  * Search the class @klass and it's parents for a field with the name @name.
4928  * 
4929  * Returns: the MonoClassField pointer of the named field or NULL
4930  */
4931 MonoClassField *
4932 mono_class_get_field_from_name (MonoClass *klass, const char *name)
4933 {
4934         int i;
4935
4936         mono_class_setup_fields_locking (klass);
4937         while (klass) {
4938                 for (i = 0; i < klass->field.count; ++i) {
4939                         if (strcmp (name, klass->fields [i].name) == 0)
4940                                 return &klass->fields [i];
4941                 }
4942                 klass = klass->parent;
4943         }
4944         return NULL;
4945 }
4946
4947 /**
4948  * mono_class_get_field_token:
4949  * @field: the field we need the token of
4950  *
4951  * Get the token of a field. Note that the tokesn is only valid for the image
4952  * the field was loaded from. Don't use this function for fields in dynamic types.
4953  * 
4954  * Returns: the token representing the field in the image it was loaded from.
4955  */
4956 guint32
4957 mono_class_get_field_token (MonoClassField *field)
4958 {
4959         MonoClass *klass = field->parent;
4960         int i;
4961
4962         mono_class_setup_fields_locking (klass);
4963         while (klass) {
4964                 for (i = 0; i < klass->field.count; ++i) {
4965                         if (&klass->fields [i] == field) {
4966                                 int idx = klass->field.first + i + 1;
4967
4968                                 if (klass->image->uncompressed_metadata)
4969                                         idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
4970                                 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
4971                         }
4972                 }
4973                 klass = klass->parent;
4974         }
4975
4976         g_assert_not_reached ();
4977         return 0;
4978 }
4979
4980 /*
4981  * mono_class_get_field_default_value:
4982  *
4983  * Return the default value of the field as a pointer into the metadata blob.
4984  */
4985 const char*
4986 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
4987 {
4988         guint32 cindex;
4989         guint32 constant_cols [MONO_CONSTANT_SIZE];
4990
4991         g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
4992
4993         if (!field->data) {
4994                 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
4995                 g_assert (cindex);
4996                 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
4997
4998                 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
4999                 field->def_type = constant_cols [MONO_CONSTANT_TYPE];
5000                 field->data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
5001         }
5002
5003         *def_type = field->def_type;
5004         return field->data;
5005 }
5006
5007 guint32
5008 mono_class_get_event_token (MonoEvent *event)
5009 {
5010         MonoClass *klass = event->parent;
5011         int i;
5012
5013         while (klass) {
5014                 for (i = 0; i < klass->event.count; ++i) {
5015                         if (&klass->events [i] == event)
5016                                 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->event.first + i + 1);
5017                 }
5018                 klass = klass->parent;
5019         }
5020
5021         g_assert_not_reached ();
5022         return 0;
5023 }
5024
5025 MonoProperty*
5026 mono_class_get_property_from_name (MonoClass *klass, const char *name)
5027 {
5028         while (klass) {
5029                 MonoProperty* p;
5030                 gpointer iter = NULL;
5031                 while ((p = mono_class_get_properties (klass, &iter))) {
5032                         if (! strcmp (name, p->name))
5033                                 return p;
5034                 }
5035                 klass = klass->parent;
5036         }
5037         return NULL;
5038 }
5039
5040 guint32
5041 mono_class_get_property_token (MonoProperty *prop)
5042 {
5043         MonoClass *klass = prop->parent;
5044         while (klass) {
5045                 MonoProperty* p;
5046                 int i = 0;
5047                 gpointer iter = NULL;
5048                 while ((p = mono_class_get_properties (klass, &iter))) {
5049                         if (&klass->properties [i] == prop)
5050                                 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->property.first + i + 1);
5051                         
5052                         i ++;
5053                 }
5054                 klass = klass->parent;
5055         }
5056
5057         g_assert_not_reached ();
5058         return 0;
5059 }
5060
5061 char *
5062 mono_class_name_from_token (MonoImage *image, guint32 type_token)
5063 {
5064         const char *name, *nspace;
5065         if (image->dynamic)
5066                 return g_strdup_printf ("DynamicType 0x%08x", type_token);
5067         
5068         switch (type_token & 0xff000000){
5069         case MONO_TOKEN_TYPE_DEF: {
5070                 guint32 cols [MONO_TYPEDEF_SIZE];
5071                 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5072                 guint tidx = mono_metadata_token_index (type_token);
5073
5074                 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5075                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5076                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5077                 if (strlen (nspace) == 0)
5078                         return g_strdup_printf ("%s", name);
5079                 else
5080                         return g_strdup_printf ("%s.%s", nspace, name);
5081         }
5082
5083         case MONO_TOKEN_TYPE_REF: {
5084                 guint32 cols [MONO_TYPEREF_SIZE];
5085                 MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
5086
5087                 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5088                 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
5089                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
5090                 if (strlen (nspace) == 0)
5091                         return g_strdup_printf ("%s", name);
5092                 else
5093                         return g_strdup_printf ("%s.%s", nspace, name);
5094         }
5095                 
5096         case MONO_TOKEN_TYPE_SPEC:
5097                 return g_strdup_printf ("Typespec 0x%08x", type_token);
5098         default:
5099                 g_assert_not_reached ();
5100         }
5101
5102         return NULL;
5103 }
5104
5105 static char *
5106 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
5107 {
5108         if (image->dynamic)
5109                 return g_strdup_printf ("DynamicAssembly %s", image->name);
5110         
5111         switch (type_token & 0xff000000){
5112         case MONO_TOKEN_TYPE_DEF:
5113                 return mono_stringify_assembly_name (&image->assembly->aname);
5114                 break;
5115         case MONO_TOKEN_TYPE_REF: {
5116                 MonoAssemblyName aname;
5117                 guint32 cols [MONO_TYPEREF_SIZE];
5118                 MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
5119                 guint32 idx;
5120         
5121                 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5122
5123                 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
5124                 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
5125                 case MONO_RESOLTION_SCOPE_MODULE:
5126                         /* FIXME: */
5127                         return g_strdup ("");
5128                 case MONO_RESOLTION_SCOPE_MODULEREF:
5129                         /* FIXME: */
5130                         return g_strdup ("");
5131                 case MONO_RESOLTION_SCOPE_TYPEREF:
5132                         /* FIXME: */
5133                         return g_strdup ("");
5134                 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
5135                         mono_assembly_get_assemblyref (image, idx - 1, &aname);
5136                         return mono_stringify_assembly_name (&aname);
5137                 default:
5138                         g_assert_not_reached ();
5139                 }
5140                 break;
5141         }
5142         case MONO_TOKEN_TYPE_SPEC:
5143                 /* FIXME: */
5144                 return g_strdup ("");
5145         default:
5146                 g_assert_not_reached ();
5147         }
5148
5149         return NULL;
5150 }
5151
5152 /**
5153  * mono_class_get_full:
5154  * @image: the image where the class resides
5155  * @type_token: the token for the class
5156  * @context: the generic context used to evaluate generic instantiations in
5157  *
5158  * Returns: the MonoClass that represents @type_token in @image
5159  */
5160 MonoClass *
5161 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5162 {
5163         MonoClass *class = NULL;
5164
5165         if (image->dynamic) {
5166                 int table = mono_metadata_token_table (type_token);
5167
5168                 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
5169                         mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
5170                         return NULL;
5171                 }
5172                 return mono_lookup_dynamic_token (image, type_token, context);
5173         }
5174
5175         switch (type_token & 0xff000000){
5176         case MONO_TOKEN_TYPE_DEF:
5177                 class = mono_class_create_from_typedef (image, type_token);
5178                 break;          
5179         case MONO_TOKEN_TYPE_REF:
5180                 class = mono_class_from_typeref (image, type_token);
5181                 break;
5182         case MONO_TOKEN_TYPE_SPEC:
5183                 class = mono_class_create_from_typespec (image, type_token, context);
5184                 break;
5185         default:
5186                 g_warning ("unknown token type %x", type_token & 0xff000000);
5187                 g_assert_not_reached ();
5188         }
5189
5190         if (!class){
5191                 char *name = mono_class_name_from_token (image, type_token);
5192                 char *assembly = mono_assembly_name_from_token (image, type_token);
5193                 mono_loader_set_error_type_load (name, assembly);
5194         }
5195
5196         return class;
5197 }
5198
5199
5200 /**
5201  * mono_type_get_full:
5202  * @image: the image where the type resides
5203  * @type_token: the token for the type
5204  * @context: the generic context used to evaluate generic instantiations in
5205  *
5206  * This functions exists to fullfill the fact that sometimes it's desirable to have access to the 
5207  * 
5208  * Returns: the MonoType that represents @type_token in @image
5209  */
5210 MonoType *
5211 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5212 {
5213         MonoType *type = NULL;
5214
5215         //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
5216         if (image->dynamic)
5217                 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
5218
5219         if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
5220                 MonoClass *class = mono_class_get_full (image, type_token, context);
5221                 return class ? mono_class_get_type (class) : NULL;
5222         }
5223
5224         type = mono_type_retrieve_from_typespec (image, type_token, context);
5225
5226         if (!type) {
5227                 char *name = mono_class_name_from_token (image, type_token);
5228                 char *assembly = mono_assembly_name_from_token (image, type_token);
5229                 mono_loader_set_error_type_load (name, assembly);
5230         }
5231
5232         return type;
5233 }
5234
5235
5236 MonoClass *
5237 mono_class_get (MonoImage *image, guint32 type_token)
5238 {
5239         return mono_class_get_full (image, type_token, NULL);
5240 }
5241
5242 /**
5243  * mono_image_init_name_cache:
5244  *
5245  *  Initializes the class name cache stored in image->name_cache.
5246  *
5247  * LOCKING: Acquires the loader lock.
5248  */
5249 void
5250 mono_image_init_name_cache (MonoImage *image)
5251 {
5252         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
5253         guint32 cols [MONO_TYPEDEF_SIZE];
5254         const char *name;
5255         const char *nspace;
5256         guint32 i, visib, nspace_index;
5257         GHashTable *name_cache2, *nspace_table;
5258
5259         mono_loader_lock ();
5260
5261         image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
5262
5263         if (image->dynamic) {
5264                 mono_loader_unlock ();
5265                 return;
5266         }
5267
5268         /* Temporary hash table to avoid lookups in the nspace_table */
5269         name_cache2 = g_hash_table_new (NULL, NULL);
5270
5271         for (i = 1; i <= t->rows; ++i) {
5272                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5273                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5274                 /*
5275                  * Nested types are accessed from the nesting name.  We use the fact that nested types use different visibility flags
5276                  * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5277                  */
5278                 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5279                         continue;
5280                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5281                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5282
5283                 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
5284                 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5285                 if (!nspace_table) {
5286                         nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5287                         g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5288                         g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5289                                                                  nspace_table);
5290                 }
5291                 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
5292         }
5293
5294         /* Load type names from EXPORTEDTYPES table */
5295         {
5296                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5297                 guint32 cols [MONO_EXP_TYPE_SIZE];
5298                 int i;
5299
5300                 for (i = 0; i < t->rows; ++i) {
5301                         mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
5302                         name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
5303                         nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
5304
5305                         nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
5306                         nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5307                         if (!nspace_table) {
5308                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5309                                 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5310                                 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5311                                                                          nspace_table);
5312                         }
5313                         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
5314                 }
5315         }
5316
5317         g_hash_table_destroy (name_cache2);
5318
5319         mono_loader_unlock ();
5320 }
5321
5322 void
5323 mono_image_add_to_name_cache (MonoImage *image, const char *nspace, 
5324                                                           const char *name, guint32 index)
5325 {
5326         GHashTable *nspace_table;
5327         GHashTable *name_cache;
5328
5329         mono_loader_lock ();
5330
5331         if (!image->name_cache)
5332                 mono_image_init_name_cache (image);
5333
5334         name_cache = image->name_cache;
5335         if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
5336                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5337                 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
5338         }
5339         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
5340
5341         mono_loader_unlock ();
5342 }
5343
5344 typedef struct {
5345         gconstpointer key;
5346         gpointer value;
5347 } FindUserData;
5348
5349 static void
5350 find_nocase (gpointer key, gpointer value, gpointer user_data)
5351 {
5352         char *name = (char*)key;
5353         FindUserData *data = (FindUserData*)user_data;
5354
5355         if (!data->value && (g_strcasecmp (name, (char*)data->key) == 0))
5356                 data->value = value;
5357 }
5358
5359 /**
5360  * mono_class_from_name_case:
5361  * @image: The MonoImage where the type is looked up in
5362  * @name_space: the type namespace
5363  * @name: the type short name.
5364  *
5365  * Obtains a MonoClass with a given namespace and a given name which
5366  * is located in the given MonoImage.   The namespace and name
5367  * lookups are case insensitive.
5368  */
5369 MonoClass *
5370 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
5371 {
5372         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
5373         guint32 cols [MONO_TYPEDEF_SIZE];
5374         const char *n;
5375         const char *nspace;
5376         guint32 i, visib;
5377
5378         if (image->dynamic) {
5379                 guint32 token = 0;
5380                 FindUserData user_data;
5381
5382                 mono_loader_lock ();
5383
5384                 if (!image->name_cache)
5385                         mono_image_init_name_cache (image);
5386
5387                 user_data.key = name_space;
5388                 user_data.value = NULL;
5389                 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
5390
5391                 if (user_data.value) {
5392                         GHashTable *nspace_table = (GHashTable*)user_data.value;
5393
5394                         user_data.key = name;
5395                         user_data.value = NULL;
5396
5397                         g_hash_table_foreach (nspace_table, find_nocase, &user_data);
5398                         
5399                         if (user_data.value)
5400                                 token = GPOINTER_TO_UINT (user_data.value);
5401                 }
5402
5403                 mono_loader_unlock ();
5404                 
5405                 if (token)
5406                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
5407                 else
5408                         return NULL;
5409
5410         }
5411
5412         /* add a cache if needed */
5413         for (i = 1; i <= t->rows; ++i) {
5414                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5415                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5416                 /*
5417                  * Nested types are accessed from the nesting name.  We use the fact that nested types use different visibility flags
5418                  * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5419                  */
5420                 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5421                         continue;
5422                 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5423                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5424                 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
5425                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
5426         }
5427         return NULL;
5428 }
5429
5430 static MonoClass*
5431 return_nested_in (MonoClass *class, char *nested) {
5432         MonoClass *found;
5433         char *s = strchr (nested, '/');
5434         GList *tmp;
5435
5436         if (s) {
5437                 *s = 0;
5438                 s++;
5439         }
5440         for (tmp = class->nested_classes; tmp; tmp = tmp->next) {
5441                 found = tmp->data;
5442                 if (strcmp (found->name, nested) == 0) {
5443                         if (s)
5444                                 return return_nested_in (found, s);
5445                         return found;
5446                 }
5447         }
5448         return NULL;
5449 }
5450
5451
5452 /**
5453  * mono_class_from_name:
5454  * @image: The MonoImage where the type is looked up in
5455  * @name_space: the type namespace
5456  * @name: the type short name.
5457  *
5458  * Obtains a MonoClass with a given namespace and a given name which
5459  * is located in the given MonoImage.   
5460  */
5461 MonoClass *
5462 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
5463 {
5464         GHashTable *nspace_table;
5465         MonoImage *loaded_image;
5466         guint32 token = 0;
5467         int i;
5468         MonoClass *class;
5469         char *nested;
5470         char buf [1024];
5471
5472         if ((nested = strchr (name, '/'))) {
5473                 int pos = nested - name;
5474                 int len = strlen (name);
5475                 if (len > 1023)
5476                         return NULL;
5477                 memcpy (buf, name, len + 1);
5478                 buf [pos] = 0;
5479                 nested = buf + pos + 1;
5480                 name = buf;
5481         }
5482
5483         if (get_class_from_name) {
5484                 gboolean res = get_class_from_name (image, name_space, name, &class);
5485                 if (res) {
5486                         if (nested)
5487                                 return class ? return_nested_in (class, nested) : NULL;
5488                         else
5489                                 return class;
5490                 }
5491         }
5492
5493         mono_loader_lock ();
5494
5495         if (!image->name_cache)
5496                 mono_image_init_name_cache (image);
5497
5498         nspace_table = g_hash_table_lookup (image->name_cache, name_space);
5499
5500         if (nspace_table)
5501                 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
5502
5503         mono_loader_unlock ();
5504
5505         if (!token && image->dynamic && image->modules) {
5506                 /* Search modules as well */
5507                 for (i = 0; i < image->module_count; ++i) {
5508                         MonoImage *module = image->modules [i];
5509
5510                         class = mono_class_from_name (module, name_space, name);
5511                         if (class)
5512                                 return class;
5513                 }
5514         }
5515
5516         if (!token)
5517                 return NULL;
5518
5519         if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
5520                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5521                 guint32 cols [MONO_EXP_TYPE_SIZE];
5522                 guint32 idx, impl;
5523
5524                 idx = mono_metadata_token_index (token);
5525
5526                 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
5527
5528                 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
5529                 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
5530                         loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
5531                         if (!loaded_image)
5532                                 return NULL;
5533                         class = mono_class_from_name (loaded_image, name_space, name);
5534                         if (nested)
5535                                 return return_nested_in (class, nested);
5536                         return class;
5537                 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
5538                         MonoAssembly **references = image->references;
5539                         if (!references [idx - 1])
5540                                 mono_assembly_load_reference (image, idx - 1);
5541                         g_assert (references == image->references);
5542                         g_assert (references [idx - 1]);
5543                         if (references [idx - 1] == (gpointer)-1)
5544                                 return NULL;                    
5545                         else
5546                                 /* FIXME: Cycle detection */
5547                                 return mono_class_from_name (references [idx - 1]->image, name_space, name);
5548                 } else {
5549                         g_error ("not yet implemented");
5550                 }
5551         }
5552
5553         token = MONO_TOKEN_TYPE_DEF | token;
5554
5555         class = mono_class_get (image, token);
5556         if (nested)
5557                 return return_nested_in (class, nested);
5558         return class;
5559 }
5560
5561 gboolean
5562 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc, 
5563                            gboolean check_interfaces)
5564 {
5565         g_assert (klassc->idepth > 0);
5566         if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
5567                 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
5568                         return TRUE;
5569         } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
5570                 int i;
5571
5572                 for (i = 0; i < klass->interface_count; i ++) {
5573                         MonoClass *ic =  klass->interfaces [i];
5574                         if (ic == klassc)
5575                                 return TRUE;
5576                 }
5577         } else {
5578                 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
5579                         return TRUE;
5580         }
5581
5582         /* 
5583          * MS.NET thinks interfaces are a subclass of Object, so we think it as
5584          * well.
5585          */
5586         if (klassc == mono_defaults.object_class)
5587                 return TRUE;
5588
5589         return FALSE;
5590 }
5591
5592 static gboolean
5593 mono_class_has_variant_generic_params (MonoClass *klass)
5594 {
5595         int i;
5596         MonoGenericContainer *container;
5597
5598         if (!klass->generic_class)
5599                 return FALSE;
5600
5601         container = klass->generic_class->container_class->generic_container;
5602
5603         for (i = 0; i < container->type_argc; ++i)
5604                 if (container->type_params [i].flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
5605                         return TRUE;
5606
5607         return FALSE;
5608 }
5609
5610 /**
5611  * mono_class_is_assignable_from:
5612  * @klass: the class to be assigned to
5613  * @oklass: the source class
5614  *
5615  * Return: true if an instance of object oklass can be assigned to an
5616  * instance of object @klass
5617  */
5618 gboolean
5619 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
5620 {
5621         if (!klass->inited)
5622                 mono_class_init (klass);
5623
5624         if (!oklass->inited)
5625                 mono_class_init (oklass);
5626
5627         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
5628                 return klass == oklass;
5629
5630         if (MONO_CLASS_IS_INTERFACE (klass)) {
5631                 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
5632                         return FALSE;
5633
5634                 /* interface_offsets might not be set for dynamic classes */
5635                 if (oklass->reflection_info && !oklass->interface_bitmap)
5636                         /* 
5637                          * oklass might be a generic type parameter but they have 
5638                          * interface_offsets set.
5639                          */
5640                         return mono_reflection_call_is_assignable_to (oklass, klass);
5641
5642                 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
5643                         return TRUE;
5644
5645                 if (mono_class_has_variant_generic_params (klass)) {
5646                         if (oklass->generic_class) {
5647                                 int i;
5648                                 gboolean match = FALSE;
5649                                 MonoClass *container_class1 = klass->generic_class->container_class;
5650                                 MonoClass *container_class2 = oklass->generic_class->container_class;
5651
5652                                 /* 
5653                                  * Check whenever the generic definition of oklass implements the 
5654                                  * generic definition of klass. The IMPLEMENTS_INTERFACE stuff is not usable
5655                                  * here since the relevant tables are not set up.
5656                                  */
5657                                 for (i = 0; i < container_class2->interface_offsets_count; ++i)
5658                                         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)))
5659                                                 match = TRUE;
5660
5661                                 if (match) {
5662                                         MonoGenericContainer *container;
5663
5664                                         container = klass->generic_class->container_class->generic_container;
5665
5666                                         match = TRUE;
5667                                         for (i = 0; i < container->type_argc; ++i) {
5668                                                 MonoClass *param1_class = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [i]);
5669                                                 MonoClass *param2_class = mono_class_from_mono_type (oklass->generic_class->context.class_inst->type_argv [i]);
5670
5671                                                 if (param1_class->valuetype != param2_class->valuetype) {
5672                                                         match = FALSE;
5673                                                         break;
5674                                                 }
5675                                                 /*
5676                                                  * The _VARIANT and _COVARIANT constants should read _COVARIANT and
5677                                                  * _CONTRAVARIANT, but they are in a public header so we can't fix it.
5678                                                  */
5679                                                 if (param1_class != param2_class) {
5680                                                         if ((container->type_params [i].flags & MONO_GEN_PARAM_VARIANT) && mono_class_is_assignable_from (param1_class, param2_class))
5681                                                                 ;
5682                                                         else if (((container->type_params [i].flags & MONO_GEN_PARAM_COVARIANT) && mono_class_is_assignable_from (param2_class, param1_class)))
5683                                                                 ;
5684                                                         else {
5685                                                                 match = FALSE;
5686                                                                 break;
5687                                                         }
5688                                                 }
5689                                         }
5690
5691                                         if (match)
5692                                                 return TRUE;
5693                                 }
5694                         }
5695                 }
5696         } else if (klass->rank) {
5697                 MonoClass *eclass, *eoclass;
5698
5699                 if (oklass->rank != klass->rank)
5700                         return FALSE;
5701
5702                 /* vectors vs. one dimensional arrays */
5703                 if (oklass->byval_arg.type != klass->byval_arg.type)
5704                         return FALSE;
5705
5706                 eclass = klass->cast_class;
5707                 eoclass = oklass->cast_class;
5708
5709                 /* 
5710                  * a is b does not imply a[] is b[] when a is a valuetype, and
5711                  * b is a reference type.
5712                  */
5713
5714                 if (eoclass->valuetype) {
5715                         if ((eclass == mono_defaults.enum_class) || 
5716                                 (eclass == mono_defaults.enum_class->parent) ||
5717                                 (eclass == mono_defaults.object_class))
5718                                 return FALSE;
5719                 }
5720
5721                 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
5722         } else if (mono_class_is_nullable (klass))
5723                 return (mono_class_is_assignable_from (klass->cast_class, oklass));
5724         else if (klass == mono_defaults.object_class)
5725                 return TRUE;
5726
5727         return mono_class_has_parent (oklass, klass);
5728 }       
5729
5730 /**
5731  * mono_class_get_cctor:
5732  * @klass: A MonoClass pointer
5733  *
5734  * Returns: the static constructor of @klass if it exists, NULL otherwise.
5735  */
5736 MonoMethod*
5737 mono_class_get_cctor (MonoClass *klass)
5738 {
5739         MonoCachedClassInfo cached_info;
5740
5741         if (!klass->has_cctor)
5742                 return NULL;
5743
5744         if (mono_class_get_cached_class_info (klass, &cached_info))
5745                 return mono_get_method (klass->image, cached_info.cctor_token, klass);
5746
5747         return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
5748 }
5749
5750 /**
5751  * mono_class_get_finalizer:
5752  * @klass: The MonoClass pointer
5753  *
5754  * Returns: the finalizer method of @klass if it exists, NULL otherwise.
5755  */
5756 MonoMethod*
5757 mono_class_get_finalizer (MonoClass *klass)
5758 {
5759         MonoCachedClassInfo cached_info;
5760
5761         if (!klass->inited)
5762                 mono_class_init (klass);
5763         if (!klass->has_finalize)
5764                 return NULL;
5765
5766         if (mono_class_get_cached_class_info (klass, &cached_info))
5767                 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
5768         else {
5769                 mono_class_setup_vtable (klass);
5770                 return klass->vtable [finalize_slot];
5771         }
5772 }
5773
5774 /**
5775  * mono_class_needs_cctor_run:
5776  * @klass: the MonoClass pointer
5777  * @caller: a MonoMethod describing the caller
5778  *
5779  * Determines whenever the class has a static constructor and whenever it
5780  * needs to be called when executing CALLER.
5781  */
5782 gboolean
5783 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
5784 {
5785         MonoMethod *method;
5786
5787         method = mono_class_get_cctor (klass);
5788         if (method)
5789                 return (method == caller) ? FALSE : TRUE;
5790         else
5791                 return TRUE;
5792 }
5793
5794 /**
5795  * mono_class_array_element_size:
5796  * @klass: 
5797  *
5798  * Returns: the number of bytes an element of type @klass
5799  * uses when stored into an array.
5800  */
5801 gint32
5802 mono_class_array_element_size (MonoClass *klass)
5803 {
5804         MonoType *type = &klass->byval_arg;
5805         
5806 handle_enum:
5807         switch (type->type) {
5808         case MONO_TYPE_I1:
5809         case MONO_TYPE_U1:
5810         case MONO_TYPE_BOOLEAN:
5811                 return 1;
5812         case MONO_TYPE_I2:
5813         case MONO_TYPE_U2:
5814         case MONO_TYPE_CHAR:
5815                 return 2;
5816         case MONO_TYPE_I4:
5817         case MONO_TYPE_U4:
5818         case MONO_TYPE_R4:
5819                 return 4;
5820         case MONO_TYPE_I:
5821         case MONO_TYPE_U:
5822         case MONO_TYPE_PTR:
5823         case MONO_TYPE_CLASS:
5824         case MONO_TYPE_STRING:
5825         case MONO_TYPE_OBJECT:
5826         case MONO_TYPE_SZARRAY:
5827         case MONO_TYPE_ARRAY: 
5828         case MONO_TYPE_VAR:
5829         case MONO_TYPE_MVAR:   
5830                 return sizeof (gpointer);
5831         case MONO_TYPE_I8:
5832         case MONO_TYPE_U8:
5833         case MONO_TYPE_R8:
5834                 return 8;
5835         case MONO_TYPE_VALUETYPE:
5836                 if (type->data.klass->enumtype) {
5837                         type = type->data.klass->enum_basetype;
5838                         klass = klass->element_class;
5839                         goto handle_enum;
5840                 }
5841                 return mono_class_instance_size (klass) - sizeof (MonoObject);
5842         case MONO_TYPE_GENERICINST:
5843                 type = &type->data.generic_class->container_class->byval_arg;
5844                 goto handle_enum;
5845         default:
5846                 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
5847         }
5848         return -1;
5849 }
5850
5851 /**
5852  * mono_array_element_size:
5853  * @ac: pointer to a #MonoArrayClass
5854  *
5855  * Returns: the size of single array element.
5856  */
5857 gint32
5858 mono_array_element_size (MonoClass *ac)
5859 {
5860         g_assert (ac->rank);
5861         return ac->sizes.element_size;
5862 }
5863
5864 gpointer
5865 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
5866               MonoGenericContext *context)
5867 {
5868         if (image->dynamic) {
5869                 MonoClass *tmp_handle_class;
5870                 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
5871
5872                 g_assert (tmp_handle_class);
5873                 if (handle_class)
5874                         *handle_class = tmp_handle_class;
5875
5876                 if (tmp_handle_class == mono_defaults.typehandle_class)
5877                         return &((MonoClass*)obj)->byval_arg;
5878                 else
5879                         return obj;
5880         }
5881
5882         switch (token & 0xff000000) {
5883         case MONO_TOKEN_TYPE_DEF:
5884         case MONO_TOKEN_TYPE_REF:
5885         case MONO_TOKEN_TYPE_SPEC: {
5886                 MonoType *type;
5887                 if (handle_class)
5888                         *handle_class = mono_defaults.typehandle_class;
5889                 type = mono_type_get_full (image, token, context);
5890                 if (!type)
5891                         return NULL;
5892                 mono_class_init (mono_class_from_mono_type (type));
5893                 /* We return a MonoType* as handle */
5894                 return type;
5895         }
5896         case MONO_TOKEN_FIELD_DEF: {
5897                 MonoClass *class;
5898                 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
5899                 if (handle_class)
5900                         *handle_class = mono_defaults.fieldhandle_class;
5901                 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
5902                 if (!class)
5903                         return NULL;
5904                 mono_class_init (class);
5905                 return mono_class_get_field (class, token);
5906         }
5907         case MONO_TOKEN_METHOD_DEF:
5908         case MONO_TOKEN_METHOD_SPEC: {
5909                 MonoMethod *meth;
5910                 meth = mono_get_method_full (image, token, NULL, context);
5911                 if (handle_class)
5912                         *handle_class = mono_defaults.methodhandle_class;
5913                 return meth;
5914         }
5915         case MONO_TOKEN_MEMBER_REF: {
5916                 guint32 cols [MONO_MEMBERREF_SIZE];
5917                 const char *sig;
5918                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
5919                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
5920                 mono_metadata_decode_blob_size (sig, &sig);
5921                 if (*sig == 0x6) { /* it's a field */
5922                         MonoClass *klass;
5923                         MonoClassField *field;
5924                         field = mono_field_from_token (image, token, &klass, context);
5925                         if (handle_class)
5926                                 *handle_class = mono_defaults.fieldhandle_class;
5927                         return field;
5928                 } else {
5929                         MonoMethod *meth;
5930                         meth = mono_get_method_full (image, token, NULL, context);
5931                         if (handle_class)
5932                                 *handle_class = mono_defaults.methodhandle_class;
5933                         return meth;
5934                 }
5935         }
5936         default:
5937                 g_warning ("Unknown token 0x%08x in ldtoken", token);
5938                 break;
5939         }
5940         return NULL;
5941 }
5942
5943 /**
5944  * This function might need to call runtime functions so it can't be part
5945  * of the metadata library.
5946  */
5947 static MonoLookupDynamicToken lookup_dynamic = NULL;
5948
5949 void
5950 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
5951 {
5952         lookup_dynamic = func;
5953 }
5954
5955 gpointer
5956 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
5957 {
5958         MonoClass *handle_class;
5959
5960         return lookup_dynamic (image, token, TRUE, &handle_class, context);
5961 }
5962
5963 gpointer
5964 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
5965 {
5966         return lookup_dynamic (image, token, valid_token, handle_class, context);
5967 }
5968
5969 static MonoGetCachedClassInfo get_cached_class_info = NULL;
5970
5971 void
5972 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
5973 {
5974         get_cached_class_info = func;
5975 }
5976
5977 static gboolean
5978 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
5979 {
5980         if (!get_cached_class_info)
5981                 return FALSE;
5982         else
5983                 return get_cached_class_info (klass, res);
5984 }
5985
5986 void
5987 mono_install_get_class_from_name (MonoGetClassFromName func)
5988 {
5989         get_class_from_name = func;
5990 }
5991
5992 MonoImage*
5993 mono_class_get_image (MonoClass *klass)
5994 {
5995         return klass->image;
5996 }
5997
5998 /**
5999  * mono_class_get_element_class:
6000  * @klass: the MonoClass to act on
6001  *
6002  * Returns: the element class of an array or an enumeration.
6003  */
6004 MonoClass*
6005 mono_class_get_element_class (MonoClass *klass)
6006 {
6007         return klass->element_class;
6008 }
6009
6010 /**
6011  * mono_class_is_valuetype:
6012  * @klass: the MonoClass to act on
6013  *
6014  * Returns: true if the MonoClass represents a ValueType.
6015  */
6016 gboolean
6017 mono_class_is_valuetype (MonoClass *klass)
6018 {
6019         return klass->valuetype;
6020 }
6021
6022 /**
6023  * mono_class_is_enum:
6024  * @klass: the MonoClass to act on
6025  *
6026  * Returns: true if the MonoClass represents an enumeration.
6027  */
6028 gboolean
6029 mono_class_is_enum (MonoClass *klass)
6030 {
6031         return klass->enumtype;
6032 }
6033
6034 /**
6035  * mono_class_enum_basetype:
6036  * @klass: the MonoClass to act on
6037  *
6038  * Returns: the underlying type representation for an enumeration.
6039  */
6040 MonoType*
6041 mono_class_enum_basetype (MonoClass *klass)
6042 {
6043         return klass->enum_basetype;
6044 }
6045
6046 /**
6047  * mono_class_get_parent
6048  * @klass: the MonoClass to act on
6049  *
6050  * Returns: the parent class for this class.
6051  */
6052 MonoClass*
6053 mono_class_get_parent (MonoClass *klass)
6054 {
6055         return klass->parent;
6056 }
6057
6058 /**
6059  * mono_class_get_nesting_type;
6060  * @klass: the MonoClass to act on
6061  *
6062  * Returns: the container type where this type is nested or NULL if this type is not a nested type.
6063  */
6064 MonoClass*
6065 mono_class_get_nesting_type (MonoClass *klass)
6066 {
6067         return klass->nested_in;
6068 }
6069
6070 /**
6071  * mono_class_get_rank:
6072  * @klass: the MonoClass to act on
6073  *
6074  * Returns: the rank for the array (the number of dimensions).
6075  */
6076 int
6077 mono_class_get_rank (MonoClass *klass)
6078 {
6079         return klass->rank;
6080 }
6081
6082 /**
6083  * mono_class_get_flags:
6084  * @klass: the MonoClass to act on
6085  *
6086  * The type flags from the TypeDef table from the metadata.
6087  * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
6088  * different values.
6089  *
6090  * Returns: the flags from the TypeDef table.
6091  */
6092 guint32
6093 mono_class_get_flags (MonoClass *klass)
6094 {
6095         return klass->flags;
6096 }
6097
6098 /**
6099  * mono_class_get_name
6100  * @klass: the MonoClass to act on
6101  *
6102  * Returns: the name of the class.
6103  */
6104 const char*
6105 mono_class_get_name (MonoClass *klass)
6106 {
6107         return klass->name;
6108 }
6109
6110 /**
6111  * mono_class_get_namespace:
6112  * @klass: the MonoClass to act on
6113  *
6114  * Returns: the namespace of the class.
6115  */
6116 const char*
6117 mono_class_get_namespace (MonoClass *klass)
6118 {
6119         return klass->name_space;
6120 }
6121
6122 /**
6123  * mono_class_get_type:
6124  * @klass: the MonoClass to act on
6125  *
6126  * This method returns the internal Type representation for the class.
6127  *
6128  * Returns: the MonoType from the class.
6129  */
6130 MonoType*
6131 mono_class_get_type (MonoClass *klass)
6132 {
6133         return &klass->byval_arg;
6134 }
6135
6136 /**
6137  * mono_class_get_type_token
6138  * @klass: the MonoClass to act on
6139  *
6140  * This method returns type token for the class.
6141  *
6142  * Returns: the type token for the class.
6143  */
6144 guint32
6145 mono_class_get_type_token (MonoClass *klass)
6146 {
6147   return klass->type_token;
6148 }
6149
6150 /**
6151  * mono_class_get_byref_type:
6152  * @klass: the MonoClass to act on
6153  *
6154  * 
6155  */
6156 MonoType*
6157 mono_class_get_byref_type (MonoClass *klass)
6158 {
6159         return &klass->this_arg;
6160 }
6161
6162 /**
6163  * mono_class_num_fields:
6164  * @klass: the MonoClass to act on
6165  *
6166  * Returns: the number of static and instance fields in the class.
6167  */
6168 int
6169 mono_class_num_fields (MonoClass *klass)
6170 {
6171         return klass->field.count;
6172 }
6173
6174 /**
6175  * mono_class_num_methods:
6176  * @klass: the MonoClass to act on
6177  *
6178  * Returns: the number of methods in the class.
6179  */
6180 int
6181 mono_class_num_methods (MonoClass *klass)
6182 {
6183         return klass->method.count;
6184 }
6185
6186 /**
6187  * mono_class_num_properties
6188  * @klass: the MonoClass to act on
6189  *
6190  * Returns: the number of properties in the class.
6191  */
6192 int
6193 mono_class_num_properties (MonoClass *klass)
6194 {
6195         mono_class_setup_properties (klass);
6196
6197         return klass->property.count;
6198 }
6199
6200 /**
6201  * mono_class_num_events:
6202  * @klass: the MonoClass to act on
6203  *
6204  * Returns: the number of events in the class.
6205  */
6206 int
6207 mono_class_num_events (MonoClass *klass)
6208 {
6209         mono_class_setup_events (klass);
6210
6211         return klass->event.count;
6212 }
6213
6214 /**
6215  * mono_class_get_fields:
6216  * @klass: the MonoClass to act on
6217  *
6218  * This routine is an iterator routine for retrieving the fields in a class.
6219  *
6220  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6221  * iterate over all of the elements.  When no more values are
6222  * available, the return value is NULL.
6223  *
6224  * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
6225  */
6226 MonoClassField*
6227 mono_class_get_fields (MonoClass* klass, gpointer *iter)
6228 {
6229         MonoClassField* field;
6230         if (!iter)
6231                 return NULL;
6232         mono_class_setup_fields_locking (klass);
6233         if (!*iter) {
6234                 /* start from the first */
6235                 if (klass->field.count) {
6236                         return *iter = &klass->fields [0];
6237                 } else {
6238                         /* no fields */
6239                         return NULL;
6240                 }
6241         }
6242         field = *iter;
6243         field++;
6244         if (field < &klass->fields [klass->field.count]) {
6245                 return *iter = field;
6246         }
6247         return NULL;
6248 }
6249
6250 /**
6251  * mono_class_get_methods
6252  * @klass: the MonoClass to act on
6253  *
6254  * This routine is an iterator routine for retrieving the fields in a class.
6255  *
6256  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6257  * iterate over all of the elements.  When no more values are
6258  * available, the return value is NULL.
6259  *
6260  * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
6261  */
6262 MonoMethod*
6263 mono_class_get_methods (MonoClass* klass, gpointer *iter)
6264 {
6265         MonoMethod** method;
6266         if (!iter)
6267                 return NULL;
6268         if (!klass->inited)
6269                 mono_class_init (klass);
6270         if (!*iter) {
6271                 mono_class_setup_methods (klass);
6272                 /* start from the first */
6273                 if (klass->method.count) {
6274                         *iter = &klass->methods [0];
6275                         return klass->methods [0];
6276                 } else {
6277                         /* no method */
6278                         return NULL;
6279                 }
6280         }
6281         method = *iter;
6282         method++;
6283         if (method < &klass->methods [klass->method.count]) {
6284                 *iter = method;
6285                 return *method;
6286         }
6287         return NULL;
6288 }
6289
6290 /**
6291  * mono_class_get_properties:
6292  * @klass: the MonoClass to act on
6293  *
6294  * This routine is an iterator routine for retrieving the properties in a class.
6295  *
6296  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6297  * iterate over all of the elements.  When no more values are
6298  * available, the return value is NULL.
6299  *
6300  * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
6301  */
6302 MonoProperty*
6303 mono_class_get_properties (MonoClass* klass, gpointer *iter)
6304 {
6305         MonoProperty* property;
6306         if (!iter)
6307                 return NULL;
6308         if (!klass->inited)
6309                 mono_class_init (klass);
6310         if (!*iter) {
6311                 mono_class_setup_properties (klass);
6312                 /* start from the first */
6313                 if (klass->property.count) {
6314                         return *iter = &klass->properties [0];
6315                 } else {
6316                         /* no fields */
6317                         return NULL;
6318                 }
6319         }
6320         property = *iter;
6321         property++;
6322         if (property < &klass->properties [klass->property.count]) {
6323                 return *iter = property;
6324         }
6325         return NULL;
6326 }
6327
6328 /**
6329  * mono_class_get_events:
6330  * @klass: the MonoClass to act on
6331  *
6332  * This routine is an iterator routine for retrieving the properties in a class.
6333  *
6334  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6335  * iterate over all of the elements.  When no more values are
6336  * available, the return value is NULL.
6337  *
6338  * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
6339  */
6340 MonoEvent*
6341 mono_class_get_events (MonoClass* klass, gpointer *iter)
6342 {
6343         MonoEvent* event;
6344         if (!iter)
6345                 return NULL;
6346         if (!klass->inited)
6347                 mono_class_init (klass);
6348         if (!*iter) {
6349                 mono_class_setup_events (klass);
6350                 /* start from the first */
6351                 if (klass->event.count) {
6352                         return *iter = &klass->events [0];
6353                 } else {
6354                         /* no fields */
6355                         return NULL;
6356                 }
6357         }
6358         event = *iter;
6359         event++;
6360         if (event < &klass->events [klass->event.count]) {
6361                 return *iter = event;
6362         }
6363         return NULL;
6364 }
6365
6366 /**
6367  * mono_class_get_interfaces
6368  * @klass: the MonoClass to act on
6369  *
6370  * This routine is an iterator routine for retrieving the interfaces implemented by this class.
6371  *
6372  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6373  * iterate over all of the elements.  When no more values are
6374  * available, the return value is NULL.
6375  *
6376  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
6377  */
6378 MonoClass*
6379 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
6380 {
6381         MonoClass** iface;
6382         if (!iter)
6383                 return NULL;
6384         if (!klass->inited)
6385                 mono_class_init (klass);
6386         if (!*iter) {
6387                 /* start from the first */
6388                 if (klass->interface_count) {
6389                         *iter = &klass->interfaces [0];
6390                         return klass->interfaces [0];
6391                 } else {
6392                         /* no interface */
6393                         return NULL;
6394                 }
6395         }
6396         iface = *iter;
6397         iface++;
6398         if (iface < &klass->interfaces [klass->interface_count]) {
6399                 *iter = iface;
6400                 return *iface;
6401         }
6402         return NULL;
6403 }
6404
6405 /**
6406  * mono_class_get_nested_types
6407  * @klass: the MonoClass to act on
6408  *
6409  * This routine is an iterator routine for retrieving the nested types of a class.
6410  * This works only if @klass is non-generic, or a generic type definition.
6411  *
6412  * You must pass a gpointer that points to zero and is treated as an opaque handle to
6413  * iterate over all of the elements.  When no more values are
6414  * available, the return value is NULL.
6415  *
6416  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
6417  */
6418 MonoClass*
6419 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
6420 {
6421         GList *item;
6422         if (!iter)
6423                 return NULL;
6424         if (!klass->inited)
6425                 mono_class_init (klass);
6426         if (!*iter) {
6427                 /* start from the first */
6428                 if (klass->nested_classes) {
6429                         *iter = klass->nested_classes;
6430                         return klass->nested_classes->data;
6431                 } else {
6432                         /* no nested types */
6433                         return NULL;
6434                 }
6435         }
6436         item = *iter;
6437         item = item->next;
6438         if (item) {
6439                 *iter = item;
6440                 return item->data;
6441         }
6442         return NULL;
6443 }
6444
6445 /**
6446  * mono_field_get_name:
6447  * @field: the MonoClassField to act on
6448  *
6449  * Returns: the name of the field.
6450  */
6451 const char*
6452 mono_field_get_name (MonoClassField *field)
6453 {
6454         return field->name;
6455 }
6456
6457 /**
6458  * mono_field_get_type:
6459  * @field: the MonoClassField to act on
6460  *
6461  * Returns: MonoType of the field.
6462  */
6463 MonoType*
6464 mono_field_get_type (MonoClassField *field)
6465 {
6466         return field->type;
6467 }
6468
6469 /**
6470  * mono_field_get_type:
6471  * @field: the MonoClassField to act on
6472  *
6473  * Returns: MonoClass where the field was defined.
6474  */
6475 MonoClass*
6476 mono_field_get_parent (MonoClassField *field)
6477 {
6478         return field->parent;
6479 }
6480
6481 /**
6482  * mono_field_get_flags;
6483  * @field: the MonoClassField to act on
6484  *
6485  * The metadata flags for a field are encoded using the
6486  * FIELD_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
6487  *
6488  * Returns: the flags for the field.
6489  */
6490 guint32
6491 mono_field_get_flags (MonoClassField *field)
6492 {
6493         return field->type->attrs;
6494 }
6495
6496 /**
6497  * mono_field_get_offset;
6498  * @field: the MonoClassField to act on
6499  *
6500  * Returns: the field offset.
6501  */
6502 guint32
6503 mono_field_get_offset (MonoClassField *field)
6504 {
6505         return field->offset;
6506 }
6507
6508 /**
6509  * mono_field_get_data;
6510  * @field: the MonoClassField to act on
6511  *
6512  * Returns: pointer to the metadata constant value or to the field
6513  * data if it has an RVA flag.
6514  */
6515 const char *
6516 mono_field_get_data  (MonoClassField *field)
6517 {
6518   return field->data;
6519 }
6520
6521 /**
6522  * mono_property_get_name: 
6523  * @prop: the MonoProperty to act on
6524  *
6525  * Returns: the name of the property
6526  */
6527 const char*
6528 mono_property_get_name (MonoProperty *prop)
6529 {
6530         return prop->name;
6531 }
6532
6533 /**
6534  * mono_property_get_set_method
6535  * @prop: the MonoProperty to act on.
6536  *
6537  * Returns: the setter method of the property (A MonoMethod)
6538  */
6539 MonoMethod*
6540 mono_property_get_set_method (MonoProperty *prop)
6541 {
6542         return prop->set;
6543 }
6544
6545 /**
6546  * mono_property_get_get_method
6547  * @prop: the MonoProperty to act on.
6548  *
6549  * Returns: the setter method of the property (A MonoMethod)
6550  */
6551 MonoMethod*
6552 mono_property_get_get_method (MonoProperty *prop)
6553 {
6554         return prop->get;
6555 }
6556
6557 /**
6558  * mono_property_get_parent:
6559  * @prop: the MonoProperty to act on.
6560  *
6561  * Returns: the MonoClass where the property was defined.
6562  */
6563 MonoClass*
6564 mono_property_get_parent (MonoProperty *prop)
6565 {
6566         return prop->parent;
6567 }
6568
6569 /**
6570  * mono_property_get_flags:
6571  * @prop: the MonoProperty to act on.
6572  *
6573  * The metadata flags for a property are encoded using the
6574  * PROPERTY_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
6575  *
6576  * Returns: the flags for the property.
6577  */
6578 guint32
6579 mono_property_get_flags (MonoProperty *prop)
6580 {
6581         return prop->attrs;
6582 }
6583
6584 /**
6585  * mono_event_get_name:
6586  * @event: the MonoEvent to act on
6587  *
6588  * Returns: the name of the event.
6589  */
6590 const char*
6591 mono_event_get_name (MonoEvent *event)
6592 {
6593         return event->name;
6594 }
6595
6596 /**
6597  * mono_event_get_add_method:
6598  * @event: The MonoEvent to act on.
6599  *
6600  * Returns: the @add' method for the event (a MonoMethod).
6601  */
6602 MonoMethod*
6603 mono_event_get_add_method (MonoEvent *event)
6604 {
6605         return event->add;
6606 }
6607
6608 /**
6609  * mono_event_get_remove_method:
6610  * @event: The MonoEvent to act on.
6611  *
6612  * Returns: the @remove method for the event (a MonoMethod).
6613  */
6614 MonoMethod*
6615 mono_event_get_remove_method (MonoEvent *event)
6616 {
6617         return event->remove;
6618 }
6619
6620 /**
6621  * mono_event_get_raise_method:
6622  * @event: The MonoEvent to act on.
6623  *
6624  * Returns: the @raise method for the event (a MonoMethod).
6625  */
6626 MonoMethod*
6627 mono_event_get_raise_method (MonoEvent *event)
6628 {
6629         return event->raise;
6630 }
6631
6632 /**
6633  * mono_event_get_parent:
6634  * @event: the MonoEvent to act on.
6635  *
6636  * Returns: the MonoClass where the event is defined.
6637  */
6638 MonoClass*
6639 mono_event_get_parent (MonoEvent *event)
6640 {
6641         return event->parent;
6642 }
6643
6644 /**
6645  * mono_event_get_flags
6646  * @event: the MonoEvent to act on.
6647  *
6648  * The metadata flags for an event are encoded using the
6649  * EVENT_* constants.  See the tabledefs.h file for details.
6650  *
6651  * Returns: the flags for the event.
6652  */
6653 guint32
6654 mono_event_get_flags (MonoEvent *event)
6655 {
6656         return event->attrs;
6657 }
6658
6659 /**
6660  * mono_class_get_method_from_name:
6661  * @klass: where to look for the method
6662  * @name_space: name of the method
6663  * @param_count: number of parameters. -1 for any number.
6664  *
6665  * Obtains a MonoMethod with a given name and number of parameters.
6666  * It only works if there are no multiple signatures for any given method name.
6667  */
6668 MonoMethod *
6669 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
6670 {
6671         return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
6672 }
6673
6674 static MonoMethod*
6675 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
6676 {
6677         MonoMethod *res = NULL;
6678         int i;
6679
6680         /* Search directly in the metadata to avoid calling setup_methods () */
6681         for (i = 0; i < klass->method.count; ++i) {
6682                 guint32 cols [MONO_METHOD_SIZE];
6683                 MonoMethod *method;
6684
6685                 /* class->method.first points into the methodptr table */
6686                 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
6687
6688                 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
6689                         method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
6690                         if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
6691                                 res = method;
6692                                 break;
6693                         }
6694                 }
6695         }
6696
6697         return res;
6698 }
6699
6700 /**
6701  * mono_class_get_method_from_name_flags:
6702  * @klass: where to look for the method
6703  * @name_space: name of the method
6704  * @param_count: number of parameters. -1 for any number.
6705  * @flags: flags which must be set in the method
6706  *
6707  * Obtains a MonoMethod with a given name and number of parameters.
6708  * It only works if there are no multiple signatures for any given method name.
6709  */
6710 MonoMethod *
6711 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
6712 {
6713         MonoMethod *res = NULL;
6714         int i;
6715
6716         mono_class_init (klass);
6717
6718         if (klass->methods || klass->generic_class) {
6719                 mono_class_setup_methods (klass);
6720                 for (i = 0; i < klass->method.count; ++i) {
6721                         MonoMethod *method = klass->methods [i];
6722
6723                         if (method->name[0] == name [0] && 
6724                                 !strcmp (name, method->name) &&
6725                                 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
6726                                 ((method->flags & flags) == flags)) {
6727                                 res = method;
6728                                 break;
6729                         }
6730                 }
6731         }
6732         else {
6733             res = find_method_in_metadata (klass, name, param_count, flags);
6734         }
6735
6736         return res;
6737 }
6738
6739 /**
6740  * mono_class_set_failure:
6741  * @klass: class in which the failure was detected
6742  * @ex_type: the kind of exception/error to be thrown (later)
6743  * @ex_data: exception data (specific to each type of exception/error)
6744  *
6745  * Keep a detected failure informations in the class for later processing.
6746  * Note that only the first failure is kept.
6747  */
6748 gboolean
6749 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
6750 {
6751         if (klass->exception_type)
6752                 return FALSE;
6753         klass->exception_type = ex_type;
6754         klass->exception_data = ex_data;
6755         return TRUE;
6756 }
6757
6758 /**
6759  * mono_classes_init:
6760  *
6761  * Initialize the resources used by this module.
6762  */
6763 void
6764 mono_classes_init (void)
6765 {
6766 }
6767
6768 /**
6769  * mono_classes_cleanup:
6770  *
6771  * Free the resources used by this module.
6772  */
6773 void
6774 mono_classes_cleanup (void)
6775 {
6776         if (global_interface_bitset)
6777                 mono_bitset_free (global_interface_bitset);
6778 }
6779
6780 /**
6781  * mono_class_get_exception_for_failure:
6782  * @klass: class in which the failure was detected
6783  *
6784  * Return a constructed MonoException than the caller can then throw
6785  * using mono_raise_exception - or NULL if no failure is present (or
6786  * doesn't result in an exception).
6787  */
6788 MonoException*
6789 mono_class_get_exception_for_failure (MonoClass *klass)
6790 {
6791         switch (klass->exception_type) {
6792         case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
6793                 MonoDomain *domain = mono_domain_get ();
6794                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
6795                 MonoMethod *method = klass->exception_data;
6796                 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
6797                 MonoObject *exc = NULL;
6798                 gpointer args [4];
6799
6800                 args [0] = &error;
6801                 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
6802                 args [2] = mono_type_get_object (domain, &klass->byval_arg);
6803                 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
6804
6805                 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
6806                 return (MonoException*) exc;
6807         }
6808         case MONO_EXCEPTION_TYPE_LOAD: {
6809                 MonoString *name;
6810                 MonoException *ex;
6811                 char *str = mono_type_get_full_name (klass);
6812                 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
6813                 name = mono_string_new (mono_domain_get (), str);
6814                 g_free (str);
6815                 ex = mono_get_exception_type_load (name, astr);
6816                 g_free (astr);
6817                 return ex;
6818         }
6819         case MONO_EXCEPTION_MISSING_METHOD: {
6820                 char *class_name = klass->exception_data;
6821                 char *assembly_name = class_name + strlen (class_name) + 1;
6822
6823                 return mono_get_exception_missing_method (class_name, assembly_name);
6824         }
6825         case MONO_EXCEPTION_MISSING_FIELD: {
6826                 char *class_name = klass->exception_data;
6827                 char *member_name = class_name + strlen (class_name) + 1;
6828
6829                 return mono_get_exception_missing_field (class_name, member_name);
6830         }
6831         case MONO_EXCEPTION_FILE_NOT_FOUND: {
6832                 char *msg_format = klass->exception_data;
6833                 char *assembly_name = msg_format + strlen (msg_format) + 1;
6834                 char *msg = g_strdup_printf (msg_format, assembly_name);
6835                 MonoException *ex;
6836
6837                 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
6838
6839                 g_free (msg);
6840
6841                 return ex;
6842         }
6843         case MONO_EXCEPTION_BAD_IMAGE: {
6844                 return mono_get_exception_bad_image_format (klass->exception_data);
6845         }
6846         default: {
6847                 MonoLoaderError *error;
6848                 MonoException *ex;
6849                 
6850                 error = mono_loader_get_last_error ();
6851                 if (error != NULL){
6852                         ex = mono_loader_error_prepare_exception (error);
6853                         return ex;
6854                 }
6855                 
6856                 /* TODO - handle other class related failures */
6857                 return NULL;
6858         }
6859         }
6860 }
6861
6862 static gboolean
6863 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
6864  {
6865         do {
6866                 if (outer_klass == inner_klass)
6867                         return TRUE;
6868                 inner_klass = inner_klass->nested_in;
6869         } while (inner_klass);
6870         return FALSE;
6871 }
6872
6873 static MonoClass *
6874 mono_class_get_generic_type_definition (MonoClass *klass)
6875 {
6876         return klass->generic_class ? klass->generic_class->container_class : klass;
6877 }
6878
6879 /*
6880  * Check if @klass is a subtype of @parent ignoring generic instantiations.
6881  * 
6882  * Generic instantiations are ignored for all super types of @klass.
6883  * 
6884  * Visibility checks ignoring generic instantiations.  
6885  */
6886 static gboolean
6887 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
6888 {
6889         int i;
6890         klass = mono_class_get_generic_type_definition (klass);
6891         parent = mono_class_get_generic_type_definition (parent);
6892         
6893         for (i = 0; i < klass->idepth; ++i) {
6894                 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
6895                         return TRUE;
6896         }
6897         return FALSE;
6898 }
6899 /*
6900  * Subtype can only access parent members with family protection if the site object
6901  * is subclass of Subtype. For example:
6902  * class A { protected int x; }
6903  * class B : A {
6904  *      void valid_access () {
6905  *              B b;
6906  *              b.x = 0;
6907  *  }
6908  *  void invalid_access () {
6909  *              A a;
6910  *              a.x = 0;
6911  *  }
6912  * }
6913  * */
6914 static gboolean
6915 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
6916 {
6917         if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
6918                 return FALSE;
6919
6920         if (context_klass == NULL)
6921                 return TRUE;
6922         /*if access_klass is not member_klass context_klass must be type compat*/
6923         if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
6924                 return FALSE;
6925         return TRUE;
6926 }
6927
6928 static gboolean
6929 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
6930 {
6931         GSList *tmp;
6932         if (accessing == accessed)
6933                 return TRUE;
6934         if (!accessed || !accessing)
6935                 return FALSE;
6936         for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
6937                 MonoAssemblyName *friend = tmp->data;
6938                 /* Be conservative with checks */
6939                 if (!friend->name)
6940                         continue;
6941                 if (strcmp (accessing->aname.name, friend->name))
6942                         continue;
6943                 if (friend->public_key_token [0]) {
6944                         if (!accessing->aname.public_key_token [0])
6945                                 continue;
6946                         if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
6947                                 continue;
6948                 }
6949                 return TRUE;
6950         }
6951         return FALSE;
6952 }
6953
6954 /*
6955  * If klass is a generic type or if it is derived from a generic type, return the
6956  * MonoClass of the generic definition
6957  * Returns NULL if not found
6958  */
6959 static MonoClass*
6960 get_generic_definition_class (MonoClass *klass)
6961 {
6962         while (klass) {
6963                 if (klass->generic_class && klass->generic_class->container_class)
6964                         return klass->generic_class->container_class;
6965                 klass = klass->parent;
6966         }
6967         return NULL;
6968 }
6969
6970 static gboolean
6971 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
6972 {
6973         int i;
6974         for (i = 0; i < ginst->type_argc; ++i) {
6975                 if (!can_access_type (access_klass, mono_class_from_mono_type (ginst->type_argv[i])))
6976                         return FALSE;
6977         }
6978         return TRUE;
6979 }
6980
6981 static gboolean
6982 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
6983 {
6984         int access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
6985
6986         if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
6987                 return FALSE;
6988
6989         if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
6990                 return TRUE;
6991
6992         if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
6993                 return FALSE;
6994
6995         switch (access_level) {
6996         case TYPE_ATTRIBUTE_NOT_PUBLIC:
6997                 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
6998
6999         case TYPE_ATTRIBUTE_PUBLIC:
7000                 return TRUE;
7001
7002         case TYPE_ATTRIBUTE_NESTED_PUBLIC:
7003                 return TRUE;
7004
7005         case TYPE_ATTRIBUTE_NESTED_PRIVATE:
7006                 return is_nesting_type (member_klass, access_klass);
7007
7008         case TYPE_ATTRIBUTE_NESTED_FAMILY:
7009                 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in); 
7010
7011         case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
7012                 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7013
7014         case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
7015                 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
7016                         mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7017
7018         case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
7019                 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
7020                         mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7021         }
7022         return FALSE;
7023 }
7024
7025 /* FIXME: check visibility of type, too */
7026 static gboolean
7027 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
7028 {
7029         MonoClass *member_generic_def;
7030         if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
7031                                         access_klass->generic_container) && 
7032                         (member_generic_def = get_generic_definition_class (member_klass))) {
7033                 MonoClass *access_container;
7034
7035                 if (access_klass->generic_container)
7036                         access_container = access_klass;
7037                 else
7038                         access_container = access_klass->generic_class->container_class;
7039
7040                 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
7041                         return TRUE;
7042         }
7043
7044         /* Partition I 8.5.3.2 */
7045         /* the access level values are the same for fields and methods */
7046         switch (access_level) {
7047         case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
7048                 /* same compilation unit */
7049                 return access_klass->image == member_klass->image;
7050         case FIELD_ATTRIBUTE_PRIVATE:
7051                 return access_klass == member_klass;
7052         case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
7053                 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
7054                     can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
7055                         return TRUE;
7056                 return FALSE;
7057         case FIELD_ATTRIBUTE_ASSEMBLY:
7058                 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7059         case FIELD_ATTRIBUTE_FAMILY:
7060                 if (is_valid_family_access (access_klass, member_klass, context_klass))
7061                         return TRUE;
7062                 return FALSE;
7063         case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
7064                 if (is_valid_family_access (access_klass, member_klass, context_klass))
7065                         return TRUE;
7066                 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7067         case FIELD_ATTRIBUTE_PUBLIC:
7068                 return TRUE;
7069         }
7070         return FALSE;
7071 }
7072
7073 gboolean
7074 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
7075 {
7076         /* FIXME: check all overlapping fields */
7077         int can = can_access_member (method->klass, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7078         if (!can) {
7079                 MonoClass *nested = method->klass->nested_in;
7080                 while (nested) {
7081                         can = can_access_member (nested, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7082                         if (can)
7083                                 return TRUE;
7084                         nested = nested->nested_in;
7085                 }
7086         }
7087         return can;
7088 }
7089
7090 gboolean
7091 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
7092 {
7093         int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7094         if (!can) {
7095                 MonoClass *nested = method->klass->nested_in;
7096                 while (nested) {
7097                         can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7098                         if (can)
7099                                 return TRUE;
7100                         nested = nested->nested_in;
7101                 }
7102         }
7103         /* 
7104          * FIXME:
7105          * with generics calls to explicit interface implementations can be expressed
7106          * directly: the method is private, but we must allow it. This may be opening
7107          * a hole or the generics code should handle this differently.
7108          * Maybe just ensure the interface type is public.
7109          */
7110         if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
7111                 return TRUE;
7112         return can;
7113 }
7114
7115 /*
7116  * mono_method_can_access_method_with_context:
7117  * @method: The caller method 
7118  * @called: The called method 
7119  * @context_klass:TThe static type on stack of the owner @called object used
7120  * 
7121  * This function must be used with instance calls, as they have more strict family accessibility.
7122  * It can be used with static mehthod, but context_klass should be NULL.
7123  * 
7124  * Returns: TRUE if caller have proper visibility and acessibility to @called
7125  */
7126 gboolean
7127 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
7128 {
7129         MonoClass *access_class = method->klass;
7130         MonoClass *member_class = called->klass;
7131         int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7132         if (!can) {
7133                 MonoClass *nested = access_class->nested_in;
7134                 while (nested) {
7135                         can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7136                         if (can)
7137                                 break;
7138                         nested = nested->nested_in;
7139                 }
7140         }
7141
7142         if (!can)
7143                 return FALSE;
7144
7145         if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
7146                 return FALSE;
7147
7148         if (called->is_inflated) {
7149                 MonoMethodInflated * infl = (MonoMethodInflated*)called;
7150                 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
7151                 return FALSE;
7152         }
7153                 
7154         return TRUE;
7155 }
7156
7157
7158 /*
7159  * mono_method_can_access_method_with_context:
7160  * @method: The caller method 
7161  * @field: The accessed field
7162  * @context_klass: The static type on stack of the owner @field object used
7163  * 
7164  * This function must be used with instance fields, as they have more strict family accessibility.
7165  * It can be used with static fields, but context_klass should be NULL.
7166  * 
7167  * Returns: TRUE if caller have proper visibility and acessibility to @field
7168  */
7169 gboolean
7170 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
7171 {
7172         MonoClass *access_class = method->klass;
7173         MonoClass *member_class = field->parent;
7174         /* FIXME: check all overlapping fields */
7175         int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7176         if (!can) {
7177                 MonoClass *nested = access_class->nested_in;
7178                 while (nested) {
7179                         can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7180                         if (can)
7181                                 break;
7182                         nested = nested->nested_in;
7183                 }
7184         }
7185
7186         if (!can)
7187                 return FALSE;
7188
7189         if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
7190                 return FALSE;
7191         return TRUE;
7192 }
7193
7194 /**
7195  * mono_type_is_valid_enum_basetype:
7196  * @type: The MonoType to check
7197  *
7198  * Returns: TRUE if the type can be used as the basetype of an enum
7199  */
7200 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
7201         switch (type->type) {
7202         case MONO_TYPE_I1:
7203         case MONO_TYPE_U1:
7204         case MONO_TYPE_BOOLEAN:
7205         case MONO_TYPE_I2:
7206         case MONO_TYPE_U2:
7207         case MONO_TYPE_CHAR:
7208         case MONO_TYPE_I4:
7209         case MONO_TYPE_U4:
7210         case MONO_TYPE_I8:
7211         case MONO_TYPE_U8:
7212         case MONO_TYPE_I:
7213         case MONO_TYPE_U:
7214                 return TRUE;
7215         }
7216         return FALSE;
7217 }
7218
7219 /**
7220  * mono_class_is_valid_enum:
7221  * @klass: An enum class to be validated
7222  *
7223  * This method verify the required properties an enum should have.
7224  *  
7225  * Returns: TRUE if the informed enum class is valid 
7226  *
7227  * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
7228  * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
7229  * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
7230  */
7231 gboolean mono_class_is_valid_enum (MonoClass *klass) {
7232         MonoClassField * field;
7233         gpointer iter = NULL;
7234         gboolean found_base_field = FALSE;
7235
7236         g_assert (klass->enumtype);
7237         /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
7238         if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
7239                 return FALSE;
7240         }
7241
7242         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
7243                 return FALSE;
7244
7245         while ((field = mono_class_get_fields (klass, &iter))) {
7246                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
7247                         if (found_base_field)
7248                                 return FALSE;
7249                         found_base_field = TRUE;
7250                         if (!mono_type_is_valid_enum_basetype (field->type))
7251                                 return FALSE;
7252                 }
7253         }
7254
7255         if (!found_base_field)
7256                 return FALSE;
7257
7258         if (klass->method.count > 0) 
7259                 return FALSE;
7260
7261         return TRUE;
7262 }
7263
7264 gboolean
7265 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
7266 {
7267         return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
7268 }
7269
7270 /*
7271  * mono_class_generic_sharing_enabled:
7272  * @class: a class
7273  *
7274  * Returns whether generic sharing is enabled for class.
7275  *
7276  * This is a stop-gap measure to slowly introduce generic sharing
7277  * until we have all the issues sorted out, at which time this
7278  * function will disappear and generic sharing will always be enabled.
7279  */
7280 gboolean
7281 mono_class_generic_sharing_enabled (MonoClass *class)
7282 {
7283 #if defined(__i386__) || defined(__x86_64__)
7284         static int generic_sharing = MONO_GENERIC_SHARING_CORLIB;
7285 #else
7286         static int generic_sharing = MONO_GENERIC_SHARING_NONE;
7287 #endif
7288         static gboolean inited = FALSE;
7289
7290         if (!inited) {
7291                 const char *option;
7292
7293                 if ((option = g_getenv ("MONO_GENERIC_SHARING"))) {
7294                         if (strcmp (option, "corlib") == 0)
7295                                 generic_sharing = MONO_GENERIC_SHARING_CORLIB;
7296                         else if (strcmp (option, "all") == 0)
7297                                 generic_sharing = MONO_GENERIC_SHARING_ALL;
7298                         else if (strcmp (option, "none") == 0)
7299                                 generic_sharing = MONO_GENERIC_SHARING_NONE;
7300                         else
7301                                 g_warning ("Unknown generic sharing option `%s'.", option);
7302                 }
7303
7304                 inited = TRUE;
7305         }
7306
7307         switch (generic_sharing) {
7308         case MONO_GENERIC_SHARING_NONE:
7309                 return FALSE;
7310         case MONO_GENERIC_SHARING_ALL:
7311                 return TRUE;
7312         case MONO_GENERIC_SHARING_CORLIB :
7313                 return class->image == mono_defaults.corlib;
7314         default:
7315                 g_assert_not_reached ();
7316         }
7317 }