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