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