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