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