2006-08-31 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 #include <mono/metadata/image.h>
17 #include <mono/metadata/assembly.h>
18 #include <mono/metadata/cil-coff.h>
19 #include <mono/metadata/metadata.h>
20 #include <mono/metadata/metadata-internals.h>
21 #include <mono/metadata/tabledefs.h>
22 #include <mono/metadata/tokentype.h>
23 #include <mono/metadata/class-internals.h>
24 #include <mono/metadata/object.h>
25 #include <mono/metadata/appdomain.h>
26 #include <mono/metadata/mono-endian.h>
27 #include <mono/metadata/debug-helpers.h>
28 #include <mono/metadata/reflection.h>
29 #include <mono/metadata/exception.h>
30 #include <mono/metadata/security-manager.h>
31 #include <mono/os/gc_wrapper.h>
32 #include <mono/utils/mono-counters.h>
33
34 MonoStats mono_stats;
35
36 gboolean mono_print_vtable = FALSE;
37
38 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
39 static void mono_class_create_generic (MonoInflatedGenericClass *gclass);
40 static gboolean mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res);
41
42 void (*mono_debugger_start_class_init_func) (MonoClass *klass) = NULL;
43 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
44
45 /*
46  * mono_class_from_typeref:
47  * @image: a MonoImage
48  * @type_token: a TypeRef token
49  *
50  * Creates the MonoClass* structure representing the type defined by
51  * the typeref token valid inside @image.
52  * Returns: the MonoClass* representing the typeref token, NULL ifcould
53  * not be loaded.
54  */
55 MonoClass *
56 mono_class_from_typeref (MonoImage *image, guint32 type_token)
57 {
58         guint32 cols [MONO_TYPEREF_SIZE];
59         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
60         guint32 idx;
61         const char *name, *nspace;
62         MonoClass *res;
63         MonoAssembly **references;
64         
65         mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
66
67         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
68         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
69
70         idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
71         switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
72         case MONO_RESOLTION_SCOPE_MODULE:
73                 if (!idx)
74                         g_error ("null ResolutionScope not yet handled");
75                 /* a typedef in disguise */
76                 return mono_class_from_name (image, nspace, name);
77         case MONO_RESOLTION_SCOPE_MODULEREF:
78                 if (image->modules [idx-1])
79                         return mono_class_from_name (image->modules [idx - 1], nspace, name);
80                 else {
81                         char *msg = g_strdup_printf ("%s%s%s", nspace, nspace [0] ? "." : "", name);
82                         char *human_name;
83                         
84                         human_name = mono_stringify_assembly_name (&image->assembly->aname);
85                         mono_loader_set_error_type_load (msg, human_name);
86                         g_free (msg);
87                         g_free (human_name);
88                 
89                         return NULL;
90                 }
91         case MONO_RESOLTION_SCOPE_TYPEREF: {
92                 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
93                 GList *tmp;
94
95                 if (enclosing->inited) {
96                         /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
97                         for (tmp = enclosing->nested_classes; tmp; tmp = tmp->next) {
98                                 res = tmp->data;
99                                 if (strcmp (res->name, name) == 0)
100                                         return res;
101                         }
102                 } else {
103                         /* Don't call mono_class_init as we might've been called by it recursively */
104                         int i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, 1);
105                         while (i) {
106                                 guint32 class_nested = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, MONO_NESTED_CLASS_NESTED);
107                                 guint32 string_offset = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_TYPEDEF], class_nested - 1, MONO_TYPEDEF_NAME);
108                                 const char *nname = mono_metadata_string_heap (enclosing->image, string_offset);
109
110                                 if (strcmp (nname, name) == 0)
111                                         return mono_class_create_from_typedef (enclosing->image, MONO_TOKEN_TYPE_DEF | class_nested);
112
113                                 i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, i + 1);
114                         }
115                 }
116                 g_warning ("TypeRef ResolutionScope not yet handled (%d)", idx);
117                 return NULL;
118         }
119         case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
120                 break;
121         }
122
123         references = image->references;
124         if (!references [idx - 1])
125                 mono_assembly_load_reference (image, idx - 1);
126         /* If this assert fails, it probably means that you haven't installed an assembly load/search hook */
127         g_assert (references == image->references);
128         g_assert (references [idx - 1]);
129
130         /* If the assembly did not load, register this as a type load exception */
131         if (references [idx - 1] == REFERENCE_MISSING){
132                 MonoAssemblyName aname;
133                 char *human_name;
134                 
135                 mono_assembly_get_assemblyref (image, idx - 1, &aname);
136                 human_name = mono_stringify_assembly_name (&aname);
137                 mono_loader_set_error_assembly_load (human_name, image->assembly->ref_only);
138                 g_free (human_name);
139                 
140                 return NULL;
141         }
142
143         return mono_class_from_name (references [idx - 1]->image, nspace, name);
144 }
145
146 static inline MonoType*
147 dup_type (MonoType* t, const MonoType *original)
148 {
149         MonoType *r = g_new0 (MonoType, 1);
150         *r = *t;
151         r->attrs = original->attrs;
152         r->byref = original->byref;
153         if (t->type == MONO_TYPE_PTR)
154                 t->data.type = dup_type (t->data.type, original->data.type);
155         else if (t->type == MONO_TYPE_ARRAY)
156                 t->data.array = mono_dup_array_type (t->data.array);
157         else if (t->type == MONO_TYPE_FNPTR)
158                 t->data.method = mono_metadata_signature_deep_dup (t->data.method);
159         mono_stats.generics_metadata_size += sizeof (MonoType);
160         return r;
161 }
162
163 /* Copy everything mono_metadata_free_array free. */
164 MonoArrayType *
165 mono_dup_array_type (MonoArrayType *a)
166 {
167         a = g_memdup (a, sizeof (MonoArrayType));
168         if (a->sizes)
169                 a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
170         if (a->lobounds)
171                 a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
172         return a;
173 }
174
175 /* Copy everything mono_metadata_free_method_signature free. */
176 MonoMethodSignature*
177 mono_metadata_signature_deep_dup (MonoMethodSignature *sig)
178 {
179         int i;
180         
181         sig = mono_metadata_signature_dup (sig);
182         
183         sig->ret = dup_type (sig->ret, sig->ret);
184         for (i = 0; i < sig->param_count; ++i)
185                 sig->params [i] = dup_type (sig->params [i], sig->params [i]);
186         
187         return sig;
188 }
189
190 static void
191 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
192 {
193         MonoAssembly *ta = klass->image->assembly;
194
195         g_string_append_printf (
196                 str, ", %s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s",
197                 ta->aname.name,
198                 ta->aname.major, ta->aname.minor, ta->aname.build, ta->aname.revision,
199                 ta->aname.culture && *ta->aname.culture? ta->aname.culture: "neutral",
200                 ta->aname.public_key_token [0] ? (char *)ta->aname.public_key_token : "null");
201 }
202
203 static void
204 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
205                             MonoTypeNameFormat format)
206 {
207         MonoClass *klass;
208         
209         switch (type->type) {
210         case MONO_TYPE_ARRAY: {
211                 int i, rank = type->data.array->rank;
212                 MonoTypeNameFormat nested_format;
213
214                 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
215                         MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
216
217                 mono_type_get_name_recurse (
218                         &type->data.array->eklass->byval_arg, str, FALSE, nested_format);
219                 g_string_append_c (str, '[');
220                 if (rank == 1)
221                         g_string_append_c (str, '*');
222                 for (i = 1; i < rank; i++)
223                         g_string_append_c (str, ',');
224                 g_string_append_c (str, ']');
225                 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
226                         _mono_type_get_assembly_name (type->data.array->eklass, str);
227                 break;
228         }
229         case MONO_TYPE_SZARRAY: {
230                 MonoTypeNameFormat nested_format;
231
232                 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
233                         MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
234
235                 mono_type_get_name_recurse (
236                         &type->data.klass->byval_arg, str, FALSE, nested_format);
237                 g_string_append (str, "[]");
238                 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
239                         _mono_type_get_assembly_name (type->data.klass, str);
240                 break;
241         }
242         case MONO_TYPE_PTR: {
243                 MonoTypeNameFormat nested_format;
244
245                 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
246                         MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
247
248                 mono_type_get_name_recurse (
249                         type->data.type, str, FALSE, nested_format);
250                 g_string_append (str, "*");
251                 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
252                         _mono_type_get_assembly_name (type->data.klass, str);
253                 break;
254         }
255         case MONO_TYPE_VAR:
256         case MONO_TYPE_MVAR:
257                 g_assert (type->data.generic_param->name);
258                 g_string_append (str, type->data.generic_param->name);
259                 break;
260         default:
261                 klass = mono_class_from_mono_type (type);
262                 if (klass->nested_in) {
263                         mono_type_get_name_recurse (
264                                 &klass->nested_in->byval_arg, str, TRUE, format);
265                         if (format == MONO_TYPE_NAME_FORMAT_IL)
266                                 g_string_append_c (str, '.');
267                         else
268                                 g_string_append_c (str, '+');
269                 } else if (*klass->name_space) {
270                         g_string_append (str, klass->name_space);
271                         g_string_append_c (str, '.');
272                 }
273                 if (format == MONO_TYPE_NAME_FORMAT_IL) {
274                         char *s = strchr (klass->name, '`');
275                         int len = s ? s - klass->name : strlen (klass->name);
276
277                         g_string_append_len (str, klass->name, len);
278                 } else
279                         g_string_append (str, klass->name);
280                 if (is_recursed)
281                         break;
282                 if (klass->generic_class) {
283                         MonoGenericClass *gclass = klass->generic_class;
284                         MonoTypeNameFormat nested_format;
285                         int i;
286
287                         nested_format = format == MONO_TYPE_NAME_FORMAT_FULL_NAME ?
288                                 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED : format;
289
290                         if (format == MONO_TYPE_NAME_FORMAT_IL)
291                                 g_string_append_c (str, '<');
292                         else
293                                 g_string_append_c (str, '[');
294                         for (i = 0; i < gclass->inst->type_argc; i++) {
295                                 MonoType *t = gclass->inst->type_argv [i];
296
297                                 if (i)
298                                         g_string_append_c (str, ',');
299                                 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
300                                     (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
301                                         g_string_append_c (str, '[');
302                                 mono_type_get_name_recurse (
303                                         gclass->inst->type_argv [i], str, FALSE, nested_format);
304                                 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
305                                     (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
306                                         g_string_append_c (str, ']');
307                         }
308                         if (format == MONO_TYPE_NAME_FORMAT_IL) 
309                                 g_string_append_c (str, '>');
310                         else
311                                 g_string_append_c (str, ']');
312                 } else if (klass->generic_container &&
313                            (format != MONO_TYPE_NAME_FORMAT_FULL_NAME) &&
314                            (format != MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)) {
315                         int i;
316
317                         if (format == MONO_TYPE_NAME_FORMAT_IL) 
318                                 g_string_append_c (str, '<');
319                         else
320                                 g_string_append_c (str, '[');
321                         for (i = 0; i < klass->generic_container->type_argc; i++) {
322                                 if (i)
323                                         g_string_append_c (str, ',');
324                                 g_string_append (str, klass->generic_container->type_params [i].name);
325                         }
326                         if (format == MONO_TYPE_NAME_FORMAT_IL) 
327                                 g_string_append_c (str, '>');
328                         else
329                                 g_string_append_c (str, ']');
330                 }
331                 if ((format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
332                     (type->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
333                         _mono_type_get_assembly_name (klass, str);
334                 break;
335         }
336 }
337
338 /**
339  * mono_type_get_name:
340  * @type: a type
341  * @format: the format for the return string.
342  *
343  * 
344  * Returns: the string representation in a number of formats:
345  *
346  * if format is MONO_TYPE_NAME_FORMAT_REFLECTION, the return string is
347  * returned in the formatrequired by System.Reflection, this is the
348  * inverse of mono_reflection_parse_type ().
349  *
350  * if format is MONO_TYPE_NAME_FORMAT_IL, it returns a syntax that can
351  * be used by the IL assembler.
352  *
353  * if format is MONO_TYPE_NAME_FORMAT_FULL_NAME
354  *
355  * if format is MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED
356  */
357 char*
358 mono_type_get_name_full (MonoType *type, MonoTypeNameFormat format)
359 {
360         GString* result;
361
362         result = g_string_new ("");
363
364         mono_type_get_name_recurse (type, result, FALSE, format);
365
366         if (type->byref)
367                 g_string_append_c (result, '&');
368
369         return g_string_free (result, FALSE);
370 }
371
372 /**
373  * mono_type_get_full_name:
374  * @class: a class
375  *
376  * Returns: the string representation for type as required by System.Reflection.
377  * The inverse of mono_reflection_parse_type ().
378  */
379 char *
380 mono_type_get_full_name (MonoClass *class)
381 {
382         return mono_type_get_name_full (mono_class_get_type (class), MONO_TYPE_NAME_FORMAT_REFLECTION);
383 }
384
385 /**
386  * mono_type_get_name:
387  * @type: a type
388  *
389  * Returns: the string representation for type as it would be represented in IL code.
390  */
391 char*
392 mono_type_get_name (MonoType *type)
393 {
394         return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_IL);
395 }
396
397 /*
398  * mono_type_get_underlying_type:
399  * @type: a type
400  *
401  * Returns: the MonoType for the underlying interger type if @type
402  * is an enum, otherwise the type itself.
403  */
404 MonoType*
405 mono_type_get_underlying_type (MonoType *type)
406 {
407         if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
408                 return type->data.klass->enum_basetype;
409         return type;
410 }
411
412 /*
413  * mono_class_is_open_constructed_type:
414  * @type: a type
415  *
416  * Returns TRUE if type represents a generics open constructed type
417  * (not all the type parameters required for the instantiation have
418  * been provided).
419  */
420 gboolean
421 mono_class_is_open_constructed_type (MonoType *t)
422 {
423         switch (t->type) {
424         case MONO_TYPE_VAR:
425         case MONO_TYPE_MVAR:
426                 return TRUE;
427         case MONO_TYPE_SZARRAY:
428                 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
429         case MONO_TYPE_ARRAY:
430                 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
431         case MONO_TYPE_PTR:
432                 return mono_class_is_open_constructed_type (t->data.type);
433         case MONO_TYPE_GENERICINST: {
434                 MonoGenericClass *gclass = t->data.generic_class;
435                 int i;
436
437                 if (mono_class_is_open_constructed_type (&gclass->container_class->byval_arg))
438                         return TRUE;
439                 for (i = 0; i < gclass->inst->type_argc; i++)
440                         if (mono_class_is_open_constructed_type (gclass->inst->type_argv [i]))
441                                 return TRUE;
442                 return FALSE;
443         }
444         default:
445                 return FALSE;
446         }
447 }
448
449 static MonoGenericClass *
450 inflate_generic_class (MonoGenericClass *ogclass, MonoGenericContext *context)
451 {
452         MonoInflatedGenericClass *igclass;
453         MonoGenericClass *ngclass, *cached;
454         MonoGenericInst *ninst;
455
456         ninst = mono_metadata_inflate_generic_inst (ogclass->inst, context);
457         if (ninst == ogclass->inst)
458                 return ogclass;
459
460         if (ogclass->is_dynamic) {
461                 MonoDynamicGenericClass *dgclass = g_new0 (MonoDynamicGenericClass, 1);
462                 igclass = &dgclass->generic_class;
463                 ngclass = &igclass->generic_class;
464                 ngclass->is_inflated = 1;
465                 ngclass->is_dynamic = 1;
466         } else {
467                 igclass = g_new0 (MonoInflatedGenericClass, 1);
468                 ngclass = &igclass->generic_class;
469                 ngclass->is_inflated = 1;
470         }
471
472         *ngclass = *ogclass;
473
474         ngclass->inst = ninst;
475
476         igclass->klass = NULL;
477
478         ngclass->context = g_new0 (MonoGenericContext, 1);
479         ngclass->context->container = ngclass->container_class->generic_container;
480         ngclass->context->gclass = ngclass;
481
482         mono_loader_lock ();
483         cached = mono_metadata_lookup_generic_class (ngclass);
484         mono_loader_unlock ();
485         if (cached) {
486                 g_free (ngclass->context);
487                 g_free (ngclass);
488                 return cached;
489         }
490
491         return ngclass;
492 }
493
494 static MonoType*
495 inflate_generic_type (MonoType *type, MonoGenericContext *context)
496 {
497         switch (type->type) {
498         case MONO_TYPE_MVAR: {
499                 int num = type->data.generic_param->num;
500                 MonoGenericInst *inst = context->gmethod ? context->gmethod->inst : NULL;
501                 if (!inst || !inst->type_argv)
502                         return NULL;
503                 if (num >= inst->type_argc)
504                         g_error ("MVAR %d (%s) cannot be expanded in this context with %d instantiations", num, type->data.generic_param->name, inst->type_argc);
505                 return dup_type (inst->type_argv [num], type);
506         }
507         case MONO_TYPE_VAR: {
508                 int num = type->data.generic_param->num;
509                 MonoGenericInst *inst = context->gclass ? context->gclass->inst : NULL;
510                 if (!inst)
511                         return NULL;
512                 if (num >= inst->type_argc)
513                         g_error ("VAR %d (%s) cannot be expanded in this context with %d instantiations", num, type->data.generic_param->name, inst->type_argc);
514                 return dup_type (inst->type_argv [num], type);
515         }
516         case MONO_TYPE_SZARRAY: {
517                 MonoClass *eclass = type->data.klass;
518                 MonoType *nt, *inflated = inflate_generic_type (&eclass->byval_arg, context);
519                 if (!inflated)
520                         return NULL;
521                 nt = dup_type (type, type);
522                 nt->data.klass = mono_class_from_mono_type (inflated);
523                 return nt;
524         }
525         case MONO_TYPE_ARRAY: {
526                 MonoClass *eclass = type->data.array->eklass;
527                 MonoType *nt, *inflated = inflate_generic_type (&eclass->byval_arg, context);
528                 if (!inflated)
529                         return NULL;
530                 nt = dup_type (type, type);
531                 nt->data.array = g_memdup (nt->data.array, sizeof (MonoArrayType));
532                 nt->data.array->eklass = mono_class_from_mono_type (inflated);
533                 return nt;
534         }
535         case MONO_TYPE_GENERICINST: {
536                 MonoGenericClass *gclass = type->data.generic_class;
537                 MonoType *nt;
538                 if (!gclass->inst->is_open)
539                         return NULL;
540                 gclass = inflate_generic_class (gclass, context);
541                 if (gclass == type->data.generic_class)
542                         return NULL;
543                 nt = dup_type (type, type);
544                 nt->data.generic_class = gclass;
545                 return nt;
546         }
547         case MONO_TYPE_CLASS:
548         case MONO_TYPE_VALUETYPE: {
549                 MonoClass *klass = type->data.klass;
550                 MonoGenericClass *gclass;
551                 MonoType *nt;
552
553                 if (!klass->generic_container)
554                         return NULL;
555                 gclass = inflate_generic_class (klass->generic_container->context.gclass, context);
556                 if (gclass == klass->generic_container->context.gclass)
557                         return NULL;
558                 nt = dup_type (type, type);
559                 nt->type = MONO_TYPE_GENERICINST;
560                 nt->data.generic_class = gclass;
561                 return nt;
562         }
563         default:
564                 return NULL;
565         }
566         return NULL;
567 }
568
569 MonoInflatedGenericClass*
570 mono_get_inflated_generic_class (MonoGenericClass *gclass)
571 {
572         g_assert (gclass->is_inflated);
573         mono_class_create_generic ((MonoInflatedGenericClass *) gclass);
574         return (MonoInflatedGenericClass *) gclass;
575 }
576
577 /*
578  * mono_class_inflate_generic_type:
579  * @type: a type
580  * @context: a generics context
581  *
582  * Instantiate the generic type @type, using the generics context @context.
583  *
584  * Returns: the instantiated type
585  */
586 MonoType*
587 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
588 {
589         MonoType *inflated = inflate_generic_type (type, context);
590
591         if (!inflated)
592                 return dup_type (type, type);
593
594         mono_stats.inflated_type_count++;
595         return inflated;
596 }
597
598 static MonoGenericContext *
599 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with)
600 {
601         MonoGenericClass *gclass = NULL;
602         MonoGenericMethod *gmethod = NULL;
603         MonoGenericContext *res;
604
605         if (context->gclass)
606                 gclass = inflate_generic_class (context->gclass, inflate_with);
607
608         if (context->gmethod) {
609                 MonoGenericInst *ninst = mono_metadata_inflate_generic_inst (context->gmethod->inst, inflate_with);
610                 if (gclass == context->gclass && ninst == context->gmethod->inst) {
611                         gmethod = context->gmethod;
612                 } else {
613                         gmethod = g_new0 (MonoGenericMethod, 1);
614                         gmethod->generic_class = gclass;
615                         gmethod->container = context->container;
616                         gmethod->inst = ninst;
617                 }
618         }
619
620         if (gclass == context->gclass && gmethod == context->gmethod)
621                 return context;
622
623         res = g_new0 (MonoGenericContext, 1);
624
625         res->container = gmethod ? gmethod->container : context->container;
626         res->gclass = gclass;
627         res->gmethod = gmethod;
628
629         return res;
630 }
631
632 /*
633  * mono_class_inflate_generic_method:
634  * @method: a generic method
635  * @context: a generics context
636  *
637  * Instantiate the generic method @method using the generics context @context.
638  *
639  * Returns: the new instantiated method
640  */
641 MonoMethod *
642 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
643 {
644         return mono_class_inflate_generic_method_full (method, NULL, context);
645 }
646
647 /**
648  * mono_class_inflate_generic_method:
649  *
650  * Instantiate method @method with the generic context @context.
651  * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
652  *         Use mono_get_inflated_method (), mono_method_signature () and mono_method_get_header () to get the correct values.
653  */
654 MonoMethod*
655 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
656 {
657         MonoMethod *result;
658         MonoMethodInflated *iresult;
659         MonoMethodSignature *sig;
660
661         /* The `method' has already been instantiated before -> we need to create a new context. */
662         while (method->is_inflated) {
663                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
664                 context = inflate_generic_context (imethod->context, context);
665                 if (context == imethod->context)
666                         return method;
667                 method = imethod->declaring;
668         }
669
670         if (!method->generic_container && !method->klass->generic_container)
671                 return method;
672
673         mono_stats.inflated_method_count++;
674         iresult = g_new0 (MonoMethodInflated, 1);
675
676         sig = mono_method_signature (method);
677         if (sig->pinvoke) {
678                 iresult->method.pinvoke = *(MonoMethodPInvoke*)method;
679         } else {
680                 iresult->method.normal = *(MonoMethodNormal*)method;
681                 iresult->method.normal.header = NULL;
682         }
683
684         result = (MonoMethod *) iresult;
685         result->is_inflated = 1;
686         result->signature = NULL;
687         iresult->context = context;
688         iresult->declaring = method;
689
690         if (!klass_hint || !klass_hint->generic_class ||
691             klass_hint->generic_class->container_class != method->klass ||
692             klass_hint->generic_class->inst != context->gclass->inst)
693                 klass_hint = NULL;
694
695         if (method->klass->generic_container)
696                 result->klass = klass_hint;
697
698         if (!result->klass) {
699                 MonoType *inflated = inflate_generic_type (&method->klass->byval_arg, context);
700                 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
701         }
702
703         if (method->generic_container && !context->gmethod) {
704                 MonoGenericMethod *gmethod = g_memdup (method->generic_container->context.gmethod, sizeof (*gmethod));
705                 gmethod->generic_class = result->klass->generic_class;
706
707                 context = g_new0 (MonoGenericContext, 1);
708                 context->container = method->generic_container;
709                 context->gclass = result->klass->generic_class;
710                 context->gmethod = gmethod;
711
712                 iresult->context = context;
713         }
714
715         return result;
716 }
717
718 /**
719  * mono_get_inflated_method:
720  *
721  * For performance reasons, mono_class_inflate_generic_method() does not actually instantiate the
722  * method, it just "prepares" it for that.  If you really need to fully instantiate the method
723  * (including its signature and header), call this method.
724  * FIXME: Martin? this description looks completely wrong.
725  */
726 MonoMethod *
727 mono_get_inflated_method (MonoMethod *method)
728 {
729         return method;
730 }
731
732 /** 
733  * mono_class_find_enum_basetype:
734  * @class: The enum class
735  *
736  *   Determine the basetype of an enum by iterating through its fields. We do this
737  * in a separate function since it is cheaper than calling mono_class_setup_fields.
738  */
739 static MonoType*
740 mono_class_find_enum_basetype (MonoClass *class)
741 {
742         MonoImage *m = class->image; 
743         const int top = class->field.count;
744         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
745         int i;
746
747         g_assert (class->enumtype);
748
749         /*
750          * Fetch all the field information.
751          */
752         for (i = 0; i < top; i++){
753                 const char *sig;
754                 guint32 cols [MONO_FIELD_SIZE];
755                 int idx = class->field.first + i;
756                 MonoGenericContainer *container = NULL;
757                 MonoType *ftype;
758
759                 mono_metadata_decode_row (t, idx, cols, MONO_FIELD_SIZE);
760                 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
761                 mono_metadata_decode_value (sig, &sig);
762                 /* FIELD signature == 0x06 */
763                 g_assert (*sig == 0x06);
764                 if (class->generic_container)
765                         container = class->generic_container;
766                 else if (class->generic_class) {
767                         MonoClass *gklass = class->generic_class->container_class;
768
769                         container = gklass->generic_container;
770                         g_assert (container);
771                 }
772                 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
773                 if (!ftype)
774                         return NULL;
775                 if (class->generic_class) {
776                         ftype = mono_class_inflate_generic_type (ftype, class->generic_class->context);
777                         ftype->attrs = cols [MONO_FIELD_FLAGS];
778                 }
779
780                 if (class->enumtype && !(cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC))
781                         return ftype;
782         }
783
784         return NULL;
785 }
786
787 /** 
788  * mono_class_setup_fields:
789  * @class: The class to initialize
790  *
791  * Initializes the class->fields.
792  * LOCKING: Assumes the loader lock is held.
793  */
794 static void
795 mono_class_setup_fields (MonoClass *class)
796 {
797         MonoImage *m = class->image; 
798         int top = class->field.count;
799         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
800         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
801         int i, blittable = TRUE;
802         guint32 real_size = 0;
803         guint32 packing_size = 0;
804         gboolean explicit_size;
805         MonoClassField *field;
806         MonoGenericContainer *container = NULL;
807         MonoClass *gklass = NULL;
808
809         if (class->size_inited)
810                 return;
811
812         if (class->generic_class) {
813                 MonoClass *gklass = class->generic_class->container_class;
814                 mono_class_setup_fields (gklass);
815                 top = gklass->field.count;
816         }
817
818         class->instance_size = 0;
819         class->class_size = 0;
820
821         if (class->parent) {
822                 /* For generic instances, class->parent might not have been initialized */
823                 mono_class_init (class->parent);
824                 if (!class->parent->size_inited)
825                         mono_class_setup_fields (class->parent);
826                 class->instance_size += class->parent->instance_size;
827                 class->min_align = class->parent->min_align;
828                 /* we use |= since it may have been set already */
829                 class->has_references |= class->parent->has_references;
830                 blittable = class->parent->blittable;
831         } else {
832                 class->instance_size = sizeof (MonoObject);
833                 class->min_align = 1;
834         }
835
836         /* Get the real size */
837         explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
838
839         if (explicit_size) {
840                 g_assert ((packing_size & 0xfffffff0) == 0);
841                 class->packing_size = packing_size;
842                 real_size += class->instance_size;
843         }
844
845         if (!top) {
846                 if (explicit_size && real_size) {
847                         class->instance_size = MAX (real_size, class->instance_size);
848                 }
849                 class->size_inited = 1;
850                 class->blittable = blittable;
851                 return;
852         }
853
854         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
855                 blittable = FALSE;
856
857         /* Prevent infinite loops if the class references itself */
858         class->size_inited = 1;
859
860         class->fields = mono_mempool_alloc0 (class->image->mempool, sizeof (MonoClassField) * top);
861
862         if (class->generic_container) {
863                 container = class->generic_container;
864         } else if (class->generic_class) {
865                 gklass = class->generic_class->container_class;
866                 container = gklass->generic_container;
867                 g_assert (container);
868
869                 mono_class_setup_fields (gklass);
870         }
871
872         /*
873          * Fetch all the field information.
874          */
875         for (i = 0; i < top; i++){
876                 int idx = class->field.first + i;
877                 field = &class->fields [i];
878
879                 field->parent = class;
880
881                 if (class->generic_class) {
882                         MonoClassField *gfield = &gklass->fields [i];
883                         MonoInflatedField *ifield = g_new0 (MonoInflatedField, 1);
884
885                         ifield->generic_type = gfield->type;
886                         field->name = gfield->name;
887                         field->generic_info = ifield;
888                         field->type = mono_class_inflate_generic_type (gfield->type, class->generic_class->context);
889                         field->type->attrs = gfield->type->attrs;
890                         if (mono_field_is_deleted (field))
891                                 continue;
892                         field->offset = gfield->offset;
893                         field->data = gfield->data;
894                 } else {
895                         guint32 rva;
896                         const char *sig;
897                         guint32 cols [MONO_FIELD_SIZE];
898
899                         mono_metadata_decode_row (t, idx, cols, MONO_FIELD_SIZE);
900                         /* The name is needed for fieldrefs */
901                         field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
902                         sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
903                         mono_metadata_decode_value (sig, &sig);
904                         /* FIELD signature == 0x06 */
905                         g_assert (*sig == 0x06);
906                         field->type = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
907                         if (!field->type) {
908                                 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
909                                 break;
910                         }
911                         if (mono_field_is_deleted (field))
912                                 continue;
913                         if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
914                                 guint32 offset;
915                                 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
916                                 field->offset = offset;
917                                 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
918                                         g_warning ("%s not initialized correctly (missing field layout info for %s)",
919                                                    class->name, field->name);
920                         }
921
922                         if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
923                                 mono_metadata_field_info (m, idx, NULL, &rva, NULL);
924                                 if (!rva)
925                                         g_warning ("field %s in %s should have RVA data, but hasn't", field->name, class->name);
926                                 field->data = mono_image_rva_map (class->image, rva);
927                         }
928                 }
929
930                 /* Only do these checks if we still think this type is blittable */
931                 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
932                         if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
933                                 blittable = FALSE;
934                         } else {
935                                 MonoClass *field_class = mono_class_from_mono_type (field->type);
936                                 if (!field_class || !field_class->blittable)
937                                         blittable = FALSE;
938                         }
939                 }
940
941                 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
942                         class->enum_basetype = field->type;
943                         class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
944                         blittable = class->element_class->blittable;
945                 }
946
947                 /* The def_value of fields is compute lazily during vtable creation */
948         }
949
950         if (class == mono_defaults.string_class)
951                 blittable = FALSE;
952
953         class->blittable = blittable;
954
955         if (class->enumtype && !class->enum_basetype) {
956                 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
957                         G_BREAKPOINT ();
958         }
959         if (explicit_size && real_size) {
960                 class->instance_size = MAX (real_size, class->instance_size);
961         }
962
963         if (class->exception_type)
964                 return;
965         mono_class_layout_fields (class);
966 }
967
968 /** 
969  * mono_class_setup_fields_locking:
970  * @class: The class to initialize
971  *
972  * Initializes the class->fields array of fields.
973  * Aquires the loader lock.
974  */
975 static void
976 mono_class_setup_fields_locking (MonoClass *class)
977 {
978         mono_loader_lock ();
979         mono_class_setup_fields (class);
980         mono_loader_unlock ();
981 }
982
983 /*
984  * mono_class_has_references:
985  *
986  *   Returns whenever @klass->has_references is set, initializing it if needed.
987  * Aquires the loader lock.
988  */
989 static gboolean
990 mono_class_has_references (MonoClass *klass)
991 {
992         if (klass->init_pending) {
993                 /* Be conservative */
994                 return TRUE;
995         } else {
996                 mono_class_init (klass);
997
998                 return klass->has_references;
999         }
1000 }
1001
1002 /* useful until we keep track of gc-references in corlib etc. */
1003 #ifdef HAVE_SGEN_GC
1004 #define IS_GC_REFERENCE(t) FALSE
1005 #else
1006 #define IS_GC_REFERENCE(t) ((t)->type == MONO_TYPE_U || (t)->type == MONO_TYPE_I || (t)->type == MONO_TYPE_PTR)
1007 #endif
1008
1009 /*
1010  * mono_class_layout_fields:
1011  * @class: a class
1012  *
1013  * Compute the placement of fields inside an object or struct, according to
1014  * the layout rules and set the following fields in @class:
1015  *  - has_references (if the class contains instance references firled or structs that contain references)
1016  *  - has_static_refs (same, but for static fields)
1017  *  - instance_size (size of the object in memory)
1018  *  - class_size (size needed for the static fields)
1019  *  - size_inited (flag set when the instance_size is set)
1020  *
1021  * LOCKING: this is supposed to be called with the loader lock held.
1022  */
1023 void
1024 mono_class_layout_fields (MonoClass *class)
1025 {
1026         int i;
1027         const int top = class->field.count;
1028         guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1029         guint32 pass, passes, real_size;
1030         gboolean gc_aware_layout = FALSE;
1031         MonoClassField *field;
1032
1033         if (class->generic_container ||
1034             (class->generic_class && class->generic_class->inst->is_open))
1035                 return;
1036
1037         /*
1038          * Enable GC aware auto layout: in this mode, reference
1039          * fields are grouped together inside objects, increasing collector 
1040          * performance.
1041          * Requires that all classes whose layout is known to native code be annotated
1042          * with [StructLayout (LayoutKind.Sequential)]
1043          * Value types have gc_aware_layout disabled by default, as per
1044          * what the default is for other runtimes.
1045          */
1046          /* corlib is missing [StructLayout] directives in many places */
1047         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1048                 if (class->image != mono_defaults.corlib &&
1049                         class->byval_arg.type != MONO_TYPE_VALUETYPE)
1050                         gc_aware_layout = TRUE;
1051         }
1052
1053         /* Compute klass->has_references */
1054         /* 
1055          * Process non-static fields first, since static fields might recursively
1056          * refer to the class itself.
1057          */
1058         for (i = 0; i < top; i++) {
1059                 MonoType *ftype;
1060
1061                 field = &class->fields [i];
1062
1063                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1064                         ftype = mono_type_get_underlying_type (field->type);
1065                         if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1066                                 class->has_references = TRUE;
1067                 }
1068         }
1069
1070         for (i = 0; i < top; i++) {
1071                 MonoType *ftype;
1072
1073                 field = &class->fields [i];
1074
1075                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1076                         ftype = mono_type_get_underlying_type (field->type);
1077                         if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1078                                 class->has_static_refs = TRUE;
1079                 }
1080         }
1081
1082         for (i = 0; i < top; i++) {
1083                 MonoType *ftype;
1084
1085                 field = &class->fields [i];
1086
1087                 ftype = mono_type_get_underlying_type (field->type);
1088                 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1089                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1090                                 class->has_static_refs = TRUE;
1091                         else
1092                                 class->has_references = TRUE;
1093                 }
1094         }
1095
1096         /*
1097          * Compute field layout and total size (not considering static fields)
1098          */
1099
1100         switch (layout) {
1101         case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1102         case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1103
1104                 if (gc_aware_layout)
1105                         passes = 2;
1106                 else
1107                         passes = 1;
1108
1109                 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1110                         passes = 1;
1111
1112                 if (class->parent)
1113                         real_size = class->parent->instance_size;
1114                 else
1115                         real_size = sizeof (MonoObject);
1116
1117                 for (pass = 0; pass < passes; ++pass) {
1118                         for (i = 0; i < top; i++){
1119                                 int size, align;
1120
1121                                 field = &class->fields [i];
1122
1123                                 if (mono_field_is_deleted (field))
1124                                         continue;
1125                                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1126                                         continue;
1127
1128                                 if (gc_aware_layout) {
1129                                         /* 
1130                                          * We process fields with reference type in the first pass,
1131                                          * and fields with non-reference type in the second pass.
1132                                          * We use IS_POINTER instead of IS_REFERENCE because in
1133                                          * some internal structures, we store GC_MALLOCed memory
1134                                          * in IntPtr fields...
1135                                          */
1136                                         if (MONO_TYPE_IS_POINTER (field->type)) {
1137                                                 if (pass == 1)
1138                                                         continue;
1139                                         } else {
1140                                                 if (pass == 0)
1141                                                         continue;
1142                                         }
1143                                 }
1144
1145                                 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1146                                         (strcmp (field->name, "$PRIVATE$") == 0)) {
1147                                         /* This field is a hack inserted by MCS to empty structures */
1148                                         continue;
1149                                 }
1150
1151                                 size = mono_type_size (field->type, &align);
1152                         
1153                                 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1154                                 align = class->packing_size ? MIN (class->packing_size, align): align;
1155                                 class->min_align = MAX (align, class->min_align);
1156                                 field->offset = real_size;
1157                                 field->offset += align - 1;
1158                                 field->offset &= ~(align - 1);
1159                                 real_size = field->offset + size;
1160                         }
1161
1162                         class->instance_size = MAX (real_size, class->instance_size);
1163        
1164                         if (class->instance_size & (class->min_align - 1)) {
1165                                 class->instance_size += class->min_align - 1;
1166                                 class->instance_size &= ~(class->min_align - 1);
1167                         }
1168                 }
1169                 break;
1170         case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1171                 real_size = 0;
1172                 for (i = 0; i < top; i++) {
1173                         int size, align;
1174
1175                         field = &class->fields [i];
1176
1177                         /*
1178                          * There must be info about all the fields in a type if it
1179                          * uses explicit layout.
1180                          */
1181
1182                         if (mono_field_is_deleted (field))
1183                                 continue;
1184                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1185                                 continue;
1186
1187                         size = mono_type_size (field->type, &align);
1188                         
1189                         /*
1190                          * When we get here, field->offset is already set by the
1191                          * loader (for either runtime fields or fields loaded from metadata).
1192                          * The offset is from the start of the object: this works for both
1193                          * classes and valuetypes.
1194                          */
1195                         field->offset += sizeof (MonoObject);
1196
1197                         /*
1198                          * Calc max size.
1199                          */
1200                         real_size = MAX (real_size, size + field->offset);
1201                 }
1202                 class->instance_size = MAX (real_size, class->instance_size);
1203                 break;
1204         }
1205
1206         if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1207                 /*
1208                  * For small structs, set min_align to at least the struct size, since the
1209                  * JIT memset/memcpy code assumes this and generates unaligned accesses
1210                  * otherwise. See #78990 for a testcase.
1211                  */
1212                 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1213                         class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1214         }
1215
1216         class->size_inited = 1;
1217
1218         /*
1219          * Compute static field layout and size
1220          */
1221         for (i = 0; i < top; i++){
1222                 int size, align;
1223
1224                 field = &class->fields [i];
1225                         
1226                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1227                         continue;
1228                 if (mono_field_is_deleted (field))
1229                         continue;
1230
1231                 size = mono_type_size (field->type, &align);
1232                 field->offset = class->class_size;
1233                 field->offset += align - 1;
1234                 field->offset &= ~(align - 1);
1235                 class->class_size = field->offset + size;
1236         }
1237 }
1238
1239 /*
1240  * mono_class_setup_methods:
1241  * @class: a class
1242  *
1243  *   Initializes the 'methods' array in the klass.
1244  * Calling this method should be avoided if possible since it allocates a lot 
1245  * of long-living MonoMethod structures.
1246  * Methods belonging to an interface are assigned a sequential slot starting
1247  * from 0.
1248  */
1249 void
1250 mono_class_setup_methods (MonoClass *class)
1251 {
1252         int i;
1253         MonoMethod **methods;
1254
1255         if (class->methods)
1256                 return;
1257
1258         mono_loader_lock ();
1259
1260         if (class->methods) {
1261                 mono_loader_unlock ();
1262                 return;
1263         }
1264
1265         //printf ("INIT: %s.%s\n", class->name_space, class->name);
1266
1267         if (!class->methods) {
1268                 methods = mono_mempool_alloc (class->image->mempool, sizeof (MonoMethod*) * class->method.count);
1269                 for (i = 0; i < class->method.count; ++i) {
1270                         methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | (i + class->method.first + 1), class);
1271                 }
1272         }
1273
1274         if (MONO_CLASS_IS_INTERFACE (class))
1275                 for (i = 0; i < class->method.count; ++i)
1276                         methods [i]->slot = i;
1277
1278         /* Leave this assignment as the last op in this function */
1279         class->methods = methods;
1280
1281         mono_loader_unlock ();
1282 }
1283
1284
1285 static void
1286 mono_class_setup_properties (MonoClass *class)
1287 {
1288         guint startm, endm, i, j;
1289         guint32 cols [MONO_PROPERTY_SIZE];
1290         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_PROPERTY];
1291         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1292         MonoProperty *properties;
1293         guint32 last;
1294
1295         if (class->properties)
1296                 return;
1297
1298         mono_loader_lock ();
1299
1300         if (class->properties) {
1301                 mono_loader_unlock ();
1302                 return;
1303         }
1304
1305         class->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1306         class->property.count = last - class->property.first;
1307
1308         if (class->property.count)
1309                 mono_class_setup_methods (class);
1310
1311         properties = mono_mempool_alloc0 (class->image->mempool, sizeof (MonoProperty) * class->property.count);
1312         for (i = class->property.first; i < last; ++i) {
1313                 mono_metadata_decode_row (pt, i, cols, MONO_PROPERTY_SIZE);
1314                 properties [i - class->property.first].parent = class;
1315                 properties [i - class->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
1316                 properties [i - class->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
1317
1318                 startm = mono_metadata_methods_from_property (class->image, i, &endm);
1319                 for (j = startm; j < endm; ++j) {
1320                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1321                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1322                         case METHOD_SEMANTIC_SETTER:
1323                                 properties [i - class->property.first].set = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1324                                 break;
1325                         case METHOD_SEMANTIC_GETTER:
1326                                 properties [i - class->property.first].get = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1327                                 break;
1328                         default:
1329                                 break;
1330                         }
1331                 }
1332         }
1333
1334         /* Leave this assignment as the last op in the function */
1335         class->properties = properties;
1336
1337         mono_loader_unlock ();
1338 }
1339
1340 /*
1341  * LOCKING: assumes the loader lock is held.
1342  */
1343 static void
1344 inflate_event (MonoClass *class, MonoEvent *event, MonoInflatedGenericClass *gclass)
1345 {
1346         event->parent = class;
1347
1348         if (event->add) {
1349                 MonoMethod *inflated = mono_class_inflate_generic_method_full (
1350                         event->add, class, gclass->generic_class.context);
1351
1352                 event->add = mono_get_inflated_method (inflated);
1353         }
1354
1355         if (event->remove) {
1356                 MonoMethod *inflated = mono_class_inflate_generic_method_full (
1357                         event->remove, class, gclass->generic_class.context);
1358
1359                 event->remove = mono_get_inflated_method (inflated);
1360         }
1361
1362         if (event->raise) {
1363                 MonoMethod *inflated = mono_class_inflate_generic_method_full (
1364                         event->raise, class, gclass->generic_class.context);
1365
1366                 event->raise = mono_get_inflated_method (inflated);
1367         }
1368
1369         if (event->other) {
1370                 MonoMethod **om = event->other;
1371                 int count = 0;
1372                 while (*om) {
1373                         count++;
1374                         om++;
1375                 }
1376                 om = event->other;
1377                 event->other = g_new0 (MonoMethod*, count + 1);
1378                 count = 0;
1379                 while (*om) {
1380                         MonoMethod *inflated = mono_class_inflate_generic_method_full (
1381                                 *om, class, gclass->generic_class.context);
1382
1383                         event->other [count++] = mono_get_inflated_method (inflated);
1384                         om++;
1385                 }
1386         }
1387 }
1388
1389 static void
1390 mono_class_setup_events (MonoClass *class)
1391 {
1392         guint startm, endm, i, j;
1393         guint32 cols [MONO_EVENT_SIZE];
1394         MonoTableInfo *pt = &class->image->tables [MONO_TABLE_EVENT];
1395         MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1396         guint32 last;
1397         MonoEvent *events;
1398
1399         if (class->events)
1400                 return;
1401
1402         mono_loader_lock ();
1403
1404         if (class->events) {
1405                 mono_loader_unlock ();
1406                 return;
1407         }
1408
1409         if (class->generic_class) {
1410                 MonoInflatedGenericClass *gclass;
1411                 MonoClass *gklass;
1412
1413                 gclass = mono_get_inflated_generic_class (class->generic_class);
1414                 gklass = gclass->generic_class.container_class;
1415
1416                 mono_class_setup_events (gklass);
1417                 class->event = gklass->event;
1418
1419                 class->events = g_new0 (MonoEvent, class->event.count);
1420
1421                 for (i = 0; i < class->event.count; i++) {
1422                         class->events [i] = gklass->events [i];
1423                         inflate_event (class, &class->events [i], gclass);
1424                 }
1425
1426                 mono_loader_unlock ();
1427                 return;
1428         }
1429
1430         class->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1431         class->event.count = last - class->event.first;
1432
1433         if (class->event.count)
1434                 mono_class_setup_methods (class);
1435
1436         events = mono_mempool_alloc0 (class->image->mempool, sizeof (MonoEvent) * class->event.count);
1437         for (i = class->event.first; i < last; ++i) {
1438                 MonoEvent *event = &events [i - class->event.first];
1439                         
1440                 mono_metadata_decode_row (pt, i, cols, MONO_EVENT_SIZE);
1441                 event->parent = class;
1442                 event->attrs = cols [MONO_EVENT_FLAGS];
1443                 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
1444
1445                 startm = mono_metadata_methods_from_event (class->image, i, &endm);
1446                 for (j = startm; j < endm; ++j) {
1447                         mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1448                         switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1449                         case METHOD_SEMANTIC_ADD_ON:
1450                                 event->add = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1451                                 break;
1452                         case METHOD_SEMANTIC_REMOVE_ON:
1453                                 event->remove = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1454                                 break;
1455                         case METHOD_SEMANTIC_FIRE:
1456                                 event->raise = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1457                                 break;
1458                         case METHOD_SEMANTIC_OTHER: {
1459                                 int n = 0;
1460
1461                                 if (event->other == NULL) {
1462                                         event->other = g_new0 (MonoMethod*, 2);
1463                                 } else {
1464                                         while (event->other [n])
1465                                                 n++;
1466                                         event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
1467                                 }
1468                                 event->other [n] = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1469                                 /* NULL terminated */
1470                                 event->other [n + 1] = NULL;
1471                                 break;
1472                         }
1473                         default:
1474                                 break;
1475                         }
1476                 }
1477         }
1478         /* Leave this assignment as the last op in the function */
1479         class->events = events;
1480
1481         mono_loader_unlock ();
1482 }
1483
1484 /*
1485  * Global pool of interface IDs, represented as a bitset.
1486  * LOCKING: this is supposed to be accessed with the loader lock held.
1487  */
1488 static MonoBitSet *global_interface_bitset = NULL;
1489
1490 /*
1491  * mono_unload_interface_ids:
1492  * @bitset: bit set of interface IDs
1493  *
1494  * When an image is unloaded, the interface IDs associated with
1495  * the image are put back in the global pool of IDs so the numbers
1496  * can be reused.
1497  */
1498 void
1499 mono_unload_interface_ids (MonoBitSet *bitset)
1500 {
1501         mono_loader_lock ();
1502         mono_bitset_sub (global_interface_bitset, bitset);
1503         mono_loader_unlock ();
1504 }
1505
1506 /*
1507  * mono_get_unique_iid:
1508  * @class: interface
1509  *
1510  * Assign a unique integer ID to the interface represented by @class.
1511  * The ID will positive and as small as possible.
1512  * LOCKING: this is supposed to be called with the loader lock held.
1513  * Returns: the new ID.
1514  */
1515 static guint
1516 mono_get_unique_iid (MonoClass *class)
1517 {
1518         int iid;
1519         
1520         g_assert (MONO_CLASS_IS_INTERFACE (class));
1521
1522         if (!global_interface_bitset) {
1523                 global_interface_bitset = mono_bitset_new (128, 0);
1524         }
1525
1526         iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
1527         if (iid < 0) {
1528                 int old_size = mono_bitset_size (global_interface_bitset);
1529                 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
1530                 mono_bitset_free (global_interface_bitset);
1531                 global_interface_bitset = new_set;
1532                 iid = old_size;
1533         }
1534         mono_bitset_set (global_interface_bitset, iid);
1535         /* set the bit also in the per-image set */
1536         if (class->image->interface_bitset) {
1537                 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
1538                         MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
1539                         mono_bitset_free (class->image->interface_bitset);
1540                         class->image->interface_bitset = new_set;
1541                 }
1542         } else {
1543                 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
1544         }
1545         mono_bitset_set (class->image->interface_bitset, iid);
1546
1547         if (mono_print_vtable) {
1548                 int generic_id;
1549                 char *type_name = mono_type_full_name (&class->byval_arg);
1550                 if (class->generic_class && !class->generic_class->inst->is_open) {
1551                         generic_id = class->generic_class->inst->id;
1552                         g_assert (generic_id != 0);
1553                 } else {
1554                         generic_id = 0;
1555                 }
1556                 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
1557                 g_free (type_name);
1558         }
1559
1560         g_assert (iid <= 65535);
1561         return iid;
1562 }
1563
1564 static void
1565 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
1566 {
1567         int i;
1568         MonoClass *ic;
1569         
1570         for (i = 0; i < klass->interface_count; i++) {
1571                 ic = klass->interfaces [i];
1572
1573                 if (*res == NULL)
1574                         *res = g_ptr_array_new ();
1575                 g_ptr_array_add (*res, ic);
1576                 mono_class_init (ic);
1577
1578                 collect_implemented_interfaces_aux (ic, res);
1579         }
1580 }
1581
1582 GPtrArray*
1583 mono_class_get_implemented_interfaces (MonoClass *klass)
1584 {
1585         GPtrArray *res = NULL;
1586
1587         collect_implemented_interfaces_aux (klass, &res);
1588         return res;
1589 }
1590
1591 typedef struct _IOffsetInfo IOffsetInfo;
1592 struct _IOffsetInfo {
1593         IOffsetInfo *next;
1594         int size;
1595         int next_free;
1596         int data [MONO_ZERO_LEN_ARRAY];
1597 };
1598
1599 static IOffsetInfo *cached_offset_info = NULL;
1600 static int next_offset_info_size = 128;
1601
1602 static int*
1603 cache_interface_offsets (int max_iid, int *data)
1604 {
1605         IOffsetInfo *cached_info;
1606         int *cached;
1607         int new_size;
1608         for (cached_info = cached_offset_info; cached_info; cached_info = cached_info->next) {
1609                 cached = cached_info->data;
1610                 while (cached < cached_info->data + cached_info->size && *cached) {
1611                         if (*cached == max_iid) {
1612                                 int i, matched = TRUE;
1613                                 cached++;
1614                                 for (i = 0; i < max_iid; ++i) {
1615                                         if (cached [i] != data [i]) {
1616                                                 matched = FALSE;
1617                                                 break;
1618                                         }
1619                                 }
1620                                 if (matched)
1621                                         return cached;
1622                                 cached += max_iid;
1623                         } else {
1624                                 cached += *cached + 1;
1625                         }
1626                 }
1627         }
1628         /* find a free slot */
1629         for (cached_info = cached_offset_info; cached_info; cached_info = cached_info->next) {
1630                 if (cached_info->size - cached_info->next_free >= max_iid + 1) {
1631                         cached = &cached_info->data [cached_info->next_free];
1632                         *cached++ = max_iid;
1633                         memcpy (cached, data, max_iid * sizeof (int));
1634                         cached_info->next_free += max_iid + 1;
1635                         return cached;
1636                 }
1637         }
1638         /* allocate a new chunk */
1639         if (max_iid + 1 < next_offset_info_size) {
1640                 new_size = next_offset_info_size;
1641                 if (next_offset_info_size < 4096)
1642                         next_offset_info_size += next_offset_info_size >> 2;
1643         } else {
1644                 new_size = max_iid + 1;
1645         }
1646         cached_info = g_malloc0 (sizeof (IOffsetInfo) + sizeof (int) * new_size);
1647         cached_info->size = new_size;
1648         /*g_print ("allocated %d offset entries at %p (total: %d)\n", new_size, cached_info->data, offset_info_total_size);*/
1649         cached = &cached_info->data [0];
1650         *cached++ = max_iid;
1651         memcpy (cached, data, max_iid * sizeof (int));
1652         cached_info->next_free += max_iid + 1;
1653         cached_info->next = cached_offset_info;
1654         cached_offset_info = cached_info;
1655         return cached;
1656 }
1657
1658 /*
1659  * LOCKING: this is supposed to be called with the loader lock held.
1660  */
1661 static int
1662 setup_interface_offsets (MonoClass *class, int cur_slot)
1663 {
1664         MonoClass *k, *ic;
1665         int i, max_iid;
1666         int *cached_data;
1667         GPtrArray *ifaces;
1668
1669         /* compute maximum number of slots and maximum interface id */
1670         max_iid = 0;
1671         for (k = class; k ; k = k->parent) {
1672                 for (i = 0; i < k->interface_count; i++) {
1673                         ic = k->interfaces [i];
1674
1675                         if (!ic->inited)
1676                                 mono_class_init (ic);
1677
1678                         if (max_iid < ic->interface_id)
1679                                 max_iid = ic->interface_id;
1680                 }
1681                 ifaces = mono_class_get_implemented_interfaces (k);
1682                 if (ifaces) {
1683                         for (i = 0; i < ifaces->len; ++i) {
1684                                 ic = g_ptr_array_index (ifaces, i);
1685                                 if (max_iid < ic->interface_id)
1686                                         max_iid = ic->interface_id;
1687                         }
1688                         g_ptr_array_free (ifaces, TRUE);
1689                 }
1690         }
1691
1692         if (MONO_CLASS_IS_INTERFACE (class)) {
1693                 if (max_iid < class->interface_id)
1694                         max_iid = class->interface_id;
1695         }
1696         class->max_interface_id = max_iid;
1697         /* compute vtable offset for interfaces */
1698         class->interface_offsets = g_malloc (sizeof (int) * (max_iid + 1));
1699
1700         for (i = 0; i <= max_iid; i++)
1701                 class->interface_offsets [i] = -1;
1702
1703         ifaces = mono_class_get_implemented_interfaces (class);
1704         if (ifaces) {
1705                 for (i = 0; i < ifaces->len; ++i) {
1706                         ic = g_ptr_array_index (ifaces, i);
1707                         class->interface_offsets [ic->interface_id] = cur_slot;
1708                         cur_slot += ic->method.count;
1709                 }
1710                 g_ptr_array_free (ifaces, TRUE);
1711         }
1712
1713         for (k = class->parent; k ; k = k->parent) {
1714                 ifaces = mono_class_get_implemented_interfaces (k);
1715                 if (ifaces) {
1716                         for (i = 0; i < ifaces->len; ++i) {
1717                                 ic = g_ptr_array_index (ifaces, i);
1718
1719                                 if (class->interface_offsets [ic->interface_id] == -1) {
1720                                         int io = k->interface_offsets [ic->interface_id];
1721
1722                                         g_assert (io >= 0);
1723
1724                                         class->interface_offsets [ic->interface_id] = io;
1725                                 }
1726                         }
1727                         g_ptr_array_free (ifaces, TRUE);
1728                 }
1729         }
1730
1731         if (MONO_CLASS_IS_INTERFACE (class))
1732                 class->interface_offsets [class->interface_id] = cur_slot;
1733
1734         cached_data = cache_interface_offsets (max_iid + 1, class->interface_offsets);
1735         g_free (class->interface_offsets);
1736         class->interface_offsets = cached_data;
1737
1738         return cur_slot;
1739 }
1740
1741 /*
1742  * Setup interface offsets for interfaces. Used by Ref.Emit.
1743  */
1744 void
1745 mono_class_setup_interface_offsets (MonoClass *class)
1746 {
1747         mono_loader_lock ();
1748
1749         setup_interface_offsets (class, 0);
1750
1751         mono_loader_unlock ();
1752 }
1753
1754 void
1755 mono_class_setup_vtable (MonoClass *class)
1756 {
1757         MonoMethod **overrides;
1758         MonoGenericContext *context;
1759         guint32 type_token;
1760         int onum = 0;
1761         gboolean ok = TRUE;
1762
1763         if (class->vtable)
1764                 return;
1765
1766         mono_class_setup_methods (class);
1767
1768         if (MONO_CLASS_IS_INTERFACE (class))
1769                 return;
1770
1771         mono_loader_lock ();
1772
1773         if (class->vtable) {
1774                 mono_loader_unlock ();
1775                 return;
1776         }
1777
1778         if (class->generic_class) {
1779                 context = class->generic_class->context;
1780                 type_token = class->generic_class->container_class->type_token;
1781         } else {
1782                 context = (MonoGenericContext *) class->generic_container;              
1783                 type_token = class->type_token;
1784         }
1785
1786         if (class->image->dynamic)
1787                 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
1788         else {
1789                 /* The following call fails if there are missing methods in the type */
1790                 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
1791         }
1792
1793         if (ok)
1794                 mono_class_setup_vtable_general (class, overrides, onum);
1795                 
1796         g_free (overrides);
1797
1798         mono_loader_unlock ();
1799
1800         return;
1801 }
1802
1803 /*
1804  * LOCKING: this is supposed to be called with the loader lock held.
1805  */
1806 void
1807 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
1808 {
1809         MonoClass *k, *ic;
1810         MonoMethod **vtable;
1811         int i, max_vtsize = 0, max_iid, cur_slot = 0;
1812         GPtrArray *ifaces, *pifaces = NULL;
1813         GHashTable *override_map = NULL;
1814         gboolean security_enabled = mono_is_security_manager_active ();
1815
1816         if (class->vtable)
1817                 return;
1818
1819         ifaces = mono_class_get_implemented_interfaces (class);
1820         if (ifaces) {
1821                 for (i = 0; i < ifaces->len; i++) {
1822                         MonoClass *ic = g_ptr_array_index (ifaces, i);
1823                         max_vtsize += ic->method.count;
1824                 }
1825                 g_ptr_array_free (ifaces, TRUE);
1826         }
1827         
1828         if (class->parent) {
1829                 mono_class_init (class->parent);
1830                 mono_class_setup_vtable (class->parent);
1831                 max_vtsize += class->parent->vtable_size;
1832                 cur_slot = class->parent->vtable_size;
1833         }
1834
1835         max_vtsize += class->method.count;
1836
1837         vtable = alloca (sizeof (gpointer) * max_vtsize);
1838         memset (vtable, 0, sizeof (gpointer) * max_vtsize);
1839
1840         /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
1841
1842         cur_slot = setup_interface_offsets (class, cur_slot);
1843         max_iid = class->max_interface_id;
1844
1845         if (class->parent && class->parent->vtable_size)
1846                 memcpy (vtable, class->parent->vtable,  sizeof (gpointer) * class->parent->vtable_size);
1847
1848         /* override interface methods */
1849         for (i = 0; i < onum; i++) {
1850                 MonoMethod *decl = overrides [i*2];
1851                 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
1852                         int dslot;
1853                         mono_class_setup_methods (decl->klass);
1854                         g_assert (decl->slot != -1);
1855                         dslot = decl->slot + class->interface_offsets [decl->klass->interface_id];
1856                         vtable [dslot] = overrides [i*2 + 1];
1857                         vtable [dslot]->slot = dslot;
1858                         if (!override_map)
1859                                 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
1860
1861                         g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
1862                 }
1863         }
1864
1865         for (k = class; k ; k = k->parent) {
1866                 int nifaces = 0;
1867
1868                 ifaces = mono_class_get_implemented_interfaces (k);
1869                 if (ifaces) {
1870                         nifaces = ifaces->len;
1871                         if (k->generic_class) {
1872                                 pifaces = mono_class_get_implemented_interfaces (
1873                                         k->generic_class->container_class);
1874                                 g_assert (pifaces && (pifaces->len == nifaces));
1875                         }
1876                 }
1877                 for (i = 0; i < nifaces; i++) {
1878                         MonoClass *pic = NULL;
1879                         int j, l, io;
1880
1881                         ic = g_ptr_array_index (ifaces, i);
1882                         if (pifaces)
1883                                 pic = g_ptr_array_index (pifaces, i);
1884                         g_assert (ic->interface_id <= k->max_interface_id);
1885                         io = k->interface_offsets [ic->interface_id];
1886
1887                         g_assert (io >= 0);
1888                         g_assert (io <= max_vtsize);
1889
1890                         if (k == class) {
1891                                 mono_class_setup_methods (ic);
1892                                 for (l = 0; l < ic->method.count; l++) {
1893                                         MonoMethod *im = ic->methods [l];                                               
1894
1895                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1896                                                 continue;
1897
1898                                         for (j = 0; j < class->method.count; ++j) {
1899                                                 MonoMethod *cm = class->methods [j];
1900                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
1901                                                     !((cm->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) ||
1902                                                     !(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT))
1903                                                         continue;
1904                                                 if (!strcmp(cm->name, im->name) && 
1905                                                     mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
1906
1907                                                         /* CAS - SecurityAction.InheritanceDemand on interface */
1908                                                         if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
1909                                                                 mono_secman_inheritancedemand_method (cm, im);
1910                                                         }
1911
1912                                                         g_assert (io + l <= max_vtsize);
1913                                                         vtable [io + l] = cm;
1914                                                 }
1915                                         }
1916                                 }
1917                         } else {
1918                                 /* already implemented */
1919                                 if (io >= k->vtable_size)
1920                                         continue;
1921                         }
1922                                 
1923                         for (l = 0; l < ic->method.count; l++) {
1924                                 MonoMethod *im = ic->methods [l];                                               
1925                                 MonoClass *k1;
1926
1927                                 g_assert (io + l <= max_vtsize);
1928
1929                                 if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1930                                         continue;
1931                                         
1932                                 for (k1 = class; k1; k1 = k1->parent) {
1933                                         for (j = 0; j < k1->method.count; ++j) {
1934                                                 MonoMethod *cm = k1->methods [j];
1935
1936                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
1937                                                     !(cm->flags & METHOD_ATTRIBUTE_PUBLIC))
1938                                                         continue;
1939                                                 
1940                                                 if (!strcmp(cm->name, im->name) && 
1941                                                     mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
1942
1943                                                         /* CAS - SecurityAction.InheritanceDemand on interface */
1944                                                         if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
1945                                                                 mono_secman_inheritancedemand_method (cm, im);
1946                                                         }
1947
1948                                                         g_assert (io + l <= max_vtsize);
1949                                                         vtable [io + l] = cm;
1950                                                         break;
1951                                                 }
1952                                                 
1953                                         }
1954                                         g_assert (io + l <= max_vtsize);
1955                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1956                                                 break;
1957                                 }
1958                         }
1959
1960                         for (l = 0; l < ic->method.count; l++) {
1961                                 MonoMethod *im = ic->methods [l];                                               
1962                                 char *qname, *fqname, *cname, *the_cname;
1963                                 MonoClass *k1;
1964                                 
1965                                 if (vtable [io + l])
1966                                         continue;
1967
1968                                 if (pic) {
1969                                         the_cname = mono_type_get_name_full (&pic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
1970                                         cname = the_cname;
1971                                 } else {
1972                                         the_cname = NULL;
1973                                         cname = (char*)ic->name;
1974                                 }
1975                                         
1976                                 qname = g_strconcat (cname, ".", im->name, NULL);
1977                                 if (ic->name_space && ic->name_space [0])
1978                                         fqname = g_strconcat (ic->name_space, ".", cname, ".", im->name, NULL);
1979                                 else
1980                                         fqname = NULL;
1981
1982                                 for (k1 = class; k1; k1 = k1->parent) {
1983                                         for (j = 0; j < k1->method.count; ++j) {
1984                                                 MonoMethod *cm = k1->methods [j];
1985
1986                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
1987                                                         continue;
1988
1989                                                 if (((fqname && !strcmp (cm->name, fqname)) || !strcmp (cm->name, qname)) &&
1990                                                     mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
1991
1992                                                         /* CAS - SecurityAction.InheritanceDemand on interface */
1993                                                         if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
1994                                                                 mono_secman_inheritancedemand_method (cm, im);
1995                                                         }
1996
1997                                                         g_assert (io + l <= max_vtsize);
1998                                                         vtable [io + l] = cm;
1999                                                         break;
2000                                                 }
2001                                         }
2002                                 }
2003                                 g_free (the_cname);
2004                                 g_free (qname);
2005                                 g_free (fqname);
2006                         }
2007
2008                         
2009                         if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
2010                                 for (l = 0; l < ic->method.count; l++) {
2011                                         char *msig;
2012                                         MonoMethod *im = ic->methods [l];
2013                                         if (im->flags & METHOD_ATTRIBUTE_STATIC)
2014                                                         continue;
2015                                         g_assert (io + l <= max_vtsize);
2016
2017                                         /* 
2018                                          * If one of our parents already implements this interface
2019                                          * we can inherit the implementation.
2020                                          */
2021                                         if (!(vtable [io + l])) {
2022                                                 MonoClass *parent = class->parent;
2023                                                 
2024                                                 for (; parent; parent = parent->parent) {
2025                                                         if ((ic->interface_id <= parent->max_interface_id) && 
2026                                                                         (parent->interface_offsets [ic->interface_id] != -1) &&
2027                                                                         parent->vtable) {
2028                                                                 vtable [io + l] = parent->vtable [parent->interface_offsets [ic->interface_id] + l];
2029                                                         }
2030                                                 }
2031                                         }
2032
2033                                         if (!(vtable [io + l])) {
2034                                                 for (j = 0; j < onum; ++j) {
2035                                                         g_print (" at slot %d: %s (%d) overrides %s (%d)\n", io+l, overrides [j*2+1]->name, 
2036                                                                  overrides [j*2+1]->slot, overrides [j*2]->name, overrides [j*2]->slot);
2037                                                 }
2038                                                 msig = mono_signature_get_desc (mono_method_signature (im), FALSE);
2039                                                 printf ("no implementation for interface method %s::%s(%s) in class %s.%s\n",
2040                                                         mono_type_get_name (&ic->byval_arg), im->name, msig, class->name_space, class->name);
2041                                                 g_free (msig);
2042                                                 for (j = 0; j < class->method.count; ++j) {
2043                                                         MonoMethod *cm = class->methods [j];
2044                                                         msig = mono_signature_get_desc (mono_method_signature (cm), TRUE);
2045                                                         
2046                                                         printf ("METHOD %s(%s)\n", cm->name, msig);
2047                                                         g_free (msig);
2048                                                 }
2049                                                 g_assert_not_reached ();
2050                                         }
2051                                 }
2052                         }
2053                 
2054                         for (l = 0; l < ic->method.count; l++) {
2055                                 MonoMethod *im = vtable [io + l];
2056
2057                                 if (im) {
2058                                         g_assert (io + l <= max_vtsize);
2059                                         if (im->slot < 0) {
2060                                                 /* FIXME: why do we need this ? */
2061                                                 im->slot = io + l;
2062                                                 /* g_assert_not_reached (); */
2063                                         }
2064                                 }
2065                         }
2066                 }
2067                 if (ifaces)
2068                         g_ptr_array_free (ifaces, TRUE);
2069         } 
2070
2071         for (i = 0; i < class->method.count; ++i) {
2072                 MonoMethod *cm;
2073                
2074                 cm = class->methods [i];
2075                 
2076                 /*
2077                  * Non-virtual method have no place in the vtable.
2078                  * This also catches static methods (since they are not virtual).
2079                  */
2080                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
2081                         continue;
2082                 
2083                 /*
2084                  * If the method is REUSE_SLOT, we must check in the
2085                  * base class for a method to override.
2086                  */
2087                 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
2088                         int slot = -1;
2089                         for (k = class->parent; k ; k = k->parent) {
2090                                 int j;
2091                                 for (j = 0; j < k->method.count; ++j) {
2092                                         MonoMethod *m1 = k->methods [j];
2093                                         MonoMethodSignature *cmsig, *m1sig;
2094
2095                                         if (!(m1->flags & METHOD_ATTRIBUTE_VIRTUAL))
2096                                                 continue;
2097
2098                                         cmsig = mono_method_signature (cm);
2099                                         m1sig = mono_method_signature (m1);
2100
2101                                         if (!cmsig || !m1sig) {
2102                                                 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
2103                                                 return;
2104                                         }
2105
2106                                         if (!strcmp(cm->name, m1->name) && 
2107                                             mono_metadata_signature_equal (cmsig, m1sig)) {
2108
2109                                                 /* CAS - SecurityAction.InheritanceDemand */
2110                                                 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2111                                                         mono_secman_inheritancedemand_method (cm, m1);
2112                                                 }
2113
2114                                                 slot = k->methods [j]->slot;
2115                                                 g_assert (cm->slot < max_vtsize);
2116                                                 if (!override_map)
2117                                                         override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
2118                                                 g_hash_table_insert (override_map, m1, cm);
2119                                                 break;
2120                                         }
2121                                 }
2122                                 if (slot >= 0) 
2123                                         break;
2124                         }
2125                         if (slot >= 0)
2126                                 cm->slot = slot;
2127                 }
2128
2129                 if (cm->slot < 0)
2130                         cm->slot = cur_slot++;
2131
2132                 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
2133                         vtable [cm->slot] = cm;
2134         }
2135
2136         /* override non interface methods */
2137         for (i = 0; i < onum; i++) {
2138                 MonoMethod *decl = overrides [i*2];
2139                 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
2140                         g_assert (decl->slot != -1);
2141                         vtable [decl->slot] = overrides [i*2 + 1];
2142                         overrides [i * 2 + 1]->slot = decl->slot;
2143                         if (!override_map)
2144                                 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
2145                         g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
2146                 }
2147         }
2148
2149         /*
2150          * If a method occupies more than one place in the vtable, and it is
2151          * overriden, then change the other occurances too.
2152          */
2153         if (override_map) {
2154                 for (i = 0; i < max_vtsize; ++i)
2155                         if (vtable [i]) {
2156                                 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
2157                                 if (cm)
2158                                         vtable [i] = cm;
2159                         }
2160
2161                 g_hash_table_destroy (override_map);
2162         }
2163
2164         if (class->generic_class) {
2165                 MonoClass *gklass = class->generic_class->container_class;
2166
2167                 mono_class_init (gklass);
2168
2169                 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
2170         } else
2171                 class->vtable_size = cur_slot;
2172
2173         class->vtable = mono_mempool_alloc0 (class->image->mempool, sizeof (gpointer) * class->vtable_size);
2174         memcpy (class->vtable, vtable,  sizeof (gpointer) * class->vtable_size);
2175
2176         if (mono_print_vtable) {
2177                 int icount = 0;
2178
2179                 for (i = 0; i <= max_iid; i++)
2180                         if (class->interface_offsets [i] != -1)
2181                                 icount++;
2182
2183                 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg), 
2184                         class->vtable_size, icount); 
2185
2186                 for (i = 0; i < class->vtable_size; ++i) {
2187                         MonoMethod *cm;
2188                
2189                         cm = vtable [i];
2190                         if (cm) {
2191                                 printf ("  slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
2192                                         mono_method_full_name (cm, TRUE));
2193                         }
2194                 }
2195
2196
2197                 if (icount) {
2198                         printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space, 
2199                                 class->name, max_iid);
2200         
2201                         for (i = 0; i < class->interface_count; i++) {
2202                                 ic = class->interfaces [i];
2203                                 printf ("  slot offset: %03d, method count: %03d, iid: %03d %s\n",  
2204                                         class->interface_offsets [ic->interface_id],
2205                                         ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
2206                         }
2207
2208                         for (k = class->parent; k ; k = k->parent) {
2209                                 for (i = 0; i < k->interface_count; i++) {
2210                                         ic = k->interfaces [i]; 
2211                                         printf ("  slot offset: %03d, method count: %03d, iid: %03d %s\n",  
2212                                                 class->interface_offsets [ic->interface_id],
2213                                                 ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
2214                                 }
2215                         }
2216                 }
2217         }
2218 }
2219
2220 static MonoMethod *default_ghc = NULL;
2221 static MonoMethod *default_finalize = NULL;
2222 static int finalize_slot = -1;
2223 static int ghc_slot = -1;
2224
2225 static void
2226 initialize_object_slots (MonoClass *class)
2227 {
2228         int i;
2229         if (default_ghc)
2230                 return;
2231         if (class == mono_defaults.object_class) { 
2232                 mono_class_setup_vtable (class);                       
2233                 for (i = 0; i < class->vtable_size; ++i) {
2234                         MonoMethod *cm = class->vtable [i];
2235        
2236                         if (!strcmp (cm->name, "GetHashCode"))
2237                                 ghc_slot = i;
2238                         else if (!strcmp (cm->name, "Finalize"))
2239                                 finalize_slot = i;
2240                 }
2241
2242                 g_assert (ghc_slot > 0);
2243                 default_ghc = class->vtable [ghc_slot];
2244
2245                 g_assert (finalize_slot > 0);
2246                 default_finalize = class->vtable [finalize_slot];
2247         }
2248 }
2249
2250 static GList*
2251 g_list_prepend_mempool (GList* l, MonoMemPool* mp, gpointer datum)
2252 {
2253         GList* n = mono_mempool_alloc (mp, sizeof (GList));
2254         n->next = l;
2255         n->prev = NULL;
2256         n->data = datum;
2257         return n;
2258 }
2259
2260 /**
2261  * mono_class_init:
2262  * @class: the class to initialize
2263  *
2264  * compute the instance_size, class_size and other infos that cannot be 
2265  * computed at mono_class_get() time. Also compute a generic vtable and 
2266  * the method slot numbers. We use this infos later to create a domain
2267  * specific vtable.
2268  *
2269  * Returns TRUE on success or FALSE if there was a problem in loading
2270  * the type (incorrect assemblies, missing assemblies, methods, etc). 
2271  */
2272 gboolean
2273 mono_class_init (MonoClass *class)
2274 {
2275         int i;
2276         MonoCachedClassInfo cached_info;
2277         gboolean has_cached_info;
2278         int class_init_ok = TRUE;
2279         
2280         g_assert (class);
2281
2282         if (class->inited)
2283                 return TRUE;
2284
2285         /*g_print ("Init class %s\n", class->name);*/
2286
2287         /* We do everything inside the lock to prevent races */
2288         mono_loader_lock ();
2289
2290         if (class->inited) {
2291                 mono_loader_unlock ();
2292                 /* Somebody might have gotten in before us */
2293                 return TRUE;
2294         }
2295
2296         if (class->init_pending) {
2297                 mono_loader_unlock ();
2298                 /* this indicates a cyclic dependency */
2299                 g_error ("pending init %s.%s\n", class->name_space, class->name);
2300         }
2301
2302         class->init_pending = 1;
2303
2304         /* CAS - SecurityAction.InheritanceDemand */
2305         if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
2306                 mono_secman_inheritancedemand_class (class, class->parent);
2307         }
2308
2309         if (mono_debugger_start_class_init_func)
2310                 mono_debugger_start_class_init_func (class);
2311
2312         mono_stats.initialized_class_count++;
2313
2314         if (class->generic_class && !class->generic_class->is_dynamic) {
2315                 MonoInflatedGenericClass *gclass;
2316                 MonoClass *gklass;
2317
2318                 gclass = mono_get_inflated_generic_class (class->generic_class);
2319                 gklass = gclass->generic_class.container_class;
2320
2321                 mono_stats.generic_class_count++;
2322
2323                 class->method = gklass->method;
2324                 class->field = gklass->field;
2325
2326                 mono_class_init (gklass);
2327                 mono_class_setup_methods (gklass);
2328                 mono_class_setup_properties (gklass);
2329
2330                 if (MONO_CLASS_IS_INTERFACE (class))
2331                         class->interface_id = mono_get_unique_iid (class);
2332
2333                 g_assert (class->method.count == gklass->method.count);
2334                 class->methods = g_new0 (MonoMethod *, class->method.count);
2335
2336                 for (i = 0; i < class->method.count; i++) {
2337                         MonoMethod *inflated = mono_class_inflate_generic_method_full (
2338                                 gklass->methods [i], class, gclass->generic_class.context);
2339
2340                         class->methods [i] = mono_get_inflated_method (inflated);
2341                 }
2342
2343                 class->property = gklass->property;
2344                 class->properties = g_new0 (MonoProperty, class->property.count);
2345
2346                 for (i = 0; i < class->property.count; i++) {
2347                         MonoProperty *prop = &class->properties [i];
2348
2349                         *prop = gklass->properties [i];
2350
2351                         if (prop->get)
2352                                 prop->get = mono_class_inflate_generic_method_full (
2353                                         prop->get, class, gclass->generic_class.context);
2354                         if (prop->set)
2355                                 prop->set = mono_class_inflate_generic_method_full (
2356                                         prop->set, class, gclass->generic_class.context);
2357
2358                         prop->parent = class;
2359                 }
2360
2361                 g_assert (class->interface_count == gklass->interface_count);
2362         }
2363
2364         if (class->parent && !class->parent->inited)
2365                 mono_class_init (class->parent);
2366
2367         has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
2368
2369         if (!class->generic_class && (!has_cached_info || (has_cached_info && cached_info.has_nested_classes))) {
2370                 i = mono_metadata_nesting_typedef (class->image, class->type_token, 1);
2371                 while (i) {
2372                         MonoClass* nclass;
2373                         guint32 cols [MONO_NESTED_CLASS_SIZE];
2374                         mono_metadata_decode_row (&class->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
2375                         nclass = mono_class_create_from_typedef (class->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
2376                         class->nested_classes = g_list_prepend_mempool (class->nested_classes, class->image->mempool, nclass);
2377
2378                         i = mono_metadata_nesting_typedef (class->image, class->type_token, i + 1);
2379                 }
2380         }
2381
2382         /*
2383          * Computes the size used by the fields, and their locations
2384          */
2385         if (has_cached_info) {
2386                 class->instance_size = cached_info.instance_size;
2387                 class->class_size = cached_info.class_size;
2388                 class->packing_size = cached_info.packing_size;
2389                 class->min_align = cached_info.min_align;
2390                 class->blittable = cached_info.blittable;
2391                 class->has_references = cached_info.has_references;
2392                 class->has_static_refs = cached_info.has_static_refs;
2393         }
2394         else
2395                 if (!class->size_inited){
2396                         mono_class_setup_fields (class);
2397                         if (class->exception_type || mono_loader_get_last_error ()){
2398                                 class_init_ok = FALSE;
2399                                 goto leave;
2400                         }
2401                 }
2402                                 
2403
2404         /* initialize method pointers */
2405         if (class->rank) {
2406                 MonoMethod *ctor;
2407                 MonoMethodSignature *sig;
2408                 class->method.count = class->rank > 1? 2: 1;
2409                 sig = mono_metadata_signature_alloc (class->image, class->rank);
2410                 sig->ret = &mono_defaults.void_class->byval_arg;
2411                 sig->pinvoke = TRUE;
2412                 for (i = 0; i < class->rank; ++i)
2413                         sig->params [i] = &mono_defaults.int32_class->byval_arg;
2414
2415                 ctor = (MonoMethod *) mono_mempool_alloc0 (class->image->mempool, sizeof (MonoMethodPInvoke));
2416                 ctor->klass = class;
2417                 ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
2418                 ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
2419                 ctor->signature = sig;
2420                 ctor->name = ".ctor";
2421                 ctor->slot = -1;
2422                 class->methods = mono_mempool_alloc0 (class->image->mempool, sizeof (MonoMethod*) * class->method.count);
2423                 class->methods [0] = ctor;
2424                 if (class->rank > 1) {
2425                         sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
2426                         sig->ret = &mono_defaults.void_class->byval_arg;
2427                         sig->pinvoke = TRUE;
2428                         for (i = 0; i < class->rank * 2; ++i)
2429                                 sig->params [i] = &mono_defaults.int32_class->byval_arg;
2430
2431                         ctor = (MonoMethod *) mono_mempool_alloc0 (class->image->mempool, sizeof (MonoMethodPInvoke));
2432                         ctor->klass = class;
2433                         ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
2434                         ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
2435                         ctor->signature = sig;
2436                         ctor->name = ".ctor";
2437                         ctor->slot = -1;
2438                         class->methods [1] = ctor;
2439                 }
2440         }
2441
2442         mono_class_setup_supertypes (class);
2443
2444         if (!default_ghc)
2445                 initialize_object_slots (class);
2446
2447         /*
2448          * If possible, avoid the creation of the generic vtable by requesting
2449          * cached info from the runtime.
2450          */
2451         if (has_cached_info) {
2452                 guint32 cur_slot = 0;
2453
2454                 class->vtable_size = cached_info.vtable_size;
2455                 class->has_finalize = cached_info.has_finalize;
2456                 class->ghcimpl = cached_info.ghcimpl;
2457                 class->has_cctor = cached_info.has_cctor;
2458
2459                 if (class->parent) {
2460                         mono_class_init (class->parent);
2461                         cur_slot = class->parent->vtable_size;
2462                 }
2463
2464                 setup_interface_offsets (class, cur_slot);
2465         }
2466         else {
2467                 mono_class_setup_vtable (class);
2468
2469                 if (class->exception_type || mono_loader_get_last_error ()){
2470                         class_init_ok = FALSE;
2471                         goto leave;
2472                 }
2473
2474                 class->ghcimpl = 1;
2475                 if (class->parent) { 
2476                         MonoMethod *cmethod = class->vtable [ghc_slot];
2477                         if (cmethod->is_inflated)
2478                                 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
2479                         if (cmethod == default_ghc) {
2480                                 class->ghcimpl = 0;
2481                         }
2482                 }
2483
2484                 /* Object::Finalize should have empty implemenatation */
2485                 class->has_finalize = 0;
2486                 if (class->parent) { 
2487                         MonoMethod *cmethod = class->vtable [finalize_slot];
2488                         if (cmethod->is_inflated)
2489                                 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
2490                         if (cmethod != default_finalize) {
2491                                 class->has_finalize = 1;
2492                         }
2493                 }
2494
2495                 for (i = 0; i < class->method.count; ++i) {
2496                         MonoMethod *method = class->methods [i];
2497                         if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
2498                                 (strcmp (".cctor", method->name) == 0)) {
2499                                 class->has_cctor = 1;
2500                                 break;
2501                         }
2502                 }
2503         }
2504
2505         if (MONO_CLASS_IS_INTERFACE (class)) {
2506                 /* 
2507                  * class->interface_offsets is needed for the castclass/isinst code, so
2508                  * we have to setup them for interfaces, too.
2509                  */
2510                 setup_interface_offsets (class, 0);
2511         }
2512
2513  leave:
2514         class->inited = 1;
2515         class->init_pending = 0;
2516
2517         mono_loader_unlock ();
2518
2519         if (mono_debugger_class_init_func)
2520                 mono_debugger_class_init_func (class);
2521
2522         return class_init_ok;
2523 }
2524
2525 /*
2526  * LOCKING: this assumes the loader lock is held
2527  */
2528 void
2529 mono_class_setup_mono_type (MonoClass *class)
2530 {
2531         const char *name = class->name;
2532         const char *nspace = class->name_space;
2533
2534         class->this_arg.byref = 1;
2535         class->this_arg.data.klass = class;
2536         class->this_arg.type = MONO_TYPE_CLASS;
2537         class->byval_arg.data.klass = class;
2538         class->byval_arg.type = MONO_TYPE_CLASS;
2539
2540         if (!strcmp (nspace, "System")) {
2541                 if (!strcmp (name, "ValueType")) {
2542                         /*
2543                          * do not set the valuetype bit for System.ValueType.
2544                          * class->valuetype = 1;
2545                          */
2546                         class->blittable = TRUE;
2547                 } else if (!strcmp (name, "Enum")) {
2548                         /*
2549                          * do not set the valuetype bit for System.Enum.
2550                          * class->valuetype = 1;
2551                          */
2552                         class->valuetype = 0;
2553                         class->enumtype = 0;
2554                 } else if (!strcmp (name, "Object")) {
2555                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
2556                 } else if (!strcmp (name, "String")) {
2557                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
2558                 } else if (!strcmp (name, "TypedReference")) {
2559                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
2560                 }
2561         }
2562         
2563         if (class->valuetype) {
2564                 int t = MONO_TYPE_VALUETYPE;
2565                 if (!strcmp (nspace, "System")) {
2566                         switch (*name) {
2567                         case 'B':
2568                                 if (!strcmp (name, "Boolean")) {
2569                                         t = MONO_TYPE_BOOLEAN;
2570                                 } else if (!strcmp(name, "Byte")) {
2571                                         t = MONO_TYPE_U1;
2572                                         class->blittable = TRUE;                                                
2573                                 }
2574                                 break;
2575                         case 'C':
2576                                 if (!strcmp (name, "Char")) {
2577                                         t = MONO_TYPE_CHAR;
2578                                 }
2579                                 break;
2580                         case 'D':
2581                                 if (!strcmp (name, "Double")) {
2582                                         t = MONO_TYPE_R8;
2583                                         class->blittable = TRUE;                                                
2584                                 }
2585                                 break;
2586                         case 'I':
2587                                 if (!strcmp (name, "Int32")) {
2588                                         t = MONO_TYPE_I4;
2589                                         class->blittable = TRUE;
2590                                 } else if (!strcmp(name, "Int16")) {
2591                                         t = MONO_TYPE_I2;
2592                                         class->blittable = TRUE;
2593                                 } else if (!strcmp(name, "Int64")) {
2594                                         t = MONO_TYPE_I8;
2595                                         class->blittable = TRUE;
2596                                 } else if (!strcmp(name, "IntPtr")) {
2597                                         t = MONO_TYPE_I;
2598                                         class->blittable = TRUE;
2599                                 }
2600                                 break;
2601                         case 'S':
2602                                 if (!strcmp (name, "Single")) {
2603                                         t = MONO_TYPE_R4;
2604                                         class->blittable = TRUE;                                                
2605                                 } else if (!strcmp(name, "SByte")) {
2606                                         t = MONO_TYPE_I1;
2607                                         class->blittable = TRUE;
2608                                 }
2609                                 break;
2610                         case 'U':
2611                                 if (!strcmp (name, "UInt32")) {
2612                                         t = MONO_TYPE_U4;
2613                                         class->blittable = TRUE;
2614                                 } else if (!strcmp(name, "UInt16")) {
2615                                         t = MONO_TYPE_U2;
2616                                         class->blittable = TRUE;
2617                                 } else if (!strcmp(name, "UInt64")) {
2618                                         t = MONO_TYPE_U8;
2619                                         class->blittable = TRUE;
2620                                 } else if (!strcmp(name, "UIntPtr")) {
2621                                         t = MONO_TYPE_U;
2622                                         class->blittable = TRUE;
2623                                 }
2624                                 break;
2625                         case 'T':
2626                                 if (!strcmp (name, "TypedReference")) {
2627                                         t = MONO_TYPE_TYPEDBYREF;
2628                                         class->blittable = TRUE;
2629                                 }
2630                                 break;
2631                         case 'V':
2632                                 if (!strcmp (name, "Void")) {
2633                                         t = MONO_TYPE_VOID;
2634                                 }
2635                                 break;
2636                         default:
2637                                 break;
2638                         }
2639                 }
2640                 class->this_arg.type = class->byval_arg.type = t;
2641         }
2642
2643         if (MONO_CLASS_IS_INTERFACE (class))
2644                 class->interface_id = mono_get_unique_iid (class);
2645
2646 }
2647
2648 /*
2649  * LOCKING: this assumes the loader lock is held
2650  */
2651 void
2652 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
2653 {
2654         gboolean system_namespace;
2655
2656         system_namespace = !strcmp (class->name_space, "System");
2657
2658         /* if root of the hierarchy */
2659         if (system_namespace && !strcmp (class->name, "Object")) {
2660                 class->parent = NULL;
2661                 class->instance_size = sizeof (MonoObject);
2662                 return;
2663         }
2664         if (!strcmp (class->name, "<Module>")) {
2665                 class->parent = NULL;
2666                 class->instance_size = 0;
2667                 return;
2668         }
2669
2670         if (!MONO_CLASS_IS_INTERFACE (class)) {
2671                 /* Imported COM Objects always derive from __ComObject. */
2672                 if (MONO_CLASS_IS_IMPORT (class)) {
2673                         if (parent == mono_defaults.object_class)
2674                                 parent = mono_defaults.com_object_class;
2675                 }
2676                 class->parent = parent;
2677
2678
2679                 if (!parent)
2680                         g_assert_not_reached (); /* FIXME */
2681
2682                 if (parent->generic_class && !parent->name) {
2683                         /*
2684                          * If the parent is a generic instance, we may get
2685                          * called before it is fully initialized, especially
2686                          * before it has its name.
2687                          */
2688                         return;
2689                 }
2690
2691                 class->marshalbyref = parent->marshalbyref;
2692                 class->contextbound  = parent->contextbound;
2693                 class->delegate  = parent->delegate;
2694                 if (MONO_CLASS_IS_IMPORT (class))
2695                         class->is_com_object = 1;
2696                 else
2697                         class->is_com_object = parent->is_com_object;
2698                 
2699                 if (system_namespace) {
2700                         if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
2701                                 class->marshalbyref = 1;
2702
2703                         if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject")) 
2704                                 class->contextbound  = 1;
2705
2706                         if (*class->name == 'D' && !strcmp (class->name, "Delegate")) 
2707                                 class->delegate  = 1;
2708                 }
2709
2710                 if (class->parent->enumtype || ((strcmp (class->parent->name, "ValueType") == 0) && 
2711                                                 (strcmp (class->parent->name_space, "System") == 0)))
2712                         class->valuetype = 1;
2713                 if (((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
2714                         class->valuetype = class->enumtype = 1;
2715                 }
2716                 /*class->enumtype = class->parent->enumtype; */
2717                 mono_class_setup_supertypes (class);
2718         } else {
2719                 class->parent = NULL;
2720         }
2721
2722 }
2723
2724 /*
2725  * mono_class_setup_supertypes:
2726  * @class: a class
2727  *
2728  * Build the data structure needed to make fast type checks work.
2729  * This currently sets two fields in @class:
2730  *  - idepth: distance between @class and System.Object in the type
2731  *    hierarchy + 1
2732  *  - supertypes: array of classes: each element has a class in the hierarchy
2733  *    starting from @class up to System.Object
2734  * 
2735  * LOCKING: this assumes the loader lock is held
2736  */
2737 void
2738 mono_class_setup_supertypes (MonoClass *class)
2739 {
2740         int ms;
2741
2742         if (class->supertypes)
2743                 return;
2744
2745         if (class->parent && !class->parent->supertypes)
2746                 mono_class_setup_supertypes (class->parent);
2747         if (class->parent)
2748                 class->idepth = class->parent->idepth + 1;
2749         else
2750                 class->idepth = 1;
2751
2752         ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
2753         class->supertypes = mono_mempool_alloc0 (class->image->mempool, sizeof (MonoClass *) * ms);
2754
2755         if (class->parent) {
2756                 class->supertypes [class->idepth - 1] = class;
2757                 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
2758         } else {
2759                 class->supertypes [0] = class;
2760         }
2761 }       
2762
2763 MonoGenericInst *
2764 mono_get_shared_generic_inst (MonoGenericContainer *container)
2765 {
2766         MonoGenericInst *nginst;
2767         int i;
2768
2769         nginst = g_new0 (MonoGenericInst, 1);
2770         nginst->type_argc = container->type_argc;
2771         nginst->type_argv = g_new0 (MonoType *, nginst->type_argc);
2772         nginst->is_reference = 1;
2773         nginst->is_open = 1;
2774
2775         for (i = 0; i < nginst->type_argc; i++) {
2776                 MonoType *t = g_new0 (MonoType, 1);
2777
2778                 t->type = container->is_method ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
2779                 t->data.generic_param = &container->type_params [i];
2780
2781                 nginst->type_argv [i] = t;
2782         }
2783
2784         return mono_metadata_lookup_generic_inst (nginst);
2785 }
2786
2787 /*
2788  * In preparation for implementing shared code.
2789  */
2790 MonoGenericClass *
2791 mono_get_shared_generic_class (MonoGenericContainer *container, gboolean is_dynamic)
2792 {
2793         MonoInflatedGenericClass *igclass;
2794         MonoGenericClass *gclass;
2795
2796         if (is_dynamic) {
2797                 MonoDynamicGenericClass *dgclass = g_new0 (MonoDynamicGenericClass, 1);
2798                 igclass = &dgclass->generic_class;
2799                 gclass = &igclass->generic_class;
2800                 gclass->is_inflated = 1;
2801                 gclass->is_dynamic = 1;
2802         } else {
2803                 igclass = g_new0 (MonoInflatedGenericClass, 1);
2804                 gclass = &igclass->generic_class;
2805                 gclass->is_inflated = 1;
2806         }
2807
2808         gclass->context = &container->context;
2809         gclass->container_class = container->klass;
2810         gclass->inst = mono_get_shared_generic_inst (container);
2811
2812         if (!is_dynamic) {
2813                 MonoGenericClass *cached = mono_metadata_lookup_generic_class (gclass);
2814
2815                 if (cached) {
2816                         g_free (gclass);
2817                         return cached;
2818                 }
2819         }
2820
2821         igclass->klass = container->klass;
2822
2823         return gclass;
2824 }
2825
2826 /**
2827  * mono_class_create_from_typedef:
2828  * @image: image where the token is valid
2829  * @type_token:  typedef token
2830  *
2831  * Create the MonoClass* representing the specified type token.
2832  * @type_token must be a TypeDef token.
2833  */
2834 static MonoClass *
2835 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
2836 {
2837         MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
2838         MonoClass *class, *parent = NULL;
2839         guint32 cols [MONO_TYPEDEF_SIZE];
2840         guint32 cols_next [MONO_TYPEDEF_SIZE];
2841         guint tidx = mono_metadata_token_index (type_token);
2842         MonoGenericContext *context = NULL;
2843         const char *name, *nspace;
2844         guint icount = 0; 
2845         MonoClass **interfaces;
2846         guint32 field_last, method_last;
2847         guint32 nesting_tokeen;
2848
2849         mono_loader_lock ();
2850
2851         if ((class = g_hash_table_lookup (image->class_cache, GUINT_TO_POINTER (type_token)))) {
2852                 mono_loader_unlock ();
2853                 return class;
2854         }
2855
2856         g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
2857
2858         mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
2859         
2860         name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2861         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2862
2863         class = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
2864
2865         class->name = name;
2866         class->name_space = nspace;
2867
2868         class->image = image;
2869         class->type_token = type_token;
2870         class->flags = cols [MONO_TYPEDEF_FLAGS];
2871
2872         g_hash_table_insert (image->class_cache, GUINT_TO_POINTER (type_token), class);
2873
2874         /*
2875          * Check whether we're a generic type definition.
2876          */
2877         class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
2878         if (class->generic_container) {
2879                 class->generic_container->klass = class;
2880                 context = &class->generic_container->context;
2881
2882                 context->gclass = mono_get_shared_generic_class (context->container, FALSE);
2883         }
2884
2885         if (cols [MONO_TYPEDEF_EXTENDS]) {
2886                 parent = mono_class_get_full (
2887                         image, mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]), context);
2888                 if (parent == NULL){
2889                         g_hash_table_remove (image->class_cache, GUINT_TO_POINTER (type_token));
2890                         mono_loader_unlock ();
2891                         return NULL;
2892                 }
2893         }
2894
2895         /* do this early so it's available for interfaces in setup_mono_type () */
2896         if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token)))
2897                 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
2898
2899         mono_class_setup_parent (class, parent);
2900
2901         /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
2902         mono_class_setup_mono_type (class);
2903
2904         if (!class->enumtype) {
2905                 if (!mono_metadata_interfaces_from_typedef_full (
2906                             image, type_token, &interfaces, &icount, context)){
2907                         mono_loader_unlock ();
2908                         return NULL;
2909                 }
2910
2911                 class->interfaces = interfaces;
2912                 class->interface_count = icount;
2913         }
2914
2915         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
2916                 class->unicode = 1;
2917
2918 #if PLATFORM_WIN32
2919         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
2920                 class->unicode = 1;
2921 #endif
2922
2923         class->cast_class = class->element_class = class;
2924
2925         /*g_print ("Load class %s\n", name);*/
2926
2927         /*
2928          * Compute the field and method lists
2929          */
2930         class->field.first  = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
2931         class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
2932
2933         if (tt->rows > tidx){           
2934                 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
2935                 field_last  = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
2936                 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
2937         } else {
2938                 field_last  = image->tables [MONO_TABLE_FIELD].rows;
2939                 method_last = image->tables [MONO_TABLE_METHOD].rows;
2940         }
2941
2942         if (cols [MONO_TYPEDEF_FIELD_LIST] && 
2943             cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
2944                 class->field.count = field_last - class->field.first;
2945         else
2946                 class->field.count = 0;
2947
2948         if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
2949                 class->method.count = method_last - class->method.first;
2950         else
2951                 class->method.count = 0;
2952
2953         /* reserve space to store vector pointer in arrays */
2954         if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
2955                 class->instance_size += 2 * sizeof (gpointer);
2956                 g_assert (class->field.count == 0);
2957         }
2958
2959         if (class->enumtype) {
2960                 class->enum_basetype = mono_class_find_enum_basetype (class);
2961                 class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
2962         }
2963
2964         /*
2965          * If we're a generic type definition, load the constraints.
2966          * We must do this after the class has been constructed to make certain recursive scenarios
2967          * work.
2968          */
2969         if (class->generic_container)
2970                 mono_metadata_load_generic_param_constraints (
2971                         image, type_token, class->generic_container);
2972
2973         mono_loader_unlock ();
2974
2975         return class;
2976 }
2977
2978 /** is klass Nullable<T>? */
2979 gboolean
2980 mono_class_is_nullable (MonoClass *klass)
2981 {
2982        return klass->generic_class != NULL &&
2983                klass->generic_class->container_class == mono_defaults.generic_nullable_class;
2984 }
2985
2986
2987 /** if klass is T? return T */
2988 MonoClass*
2989 mono_class_get_nullable_param (MonoClass *klass)
2990 {
2991        g_assert (mono_class_is_nullable (klass));
2992        return mono_class_from_mono_type (klass->generic_class->inst->type_argv [0]);
2993 }
2994
2995 /*
2996  * Create the `MonoClass' for an instantiation of a generic type.
2997  * We only do this if we actually need it.
2998  */
2999 static void
3000 mono_class_create_generic (MonoInflatedGenericClass *gclass)
3001 {
3002         MonoClass *klass, *gklass;
3003         int i;
3004
3005         mono_loader_lock ();
3006         if (gclass->is_initialized) {
3007                 mono_loader_unlock ();
3008                 return;
3009         }
3010
3011         if (!gclass->klass)
3012                 gclass->klass = g_malloc0 (sizeof (MonoClass));
3013         klass = gclass->klass;
3014
3015         gklass = gclass->generic_class.container_class;
3016
3017         if (gklass->nested_in) {
3018                 /* 
3019                  * FIXME: the nested type context should include everything the
3020                  * nesting context should have, but it may also have additional
3021                  * generic parameters...
3022                  */
3023                 MonoType *inflated = mono_class_inflate_generic_type (
3024                         &gklass->nested_in->byval_arg, gclass->generic_class.context);
3025                 klass->nested_in = mono_class_from_mono_type (inflated);
3026         }
3027
3028         klass->name = gklass->name;
3029         klass->name_space = gklass->name_space;
3030         klass->image = gklass->image;
3031         klass->flags = gklass->flags;
3032         klass->type_token = gklass->type_token;
3033
3034         klass->generic_class = &gclass->generic_class;
3035
3036         klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
3037         klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = &gclass->generic_class;
3038         klass->this_arg.byref = TRUE;
3039
3040         klass->cast_class = klass->element_class = klass;
3041
3042         if (mono_class_is_nullable (klass))
3043                 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
3044
3045         if (gclass->generic_class.is_dynamic) {
3046                 klass->instance_size = gklass->instance_size;
3047                 klass->class_size = gklass->class_size;
3048                 klass->size_inited = 1;
3049                 klass->inited = 1;
3050
3051                 klass->valuetype = gklass->valuetype;
3052
3053                 mono_class_setup_supertypes (klass);
3054         }
3055
3056         klass->interface_count = gklass->interface_count;
3057         klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
3058         for (i = 0; i < klass->interface_count; i++) {
3059                 MonoType *it = &gklass->interfaces [i]->byval_arg;
3060                 MonoType *inflated = mono_class_inflate_generic_type (
3061                         it, gclass->generic_class.context);
3062                 klass->interfaces [i] = mono_class_from_mono_type (inflated);
3063         }
3064
3065         i = mono_metadata_nesting_typedef (klass->image, gklass->type_token, 1);
3066         while (i) {
3067                 MonoClass* nclass;
3068                 guint32 cols [MONO_NESTED_CLASS_SIZE];
3069                 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
3070                 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
3071                 klass->nested_classes = g_list_prepend (klass->nested_classes, nclass);
3072                 
3073                 i = mono_metadata_nesting_typedef (klass->image, gklass->type_token, i + 1);
3074         }
3075
3076         if (gklass->parent) {
3077                 MonoType *inflated = mono_class_inflate_generic_type (
3078                         &gklass->parent->byval_arg, gclass->generic_class.context);
3079
3080                 klass->parent = mono_class_from_mono_type (inflated);
3081         }
3082
3083         if (klass->parent)
3084                 mono_class_setup_parent (klass, klass->parent);
3085
3086         if (MONO_CLASS_IS_INTERFACE (klass))
3087                 setup_interface_offsets (klass, 0);
3088         gclass->is_initialized = TRUE;
3089         mono_loader_unlock ();
3090 }
3091
3092 MonoClass *
3093 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
3094 {
3095         MonoClass *klass, **ptr;
3096         int count, pos, i;
3097
3098         if (param->pklass)
3099                 return param->pklass;
3100
3101         klass = param->pklass = g_new0 (MonoClass, 1);
3102
3103         for (count = 0, ptr = param->constraints; ptr && *ptr; ptr++, count++)
3104                 ;
3105
3106         pos = 0;
3107         if ((count > 0) && !MONO_CLASS_IS_INTERFACE (param->constraints [0])) {
3108                 klass->parent = param->constraints [0];
3109                 pos++;
3110         } else if (param->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
3111                 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
3112         else
3113                 klass->parent = mono_defaults.object_class;
3114
3115         if (count - pos > 0) {
3116                 klass->interface_count = count - pos;
3117                 klass->interfaces = g_new0 (MonoClass *, count - pos);
3118                 for (i = pos; i < count; i++)
3119                         klass->interfaces [i - pos] = param->constraints [i];
3120         }
3121
3122         if (param->name)
3123                 klass->name = param->name;
3124         else
3125                 klass->name = g_strdup_printf (is_mvar ? "!!%d" : "!%d", param->num);
3126
3127         klass->name_space = "";
3128
3129         if (image)
3130                 klass->image = image;
3131         else if (is_mvar && param->method && param->method->klass)
3132                 klass->image = param->method->klass->image;
3133         else if (param->owner && param->owner->klass)
3134                 klass->image = param->owner->klass->image;
3135         else
3136                 klass->image = mono_defaults.corlib;
3137
3138         klass->inited = TRUE;
3139         klass->cast_class = klass->element_class = klass;
3140         klass->enum_basetype = &klass->element_class->byval_arg;
3141         klass->flags = TYPE_ATTRIBUTE_PUBLIC;
3142
3143         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
3144         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
3145         klass->this_arg.byref = TRUE;
3146
3147         mono_class_setup_supertypes (klass);
3148
3149         return klass;
3150 }
3151
3152 MonoClass *
3153 mono_ptr_class_get (MonoType *type)
3154 {
3155         MonoClass *result;
3156         MonoClass *el_class;
3157         MonoImage *image;
3158         char *name;
3159
3160         el_class = mono_class_from_mono_type (type);
3161         image = el_class->image;
3162
3163         mono_loader_lock ();
3164
3165         if (!image->ptr_cache)
3166                 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
3167
3168         if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
3169                 mono_loader_unlock ();
3170                 return result;
3171         }
3172         result = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
3173
3174         result->parent = NULL; /* no parent for PTR types */
3175         result->name_space = el_class->name_space;
3176         name = g_strdup_printf ("%s*", el_class->name);
3177         result->name = mono_mempool_strdup (image->mempool, name);
3178         g_free (name);
3179         result->image = el_class->image;
3180         result->inited = TRUE;
3181         result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
3182         /* Can pointers get boxed? */
3183         result->instance_size = sizeof (gpointer);
3184         result->cast_class = result->element_class = el_class;
3185         result->enum_basetype = &result->element_class->byval_arg;
3186         result->blittable = TRUE;
3187
3188         result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
3189         result->this_arg.data.type = result->byval_arg.data.type = result->enum_basetype;
3190         result->this_arg.byref = TRUE;
3191
3192         mono_class_setup_supertypes (result);
3193
3194         g_hash_table_insert (image->ptr_cache, el_class, result);
3195
3196         mono_loader_unlock ();
3197
3198         return result;
3199 }
3200
3201 static MonoClass *
3202 mono_fnptr_class_get (MonoMethodSignature *sig)
3203 {
3204         MonoClass *result;
3205         static GHashTable *ptr_hash = NULL;
3206
3207         /* FIXME: These should be allocate from a mempool as well, but which one ? */
3208
3209         mono_loader_lock ();
3210
3211         if (!ptr_hash)
3212                 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3213         
3214         if ((result = g_hash_table_lookup (ptr_hash, sig))) {
3215                 mono_loader_unlock ();
3216                 return result;
3217         }
3218         result = g_new0 (MonoClass, 1);
3219
3220         result->parent = NULL; /* no parent for PTR types */
3221         result->name_space = "System";
3222         result->name = "MonoFNPtrFakeClass";
3223         result->image = mono_defaults.corlib; /* need to fix... */
3224         result->inited = TRUE;
3225         result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
3226         /* Can pointers get boxed? */
3227         result->instance_size = sizeof (gpointer);
3228         result->cast_class = result->element_class = result;
3229         result->blittable = TRUE;
3230
3231         result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
3232         result->this_arg.data.method = result->byval_arg.data.method = sig;
3233         result->this_arg.byref = TRUE;
3234         result->enum_basetype = &result->element_class->byval_arg;
3235         result->blittable = TRUE;
3236
3237         mono_class_setup_supertypes (result);
3238
3239         g_hash_table_insert (ptr_hash, sig, result);
3240
3241         mono_loader_unlock ();
3242
3243         return result;
3244 }
3245
3246 MonoClass *
3247 mono_class_from_mono_type (MonoType *type)
3248 {
3249         switch (type->type) {
3250         case MONO_TYPE_OBJECT:
3251                 return type->data.klass? type->data.klass: mono_defaults.object_class;
3252         case MONO_TYPE_VOID:
3253                 return type->data.klass? type->data.klass: mono_defaults.void_class;
3254         case MONO_TYPE_BOOLEAN:
3255                 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
3256         case MONO_TYPE_CHAR:
3257                 return type->data.klass? type->data.klass: mono_defaults.char_class;
3258         case MONO_TYPE_I1:
3259                 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
3260         case MONO_TYPE_U1:
3261                 return type->data.klass? type->data.klass: mono_defaults.byte_class;
3262         case MONO_TYPE_I2:
3263                 return type->data.klass? type->data.klass: mono_defaults.int16_class;
3264         case MONO_TYPE_U2:
3265                 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
3266         case MONO_TYPE_I4:
3267                 return type->data.klass? type->data.klass: mono_defaults.int32_class;
3268         case MONO_TYPE_U4:
3269                 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
3270         case MONO_TYPE_I:
3271                 return type->data.klass? type->data.klass: mono_defaults.int_class;
3272         case MONO_TYPE_U:
3273                 return type->data.klass? type->data.klass: mono_defaults.uint_class;
3274         case MONO_TYPE_I8:
3275                 return type->data.klass? type->data.klass: mono_defaults.int64_class;
3276         case MONO_TYPE_U8:
3277                 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
3278         case MONO_TYPE_R4:
3279                 return type->data.klass? type->data.klass: mono_defaults.single_class;
3280         case MONO_TYPE_R8:
3281                 return type->data.klass? type->data.klass: mono_defaults.double_class;
3282         case MONO_TYPE_STRING:
3283                 return type->data.klass? type->data.klass: mono_defaults.string_class;
3284         case MONO_TYPE_TYPEDBYREF:
3285                 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
3286         case MONO_TYPE_ARRAY:
3287                 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
3288         case MONO_TYPE_PTR:
3289                 return mono_ptr_class_get (type->data.type);
3290         case MONO_TYPE_FNPTR:
3291                 return mono_fnptr_class_get (type->data.method);
3292         case MONO_TYPE_SZARRAY:
3293                 return mono_array_class_get (type->data.klass, 1);
3294         case MONO_TYPE_CLASS:
3295         case MONO_TYPE_VALUETYPE:
3296                 return type->data.klass;
3297         case MONO_TYPE_GENERICINST: {
3298                 MonoInflatedGenericClass *gclass;
3299                 gclass = mono_get_inflated_generic_class (type->data.generic_class);
3300                 g_assert (gclass->klass);
3301                 return gclass->klass;
3302         }
3303         case MONO_TYPE_VAR:
3304                 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
3305         case MONO_TYPE_MVAR:
3306                 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
3307         default:
3308                 g_warning ("implement me 0x%02x\n", type->type);
3309                 g_assert_not_reached ();
3310         }
3311         
3312         return NULL;
3313 }
3314
3315 /**
3316  * @image: context where the image is created
3317  * @type_spec:  typespec token
3318  * @context: the generic context used to evaluate generic instantiations in
3319  */
3320 static MonoClass *
3321 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
3322 {
3323         MonoType *t = mono_type_create_from_typespec (image, type_spec);
3324         if (!t)
3325                 return NULL;
3326         if (context && (context->gclass || context->gmethod)) {
3327                 MonoType *inflated = inflate_generic_type (t, context);
3328                 if (inflated)
3329                         t = inflated;
3330         }
3331         return mono_class_from_mono_type (t);
3332 }
3333
3334 /**
3335  * mono_bounded_array_class_get:
3336  * @element_class: element class 
3337  * @rank: the dimension of the array class
3338  * @bounded: whenever the array has non-zero bounds
3339  *
3340  * Returns: a class object describing the array with element type @element_type and 
3341  * dimension @rank. 
3342  */
3343 MonoClass *
3344 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
3345 {
3346         MonoImage *image;
3347         MonoClass *class;
3348         MonoClass *parent = NULL;
3349         GSList *list, *rootlist;
3350         int nsize;
3351         char *name;
3352         gboolean corlib_type = FALSE;
3353
3354         g_assert (rank <= 255);
3355
3356         if (rank > 1)
3357                 /* bounded only matters for one-dimensional arrays */
3358                 bounded = FALSE;
3359
3360         image = eclass->image;
3361
3362         mono_loader_lock ();
3363
3364         if (!image->array_cache)
3365                 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
3366
3367         if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
3368                 for (; list; list = list->next) {
3369                         class = list->data;
3370                         if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
3371                                 mono_loader_unlock ();
3372                                 return class;
3373                         }
3374                 }
3375         }
3376
3377         /* for the building corlib use System.Array from it */
3378         if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
3379                 parent = mono_class_from_name (image, "System", "Array");
3380                 corlib_type = TRUE;
3381         } else if (mono_defaults.generic_array_class) {
3382                 MonoType *inflated, **args;
3383
3384                 args = g_new0 (MonoType *, 1);
3385                 args [0] = &eclass->byval_arg;
3386
3387                 inflated = mono_class_bind_generic_parameters (
3388                         &mono_defaults.generic_array_class->byval_arg, 1, args);
3389                 parent = mono_class_from_mono_type (inflated);
3390
3391                 if (!parent->inited)
3392                         mono_class_init (parent);
3393         } else {
3394                 parent = mono_defaults.array_class;
3395                 if (!parent->inited)
3396                         mono_class_init (parent);
3397         }
3398
3399         class = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
3400
3401         class->image = image;
3402         class->name_space = eclass->name_space;
3403         nsize = strlen (eclass->name);
3404         name = g_malloc (nsize + 2 + rank);
3405         memcpy (name, eclass->name, nsize);
3406         name [nsize] = '[';
3407         if (rank > 1)
3408                 memset (name + nsize + 1, ',', rank - 1);
3409         name [nsize + rank] = ']';
3410         name [nsize + rank + 1] = 0;
3411         class->name = mono_mempool_strdup (image->mempool, name);
3412         g_free (name);
3413         class->type_token = 0;
3414         /* all arrays are marked serializable and sealed, bug #42779 */
3415         class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
3416                 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
3417         class->parent = parent;
3418         class->instance_size = mono_class_instance_size (class->parent);
3419         class->class_size = 0;
3420         mono_class_setup_supertypes (class);
3421         if (eclass->generic_class)
3422                 mono_class_init (eclass);
3423         if (!eclass->size_inited)
3424                 mono_class_setup_fields (eclass);
3425         class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
3426
3427         class->rank = rank;
3428         
3429         if (eclass->enumtype)
3430                 class->cast_class = eclass->element_class;
3431         else
3432                 class->cast_class = eclass;
3433
3434         class->element_class = eclass;
3435
3436         if ((rank > 1) || bounded) {
3437                 MonoArrayType *at = mono_mempool_alloc0 (image->mempool, sizeof (MonoArrayType));
3438                 class->byval_arg.type = MONO_TYPE_ARRAY;
3439                 class->byval_arg.data.array = at;
3440                 at->eklass = eclass;
3441                 at->rank = rank;
3442                 /* FIXME: complete.... */
3443         } else {
3444                 class->byval_arg.type = MONO_TYPE_SZARRAY;
3445                 class->byval_arg.data.klass = eclass;
3446         }
3447         class->this_arg = class->byval_arg;
3448         class->this_arg.byref = 1;
3449         if (corlib_type) {
3450                 class->inited = 1;
3451         }
3452
3453         class->generic_container = eclass->generic_container;
3454
3455         list = g_slist_append (rootlist, class);
3456         g_hash_table_insert (image->array_cache, eclass, list);
3457
3458         mono_loader_unlock ();
3459
3460         return class;
3461 }
3462
3463 /**
3464  * mono_array_class_get:
3465  * @element_class: element class 
3466  * @rank: the dimension of the array class
3467  *
3468  * Returns: a class object describing the array with element type @element_type and 
3469  * dimension @rank. 
3470  */
3471 MonoClass *
3472 mono_array_class_get (MonoClass *eclass, guint32 rank)
3473 {
3474         return mono_bounded_array_class_get (eclass, rank, FALSE);
3475 }
3476
3477 /**
3478  * mono_class_instance_size:
3479  * @klass: a class 
3480  * 
3481  * Returns: the size of an object instance
3482  */
3483 gint32
3484 mono_class_instance_size (MonoClass *klass)
3485 {       
3486         if (!klass->size_inited)
3487                 mono_class_init (klass);
3488
3489         return klass->instance_size;
3490 }
3491
3492 /**
3493  * mono_class_min_align:
3494  * @klass: a class 
3495  * 
3496  * Returns: minimm alignment requirements 
3497  */
3498 gint32
3499 mono_class_min_align (MonoClass *klass)
3500 {       
3501         if (!klass->size_inited)
3502                 mono_class_init (klass);
3503
3504         return klass->min_align;
3505 }
3506
3507 /**
3508  * mono_class_value_size:
3509  * @klass: a class 
3510  *
3511  * This function is used for value types, and return the
3512  * space and the alignment to store that kind of value object.
3513  *
3514  * Returns: the size of a value of kind @klass
3515  */
3516 gint32
3517 mono_class_value_size      (MonoClass *klass, guint32 *align)
3518 {
3519         gint32 size;
3520
3521         /* fixme: check disable, because we still have external revereces to
3522          * mscorlib and Dummy Objects 
3523          */
3524         /*g_assert (klass->valuetype);*/
3525
3526         size = mono_class_instance_size (klass) - sizeof (MonoObject);
3527
3528         if (align)
3529                 *align = klass->min_align;
3530
3531         return size;
3532 }
3533
3534 /**
3535  * mono_class_data_size:
3536  * @klass: a class 
3537  * 
3538  * Returns: the size of the static class data
3539  */
3540 gint32
3541 mono_class_data_size (MonoClass *klass)
3542 {       
3543         if (!klass->inited)
3544                 mono_class_init (klass);
3545
3546         return klass->class_size;
3547 }
3548
3549 /*
3550  * Auxiliary routine to mono_class_get_field
3551  *
3552  * Takes a field index instead of a field token.
3553  */
3554 static MonoClassField *
3555 mono_class_get_field_idx (MonoClass *class, int idx)
3556 {
3557         mono_class_setup_fields_locking (class);
3558
3559         while (class) {
3560                 if (class->field.count) {
3561                         if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
3562                                 return &class->fields [idx - class->field.first];
3563                         }
3564                 }
3565                 class = class->parent;
3566         }
3567         return NULL;
3568 }
3569
3570 /**
3571  * mono_class_get_field:
3572  * @class: the class to lookup the field.
3573  * @field_token: the field token
3574  *
3575  * Returns: A MonoClassField representing the type and offset of
3576  * the field, or a NULL value if the field does not belong to this
3577  * class.
3578  */
3579 MonoClassField *
3580 mono_class_get_field (MonoClass *class, guint32 field_token)
3581 {
3582         int idx = mono_metadata_token_index (field_token);
3583
3584         g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
3585
3586         return mono_class_get_field_idx (class, idx - 1);
3587 }
3588
3589 /**
3590  * mono_class_get_field_from_name:
3591  * @klass: the class to lookup the field.
3592  * @name: the field name
3593  *
3594  * Search the class @klass and it's parents for a field with the name @name.
3595  * 
3596  * Returns: the MonoClassField pointer of the named field or NULL
3597  */
3598 MonoClassField *
3599 mono_class_get_field_from_name (MonoClass *klass, const char *name)
3600 {
3601         int i;
3602
3603         mono_class_setup_fields_locking (klass);
3604         while (klass) {
3605                 for (i = 0; i < klass->field.count; ++i) {
3606                         if (strcmp (name, klass->fields [i].name) == 0)
3607                                 return &klass->fields [i];
3608                 }
3609                 klass = klass->parent;
3610         }
3611         return NULL;
3612 }
3613
3614 /**
3615  * mono_class_get_field_token:
3616  * @field: the field we need the token of
3617  *
3618  * Get the token of a field. Note that the tokesn is only valid for the image
3619  * the field was loaded from. Don't use this function for fields in dynamic types.
3620  * 
3621  * Returns: the token representing the field in the image it was loaded from.
3622  */
3623 guint32
3624 mono_class_get_field_token (MonoClassField *field)
3625 {
3626         MonoClass *klass = field->parent;
3627         int i;
3628
3629         mono_class_setup_fields_locking (klass);
3630         while (klass) {
3631                 for (i = 0; i < klass->field.count; ++i) {
3632                         if (&klass->fields [i] == field)
3633                                 return mono_metadata_make_token (MONO_TABLE_FIELD, klass->field.first + i + 1);
3634                 }
3635                 klass = klass->parent;
3636         }
3637
3638         g_assert_not_reached ();
3639         return 0;
3640 }
3641
3642 guint32
3643 mono_class_get_event_token (MonoEvent *event)
3644 {
3645         MonoClass *klass = event->parent;
3646         int i;
3647
3648         while (klass) {
3649                 for (i = 0; i < klass->event.count; ++i) {
3650                         if (&klass->events [i] == event)
3651                                 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->event.first + i + 1);
3652                 }
3653                 klass = klass->parent;
3654         }
3655
3656         g_assert_not_reached ();
3657         return 0;
3658 }
3659
3660 MonoProperty*
3661 mono_class_get_property_from_name (MonoClass *klass, const char *name)
3662 {
3663         while (klass) {
3664                 MonoProperty* p;
3665                 gpointer iter = NULL;
3666                 while ((p = mono_class_get_properties (klass, &iter))) {
3667                         if (! strcmp (name, p->name))
3668                                 return p;
3669                 }
3670                 klass = klass->parent;
3671         }
3672         return NULL;
3673 }
3674
3675 guint32
3676 mono_class_get_property_token (MonoProperty *prop)
3677 {
3678         MonoClass *klass = prop->parent;
3679         while (klass) {
3680                 MonoProperty* p;
3681                 int i = 0;
3682                 gpointer iter = NULL;
3683                 while ((p = mono_class_get_properties (klass, &iter))) {
3684                         if (&klass->properties [i] == prop)
3685                                 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->property.first + i + 1);
3686                         
3687                         i ++;
3688                 }
3689                 klass = klass->parent;
3690         }
3691
3692         g_assert_not_reached ();
3693         return 0;
3694 }
3695
3696 char *
3697 mono_class_name_from_token (MonoImage *image, guint32 type_token)
3698 {
3699         const char *name, *nspace;
3700         if (image->dynamic)
3701                 return g_strdup_printf ("DynamicType 0x%08x", type_token);
3702         
3703         switch (type_token & 0xff000000){
3704         case MONO_TOKEN_TYPE_DEF: {
3705                 guint32 cols [MONO_TYPEDEF_SIZE];
3706                 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
3707                 guint tidx = mono_metadata_token_index (type_token);
3708
3709                 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
3710                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
3711                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
3712                 if (strlen (nspace) == 0)
3713                         return g_strdup_printf ("%s", name);
3714                 else
3715                         return g_strdup_printf ("%s.%s", nspace, name);
3716         }
3717
3718         case MONO_TOKEN_TYPE_REF: {
3719                 guint32 cols [MONO_TYPEREF_SIZE];
3720                 MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
3721
3722                 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
3723                 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
3724                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
3725                 if (strlen (nspace) == 0)
3726                         return g_strdup_printf ("%s", name);
3727                 else
3728                         return g_strdup_printf ("%s.%s", nspace, name);
3729         }
3730                 
3731         case MONO_TOKEN_TYPE_SPEC:
3732                 return g_strdup_printf ("Typespec 0x%08x", type_token);
3733         default:
3734                 g_assert_not_reached ();
3735         }
3736
3737         return NULL;
3738 }
3739
3740 static char *
3741 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
3742 {
3743         if (image->dynamic)
3744                 return g_strdup_printf ("DynamicAssembly %s", image->name);
3745         
3746         switch (type_token & 0xff000000){
3747         case MONO_TOKEN_TYPE_DEF:
3748                 return mono_stringify_assembly_name (&image->assembly->aname);
3749                 break;
3750         case MONO_TOKEN_TYPE_REF: {
3751                 MonoAssemblyName aname;
3752                 guint32 cols [MONO_TYPEREF_SIZE];
3753                 MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
3754                 guint32 idx;
3755         
3756                 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
3757
3758                 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
3759                 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
3760                 case MONO_RESOLTION_SCOPE_MODULE:
3761                         /* FIXME: */
3762                         return g_strdup ("");
3763                 case MONO_RESOLTION_SCOPE_MODULEREF:
3764                         /* FIXME: */
3765                         return g_strdup ("");
3766                 case MONO_RESOLTION_SCOPE_TYPEREF:
3767                         /* FIXME: */
3768                         return g_strdup ("");
3769                 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
3770                         mono_assembly_get_assemblyref (image, idx - 1, &aname);
3771                         return mono_stringify_assembly_name (&aname);
3772                 default:
3773                         g_assert_not_reached ();
3774                 }
3775                 break;
3776         }
3777         case MONO_TOKEN_TYPE_SPEC:
3778                 /* FIXME: */
3779                 return g_strdup ("");
3780         default:
3781                 g_assert_not_reached ();
3782         }
3783
3784         return NULL;
3785 }
3786
3787 /**
3788  * mono_class_get_full:
3789  * @image: the image where the class resides
3790  * @type_token: the token for the class
3791  * @context: the generic context used to evaluate generic instantiations in
3792  *
3793  * Returns: the MonoClass that represents @type_token in @image
3794  */
3795 MonoClass *
3796 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
3797 {
3798         MonoClass *class = NULL;
3799
3800         if (image->dynamic)
3801                 return mono_lookup_dynamic_token (image, type_token);
3802
3803         switch (type_token & 0xff000000){
3804         case MONO_TOKEN_TYPE_DEF:
3805                 class = mono_class_create_from_typedef (image, type_token);
3806                 break;          
3807         case MONO_TOKEN_TYPE_REF:
3808                 class = mono_class_from_typeref (image, type_token);
3809                 break;
3810         case MONO_TOKEN_TYPE_SPEC:
3811                 class = mono_class_create_from_typespec (image, type_token, context);
3812                 break;
3813         default:
3814                 g_warning ("unknown token type %x", type_token & 0xff000000);
3815                 g_assert_not_reached ();
3816         }
3817
3818         if (!class){
3819                 char *name = mono_class_name_from_token (image, type_token);
3820                 char *assembly = mono_assembly_name_from_token (image, type_token);
3821                 mono_loader_set_error_type_load (name, assembly);
3822         }
3823
3824         return class;
3825 }
3826
3827 MonoClass *
3828 mono_class_get (MonoImage *image, guint32 type_token)
3829 {
3830         return mono_class_get_full (image, type_token, NULL);
3831 }
3832
3833 typedef struct {
3834         gconstpointer key;
3835         gpointer value;
3836 } FindUserData;
3837
3838 static void
3839 find_nocase (gpointer key, gpointer value, gpointer user_data)
3840 {
3841         char *name = (char*)key;
3842         FindUserData *data = (FindUserData*)user_data;
3843
3844         if (!data->value && (g_strcasecmp (name, (char*)data->key) == 0))
3845                 data->value = value;
3846 }
3847
3848 /**
3849  * mono_class_from_name_case:
3850  * @image: The MonoImage where the type is looked up in, or NULL for looking up in all loaded assemblies
3851  * @name_space: the type namespace
3852  * @name: the type short name.
3853  *
3854  * Obtains a MonoClass with a given namespace and a given name which
3855  * is located in the given MonoImage.   The namespace and name
3856  * lookups are case insensitive.
3857  *
3858  * You can also pass @NULL to the image, and that will lookup for
3859  * a type with the given namespace and name in all of the loaded
3860  * assemblies: notice that since there might be a name clash in this
3861  * case, passing @NULL is not encouraged if you need a precise type.
3862  *
3863  */
3864 MonoClass *
3865 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
3866 {
3867         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
3868         guint32 cols [MONO_TYPEDEF_SIZE];
3869         const char *n;
3870         const char *nspace;
3871         guint32 i, visib;
3872
3873         if (image->dynamic) {
3874                 guint32 token = 0;
3875                 FindUserData user_data;
3876
3877                 mono_loader_lock ();
3878
3879                 user_data.key = name_space;
3880                 user_data.value = NULL;
3881                 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
3882
3883                 if (user_data.value) {
3884                         GHashTable *nspace_table = (GHashTable*)user_data.value;
3885
3886                         user_data.key = name;
3887                         user_data.value = NULL;
3888
3889                         g_hash_table_foreach (nspace_table, find_nocase, &user_data);
3890                         
3891                         if (user_data.value)
3892                                 token = GPOINTER_TO_UINT (user_data.value);
3893                 }
3894
3895                 mono_loader_unlock ();
3896                 
3897                 if (token)
3898                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
3899                 else
3900                         return NULL;
3901
3902         }
3903
3904         /* add a cache if needed */
3905         for (i = 1; i <= t->rows; ++i) {
3906                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
3907                 /* nested types are accessed from the nesting name */
3908                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
3909                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
3910                         continue;
3911                 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
3912                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
3913                 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
3914                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
3915         }
3916         return NULL;
3917 }
3918
3919 static MonoClass*
3920 return_nested_in (MonoClass *class, char *nested) {
3921         MonoClass *found;
3922         char *s = strchr (nested, '/');
3923         GList *tmp;
3924
3925         if (s) {
3926                 *s = 0;
3927                 s++;
3928         }
3929         for (tmp = class->nested_classes; tmp; tmp = tmp->next) {
3930                 found = tmp->data;
3931                 if (strcmp (found->name, nested) == 0) {
3932                         if (s)
3933                                 return return_nested_in (found, s);
3934                         return found;
3935                 }
3936         }
3937         return NULL;
3938 }
3939
3940
3941 /**
3942  * mono_class_from_name:
3943  * @image: The MonoImage where the type is looked up in, or NULL for looking up in all loaded assemblies
3944  * @name_space: the type namespace
3945  * @name: the type short name.
3946  *
3947  * Obtains a MonoClass with a given namespace and a given name which
3948  * is located in the given MonoImage.   
3949  *
3950  * You can also pass `NULL' to the image, and that will lookup for
3951  * a type with the given namespace and name in all of the loaded
3952  * assemblies: notice that since there might be a name clash in this
3953  * case, passing NULL is not encouraged if you need a precise type.
3954  *
3955  */
3956 MonoClass *
3957 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
3958 {
3959         GHashTable *nspace_table;
3960         MonoImage *loaded_image;
3961         guint32 token = 0;
3962         MonoClass *class;
3963         char *nested;
3964         char buf [1024];
3965
3966         if ((nested = strchr (name, '/'))) {
3967                 int pos = nested - name;
3968                 int len = strlen (name);
3969                 if (len > 1023)
3970                         return NULL;
3971                 memcpy (buf, name, len + 1);
3972                 buf [pos] = 0;
3973                 nested = buf + pos + 1;
3974                 name = buf;
3975         }
3976
3977         mono_loader_lock ();
3978
3979         nspace_table = g_hash_table_lookup (image->name_cache, name_space);
3980
3981         if (nspace_table)
3982                 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
3983
3984         mono_loader_unlock ();
3985
3986         if (!token)
3987                 return NULL;
3988
3989         if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
3990                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
3991                 guint32 cols [MONO_EXP_TYPE_SIZE];
3992                 guint32 idx, impl;
3993
3994                 idx = mono_metadata_token_index (token);
3995
3996                 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
3997
3998                 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
3999                 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
4000                         loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
4001                         if (!loaded_image)
4002                                 return NULL;
4003                         class = mono_class_from_name (loaded_image, name_space, name);
4004                         if (nested)
4005                                 return return_nested_in (class, nested);
4006                         return class;
4007                 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
4008                         MonoAssembly **references = image->references;
4009                         if (!references [idx - 1])
4010                                 mono_assembly_load_reference (image, idx - 1);
4011                         g_assert (references == image->references);
4012                         g_assert (references [idx - 1]);
4013                         if (references [idx - 1] == (gpointer)-1)
4014                                 return NULL;                    
4015                         else
4016                                 /* FIXME: Cycle detection */
4017                                 return mono_class_from_name (references [idx - 1]->image, name_space, name);
4018                 } else {
4019                         g_error ("not yet implemented");
4020                 }
4021         }
4022
4023         token = MONO_TOKEN_TYPE_DEF | token;
4024
4025         class = mono_class_get (image, token);
4026         if (nested)
4027                 return return_nested_in (class, nested);
4028         return class;
4029 }
4030
4031 gboolean
4032 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc, 
4033                            gboolean check_interfaces)
4034 {
4035         g_assert (klassc->idepth > 0);
4036         if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
4037                 if ((klassc->interface_id <= klass->max_interface_id) &&
4038                         (klass->interface_offsets [klassc->interface_id] >= 0))
4039                         return TRUE;
4040         } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
4041                 int i;
4042
4043                 for (i = 0; i < klass->interface_count; i ++) {
4044                         MonoClass *ic =  klass->interfaces [i];
4045                         if (ic == klassc)
4046                                 return TRUE;
4047                 }
4048         } else {
4049                 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
4050                         return TRUE;
4051         }
4052
4053         /* 
4054          * MS.NET thinks interfaces are a subclass of Object, so we think it as
4055          * well.
4056          */
4057         if (klassc == mono_defaults.object_class)
4058                 return TRUE;
4059
4060         return FALSE;
4061 }
4062
4063 gboolean
4064 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
4065 {
4066         if (!klass->inited)
4067                 mono_class_init (klass);
4068
4069         if (!oklass->inited)
4070                 mono_class_init (oklass);
4071
4072         if (MONO_CLASS_IS_INTERFACE (klass)) {
4073                 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
4074                         return FALSE;
4075
4076                 /* interface_offsets might not be set for dynamic classes */
4077                 if (oklass->reflection_info && !oklass->interface_offsets)
4078                         /* 
4079                          * oklass might be a generic type parameter but they have 
4080                          * interface_offsets set.
4081                          */
4082                         return mono_reflection_call_is_assignable_to (oklass, klass);
4083
4084                 if ((klass->interface_id <= oklass->max_interface_id) &&
4085                     (oklass->interface_offsets [klass->interface_id] != -1))
4086                         return TRUE;
4087         } else if (klass->rank) {
4088                 MonoClass *eclass, *eoclass;
4089
4090                 if (oklass->rank != klass->rank)
4091                         return FALSE;
4092
4093                 /* vectors vs. one dimensional arrays */
4094                 if (oklass->byval_arg.type != klass->byval_arg.type)
4095                         return FALSE;
4096
4097                 eclass = klass->cast_class;
4098                 eoclass = oklass->cast_class;
4099
4100                 /* 
4101                  * a is b does not imply a[] is b[] when a is a valuetype, and
4102                  * b is a reference type.
4103                  */
4104
4105                 if (eoclass->valuetype) {
4106                         if ((eclass == mono_defaults.enum_class) || 
4107                                 (eclass == mono_defaults.enum_class->parent) ||
4108                                 (eclass == mono_defaults.object_class))
4109                                 return FALSE;
4110                 }
4111
4112                 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
4113         } else if (mono_class_is_nullable (klass))
4114                 return (mono_class_is_assignable_from (klass->cast_class, oklass));
4115         else if (klass == mono_defaults.object_class)
4116                 return TRUE;
4117
4118         return mono_class_has_parent (oklass, klass);
4119 }       
4120
4121 /*
4122  * mono_class_get_cctor:
4123  *
4124  *   Returns the static constructor of @klass if it exists, NULL otherwise.
4125  */
4126 MonoMethod*
4127 mono_class_get_cctor (MonoClass *klass)
4128 {
4129         MonoCachedClassInfo cached_info;
4130
4131         if (!klass->has_cctor)
4132                 return NULL;
4133
4134         if (mono_class_get_cached_class_info (klass, &cached_info))
4135                 return mono_get_method (klass->image, cached_info.cctor_token, klass);
4136
4137         return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
4138 }
4139
4140 /*
4141  * mono_class_get_finalizer:
4142  *
4143  *   Returns the finalizer method of @klass if it exists, NULL otherwise.
4144  */
4145 MonoMethod*
4146 mono_class_get_finalizer (MonoClass *klass)
4147 {
4148         MonoCachedClassInfo cached_info;
4149
4150         if (!klass->inited)
4151                 mono_class_init (klass);
4152         if (!klass->has_finalize)
4153                 return NULL;
4154
4155         if (mono_class_get_cached_class_info (klass, &cached_info))
4156                 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
4157         else {
4158                 mono_class_setup_vtable (klass);
4159                 return klass->vtable [finalize_slot];
4160         }
4161 }
4162
4163 /*
4164  * mono_class_needs_cctor_run:
4165  *
4166  *  Determines whenever the class has a static constructor and whenever it
4167  * needs to be called when executing CALLER.
4168  */
4169 gboolean
4170 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
4171 {
4172         MonoMethod *method;
4173
4174         method = mono_class_get_cctor (klass);
4175         if (method)
4176                 return (method == caller) ? FALSE : TRUE;
4177         else
4178                 return TRUE;
4179 }
4180
4181 /**
4182  * mono_class_array_element_size:
4183  * @klass: 
4184  *
4185  * Returns: the number of bytes an element of type @klass
4186  * uses when stored into an array.
4187  */
4188 gint32
4189 mono_class_array_element_size (MonoClass *klass)
4190 {
4191         MonoType *type = &klass->byval_arg;
4192         
4193 handle_enum:
4194         switch (type->type) {
4195         case MONO_TYPE_I1:
4196         case MONO_TYPE_U1:
4197         case MONO_TYPE_BOOLEAN:
4198                 return 1;
4199         case MONO_TYPE_I2:
4200         case MONO_TYPE_U2:
4201         case MONO_TYPE_CHAR:
4202                 return 2;
4203         case MONO_TYPE_I4:
4204         case MONO_TYPE_U4:
4205         case MONO_TYPE_R4:
4206                 return 4;
4207         case MONO_TYPE_I:
4208         case MONO_TYPE_U:
4209         case MONO_TYPE_PTR:
4210         case MONO_TYPE_CLASS:
4211         case MONO_TYPE_STRING:
4212         case MONO_TYPE_OBJECT:
4213         case MONO_TYPE_SZARRAY:
4214         case MONO_TYPE_ARRAY: 
4215         case MONO_TYPE_VAR:
4216         case MONO_TYPE_MVAR:   
4217                 return sizeof (gpointer);
4218         case MONO_TYPE_I8:
4219         case MONO_TYPE_U8:
4220         case MONO_TYPE_R8:
4221                 return 8;
4222         case MONO_TYPE_VALUETYPE:
4223                 if (type->data.klass->enumtype) {
4224                         type = type->data.klass->enum_basetype;
4225                         klass = klass->element_class;
4226                         goto handle_enum;
4227                 }
4228                 return mono_class_instance_size (klass) - sizeof (MonoObject);
4229         case MONO_TYPE_GENERICINST:
4230                 type = &type->data.generic_class->container_class->byval_arg;
4231                 goto handle_enum;
4232         default:
4233                 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
4234         }
4235         return -1;
4236 }
4237
4238 /**
4239  * mono_array_element_size:
4240  * @ac: pointer to a #MonoArrayClass
4241  *
4242  * Returns: the size of single array element.
4243  */
4244 gint32
4245 mono_array_element_size (MonoClass *ac)
4246 {
4247         return mono_class_array_element_size (ac->element_class);
4248 }
4249
4250 gpointer
4251 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
4252               MonoGenericContext *context)
4253 {
4254         if (image->dynamic) {
4255                 MonoClass *tmp_handle_class;
4256                 gpointer obj = mono_lookup_dynamic_token_class (image, token, &tmp_handle_class);
4257
4258                 g_assert (tmp_handle_class);
4259                 if (handle_class)
4260                         *handle_class = tmp_handle_class;
4261
4262                 if (tmp_handle_class == mono_defaults.typehandle_class)
4263                         return &((MonoClass*)obj)->byval_arg;
4264                 else
4265                         return obj;
4266         }
4267
4268         switch (token & 0xff000000) {
4269         case MONO_TOKEN_TYPE_DEF:
4270         case MONO_TOKEN_TYPE_REF:
4271         case MONO_TOKEN_TYPE_SPEC: {
4272                 MonoClass *class;
4273                 if (handle_class)
4274                         *handle_class = mono_defaults.typehandle_class;
4275                 class = mono_class_get_full (image, token, context);
4276                 if (!class)
4277                         return NULL;
4278                 mono_class_init (class);
4279                 /* We return a MonoType* as handle */
4280                 return &class->byval_arg;
4281         }
4282         case MONO_TOKEN_FIELD_DEF: {
4283                 MonoClass *class;
4284                 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
4285                 if (handle_class)
4286                         *handle_class = mono_defaults.fieldhandle_class;
4287                 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
4288                 if (!class)
4289                         return NULL;
4290                 mono_class_init (class);
4291                 return mono_class_get_field (class, token);
4292         }
4293         case MONO_TOKEN_METHOD_DEF: {
4294                 MonoMethod *meth;
4295                 meth = mono_get_method_full (image, token, NULL, context);
4296                 if (handle_class)
4297                         *handle_class = mono_defaults.methodhandle_class;
4298                 return meth;
4299         }
4300         case MONO_TOKEN_MEMBER_REF: {
4301                 guint32 cols [MONO_MEMBERREF_SIZE];
4302                 const char *sig;
4303                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
4304                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
4305                 mono_metadata_decode_blob_size (sig, &sig);
4306                 if (*sig == 0x6) { /* it's a field */
4307                         MonoClass *klass;
4308                         MonoClassField *field;
4309                         field = mono_field_from_token (image, token, &klass, context);
4310                         if (handle_class)
4311                                 *handle_class = mono_defaults.fieldhandle_class;
4312                         return field;
4313                 } else {
4314                         MonoMethod *meth;
4315                         meth = mono_get_method_full (image, token, NULL, context);
4316                         if (handle_class)
4317                                 *handle_class = mono_defaults.methodhandle_class;
4318                         return meth;
4319                 }
4320         }
4321         default:
4322                 g_warning ("Unknown token 0x%08x in ldtoken", token);
4323                 break;
4324         }
4325         return NULL;
4326 }
4327
4328 /**
4329  * This function might need to call runtime functions so it can't be part
4330  * of the metadata library.
4331  */
4332 static MonoLookupDynamicToken lookup_dynamic = NULL;
4333
4334 void
4335 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
4336 {
4337         lookup_dynamic = func;
4338 }
4339
4340 gpointer
4341 mono_lookup_dynamic_token (MonoImage *image, guint32 token)
4342 {
4343         MonoClass *handle_class;
4344
4345         return lookup_dynamic (image, token, &handle_class);
4346 }
4347
4348 gpointer
4349 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, MonoClass **handle_class)
4350 {
4351         return lookup_dynamic (image, token, handle_class);
4352 }
4353
4354 static MonoGetCachedClassInfo get_cached_class_info = NULL;
4355
4356 void
4357 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
4358 {
4359         get_cached_class_info = func;
4360 }
4361
4362 static gboolean
4363 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
4364 {
4365         if (!get_cached_class_info)
4366                 return FALSE;
4367         else
4368                 return get_cached_class_info (klass, res);
4369 }
4370
4371 MonoImage*
4372 mono_class_get_image (MonoClass *klass)
4373 {
4374         return klass->image;
4375 }
4376
4377 /**
4378  * mono_class_get_element_class:
4379  * @klass: the MonoClass to act on
4380  *
4381  * Returns: the element class of an array or an enumeration.
4382  */
4383 MonoClass*
4384 mono_class_get_element_class (MonoClass *klass)
4385 {
4386         return klass->element_class;
4387 }
4388
4389 /**
4390  * mono_class_is_valuetype:
4391  * @klass: the MonoClass to act on
4392  *
4393  * Returns: true if the MonoClass represents a ValueType.
4394  */
4395 gboolean
4396 mono_class_is_valuetype (MonoClass *klass)
4397 {
4398         return klass->valuetype;
4399 }
4400
4401 /**
4402  * mono_class_is_enum:
4403  * @klass: the MonoClass to act on
4404  *
4405  * Returns: true if the MonoClass represents an enumeration.
4406  */
4407 gboolean
4408 mono_class_is_enum (MonoClass *klass)
4409 {
4410         return klass->enumtype;
4411 }
4412
4413 /**
4414  * mono_class_enum_basetype:
4415  * @klass: the MonoClass to act on
4416  *
4417  * Returns: the underlying type representation for an enumeration.
4418  */
4419 MonoType*
4420 mono_class_enum_basetype (MonoClass *klass)
4421 {
4422         return klass->enum_basetype;
4423 }
4424
4425 /**
4426  * mono_class_get_parent
4427  * @klass: the MonoClass to act on
4428  *
4429  * Returns: the parent class for this class.
4430  */
4431 MonoClass*
4432 mono_class_get_parent (MonoClass *klass)
4433 {
4434         return klass->parent;
4435 }
4436
4437 /**
4438  * mono_class_get_nesting_type;
4439  * @klass: the MonoClass to act on
4440  *
4441  * Returns: the container type where this type is nested or NULL if this type is not a nested type.
4442  */
4443 MonoClass*
4444 mono_class_get_nesting_type (MonoClass *klass)
4445 {
4446         return klass->nested_in;
4447 }
4448
4449 /**
4450  * mono_class_get_rank:
4451  * @klass: the MonoClass to act on
4452  *
4453  * Returns: the rank for the array (the number of dimensions).
4454  */
4455 int
4456 mono_class_get_rank (MonoClass *klass)
4457 {
4458         return klass->rank;
4459 }
4460
4461 /**
4462  * mono_class_get_flags:
4463  * @klass: the MonoClass to act on
4464  *
4465  * The type flags from the TypeDef table from the metadata.
4466  * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
4467  * different values.
4468  *
4469  * Returns: the flags from the TypeDef table.
4470  */
4471 guint32
4472 mono_class_get_flags (MonoClass *klass)
4473 {
4474         return klass->flags;
4475 }
4476
4477 /**
4478  * mono_class_get_name
4479  * @klass: the MonoClass to act on
4480  *
4481  * Returns: the name of the class.
4482  */
4483 const char*
4484 mono_class_get_name (MonoClass *klass)
4485 {
4486         return klass->name;
4487 }
4488
4489 /**
4490  * mono_class_get_namespace:
4491  * @klass: the MonoClass to act on
4492  *
4493  * Returns: the namespace of the class.
4494  */
4495 const char*
4496 mono_class_get_namespace (MonoClass *klass)
4497 {
4498         return klass->name_space;
4499 }
4500
4501 /**
4502  * mono_class_get_type:
4503  * @klass: the MonoClass to act on
4504  *
4505  * This method returns the internal Type representation for the class.
4506  *
4507  * Returns: the MonoType from the class.
4508  */
4509 MonoType*
4510 mono_class_get_type (MonoClass *klass)
4511 {
4512         return &klass->byval_arg;
4513 }
4514
4515 /**
4516  * mono_class_get_byref_type:
4517  * @klass: the MonoClass to act on
4518  *
4519  * 
4520  */
4521 MonoType*
4522 mono_class_get_byref_type (MonoClass *klass)
4523 {
4524         return &klass->this_arg;
4525 }
4526
4527 /**
4528  * mono_class_num_fields:
4529  * @klass: the MonoClass to act on
4530  *
4531  * Returns: the number of static and instance fields in the class.
4532  */
4533 int
4534 mono_class_num_fields (MonoClass *klass)
4535 {
4536         return klass->field.count;
4537 }
4538
4539 /**
4540  * mono_class_num_methods:
4541  * @klass: the MonoClass to act on
4542  *
4543  * Returns: the number of methods in the class.
4544  */
4545 int
4546 mono_class_num_methods (MonoClass *klass)
4547 {
4548         return klass->method.count;
4549 }
4550
4551 /**
4552  * mono_class_num_properties
4553  * @klass: the MonoClass to act on
4554  *
4555  * Returns: the number of properties in the class.
4556  */
4557 int
4558 mono_class_num_properties (MonoClass *klass)
4559 {
4560         mono_class_setup_properties (klass);
4561
4562         return klass->property.count;
4563 }
4564
4565 /**
4566  * mono_class_num_events:
4567  * @klass: the MonoClass to act on
4568  *
4569  * Returns: the number of events in the class.
4570  */
4571 int
4572 mono_class_num_events (MonoClass *klass)
4573 {
4574         mono_class_setup_events (klass);
4575
4576         return klass->event.count;
4577 }
4578
4579 /**
4580  * mono_class_get_fields:
4581  * @klass: the MonoClass to act on
4582  *
4583  * This routine is an iterator routine for retrieving the fields in a class.
4584  *
4585  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4586  * iterate over all of the elements.  When no more values are
4587  * available, the return value is NULL.
4588  *
4589  * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
4590  */
4591 MonoClassField*
4592 mono_class_get_fields (MonoClass* klass, gpointer *iter)
4593 {
4594         MonoClassField* field;
4595         if (!iter)
4596                 return NULL;
4597         mono_class_setup_fields_locking (klass);
4598         if (!*iter) {
4599                 /* start from the first */
4600                 if (klass->field.count) {
4601                         return *iter = &klass->fields [0];
4602                 } else {
4603                         /* no fields */
4604                         return NULL;
4605                 }
4606         }
4607         field = *iter;
4608         field++;
4609         if (field < &klass->fields [klass->field.count]) {
4610                 return *iter = field;
4611         }
4612         return NULL;
4613 }
4614
4615 /**
4616  * mono_class_get_methods
4617  * @klass: the MonoClass to act on
4618  *
4619  * This routine is an iterator routine for retrieving the fields in a class.
4620  *
4621  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4622  * iterate over all of the elements.  When no more values are
4623  * available, the return value is NULL.
4624  *
4625  * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
4626  */
4627 MonoMethod*
4628 mono_class_get_methods (MonoClass* klass, gpointer *iter)
4629 {
4630         MonoMethod** method;
4631         if (!iter)
4632                 return NULL;
4633         if (!klass->inited)
4634                 mono_class_init (klass);
4635         if (!*iter) {
4636                 mono_class_setup_methods (klass);
4637                 /* start from the first */
4638                 if (klass->method.count) {
4639                         *iter = &klass->methods [0];
4640                         return klass->methods [0];
4641                 } else {
4642                         /* no method */
4643                         return NULL;
4644                 }
4645         }
4646         method = *iter;
4647         method++;
4648         if (method < &klass->methods [klass->method.count]) {
4649                 *iter = method;
4650                 return *method;
4651         }
4652         return NULL;
4653 }
4654
4655 /**
4656  * mono_class_get_properties:
4657  * @klass: the MonoClass to act on
4658  *
4659  * This routine is an iterator routine for retrieving the properties in a class.
4660  *
4661  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4662  * iterate over all of the elements.  When no more values are
4663  * available, the return value is NULL.
4664  *
4665  * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
4666  */
4667 MonoProperty*
4668 mono_class_get_properties (MonoClass* klass, gpointer *iter)
4669 {
4670         MonoProperty* property;
4671         if (!iter)
4672                 return NULL;
4673         if (!klass->inited)
4674                 mono_class_init (klass);
4675         if (!*iter) {
4676                 mono_class_setup_properties (klass);
4677                 /* start from the first */
4678                 if (klass->property.count) {
4679                         return *iter = &klass->properties [0];
4680                 } else {
4681                         /* no fields */
4682                         return NULL;
4683                 }
4684         }
4685         property = *iter;
4686         property++;
4687         if (property < &klass->properties [klass->property.count]) {
4688                 return *iter = property;
4689         }
4690         return NULL;
4691 }
4692
4693 /**
4694  * mono_class_get_events:
4695  * @klass: the MonoClass to act on
4696  *
4697  * This routine is an iterator routine for retrieving the properties in a class.
4698  *
4699  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4700  * iterate over all of the elements.  When no more values are
4701  * available, the return value is NULL.
4702  *
4703  * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
4704  */
4705 MonoEvent*
4706 mono_class_get_events (MonoClass* klass, gpointer *iter)
4707 {
4708         MonoEvent* event;
4709         if (!iter)
4710                 return NULL;
4711         if (!klass->inited)
4712                 mono_class_init (klass);
4713         if (!*iter) {
4714                 mono_class_setup_events (klass);
4715                 /* start from the first */
4716                 if (klass->event.count) {
4717                         return *iter = &klass->events [0];
4718                 } else {
4719                         /* no fields */
4720                         return NULL;
4721                 }
4722         }
4723         event = *iter;
4724         event++;
4725         if (event < &klass->events [klass->event.count]) {
4726                 return *iter = event;
4727         }
4728         return NULL;
4729 }
4730
4731 /**
4732  * mono_class_get_interfaces
4733  * @klass: the MonoClass to act on
4734  *
4735  * This routine is an iterator routine for retrieving the interfaces implemented by this class.
4736  *
4737  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4738  * iterate over all of the elements.  When no more values are
4739  * available, the return value is NULL.
4740  *
4741  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
4742  */
4743 MonoClass*
4744 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
4745 {
4746         MonoClass** iface;
4747         if (!iter)
4748                 return NULL;
4749         if (!klass->inited)
4750                 mono_class_init (klass);
4751         if (!*iter) {
4752                 /* start from the first */
4753                 if (klass->interface_count) {
4754                         *iter = &klass->interfaces [0];
4755                         return klass->interfaces [0];
4756                 } else {
4757                         /* no interface */
4758                         return NULL;
4759                 }
4760         }
4761         iface = *iter;
4762         iface++;
4763         if (iface < &klass->interfaces [klass->interface_count]) {
4764                 *iter = iface;
4765                 return *iface;
4766         }
4767         return NULL;
4768 }
4769
4770 /**
4771  * mono_class_get_nested_types
4772  * @klass: the MonoClass to act on
4773  *
4774  * This routine is an iterator routine for retrieving the nested types of a class.
4775  *
4776  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4777  * iterate over all of the elements.  When no more values are
4778  * available, the return value is NULL.
4779  *
4780  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
4781  */
4782 MonoClass*
4783 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
4784 {
4785         GList *item;
4786         if (!iter)
4787                 return NULL;
4788         if (!klass->inited)
4789                 mono_class_init (klass);
4790         if (!*iter) {
4791                 /* start from the first */
4792                 if (klass->nested_classes) {
4793                         *iter = klass->nested_classes;
4794                         return klass->nested_classes->data;
4795                 } else {
4796                         /* no nested types */
4797                         return NULL;
4798                 }
4799         }
4800         item = *iter;
4801         item = item->next;
4802         if (item) {
4803                 *iter = item;
4804                 return item->data;
4805         }
4806         return NULL;
4807 }
4808
4809 /**
4810  * mono_field_get_name:
4811  * @field: the MonoClassField to act on
4812  *
4813  * Returns: the name of the field.
4814  */
4815 const char*
4816 mono_field_get_name (MonoClassField *field)
4817 {
4818         return field->name;
4819 }
4820
4821 /**
4822  * mono_field_get_type:
4823  * @field: the MonoClassField to act on
4824  *
4825  * Returns: MonoType of the field.
4826  */
4827 MonoType*
4828 mono_field_get_type (MonoClassField *field)
4829 {
4830         return field->type;
4831 }
4832
4833 /**
4834  * mono_field_get_type:
4835  * @field: the MonoClassField to act on
4836  *
4837  * Returns: MonoClass where the field was defined.
4838  */
4839 MonoClass*
4840 mono_field_get_parent (MonoClassField *field)
4841 {
4842         return field->parent;
4843 }
4844
4845 /**
4846  * mono_field_get_flags;
4847  * @field: the MonoClassField to act on
4848  *
4849  * The metadata flags for a field are encoded using the
4850  * FIELD_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
4851  *
4852  * Returns: the flags for the field.
4853  */
4854 guint32
4855 mono_field_get_flags (MonoClassField *field)
4856 {
4857         return field->type->attrs;
4858 }
4859
4860 /**
4861  * mono_property_get_name: 
4862  * @prop: the MonoProperty to act on
4863  *
4864  * Returns: the name of the property
4865  */
4866 const char*
4867 mono_property_get_name (MonoProperty *prop)
4868 {
4869         return prop->name;
4870 }
4871
4872 /**
4873  * mono_property_get_set_method
4874  * @prop: the MonoProperty to act on.
4875  *
4876  * Returns: the setter method of the property (A MonoMethod)
4877  */
4878 MonoMethod*
4879 mono_property_get_set_method (MonoProperty *prop)
4880 {
4881         return prop->set;
4882 }
4883
4884 /**
4885  * mono_property_get_get_method
4886  * @prop: the MonoProperty to act on.
4887  *
4888  * Returns: the setter method of the property (A MonoMethod)
4889  */
4890 MonoMethod*
4891 mono_property_get_get_method (MonoProperty *prop)
4892 {
4893         return prop->get;
4894 }
4895
4896 /**
4897  * mono_property_get_parent:
4898  * @prop: the MonoProperty to act on.
4899  *
4900  * Returns: the MonoClass where the property was defined.
4901  */
4902 MonoClass*
4903 mono_property_get_parent (MonoProperty *prop)
4904 {
4905         return prop->parent;
4906 }
4907
4908 /**
4909  * mono_property_get_flags:
4910  * @prop: the MonoProperty to act on.
4911  *
4912  * The metadata flags for a property are encoded using the
4913  * PROPERTY_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
4914  *
4915  * Returns: the flags for the property.
4916  */
4917 guint32
4918 mono_property_get_flags (MonoProperty *prop)
4919 {
4920         return prop->attrs;
4921 }
4922
4923 /**
4924  * mono_event_get_name:
4925  * @event: the MonoEvent to act on
4926  *
4927  * Returns: the name of the event.
4928  */
4929 const char*
4930 mono_event_get_name (MonoEvent *event)
4931 {
4932         return event->name;
4933 }
4934
4935 /**
4936  * mono_event_get_add_method:
4937  * @event: The MonoEvent to act on.
4938  *
4939  * Returns: the @add' method for the event (a MonoMethod).
4940  */
4941 MonoMethod*
4942 mono_event_get_add_method (MonoEvent *event)
4943 {
4944         return event->add;
4945 }
4946
4947 /**
4948  * mono_event_get_remove_method:
4949  * @event: The MonoEvent to act on.
4950  *
4951  * Returns: the @remove method for the event (a MonoMethod).
4952  */
4953 MonoMethod*
4954 mono_event_get_remove_method (MonoEvent *event)
4955 {
4956         return event->remove;
4957 }
4958
4959 /**
4960  * mono_event_get_raise_method:
4961  * @event: The MonoEvent to act on.
4962  *
4963  * Returns: the @raise method for the event (a MonoMethod).
4964  */
4965 MonoMethod*
4966 mono_event_get_raise_method (MonoEvent *event)
4967 {
4968         return event->raise;
4969 }
4970
4971 /**
4972  * mono_event_get_parent:
4973  * @event: the MonoEvent to act on.
4974  *
4975  * Returns: the MonoClass where the event is defined.
4976  */
4977 MonoClass*
4978 mono_event_get_parent (MonoEvent *event)
4979 {
4980         return event->parent;
4981 }
4982
4983 /**
4984  * mono_event_get_flags
4985  * @event: the MonoEvent to act on.
4986  *
4987  * The metadata flags for an event are encoded using the
4988  * EVENT_* constants.  See the tabledefs.h file for details.
4989  *
4990  * Returns: the flags for the event.
4991  */
4992 guint32
4993 mono_event_get_flags (MonoEvent *event)
4994 {
4995         return event->attrs;
4996 }
4997
4998 /**
4999  * mono_class_get_method_from_name:
5000  * @klass: where to look for the method
5001  * @name_space: name of the method
5002  * @param_count: number of parameters. -1 for any number.
5003  *
5004  * Obtains a MonoMethod with a given name and number of parameters.
5005  * It only works if there are no multiple signatures for any given method name.
5006  */
5007 MonoMethod *
5008 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
5009 {
5010         return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
5011 }
5012
5013 /**
5014  * mono_class_get_method_from_name_flags:
5015  * @klass: where to look for the method
5016  * @name_space: name of the method
5017  * @param_count: number of parameters. -1 for any number.
5018  * @flags: flags which must be set in the method
5019  *
5020  * Obtains a MonoMethod with a given name and number of parameters.
5021  * It only works if there are no multiple signatures for any given method name.
5022  */
5023 MonoMethod *
5024 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
5025 {
5026         MonoMethod *res = NULL;
5027         int i;
5028
5029         mono_class_init (klass);
5030
5031         if (klass->methods) {
5032                 mono_class_setup_methods (klass);
5033                 for (i = 0; i < klass->method.count; ++i) {
5034                         MonoMethod *method = klass->methods [i];
5035
5036                         if (method->name[0] == name [0] && 
5037                                 !strcmp (name, method->name) &&
5038                                 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
5039                                 ((method->flags & flags) == flags)) {
5040                                 res = method;
5041                                 break;
5042                         }
5043                 }
5044         }
5045         else {
5046                 /* Search directly in the metadata to avoid calling setup_methods () */
5047                 for (i = 0; i < klass->method.count; ++i) {
5048                         guint32 cols [MONO_METHOD_SIZE];
5049                         MonoMethod *method;
5050
5051                         mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_METHOD], klass->method.first + i, cols, MONO_METHOD_SIZE);
5052
5053                         if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
5054                                 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
5055                                 if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
5056                                         res = method;
5057                                         break;
5058                                 }
5059                         }
5060                 }
5061         }
5062
5063         return res;
5064 }
5065
5066 /**
5067  * mono_class_set_failure:
5068  * @klass: class in which the failure was detected
5069  * @ex_type: the kind of exception/error to be thrown (later)
5070  * @ex_data: exception data (specific to each type of exception/error)
5071  *
5072  * Keep a detected failure informations in the class for later processing.
5073  * Note that only the first failure is kept.
5074  */
5075 gboolean
5076 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
5077 {
5078         if (klass->exception_type)
5079                 return FALSE;
5080         klass->exception_type = ex_type;
5081         klass->exception_data = ex_data;
5082         return TRUE;
5083 }
5084
5085 /**
5086  * mono_classes_init:
5087  *
5088  * Initialize the resources used by this module.
5089  */
5090 void
5091 mono_classes_init (void)
5092 {
5093 }
5094
5095 /**
5096  * mono_classes_cleanup:
5097  *
5098  * Free the resources used by this module.
5099  */
5100 void
5101 mono_classes_cleanup (void)
5102 {
5103         IOffsetInfo *cached_info, *next;
5104
5105         if (global_interface_bitset)
5106                 mono_bitset_free (global_interface_bitset);
5107
5108         for (cached_info = cached_offset_info; cached_info;) {
5109                 next = cached_info->next;
5110
5111                 g_free (cached_info);
5112                 cached_info = next;
5113         }
5114 }
5115
5116 /**
5117  * mono_class_get_exception_for_failure:
5118  * @klass: class in which the failure was detected
5119  *
5120  * Return a constructed MonoException than the caller can then throw
5121  * using mono_raise_exception - or NULL if no failure is present (or
5122  * doesn't result in an exception).
5123  */
5124 MonoException*
5125 mono_class_get_exception_for_failure (MonoClass *klass)
5126 {
5127         switch (klass->exception_type) {
5128         case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
5129                 MonoDomain *domain = mono_domain_get ();
5130                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
5131                 MonoMethod *method = klass->exception_data;
5132                 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
5133                 MonoObject *exc = NULL;
5134                 gpointer args [4];
5135
5136                 args [0] = &error;
5137                 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
5138                 args [2] = mono_type_get_object (domain, &klass->byval_arg);
5139                 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
5140
5141                 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
5142                 return (MonoException*) exc;
5143         }
5144         case MONO_EXCEPTION_TYPE_LOAD:
5145                 return mono_exception_from_name (mono_defaults.corlib, "System", "TypeLoadException");
5146
5147         default: {
5148                 MonoLoaderError *error;
5149                 MonoException *ex;
5150                 
5151                 error = mono_loader_get_last_error ();
5152                 if (error != NULL){
5153                         ex = mono_loader_error_prepare_exception (error);
5154                         return ex;
5155                 }
5156                 
5157                 /* TODO - handle other class related failures */
5158                 return NULL;
5159         }
5160         }
5161 }