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