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