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