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