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