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