2006-09-01 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         mono_stats.generic_vtable_count ++;
1779
1780         if (class->generic_class) {
1781                 context = class->generic_class->context;
1782                 type_token = class->generic_class->container_class->type_token;
1783         } else {
1784                 context = (MonoGenericContext *) class->generic_container;              
1785                 type_token = class->type_token;
1786         }
1787
1788         if (class->image->dynamic)
1789                 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
1790         else {
1791                 /* The following call fails if there are missing methods in the type */
1792                 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
1793         }
1794
1795         if (ok)
1796                 mono_class_setup_vtable_general (class, overrides, onum);
1797                 
1798         g_free (overrides);
1799
1800         mono_loader_unlock ();
1801
1802         return;
1803 }
1804
1805 /*
1806  * LOCKING: this is supposed to be called with the loader lock held.
1807  */
1808 void
1809 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
1810 {
1811         MonoClass *k, *ic;
1812         MonoMethod **vtable;
1813         int i, max_vtsize = 0, max_iid, cur_slot = 0;
1814         GPtrArray *ifaces, *pifaces = NULL;
1815         GHashTable *override_map = NULL;
1816         gboolean security_enabled = mono_is_security_manager_active ();
1817
1818         if (class->vtable)
1819                 return;
1820
1821         ifaces = mono_class_get_implemented_interfaces (class);
1822         if (ifaces) {
1823                 for (i = 0; i < ifaces->len; i++) {
1824                         MonoClass *ic = g_ptr_array_index (ifaces, i);
1825                         max_vtsize += ic->method.count;
1826                 }
1827                 g_ptr_array_free (ifaces, TRUE);
1828         }
1829         
1830         if (class->parent) {
1831                 mono_class_init (class->parent);
1832                 mono_class_setup_vtable (class->parent);
1833                 max_vtsize += class->parent->vtable_size;
1834                 cur_slot = class->parent->vtable_size;
1835         }
1836
1837         max_vtsize += class->method.count;
1838
1839         vtable = alloca (sizeof (gpointer) * max_vtsize);
1840         memset (vtable, 0, sizeof (gpointer) * max_vtsize);
1841
1842         /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
1843
1844         cur_slot = setup_interface_offsets (class, cur_slot);
1845         max_iid = class->max_interface_id;
1846
1847         if (class->parent && class->parent->vtable_size)
1848                 memcpy (vtable, class->parent->vtable,  sizeof (gpointer) * class->parent->vtable_size);
1849
1850         /* override interface methods */
1851         for (i = 0; i < onum; i++) {
1852                 MonoMethod *decl = overrides [i*2];
1853                 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
1854                         int dslot;
1855                         mono_class_setup_methods (decl->klass);
1856                         g_assert (decl->slot != -1);
1857                         dslot = decl->slot + class->interface_offsets [decl->klass->interface_id];
1858                         vtable [dslot] = overrides [i*2 + 1];
1859                         vtable [dslot]->slot = dslot;
1860                         if (!override_map)
1861                                 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
1862
1863                         g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
1864                 }
1865         }
1866
1867         for (k = class; k ; k = k->parent) {
1868                 int nifaces = 0;
1869
1870                 ifaces = mono_class_get_implemented_interfaces (k);
1871                 if (ifaces) {
1872                         nifaces = ifaces->len;
1873                         if (k->generic_class) {
1874                                 pifaces = mono_class_get_implemented_interfaces (
1875                                         k->generic_class->container_class);
1876                                 g_assert (pifaces && (pifaces->len == nifaces));
1877                         }
1878                 }
1879                 for (i = 0; i < nifaces; i++) {
1880                         MonoClass *pic = NULL;
1881                         int j, l, io;
1882
1883                         ic = g_ptr_array_index (ifaces, i);
1884                         if (pifaces)
1885                                 pic = g_ptr_array_index (pifaces, i);
1886                         g_assert (ic->interface_id <= k->max_interface_id);
1887                         io = k->interface_offsets [ic->interface_id];
1888
1889                         g_assert (io >= 0);
1890                         g_assert (io <= max_vtsize);
1891
1892                         if (k == class) {
1893                                 mono_class_setup_methods (ic);
1894                                 for (l = 0; l < ic->method.count; l++) {
1895                                         MonoMethod *im = ic->methods [l];                                               
1896
1897                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1898                                                 continue;
1899
1900                                         for (j = 0; j < class->method.count; ++j) {
1901                                                 MonoMethod *cm = class->methods [j];
1902                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
1903                                                     !((cm->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) ||
1904                                                     !(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT))
1905                                                         continue;
1906                                                 if (!strcmp(cm->name, im->name) && 
1907                                                     mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
1908
1909                                                         /* CAS - SecurityAction.InheritanceDemand on interface */
1910                                                         if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
1911                                                                 mono_secman_inheritancedemand_method (cm, im);
1912                                                         }
1913
1914                                                         g_assert (io + l <= max_vtsize);
1915                                                         vtable [io + l] = cm;
1916                                                 }
1917                                         }
1918                                 }
1919                         } else {
1920                                 /* already implemented */
1921                                 if (io >= k->vtable_size)
1922                                         continue;
1923                         }
1924                                 
1925                         for (l = 0; l < ic->method.count; l++) {
1926                                 MonoMethod *im = ic->methods [l];                                               
1927                                 MonoClass *k1;
1928
1929                                 g_assert (io + l <= max_vtsize);
1930
1931                                 if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1932                                         continue;
1933                                         
1934                                 for (k1 = class; k1; k1 = k1->parent) {
1935                                         for (j = 0; j < k1->method.count; ++j) {
1936                                                 MonoMethod *cm = k1->methods [j];
1937
1938                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
1939                                                     !(cm->flags & METHOD_ATTRIBUTE_PUBLIC))
1940                                                         continue;
1941                                                 
1942                                                 if (!strcmp(cm->name, im->name) && 
1943                                                     mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
1944
1945                                                         /* CAS - SecurityAction.InheritanceDemand on interface */
1946                                                         if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
1947                                                                 mono_secman_inheritancedemand_method (cm, im);
1948                                                         }
1949
1950                                                         g_assert (io + l <= max_vtsize);
1951                                                         vtable [io + l] = cm;
1952                                                         break;
1953                                                 }
1954                                                 
1955                                         }
1956                                         g_assert (io + l <= max_vtsize);
1957                                         if (vtable [io + l] && !(vtable [io + l]->flags & METHOD_ATTRIBUTE_ABSTRACT))
1958                                                 break;
1959                                 }
1960                         }
1961
1962                         for (l = 0; l < ic->method.count; l++) {
1963                                 MonoMethod *im = ic->methods [l];                                               
1964                                 char *qname, *fqname, *cname, *the_cname;
1965                                 MonoClass *k1;
1966                                 
1967                                 if (vtable [io + l])
1968                                         continue;
1969
1970                                 if (pic) {
1971                                         the_cname = mono_type_get_name_full (&pic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
1972                                         cname = the_cname;
1973                                 } else {
1974                                         the_cname = NULL;
1975                                         cname = (char*)ic->name;
1976                                 }
1977                                         
1978                                 qname = g_strconcat (cname, ".", im->name, NULL);
1979                                 if (ic->name_space && ic->name_space [0])
1980                                         fqname = g_strconcat (ic->name_space, ".", cname, ".", im->name, NULL);
1981                                 else
1982                                         fqname = NULL;
1983
1984                                 for (k1 = class; k1; k1 = k1->parent) {
1985                                         for (j = 0; j < k1->method.count; ++j) {
1986                                                 MonoMethod *cm = k1->methods [j];
1987
1988                                                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
1989                                                         continue;
1990
1991                                                 if (((fqname && !strcmp (cm->name, fqname)) || !strcmp (cm->name, qname)) &&
1992                                                     mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
1993
1994                                                         /* CAS - SecurityAction.InheritanceDemand on interface */
1995                                                         if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
1996                                                                 mono_secman_inheritancedemand_method (cm, im);
1997                                                         }
1998
1999                                                         g_assert (io + l <= max_vtsize);
2000                                                         vtable [io + l] = cm;
2001                                                         break;
2002                                                 }
2003                                         }
2004                                 }
2005                                 g_free (the_cname);
2006                                 g_free (qname);
2007                                 g_free (fqname);
2008                         }
2009
2010                         
2011                         if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
2012                                 for (l = 0; l < ic->method.count; l++) {
2013                                         char *msig;
2014                                         MonoMethod *im = ic->methods [l];
2015                                         if (im->flags & METHOD_ATTRIBUTE_STATIC)
2016                                                         continue;
2017                                         g_assert (io + l <= max_vtsize);
2018
2019                                         /* 
2020                                          * If one of our parents already implements this interface
2021                                          * we can inherit the implementation.
2022                                          */
2023                                         if (!(vtable [io + l])) {
2024                                                 MonoClass *parent = class->parent;
2025                                                 
2026                                                 for (; parent; parent = parent->parent) {
2027                                                         if ((ic->interface_id <= parent->max_interface_id) && 
2028                                                                         (parent->interface_offsets [ic->interface_id] != -1) &&
2029                                                                         parent->vtable) {
2030                                                                 vtable [io + l] = parent->vtable [parent->interface_offsets [ic->interface_id] + l];
2031                                                         }
2032                                                 }
2033                                         }
2034
2035                                         if (!(vtable [io + l])) {
2036                                                 for (j = 0; j < onum; ++j) {
2037                                                         g_print (" at slot %d: %s (%d) overrides %s (%d)\n", io+l, overrides [j*2+1]->name, 
2038                                                                  overrides [j*2+1]->slot, overrides [j*2]->name, overrides [j*2]->slot);
2039                                                 }
2040                                                 msig = mono_signature_get_desc (mono_method_signature (im), FALSE);
2041                                                 printf ("no implementation for interface method %s::%s(%s) in class %s.%s\n",
2042                                                         mono_type_get_name (&ic->byval_arg), im->name, msig, class->name_space, class->name);
2043                                                 g_free (msig);
2044                                                 for (j = 0; j < class->method.count; ++j) {
2045                                                         MonoMethod *cm = class->methods [j];
2046                                                         msig = mono_signature_get_desc (mono_method_signature (cm), TRUE);
2047                                                         
2048                                                         printf ("METHOD %s(%s)\n", cm->name, msig);
2049                                                         g_free (msig);
2050                                                 }
2051                                                 g_assert_not_reached ();
2052                                         }
2053                                 }
2054                         }
2055                 
2056                         for (l = 0; l < ic->method.count; l++) {
2057                                 MonoMethod *im = vtable [io + l];
2058
2059                                 if (im) {
2060                                         g_assert (io + l <= max_vtsize);
2061                                         if (im->slot < 0) {
2062                                                 /* FIXME: why do we need this ? */
2063                                                 im->slot = io + l;
2064                                                 /* g_assert_not_reached (); */
2065                                         }
2066                                 }
2067                         }
2068                 }
2069                 if (ifaces)
2070                         g_ptr_array_free (ifaces, TRUE);
2071         } 
2072
2073         for (i = 0; i < class->method.count; ++i) {
2074                 MonoMethod *cm;
2075                
2076                 cm = class->methods [i];
2077                 
2078                 /*
2079                  * Non-virtual method have no place in the vtable.
2080                  * This also catches static methods (since they are not virtual).
2081                  */
2082                 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
2083                         continue;
2084                 
2085                 /*
2086                  * If the method is REUSE_SLOT, we must check in the
2087                  * base class for a method to override.
2088                  */
2089                 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
2090                         int slot = -1;
2091                         for (k = class->parent; k ; k = k->parent) {
2092                                 int j;
2093                                 for (j = 0; j < k->method.count; ++j) {
2094                                         MonoMethod *m1 = k->methods [j];
2095                                         MonoMethodSignature *cmsig, *m1sig;
2096
2097                                         if (!(m1->flags & METHOD_ATTRIBUTE_VIRTUAL))
2098                                                 continue;
2099
2100                                         cmsig = mono_method_signature (cm);
2101                                         m1sig = mono_method_signature (m1);
2102
2103                                         if (!cmsig || !m1sig) {
2104                                                 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
2105                                                 return;
2106                                         }
2107
2108                                         if (!strcmp(cm->name, m1->name) && 
2109                                             mono_metadata_signature_equal (cmsig, m1sig)) {
2110
2111                                                 /* CAS - SecurityAction.InheritanceDemand */
2112                                                 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2113                                                         mono_secman_inheritancedemand_method (cm, m1);
2114                                                 }
2115
2116                                                 slot = k->methods [j]->slot;
2117                                                 g_assert (cm->slot < max_vtsize);
2118                                                 if (!override_map)
2119                                                         override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
2120                                                 g_hash_table_insert (override_map, m1, cm);
2121                                                 break;
2122                                         }
2123                                 }
2124                                 if (slot >= 0) 
2125                                         break;
2126                         }
2127                         if (slot >= 0)
2128                                 cm->slot = slot;
2129                 }
2130
2131                 if (cm->slot < 0)
2132                         cm->slot = cur_slot++;
2133
2134                 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
2135                         vtable [cm->slot] = cm;
2136         }
2137
2138         /* override non interface methods */
2139         for (i = 0; i < onum; i++) {
2140                 MonoMethod *decl = overrides [i*2];
2141                 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
2142                         g_assert (decl->slot != -1);
2143                         vtable [decl->slot] = overrides [i*2 + 1];
2144                         overrides [i * 2 + 1]->slot = decl->slot;
2145                         if (!override_map)
2146                                 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
2147                         g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
2148                 }
2149         }
2150
2151         /*
2152          * If a method occupies more than one place in the vtable, and it is
2153          * overriden, then change the other occurances too.
2154          */
2155         if (override_map) {
2156                 for (i = 0; i < max_vtsize; ++i)
2157                         if (vtable [i]) {
2158                                 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
2159                                 if (cm)
2160                                         vtable [i] = cm;
2161                         }
2162
2163                 g_hash_table_destroy (override_map);
2164         }
2165
2166         if (class->generic_class) {
2167                 MonoClass *gklass = class->generic_class->container_class;
2168
2169                 mono_class_init (gklass);
2170
2171                 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
2172         } else
2173                 class->vtable_size = cur_slot;
2174
2175         class->vtable = mono_mempool_alloc0 (class->image->mempool, sizeof (gpointer) * class->vtable_size);
2176         memcpy (class->vtable, vtable,  sizeof (gpointer) * class->vtable_size);
2177
2178         if (mono_print_vtable) {
2179                 int icount = 0;
2180
2181                 for (i = 0; i <= max_iid; i++)
2182                         if (class->interface_offsets [i] != -1)
2183                                 icount++;
2184
2185                 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg), 
2186                         class->vtable_size, icount); 
2187
2188                 for (i = 0; i < class->vtable_size; ++i) {
2189                         MonoMethod *cm;
2190                
2191                         cm = vtable [i];
2192                         if (cm) {
2193                                 printf ("  slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
2194                                         mono_method_full_name (cm, TRUE));
2195                         }
2196                 }
2197
2198
2199                 if (icount) {
2200                         printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space, 
2201                                 class->name, max_iid);
2202         
2203                         for (i = 0; i < class->interface_count; i++) {
2204                                 ic = class->interfaces [i];
2205                                 printf ("  slot offset: %03d, method count: %03d, iid: %03d %s\n",  
2206                                         class->interface_offsets [ic->interface_id],
2207                                         ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
2208                         }
2209
2210                         for (k = class->parent; k ; k = k->parent) {
2211                                 for (i = 0; i < k->interface_count; i++) {
2212                                         ic = k->interfaces [i]; 
2213                                         printf ("  slot offset: %03d, method count: %03d, iid: %03d %s\n",  
2214                                                 class->interface_offsets [ic->interface_id],
2215                                                 ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
2216                                 }
2217                         }
2218                 }
2219         }
2220 }
2221
2222 static MonoMethod *default_ghc = NULL;
2223 static MonoMethod *default_finalize = NULL;
2224 static int finalize_slot = -1;
2225 static int ghc_slot = -1;
2226
2227 static void
2228 initialize_object_slots (MonoClass *class)
2229 {
2230         int i;
2231         if (default_ghc)
2232                 return;
2233         if (class == mono_defaults.object_class) { 
2234                 mono_class_setup_vtable (class);                       
2235                 for (i = 0; i < class->vtable_size; ++i) {
2236                         MonoMethod *cm = class->vtable [i];
2237        
2238                         if (!strcmp (cm->name, "GetHashCode"))
2239                                 ghc_slot = i;
2240                         else if (!strcmp (cm->name, "Finalize"))
2241                                 finalize_slot = i;
2242                 }
2243
2244                 g_assert (ghc_slot > 0);
2245                 default_ghc = class->vtable [ghc_slot];
2246
2247                 g_assert (finalize_slot > 0);
2248                 default_finalize = class->vtable [finalize_slot];
2249         }
2250 }
2251
2252 static GList*
2253 g_list_prepend_mempool (GList* l, MonoMemPool* mp, gpointer datum)
2254 {
2255         GList* n = mono_mempool_alloc (mp, sizeof (GList));
2256         n->next = l;
2257         n->prev = NULL;
2258         n->data = datum;
2259         return n;
2260 }
2261
2262 /**
2263  * mono_class_init:
2264  * @class: the class to initialize
2265  *
2266  * compute the instance_size, class_size and other infos that cannot be 
2267  * computed at mono_class_get() time. Also compute a generic vtable and 
2268  * the method slot numbers. We use this infos later to create a domain
2269  * specific vtable.
2270  *
2271  * Returns TRUE on success or FALSE if there was a problem in loading
2272  * the type (incorrect assemblies, missing assemblies, methods, etc). 
2273  */
2274 gboolean
2275 mono_class_init (MonoClass *class)
2276 {
2277         int i;
2278         MonoCachedClassInfo cached_info;
2279         gboolean has_cached_info;
2280         int class_init_ok = TRUE;
2281         
2282         g_assert (class);
2283
2284         if (class->inited)
2285                 return TRUE;
2286
2287         /*g_print ("Init class %s\n", class->name);*/
2288
2289         /* We do everything inside the lock to prevent races */
2290         mono_loader_lock ();
2291
2292         if (class->inited) {
2293                 mono_loader_unlock ();
2294                 /* Somebody might have gotten in before us */
2295                 return TRUE;
2296         }
2297
2298         if (class->init_pending) {
2299                 mono_loader_unlock ();
2300                 /* this indicates a cyclic dependency */
2301                 g_error ("pending init %s.%s\n", class->name_space, class->name);
2302         }
2303
2304         class->init_pending = 1;
2305
2306         /* CAS - SecurityAction.InheritanceDemand */
2307         if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
2308                 mono_secman_inheritancedemand_class (class, class->parent);
2309         }
2310
2311         if (mono_debugger_start_class_init_func)
2312                 mono_debugger_start_class_init_func (class);
2313
2314         mono_stats.initialized_class_count++;
2315
2316         if (class->generic_class && !class->generic_class->is_dynamic) {
2317                 MonoInflatedGenericClass *gclass;
2318                 MonoClass *gklass;
2319
2320                 gclass = mono_get_inflated_generic_class (class->generic_class);
2321                 gklass = gclass->generic_class.container_class;
2322
2323                 mono_stats.generic_class_count++;
2324
2325                 class->method = gklass->method;
2326                 class->field = gklass->field;
2327
2328                 mono_class_init (gklass);
2329                 mono_class_setup_methods (gklass);
2330                 mono_class_setup_properties (gklass);
2331
2332                 if (MONO_CLASS_IS_INTERFACE (class))
2333                         class->interface_id = mono_get_unique_iid (class);
2334
2335                 g_assert (class->method.count == gklass->method.count);
2336                 class->methods = g_new0 (MonoMethod *, class->method.count);
2337
2338                 for (i = 0; i < class->method.count; i++) {
2339                         MonoMethod *inflated = mono_class_inflate_generic_method_full (
2340                                 gklass->methods [i], class, gclass->generic_class.context);
2341
2342                         class->methods [i] = mono_get_inflated_method (inflated);
2343                 }
2344
2345                 class->property = gklass->property;
2346                 class->properties = g_new0 (MonoProperty, class->property.count);
2347
2348                 for (i = 0; i < class->property.count; i++) {
2349                         MonoProperty *prop = &class->properties [i];
2350
2351                         *prop = gklass->properties [i];
2352
2353                         if (prop->get)
2354                                 prop->get = mono_class_inflate_generic_method_full (
2355                                         prop->get, class, gclass->generic_class.context);
2356                         if (prop->set)
2357                                 prop->set = mono_class_inflate_generic_method_full (
2358                                         prop->set, class, gclass->generic_class.context);
2359
2360                         prop->parent = class;
2361                 }
2362
2363                 g_assert (class->interface_count == gklass->interface_count);
2364         }
2365
2366         if (class->parent && !class->parent->inited)
2367                 mono_class_init (class->parent);
2368
2369         has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
2370
2371         if (!class->generic_class && (!has_cached_info || (has_cached_info && cached_info.has_nested_classes))) {
2372                 i = mono_metadata_nesting_typedef (class->image, class->type_token, 1);
2373                 while (i) {
2374                         MonoClass* nclass;
2375                         guint32 cols [MONO_NESTED_CLASS_SIZE];
2376                         mono_metadata_decode_row (&class->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
2377                         nclass = mono_class_create_from_typedef (class->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
2378                         class->nested_classes = g_list_prepend_mempool (class->nested_classes, class->image->mempool, nclass);
2379
2380                         i = mono_metadata_nesting_typedef (class->image, class->type_token, i + 1);
2381                 }
2382         }
2383
2384         /*
2385          * Computes the size used by the fields, and their locations
2386          */
2387         if (has_cached_info) {
2388                 class->instance_size = cached_info.instance_size;
2389                 class->class_size = cached_info.class_size;
2390                 class->packing_size = cached_info.packing_size;
2391                 class->min_align = cached_info.min_align;
2392                 class->blittable = cached_info.blittable;
2393                 class->has_references = cached_info.has_references;
2394                 class->has_static_refs = cached_info.has_static_refs;
2395         }
2396         else
2397                 if (!class->size_inited){
2398                         mono_class_setup_fields (class);
2399                         if (class->exception_type || mono_loader_get_last_error ()){
2400                                 class_init_ok = FALSE;
2401                                 goto leave;
2402                         }
2403                 }
2404                                 
2405
2406         /* initialize method pointers */
2407         if (class->rank) {
2408                 MonoMethod *ctor;
2409                 MonoMethodSignature *sig;
2410                 class->method.count = class->rank > 1? 2: 1;
2411                 sig = mono_metadata_signature_alloc (class->image, class->rank);
2412                 sig->ret = &mono_defaults.void_class->byval_arg;
2413                 sig->pinvoke = TRUE;
2414                 for (i = 0; i < class->rank; ++i)
2415                         sig->params [i] = &mono_defaults.int32_class->byval_arg;
2416
2417                 ctor = (MonoMethod *) mono_mempool_alloc0 (class->image->mempool, sizeof (MonoMethodPInvoke));
2418                 ctor->klass = class;
2419                 ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
2420                 ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
2421                 ctor->signature = sig;
2422                 ctor->name = ".ctor";
2423                 ctor->slot = -1;
2424                 class->methods = mono_mempool_alloc0 (class->image->mempool, sizeof (MonoMethod*) * class->method.count);
2425                 class->methods [0] = ctor;
2426                 if (class->rank > 1) {
2427                         sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
2428                         sig->ret = &mono_defaults.void_class->byval_arg;
2429                         sig->pinvoke = TRUE;
2430                         for (i = 0; i < class->rank * 2; ++i)
2431                                 sig->params [i] = &mono_defaults.int32_class->byval_arg;
2432
2433                         ctor = (MonoMethod *) mono_mempool_alloc0 (class->image->mempool, sizeof (MonoMethodPInvoke));
2434                         ctor->klass = class;
2435                         ctor->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
2436                         ctor->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
2437                         ctor->signature = sig;
2438                         ctor->name = ".ctor";
2439                         ctor->slot = -1;
2440                         class->methods [1] = ctor;
2441                 }
2442         }
2443
2444         mono_class_setup_supertypes (class);
2445
2446         if (!default_ghc)
2447                 initialize_object_slots (class);
2448
2449         /*
2450          * If possible, avoid the creation of the generic vtable by requesting
2451          * cached info from the runtime.
2452          */
2453         if (has_cached_info) {
2454                 guint32 cur_slot = 0;
2455
2456                 class->vtable_size = cached_info.vtable_size;
2457                 class->has_finalize = cached_info.has_finalize;
2458                 class->ghcimpl = cached_info.ghcimpl;
2459                 class->has_cctor = cached_info.has_cctor;
2460
2461                 if (class->parent) {
2462                         mono_class_init (class->parent);
2463                         cur_slot = class->parent->vtable_size;
2464                 }
2465
2466                 setup_interface_offsets (class, cur_slot);
2467         }
2468         else {
2469                 mono_class_setup_vtable (class);
2470
2471                 if (class->exception_type || mono_loader_get_last_error ()){
2472                         class_init_ok = FALSE;
2473                         goto leave;
2474                 }
2475
2476                 class->ghcimpl = 1;
2477                 if (class->parent) { 
2478                         MonoMethod *cmethod = class->vtable [ghc_slot];
2479                         if (cmethod->is_inflated)
2480                                 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
2481                         if (cmethod == default_ghc) {
2482                                 class->ghcimpl = 0;
2483                         }
2484                 }
2485
2486                 /* Object::Finalize should have empty implemenatation */
2487                 class->has_finalize = 0;
2488                 if (class->parent) { 
2489                         MonoMethod *cmethod = class->vtable [finalize_slot];
2490                         if (cmethod->is_inflated)
2491                                 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
2492                         if (cmethod != default_finalize) {
2493                                 class->has_finalize = 1;
2494                         }
2495                 }
2496
2497                 for (i = 0; i < class->method.count; ++i) {
2498                         MonoMethod *method = class->methods [i];
2499                         if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
2500                                 (strcmp (".cctor", method->name) == 0)) {
2501                                 class->has_cctor = 1;
2502                                 break;
2503                         }
2504                 }
2505         }
2506
2507         if (MONO_CLASS_IS_INTERFACE (class)) {
2508                 /* 
2509                  * class->interface_offsets is needed for the castclass/isinst code, so
2510                  * we have to setup them for interfaces, too.
2511                  */
2512                 setup_interface_offsets (class, 0);
2513         }
2514
2515  leave:
2516         class->inited = 1;
2517         class->init_pending = 0;
2518
2519         mono_loader_unlock ();
2520
2521         if (mono_debugger_class_init_func)
2522                 mono_debugger_class_init_func (class);
2523
2524         return class_init_ok;
2525 }
2526
2527 /*
2528  * LOCKING: this assumes the loader lock is held
2529  */
2530 void
2531 mono_class_setup_mono_type (MonoClass *class)
2532 {
2533         const char *name = class->name;
2534         const char *nspace = class->name_space;
2535
2536         class->this_arg.byref = 1;
2537         class->this_arg.data.klass = class;
2538         class->this_arg.type = MONO_TYPE_CLASS;
2539         class->byval_arg.data.klass = class;
2540         class->byval_arg.type = MONO_TYPE_CLASS;
2541
2542         if (!strcmp (nspace, "System")) {
2543                 if (!strcmp (name, "ValueType")) {
2544                         /*
2545                          * do not set the valuetype bit for System.ValueType.
2546                          * class->valuetype = 1;
2547                          */
2548                         class->blittable = TRUE;
2549                 } else if (!strcmp (name, "Enum")) {
2550                         /*
2551                          * do not set the valuetype bit for System.Enum.
2552                          * class->valuetype = 1;
2553                          */
2554                         class->valuetype = 0;
2555                         class->enumtype = 0;
2556                 } else if (!strcmp (name, "Object")) {
2557                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
2558                 } else if (!strcmp (name, "String")) {
2559                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
2560                 } else if (!strcmp (name, "TypedReference")) {
2561                         class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
2562                 }
2563         }
2564         
2565         if (class->valuetype) {
2566                 int t = MONO_TYPE_VALUETYPE;
2567                 if (!strcmp (nspace, "System")) {
2568                         switch (*name) {
2569                         case 'B':
2570                                 if (!strcmp (name, "Boolean")) {
2571                                         t = MONO_TYPE_BOOLEAN;
2572                                 } else if (!strcmp(name, "Byte")) {
2573                                         t = MONO_TYPE_U1;
2574                                         class->blittable = TRUE;                                                
2575                                 }
2576                                 break;
2577                         case 'C':
2578                                 if (!strcmp (name, "Char")) {
2579                                         t = MONO_TYPE_CHAR;
2580                                 }
2581                                 break;
2582                         case 'D':
2583                                 if (!strcmp (name, "Double")) {
2584                                         t = MONO_TYPE_R8;
2585                                         class->blittable = TRUE;                                                
2586                                 }
2587                                 break;
2588                         case 'I':
2589                                 if (!strcmp (name, "Int32")) {
2590                                         t = MONO_TYPE_I4;
2591                                         class->blittable = TRUE;
2592                                 } else if (!strcmp(name, "Int16")) {
2593                                         t = MONO_TYPE_I2;
2594                                         class->blittable = TRUE;
2595                                 } else if (!strcmp(name, "Int64")) {
2596                                         t = MONO_TYPE_I8;
2597                                         class->blittable = TRUE;
2598                                 } else if (!strcmp(name, "IntPtr")) {
2599                                         t = MONO_TYPE_I;
2600                                         class->blittable = TRUE;
2601                                 }
2602                                 break;
2603                         case 'S':
2604                                 if (!strcmp (name, "Single")) {
2605                                         t = MONO_TYPE_R4;
2606                                         class->blittable = TRUE;                                                
2607                                 } else if (!strcmp(name, "SByte")) {
2608                                         t = MONO_TYPE_I1;
2609                                         class->blittable = TRUE;
2610                                 }
2611                                 break;
2612                         case 'U':
2613                                 if (!strcmp (name, "UInt32")) {
2614                                         t = MONO_TYPE_U4;
2615                                         class->blittable = TRUE;
2616                                 } else if (!strcmp(name, "UInt16")) {
2617                                         t = MONO_TYPE_U2;
2618                                         class->blittable = TRUE;
2619                                 } else if (!strcmp(name, "UInt64")) {
2620                                         t = MONO_TYPE_U8;
2621                                         class->blittable = TRUE;
2622                                 } else if (!strcmp(name, "UIntPtr")) {
2623                                         t = MONO_TYPE_U;
2624                                         class->blittable = TRUE;
2625                                 }
2626                                 break;
2627                         case 'T':
2628                                 if (!strcmp (name, "TypedReference")) {
2629                                         t = MONO_TYPE_TYPEDBYREF;
2630                                         class->blittable = TRUE;
2631                                 }
2632                                 break;
2633                         case 'V':
2634                                 if (!strcmp (name, "Void")) {
2635                                         t = MONO_TYPE_VOID;
2636                                 }
2637                                 break;
2638                         default:
2639                                 break;
2640                         }
2641                 }
2642                 class->this_arg.type = class->byval_arg.type = t;
2643         }
2644
2645         if (MONO_CLASS_IS_INTERFACE (class))
2646                 class->interface_id = mono_get_unique_iid (class);
2647
2648 }
2649
2650 /*
2651  * LOCKING: this assumes the loader lock is held
2652  */
2653 void
2654 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
2655 {
2656         gboolean system_namespace;
2657
2658         system_namespace = !strcmp (class->name_space, "System");
2659
2660         /* if root of the hierarchy */
2661         if (system_namespace && !strcmp (class->name, "Object")) {
2662                 class->parent = NULL;
2663                 class->instance_size = sizeof (MonoObject);
2664                 return;
2665         }
2666         if (!strcmp (class->name, "<Module>")) {
2667                 class->parent = NULL;
2668                 class->instance_size = 0;
2669                 return;
2670         }
2671
2672         if (!MONO_CLASS_IS_INTERFACE (class)) {
2673                 /* Imported COM Objects always derive from __ComObject. */
2674                 if (MONO_CLASS_IS_IMPORT (class)) {
2675                         if (parent == mono_defaults.object_class)
2676                                 parent = mono_defaults.com_object_class;
2677                 }
2678                 class->parent = parent;
2679
2680
2681                 if (!parent)
2682                         g_assert_not_reached (); /* FIXME */
2683
2684                 if (parent->generic_class && !parent->name) {
2685                         /*
2686                          * If the parent is a generic instance, we may get
2687                          * called before it is fully initialized, especially
2688                          * before it has its name.
2689                          */
2690                         return;
2691                 }
2692
2693                 class->marshalbyref = parent->marshalbyref;
2694                 class->contextbound  = parent->contextbound;
2695                 class->delegate  = parent->delegate;
2696                 if (MONO_CLASS_IS_IMPORT (class))
2697                         class->is_com_object = 1;
2698                 else
2699                         class->is_com_object = parent->is_com_object;
2700                 
2701                 if (system_namespace) {
2702                         if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
2703                                 class->marshalbyref = 1;
2704
2705                         if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject")) 
2706                                 class->contextbound  = 1;
2707
2708                         if (*class->name == 'D' && !strcmp (class->name, "Delegate")) 
2709                                 class->delegate  = 1;
2710                 }
2711
2712                 if (class->parent->enumtype || ((strcmp (class->parent->name, "ValueType") == 0) && 
2713                                                 (strcmp (class->parent->name_space, "System") == 0)))
2714                         class->valuetype = 1;
2715                 if (((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
2716                         class->valuetype = class->enumtype = 1;
2717                 }
2718                 /*class->enumtype = class->parent->enumtype; */
2719                 mono_class_setup_supertypes (class);
2720         } else {
2721                 class->parent = NULL;
2722         }
2723
2724 }
2725
2726 /*
2727  * mono_class_setup_supertypes:
2728  * @class: a class
2729  *
2730  * Build the data structure needed to make fast type checks work.
2731  * This currently sets two fields in @class:
2732  *  - idepth: distance between @class and System.Object in the type
2733  *    hierarchy + 1
2734  *  - supertypes: array of classes: each element has a class in the hierarchy
2735  *    starting from @class up to System.Object
2736  * 
2737  * LOCKING: this assumes the loader lock is held
2738  */
2739 void
2740 mono_class_setup_supertypes (MonoClass *class)
2741 {
2742         int ms;
2743
2744         if (class->supertypes)
2745                 return;
2746
2747         if (class->parent && !class->parent->supertypes)
2748                 mono_class_setup_supertypes (class->parent);
2749         if (class->parent)
2750                 class->idepth = class->parent->idepth + 1;
2751         else
2752                 class->idepth = 1;
2753
2754         ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
2755         class->supertypes = mono_mempool_alloc0 (class->image->mempool, sizeof (MonoClass *) * ms);
2756
2757         if (class->parent) {
2758                 class->supertypes [class->idepth - 1] = class;
2759                 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
2760         } else {
2761                 class->supertypes [0] = class;
2762         }
2763 }       
2764
2765 MonoGenericInst *
2766 mono_get_shared_generic_inst (MonoGenericContainer *container)
2767 {
2768         MonoGenericInst *nginst;
2769         int i;
2770
2771         nginst = g_new0 (MonoGenericInst, 1);
2772         nginst->type_argc = container->type_argc;
2773         nginst->type_argv = g_new0 (MonoType *, nginst->type_argc);
2774         nginst->is_reference = 1;
2775         nginst->is_open = 1;
2776
2777         for (i = 0; i < nginst->type_argc; i++) {
2778                 MonoType *t = g_new0 (MonoType, 1);
2779
2780                 t->type = container->is_method ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
2781                 t->data.generic_param = &container->type_params [i];
2782
2783                 nginst->type_argv [i] = t;
2784         }
2785
2786         return mono_metadata_lookup_generic_inst (nginst);
2787 }
2788
2789 /*
2790  * In preparation for implementing shared code.
2791  */
2792 MonoGenericClass *
2793 mono_get_shared_generic_class (MonoGenericContainer *container, gboolean is_dynamic)
2794 {
2795         MonoInflatedGenericClass *igclass;
2796         MonoGenericClass *gclass;
2797
2798         if (is_dynamic) {
2799                 MonoDynamicGenericClass *dgclass = g_new0 (MonoDynamicGenericClass, 1);
2800                 igclass = &dgclass->generic_class;
2801                 gclass = &igclass->generic_class;
2802                 gclass->is_inflated = 1;
2803                 gclass->is_dynamic = 1;
2804         } else {
2805                 igclass = g_new0 (MonoInflatedGenericClass, 1);
2806                 gclass = &igclass->generic_class;
2807                 gclass->is_inflated = 1;
2808         }
2809
2810         gclass->context = &container->context;
2811         gclass->container_class = container->klass;
2812         gclass->inst = mono_get_shared_generic_inst (container);
2813
2814         if (!is_dynamic) {
2815                 MonoGenericClass *cached = mono_metadata_lookup_generic_class (gclass);
2816
2817                 if (cached) {
2818                         g_free (gclass);
2819                         return cached;
2820                 }
2821         }
2822
2823         igclass->klass = container->klass;
2824
2825         return gclass;
2826 }
2827
2828 /**
2829  * mono_class_create_from_typedef:
2830  * @image: image where the token is valid
2831  * @type_token:  typedef token
2832  *
2833  * Create the MonoClass* representing the specified type token.
2834  * @type_token must be a TypeDef token.
2835  */
2836 static MonoClass *
2837 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
2838 {
2839         MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
2840         MonoClass *class, *parent = NULL;
2841         guint32 cols [MONO_TYPEDEF_SIZE];
2842         guint32 cols_next [MONO_TYPEDEF_SIZE];
2843         guint tidx = mono_metadata_token_index (type_token);
2844         MonoGenericContext *context = NULL;
2845         const char *name, *nspace;
2846         guint icount = 0; 
2847         MonoClass **interfaces;
2848         guint32 field_last, method_last;
2849         guint32 nesting_tokeen;
2850
2851         mono_loader_lock ();
2852
2853         if ((class = g_hash_table_lookup (image->class_cache, GUINT_TO_POINTER (type_token)))) {
2854                 mono_loader_unlock ();
2855                 return class;
2856         }
2857
2858         g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
2859
2860         mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
2861         
2862         name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2863         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2864
2865         class = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
2866
2867         class->name = name;
2868         class->name_space = nspace;
2869
2870         class->image = image;
2871         class->type_token = type_token;
2872         class->flags = cols [MONO_TYPEDEF_FLAGS];
2873
2874         g_hash_table_insert (image->class_cache, GUINT_TO_POINTER (type_token), class);
2875
2876         /*
2877          * Check whether we're a generic type definition.
2878          */
2879         class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
2880         if (class->generic_container) {
2881                 class->generic_container->klass = class;
2882                 context = &class->generic_container->context;
2883
2884                 context->gclass = mono_get_shared_generic_class (context->container, FALSE);
2885         }
2886
2887         if (cols [MONO_TYPEDEF_EXTENDS]) {
2888                 parent = mono_class_get_full (
2889                         image, mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]), context);
2890                 if (parent == NULL){
2891                         g_hash_table_remove (image->class_cache, GUINT_TO_POINTER (type_token));
2892                         mono_loader_unlock ();
2893                         return NULL;
2894                 }
2895         }
2896
2897         /* do this early so it's available for interfaces in setup_mono_type () */
2898         if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token)))
2899                 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
2900
2901         mono_class_setup_parent (class, parent);
2902
2903         /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
2904         mono_class_setup_mono_type (class);
2905
2906         if (!class->enumtype) {
2907                 if (!mono_metadata_interfaces_from_typedef_full (
2908                             image, type_token, &interfaces, &icount, context)){
2909                         mono_loader_unlock ();
2910                         return NULL;
2911                 }
2912
2913                 class->interfaces = interfaces;
2914                 class->interface_count = icount;
2915         }
2916
2917         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
2918                 class->unicode = 1;
2919
2920 #if PLATFORM_WIN32
2921         if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
2922                 class->unicode = 1;
2923 #endif
2924
2925         class->cast_class = class->element_class = class;
2926
2927         /*g_print ("Load class %s\n", name);*/
2928
2929         /*
2930          * Compute the field and method lists
2931          */
2932         class->field.first  = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
2933         class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
2934
2935         if (tt->rows > tidx){           
2936                 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
2937                 field_last  = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
2938                 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
2939         } else {
2940                 field_last  = image->tables [MONO_TABLE_FIELD].rows;
2941                 method_last = image->tables [MONO_TABLE_METHOD].rows;
2942         }
2943
2944         if (cols [MONO_TYPEDEF_FIELD_LIST] && 
2945             cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
2946                 class->field.count = field_last - class->field.first;
2947         else
2948                 class->field.count = 0;
2949
2950         if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
2951                 class->method.count = method_last - class->method.first;
2952         else
2953                 class->method.count = 0;
2954
2955         /* reserve space to store vector pointer in arrays */
2956         if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
2957                 class->instance_size += 2 * sizeof (gpointer);
2958                 g_assert (class->field.count == 0);
2959         }
2960
2961         if (class->enumtype) {
2962                 class->enum_basetype = mono_class_find_enum_basetype (class);
2963                 class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
2964         }
2965
2966         /*
2967          * If we're a generic type definition, load the constraints.
2968          * We must do this after the class has been constructed to make certain recursive scenarios
2969          * work.
2970          */
2971         if (class->generic_container)
2972                 mono_metadata_load_generic_param_constraints (
2973                         image, type_token, class->generic_container);
2974
2975         mono_loader_unlock ();
2976
2977         return class;
2978 }
2979
2980 /** is klass Nullable<T>? */
2981 gboolean
2982 mono_class_is_nullable (MonoClass *klass)
2983 {
2984        return klass->generic_class != NULL &&
2985                klass->generic_class->container_class == mono_defaults.generic_nullable_class;
2986 }
2987
2988
2989 /** if klass is T? return T */
2990 MonoClass*
2991 mono_class_get_nullable_param (MonoClass *klass)
2992 {
2993        g_assert (mono_class_is_nullable (klass));
2994        return mono_class_from_mono_type (klass->generic_class->inst->type_argv [0]);
2995 }
2996
2997 /*
2998  * Create the `MonoClass' for an instantiation of a generic type.
2999  * We only do this if we actually need it.
3000  */
3001 static void
3002 mono_class_create_generic (MonoInflatedGenericClass *gclass)
3003 {
3004         MonoClass *klass, *gklass;
3005         int i;
3006
3007         mono_loader_lock ();
3008         if (gclass->is_initialized) {
3009                 mono_loader_unlock ();
3010                 return;
3011         }
3012
3013         if (!gclass->klass)
3014                 gclass->klass = g_malloc0 (sizeof (MonoClass));
3015         klass = gclass->klass;
3016
3017         gklass = gclass->generic_class.container_class;
3018
3019         if (gklass->nested_in) {
3020                 /* 
3021                  * FIXME: the nested type context should include everything the
3022                  * nesting context should have, but it may also have additional
3023                  * generic parameters...
3024                  */
3025                 MonoType *inflated = mono_class_inflate_generic_type (
3026                         &gklass->nested_in->byval_arg, gclass->generic_class.context);
3027                 klass->nested_in = mono_class_from_mono_type (inflated);
3028         }
3029
3030         klass->name = gklass->name;
3031         klass->name_space = gklass->name_space;
3032         klass->image = gklass->image;
3033         klass->flags = gklass->flags;
3034         klass->type_token = gklass->type_token;
3035
3036         klass->generic_class = &gclass->generic_class;
3037
3038         klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
3039         klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = &gclass->generic_class;
3040         klass->this_arg.byref = TRUE;
3041
3042         klass->cast_class = klass->element_class = klass;
3043
3044         if (mono_class_is_nullable (klass))
3045                 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
3046
3047         if (gclass->generic_class.is_dynamic) {
3048                 klass->instance_size = gklass->instance_size;
3049                 klass->class_size = gklass->class_size;
3050                 klass->size_inited = 1;
3051                 klass->inited = 1;
3052
3053                 klass->valuetype = gklass->valuetype;
3054
3055                 mono_class_setup_supertypes (klass);
3056         }
3057
3058         klass->interface_count = gklass->interface_count;
3059         klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
3060         for (i = 0; i < klass->interface_count; i++) {
3061                 MonoType *it = &gklass->interfaces [i]->byval_arg;
3062                 MonoType *inflated = mono_class_inflate_generic_type (
3063                         it, gclass->generic_class.context);
3064                 klass->interfaces [i] = mono_class_from_mono_type (inflated);
3065         }
3066
3067         i = mono_metadata_nesting_typedef (klass->image, gklass->type_token, 1);
3068         while (i) {
3069                 MonoClass* nclass;
3070                 guint32 cols [MONO_NESTED_CLASS_SIZE];
3071                 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
3072                 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
3073                 klass->nested_classes = g_list_prepend (klass->nested_classes, nclass);
3074                 
3075                 i = mono_metadata_nesting_typedef (klass->image, gklass->type_token, i + 1);
3076         }
3077
3078         if (gklass->parent) {
3079                 MonoType *inflated = mono_class_inflate_generic_type (
3080                         &gklass->parent->byval_arg, gclass->generic_class.context);
3081
3082                 klass->parent = mono_class_from_mono_type (inflated);
3083         }
3084
3085         if (klass->parent)
3086                 mono_class_setup_parent (klass, klass->parent);
3087
3088         if (MONO_CLASS_IS_INTERFACE (klass))
3089                 setup_interface_offsets (klass, 0);
3090         gclass->is_initialized = TRUE;
3091         mono_loader_unlock ();
3092 }
3093
3094 MonoClass *
3095 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
3096 {
3097         MonoClass *klass, **ptr;
3098         int count, pos, i;
3099
3100         if (param->pklass)
3101                 return param->pklass;
3102
3103         klass = param->pklass = g_new0 (MonoClass, 1);
3104
3105         for (count = 0, ptr = param->constraints; ptr && *ptr; ptr++, count++)
3106                 ;
3107
3108         pos = 0;
3109         if ((count > 0) && !MONO_CLASS_IS_INTERFACE (param->constraints [0])) {
3110                 klass->parent = param->constraints [0];
3111                 pos++;
3112         } else if (param->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
3113                 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
3114         else
3115                 klass->parent = mono_defaults.object_class;
3116
3117         if (count - pos > 0) {
3118                 klass->interface_count = count - pos;
3119                 klass->interfaces = g_new0 (MonoClass *, count - pos);
3120                 for (i = pos; i < count; i++)
3121                         klass->interfaces [i - pos] = param->constraints [i];
3122         }
3123
3124         if (param->name)
3125                 klass->name = param->name;
3126         else
3127                 klass->name = g_strdup_printf (is_mvar ? "!!%d" : "!%d", param->num);
3128
3129         klass->name_space = "";
3130
3131         if (image)
3132                 klass->image = image;
3133         else if (is_mvar && param->method && param->method->klass)
3134                 klass->image = param->method->klass->image;
3135         else if (param->owner && param->owner->klass)
3136                 klass->image = param->owner->klass->image;
3137         else
3138                 klass->image = mono_defaults.corlib;
3139
3140         klass->inited = TRUE;
3141         klass->cast_class = klass->element_class = klass;
3142         klass->enum_basetype = &klass->element_class->byval_arg;
3143         klass->flags = TYPE_ATTRIBUTE_PUBLIC;
3144
3145         klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
3146         klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
3147         klass->this_arg.byref = TRUE;
3148
3149         mono_class_setup_supertypes (klass);
3150
3151         return klass;
3152 }
3153
3154 MonoClass *
3155 mono_ptr_class_get (MonoType *type)
3156 {
3157         MonoClass *result;
3158         MonoClass *el_class;
3159         MonoImage *image;
3160         char *name;
3161
3162         el_class = mono_class_from_mono_type (type);
3163         image = el_class->image;
3164
3165         mono_loader_lock ();
3166
3167         if (!image->ptr_cache)
3168                 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
3169
3170         if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
3171                 mono_loader_unlock ();
3172                 return result;
3173         }
3174         result = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
3175
3176         result->parent = NULL; /* no parent for PTR types */
3177         result->name_space = el_class->name_space;
3178         name = g_strdup_printf ("%s*", el_class->name);
3179         result->name = mono_mempool_strdup (image->mempool, name);
3180         g_free (name);
3181         result->image = el_class->image;
3182         result->inited = TRUE;
3183         result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
3184         /* Can pointers get boxed? */
3185         result->instance_size = sizeof (gpointer);
3186         result->cast_class = result->element_class = el_class;
3187         result->enum_basetype = &result->element_class->byval_arg;
3188         result->blittable = TRUE;
3189
3190         result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
3191         result->this_arg.data.type = result->byval_arg.data.type = result->enum_basetype;
3192         result->this_arg.byref = TRUE;
3193
3194         mono_class_setup_supertypes (result);
3195
3196         g_hash_table_insert (image->ptr_cache, el_class, result);
3197
3198         mono_loader_unlock ();
3199
3200         return result;
3201 }
3202
3203 static MonoClass *
3204 mono_fnptr_class_get (MonoMethodSignature *sig)
3205 {
3206         MonoClass *result;
3207         static GHashTable *ptr_hash = NULL;
3208
3209         /* FIXME: These should be allocate from a mempool as well, but which one ? */
3210
3211         mono_loader_lock ();
3212
3213         if (!ptr_hash)
3214                 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3215         
3216         if ((result = g_hash_table_lookup (ptr_hash, sig))) {
3217                 mono_loader_unlock ();
3218                 return result;
3219         }
3220         result = g_new0 (MonoClass, 1);
3221
3222         result->parent = NULL; /* no parent for PTR types */
3223         result->name_space = "System";
3224         result->name = "MonoFNPtrFakeClass";
3225         result->image = mono_defaults.corlib; /* need to fix... */
3226         result->inited = TRUE;
3227         result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
3228         /* Can pointers get boxed? */
3229         result->instance_size = sizeof (gpointer);
3230         result->cast_class = result->element_class = result;
3231         result->blittable = TRUE;
3232
3233         result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
3234         result->this_arg.data.method = result->byval_arg.data.method = sig;
3235         result->this_arg.byref = TRUE;
3236         result->enum_basetype = &result->element_class->byval_arg;
3237         result->blittable = TRUE;
3238
3239         mono_class_setup_supertypes (result);
3240
3241         g_hash_table_insert (ptr_hash, sig, result);
3242
3243         mono_loader_unlock ();
3244
3245         return result;
3246 }
3247
3248 MonoClass *
3249 mono_class_from_mono_type (MonoType *type)
3250 {
3251         switch (type->type) {
3252         case MONO_TYPE_OBJECT:
3253                 return type->data.klass? type->data.klass: mono_defaults.object_class;
3254         case MONO_TYPE_VOID:
3255                 return type->data.klass? type->data.klass: mono_defaults.void_class;
3256         case MONO_TYPE_BOOLEAN:
3257                 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
3258         case MONO_TYPE_CHAR:
3259                 return type->data.klass? type->data.klass: mono_defaults.char_class;
3260         case MONO_TYPE_I1:
3261                 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
3262         case MONO_TYPE_U1:
3263                 return type->data.klass? type->data.klass: mono_defaults.byte_class;
3264         case MONO_TYPE_I2:
3265                 return type->data.klass? type->data.klass: mono_defaults.int16_class;
3266         case MONO_TYPE_U2:
3267                 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
3268         case MONO_TYPE_I4:
3269                 return type->data.klass? type->data.klass: mono_defaults.int32_class;
3270         case MONO_TYPE_U4:
3271                 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
3272         case MONO_TYPE_I:
3273                 return type->data.klass? type->data.klass: mono_defaults.int_class;
3274         case MONO_TYPE_U:
3275                 return type->data.klass? type->data.klass: mono_defaults.uint_class;
3276         case MONO_TYPE_I8:
3277                 return type->data.klass? type->data.klass: mono_defaults.int64_class;
3278         case MONO_TYPE_U8:
3279                 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
3280         case MONO_TYPE_R4:
3281                 return type->data.klass? type->data.klass: mono_defaults.single_class;
3282         case MONO_TYPE_R8:
3283                 return type->data.klass? type->data.klass: mono_defaults.double_class;
3284         case MONO_TYPE_STRING:
3285                 return type->data.klass? type->data.klass: mono_defaults.string_class;
3286         case MONO_TYPE_TYPEDBYREF:
3287                 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
3288         case MONO_TYPE_ARRAY:
3289                 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
3290         case MONO_TYPE_PTR:
3291                 return mono_ptr_class_get (type->data.type);
3292         case MONO_TYPE_FNPTR:
3293                 return mono_fnptr_class_get (type->data.method);
3294         case MONO_TYPE_SZARRAY:
3295                 return mono_array_class_get (type->data.klass, 1);
3296         case MONO_TYPE_CLASS:
3297         case MONO_TYPE_VALUETYPE:
3298                 return type->data.klass;
3299         case MONO_TYPE_GENERICINST: {
3300                 MonoInflatedGenericClass *gclass;
3301                 gclass = mono_get_inflated_generic_class (type->data.generic_class);
3302                 g_assert (gclass->klass);
3303                 return gclass->klass;
3304         }
3305         case MONO_TYPE_VAR:
3306                 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
3307         case MONO_TYPE_MVAR:
3308                 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
3309         default:
3310                 g_warning ("implement me 0x%02x\n", type->type);
3311                 g_assert_not_reached ();
3312         }
3313         
3314         return NULL;
3315 }
3316
3317 /**
3318  * @image: context where the image is created
3319  * @type_spec:  typespec token
3320  * @context: the generic context used to evaluate generic instantiations in
3321  */
3322 static MonoClass *
3323 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
3324 {
3325         MonoType *t = mono_type_create_from_typespec (image, type_spec);
3326         if (!t)
3327                 return NULL;
3328         if (context && (context->gclass || context->gmethod)) {
3329                 MonoType *inflated = inflate_generic_type (t, context);
3330                 if (inflated)
3331                         t = inflated;
3332         }
3333         return mono_class_from_mono_type (t);
3334 }
3335
3336 /**
3337  * mono_bounded_array_class_get:
3338  * @element_class: element class 
3339  * @rank: the dimension of the array class
3340  * @bounded: whenever the array has non-zero bounds
3341  *
3342  * Returns: a class object describing the array with element type @element_type and 
3343  * dimension @rank. 
3344  */
3345 MonoClass *
3346 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
3347 {
3348         MonoImage *image;
3349         MonoClass *class;
3350         MonoClass *parent = NULL;
3351         GSList *list, *rootlist;
3352         int nsize;
3353         char *name;
3354         gboolean corlib_type = FALSE;
3355
3356         g_assert (rank <= 255);
3357
3358         if (rank > 1)
3359                 /* bounded only matters for one-dimensional arrays */
3360                 bounded = FALSE;
3361
3362         image = eclass->image;
3363
3364         mono_loader_lock ();
3365
3366         if (!image->array_cache)
3367                 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
3368
3369         if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
3370                 for (; list; list = list->next) {
3371                         class = list->data;
3372                         if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
3373                                 mono_loader_unlock ();
3374                                 return class;
3375                         }
3376                 }
3377         }
3378
3379         /* for the building corlib use System.Array from it */
3380         if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
3381                 parent = mono_class_from_name (image, "System", "Array");
3382                 corlib_type = TRUE;
3383         } else if (mono_defaults.generic_array_class) {
3384                 MonoType *inflated, **args;
3385
3386                 args = g_new0 (MonoType *, 1);
3387                 args [0] = &eclass->byval_arg;
3388
3389                 inflated = mono_class_bind_generic_parameters (
3390                         &mono_defaults.generic_array_class->byval_arg, 1, args);
3391                 parent = mono_class_from_mono_type (inflated);
3392
3393                 if (!parent->inited)
3394                         mono_class_init (parent);
3395         } else {
3396                 parent = mono_defaults.array_class;
3397                 if (!parent->inited)
3398                         mono_class_init (parent);
3399         }
3400
3401         class = mono_mempool_alloc0 (image->mempool, sizeof (MonoClass));
3402
3403         class->image = image;
3404         class->name_space = eclass->name_space;
3405         nsize = strlen (eclass->name);
3406         name = g_malloc (nsize + 2 + rank);
3407         memcpy (name, eclass->name, nsize);
3408         name [nsize] = '[';
3409         if (rank > 1)
3410                 memset (name + nsize + 1, ',', rank - 1);
3411         name [nsize + rank] = ']';
3412         name [nsize + rank + 1] = 0;
3413         class->name = mono_mempool_strdup (image->mempool, name);
3414         g_free (name);
3415         class->type_token = 0;
3416         /* all arrays are marked serializable and sealed, bug #42779 */
3417         class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
3418                 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
3419         class->parent = parent;
3420         class->instance_size = mono_class_instance_size (class->parent);
3421         class->class_size = 0;
3422         mono_class_setup_supertypes (class);
3423         if (eclass->generic_class)
3424                 mono_class_init (eclass);
3425         if (!eclass->size_inited)
3426                 mono_class_setup_fields (eclass);
3427         class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
3428
3429         class->rank = rank;
3430         
3431         if (eclass->enumtype)
3432                 class->cast_class = eclass->element_class;
3433         else
3434                 class->cast_class = eclass;
3435
3436         class->element_class = eclass;
3437
3438         if ((rank > 1) || bounded) {
3439                 MonoArrayType *at = mono_mempool_alloc0 (image->mempool, sizeof (MonoArrayType));
3440                 class->byval_arg.type = MONO_TYPE_ARRAY;
3441                 class->byval_arg.data.array = at;
3442                 at->eklass = eclass;
3443                 at->rank = rank;
3444                 /* FIXME: complete.... */
3445         } else {
3446                 class->byval_arg.type = MONO_TYPE_SZARRAY;
3447                 class->byval_arg.data.klass = eclass;
3448         }
3449         class->this_arg = class->byval_arg;
3450         class->this_arg.byref = 1;
3451         if (corlib_type) {
3452                 class->inited = 1;
3453         }
3454
3455         class->generic_container = eclass->generic_container;
3456
3457         list = g_slist_append (rootlist, class);
3458         g_hash_table_insert (image->array_cache, eclass, list);
3459
3460         mono_loader_unlock ();
3461
3462         return class;
3463 }
3464
3465 /**
3466  * mono_array_class_get:
3467  * @element_class: element class 
3468  * @rank: the dimension of the array class
3469  *
3470  * Returns: a class object describing the array with element type @element_type and 
3471  * dimension @rank. 
3472  */
3473 MonoClass *
3474 mono_array_class_get (MonoClass *eclass, guint32 rank)
3475 {
3476         return mono_bounded_array_class_get (eclass, rank, FALSE);
3477 }
3478
3479 /**
3480  * mono_class_instance_size:
3481  * @klass: a class 
3482  * 
3483  * Returns: the size of an object instance
3484  */
3485 gint32
3486 mono_class_instance_size (MonoClass *klass)
3487 {       
3488         if (!klass->size_inited)
3489                 mono_class_init (klass);
3490
3491         return klass->instance_size;
3492 }
3493
3494 /**
3495  * mono_class_min_align:
3496  * @klass: a class 
3497  * 
3498  * Returns: minimm alignment requirements 
3499  */
3500 gint32
3501 mono_class_min_align (MonoClass *klass)
3502 {       
3503         if (!klass->size_inited)
3504                 mono_class_init (klass);
3505
3506         return klass->min_align;
3507 }
3508
3509 /**
3510  * mono_class_value_size:
3511  * @klass: a class 
3512  *
3513  * This function is used for value types, and return the
3514  * space and the alignment to store that kind of value object.
3515  *
3516  * Returns: the size of a value of kind @klass
3517  */
3518 gint32
3519 mono_class_value_size      (MonoClass *klass, guint32 *align)
3520 {
3521         gint32 size;
3522
3523         /* fixme: check disable, because we still have external revereces to
3524          * mscorlib and Dummy Objects 
3525          */
3526         /*g_assert (klass->valuetype);*/
3527
3528         size = mono_class_instance_size (klass) - sizeof (MonoObject);
3529
3530         if (align)
3531                 *align = klass->min_align;
3532
3533         return size;
3534 }
3535
3536 /**
3537  * mono_class_data_size:
3538  * @klass: a class 
3539  * 
3540  * Returns: the size of the static class data
3541  */
3542 gint32
3543 mono_class_data_size (MonoClass *klass)
3544 {       
3545         if (!klass->inited)
3546                 mono_class_init (klass);
3547
3548         return klass->class_size;
3549 }
3550
3551 /*
3552  * Auxiliary routine to mono_class_get_field
3553  *
3554  * Takes a field index instead of a field token.
3555  */
3556 static MonoClassField *
3557 mono_class_get_field_idx (MonoClass *class, int idx)
3558 {
3559         mono_class_setup_fields_locking (class);
3560
3561         while (class) {
3562                 if (class->field.count) {
3563                         if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
3564                                 return &class->fields [idx - class->field.first];
3565                         }
3566                 }
3567                 class = class->parent;
3568         }
3569         return NULL;
3570 }
3571
3572 /**
3573  * mono_class_get_field:
3574  * @class: the class to lookup the field.
3575  * @field_token: the field token
3576  *
3577  * Returns: A MonoClassField representing the type and offset of
3578  * the field, or a NULL value if the field does not belong to this
3579  * class.
3580  */
3581 MonoClassField *
3582 mono_class_get_field (MonoClass *class, guint32 field_token)
3583 {
3584         int idx = mono_metadata_token_index (field_token);
3585
3586         g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
3587
3588         return mono_class_get_field_idx (class, idx - 1);
3589 }
3590
3591 /**
3592  * mono_class_get_field_from_name:
3593  * @klass: the class to lookup the field.
3594  * @name: the field name
3595  *
3596  * Search the class @klass and it's parents for a field with the name @name.
3597  * 
3598  * Returns: the MonoClassField pointer of the named field or NULL
3599  */
3600 MonoClassField *
3601 mono_class_get_field_from_name (MonoClass *klass, const char *name)
3602 {
3603         int i;
3604
3605         mono_class_setup_fields_locking (klass);
3606         while (klass) {
3607                 for (i = 0; i < klass->field.count; ++i) {
3608                         if (strcmp (name, klass->fields [i].name) == 0)
3609                                 return &klass->fields [i];
3610                 }
3611                 klass = klass->parent;
3612         }
3613         return NULL;
3614 }
3615
3616 /**
3617  * mono_class_get_field_token:
3618  * @field: the field we need the token of
3619  *
3620  * Get the token of a field. Note that the tokesn is only valid for the image
3621  * the field was loaded from. Don't use this function for fields in dynamic types.
3622  * 
3623  * Returns: the token representing the field in the image it was loaded from.
3624  */
3625 guint32
3626 mono_class_get_field_token (MonoClassField *field)
3627 {
3628         MonoClass *klass = field->parent;
3629         int i;
3630
3631         mono_class_setup_fields_locking (klass);
3632         while (klass) {
3633                 for (i = 0; i < klass->field.count; ++i) {
3634                         if (&klass->fields [i] == field)
3635                                 return mono_metadata_make_token (MONO_TABLE_FIELD, klass->field.first + i + 1);
3636                 }
3637                 klass = klass->parent;
3638         }
3639
3640         g_assert_not_reached ();
3641         return 0;
3642 }
3643
3644 guint32
3645 mono_class_get_event_token (MonoEvent *event)
3646 {
3647         MonoClass *klass = event->parent;
3648         int i;
3649
3650         while (klass) {
3651                 for (i = 0; i < klass->event.count; ++i) {
3652                         if (&klass->events [i] == event)
3653                                 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->event.first + i + 1);
3654                 }
3655                 klass = klass->parent;
3656         }
3657
3658         g_assert_not_reached ();
3659         return 0;
3660 }
3661
3662 MonoProperty*
3663 mono_class_get_property_from_name (MonoClass *klass, const char *name)
3664 {
3665         while (klass) {
3666                 MonoProperty* p;
3667                 gpointer iter = NULL;
3668                 while ((p = mono_class_get_properties (klass, &iter))) {
3669                         if (! strcmp (name, p->name))
3670                                 return p;
3671                 }
3672                 klass = klass->parent;
3673         }
3674         return NULL;
3675 }
3676
3677 guint32
3678 mono_class_get_property_token (MonoProperty *prop)
3679 {
3680         MonoClass *klass = prop->parent;
3681         while (klass) {
3682                 MonoProperty* p;
3683                 int i = 0;
3684                 gpointer iter = NULL;
3685                 while ((p = mono_class_get_properties (klass, &iter))) {
3686                         if (&klass->properties [i] == prop)
3687                                 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->property.first + i + 1);
3688                         
3689                         i ++;
3690                 }
3691                 klass = klass->parent;
3692         }
3693
3694         g_assert_not_reached ();
3695         return 0;
3696 }
3697
3698 char *
3699 mono_class_name_from_token (MonoImage *image, guint32 type_token)
3700 {
3701         const char *name, *nspace;
3702         if (image->dynamic)
3703                 return g_strdup_printf ("DynamicType 0x%08x", type_token);
3704         
3705         switch (type_token & 0xff000000){
3706         case MONO_TOKEN_TYPE_DEF: {
3707                 guint32 cols [MONO_TYPEDEF_SIZE];
3708                 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
3709                 guint tidx = mono_metadata_token_index (type_token);
3710
3711                 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
3712                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
3713                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
3714                 if (strlen (nspace) == 0)
3715                         return g_strdup_printf ("%s", name);
3716                 else
3717                         return g_strdup_printf ("%s.%s", nspace, name);
3718         }
3719
3720         case MONO_TOKEN_TYPE_REF: {
3721                 guint32 cols [MONO_TYPEREF_SIZE];
3722                 MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
3723
3724                 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
3725                 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
3726                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
3727                 if (strlen (nspace) == 0)
3728                         return g_strdup_printf ("%s", name);
3729                 else
3730                         return g_strdup_printf ("%s.%s", nspace, name);
3731         }
3732                 
3733         case MONO_TOKEN_TYPE_SPEC:
3734                 return g_strdup_printf ("Typespec 0x%08x", type_token);
3735         default:
3736                 g_assert_not_reached ();
3737         }
3738
3739         return NULL;
3740 }
3741
3742 static char *
3743 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
3744 {
3745         if (image->dynamic)
3746                 return g_strdup_printf ("DynamicAssembly %s", image->name);
3747         
3748         switch (type_token & 0xff000000){
3749         case MONO_TOKEN_TYPE_DEF:
3750                 return mono_stringify_assembly_name (&image->assembly->aname);
3751                 break;
3752         case MONO_TOKEN_TYPE_REF: {
3753                 MonoAssemblyName aname;
3754                 guint32 cols [MONO_TYPEREF_SIZE];
3755                 MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEREF];
3756                 guint32 idx;
3757         
3758                 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
3759
3760                 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
3761                 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
3762                 case MONO_RESOLTION_SCOPE_MODULE:
3763                         /* FIXME: */
3764                         return g_strdup ("");
3765                 case MONO_RESOLTION_SCOPE_MODULEREF:
3766                         /* FIXME: */
3767                         return g_strdup ("");
3768                 case MONO_RESOLTION_SCOPE_TYPEREF:
3769                         /* FIXME: */
3770                         return g_strdup ("");
3771                 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
3772                         mono_assembly_get_assemblyref (image, idx - 1, &aname);
3773                         return mono_stringify_assembly_name (&aname);
3774                 default:
3775                         g_assert_not_reached ();
3776                 }
3777                 break;
3778         }
3779         case MONO_TOKEN_TYPE_SPEC:
3780                 /* FIXME: */
3781                 return g_strdup ("");
3782         default:
3783                 g_assert_not_reached ();
3784         }
3785
3786         return NULL;
3787 }
3788
3789 /**
3790  * mono_class_get_full:
3791  * @image: the image where the class resides
3792  * @type_token: the token for the class
3793  * @context: the generic context used to evaluate generic instantiations in
3794  *
3795  * Returns: the MonoClass that represents @type_token in @image
3796  */
3797 MonoClass *
3798 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
3799 {
3800         MonoClass *class = NULL;
3801
3802         if (image->dynamic)
3803                 return mono_lookup_dynamic_token (image, type_token);
3804
3805         switch (type_token & 0xff000000){
3806         case MONO_TOKEN_TYPE_DEF:
3807                 class = mono_class_create_from_typedef (image, type_token);
3808                 break;          
3809         case MONO_TOKEN_TYPE_REF:
3810                 class = mono_class_from_typeref (image, type_token);
3811                 break;
3812         case MONO_TOKEN_TYPE_SPEC:
3813                 class = mono_class_create_from_typespec (image, type_token, context);
3814                 break;
3815         default:
3816                 g_warning ("unknown token type %x", type_token & 0xff000000);
3817                 g_assert_not_reached ();
3818         }
3819
3820         if (!class){
3821                 char *name = mono_class_name_from_token (image, type_token);
3822                 char *assembly = mono_assembly_name_from_token (image, type_token);
3823                 mono_loader_set_error_type_load (name, assembly);
3824         }
3825
3826         return class;
3827 }
3828
3829 MonoClass *
3830 mono_class_get (MonoImage *image, guint32 type_token)
3831 {
3832         return mono_class_get_full (image, type_token, NULL);
3833 }
3834
3835 typedef struct {
3836         gconstpointer key;
3837         gpointer value;
3838 } FindUserData;
3839
3840 static void
3841 find_nocase (gpointer key, gpointer value, gpointer user_data)
3842 {
3843         char *name = (char*)key;
3844         FindUserData *data = (FindUserData*)user_data;
3845
3846         if (!data->value && (g_strcasecmp (name, (char*)data->key) == 0))
3847                 data->value = value;
3848 }
3849
3850 /**
3851  * mono_class_from_name_case:
3852  * @image: The MonoImage where the type is looked up in, or NULL for looking up in all loaded assemblies
3853  * @name_space: the type namespace
3854  * @name: the type short name.
3855  *
3856  * Obtains a MonoClass with a given namespace and a given name which
3857  * is located in the given MonoImage.   The namespace and name
3858  * lookups are case insensitive.
3859  *
3860  * You can also pass @NULL to the image, and that will lookup for
3861  * a type with the given namespace and name in all of the loaded
3862  * assemblies: notice that since there might be a name clash in this
3863  * case, passing @NULL is not encouraged if you need a precise type.
3864  *
3865  */
3866 MonoClass *
3867 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
3868 {
3869         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
3870         guint32 cols [MONO_TYPEDEF_SIZE];
3871         const char *n;
3872         const char *nspace;
3873         guint32 i, visib;
3874
3875         if (image->dynamic) {
3876                 guint32 token = 0;
3877                 FindUserData user_data;
3878
3879                 mono_loader_lock ();
3880
3881                 user_data.key = name_space;
3882                 user_data.value = NULL;
3883                 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
3884
3885                 if (user_data.value) {
3886                         GHashTable *nspace_table = (GHashTable*)user_data.value;
3887
3888                         user_data.key = name;
3889                         user_data.value = NULL;
3890
3891                         g_hash_table_foreach (nspace_table, find_nocase, &user_data);
3892                         
3893                         if (user_data.value)
3894                                 token = GPOINTER_TO_UINT (user_data.value);
3895                 }
3896
3897                 mono_loader_unlock ();
3898                 
3899                 if (token)
3900                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
3901                 else
3902                         return NULL;
3903
3904         }
3905
3906         /* add a cache if needed */
3907         for (i = 1; i <= t->rows; ++i) {
3908                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
3909                 /* nested types are accessed from the nesting name */
3910                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
3911                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
3912                         continue;
3913                 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
3914                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
3915                 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
3916                         return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
3917         }
3918         return NULL;
3919 }
3920
3921 static MonoClass*
3922 return_nested_in (MonoClass *class, char *nested) {
3923         MonoClass *found;
3924         char *s = strchr (nested, '/');
3925         GList *tmp;
3926
3927         if (s) {
3928                 *s = 0;
3929                 s++;
3930         }
3931         for (tmp = class->nested_classes; tmp; tmp = tmp->next) {
3932                 found = tmp->data;
3933                 if (strcmp (found->name, nested) == 0) {
3934                         if (s)
3935                                 return return_nested_in (found, s);
3936                         return found;
3937                 }
3938         }
3939         return NULL;
3940 }
3941
3942
3943 /**
3944  * mono_class_from_name:
3945  * @image: The MonoImage where the type is looked up in, or NULL for looking up in all loaded assemblies
3946  * @name_space: the type namespace
3947  * @name: the type short name.
3948  *
3949  * Obtains a MonoClass with a given namespace and a given name which
3950  * is located in the given MonoImage.   
3951  *
3952  * You can also pass `NULL' to the image, and that will lookup for
3953  * a type with the given namespace and name in all of the loaded
3954  * assemblies: notice that since there might be a name clash in this
3955  * case, passing NULL is not encouraged if you need a precise type.
3956  *
3957  */
3958 MonoClass *
3959 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
3960 {
3961         GHashTable *nspace_table;
3962         MonoImage *loaded_image;
3963         guint32 token = 0;
3964         MonoClass *class;
3965         char *nested;
3966         char buf [1024];
3967
3968         if ((nested = strchr (name, '/'))) {
3969                 int pos = nested - name;
3970                 int len = strlen (name);
3971                 if (len > 1023)
3972                         return NULL;
3973                 memcpy (buf, name, len + 1);
3974                 buf [pos] = 0;
3975                 nested = buf + pos + 1;
3976                 name = buf;
3977         }
3978
3979         mono_loader_lock ();
3980
3981         nspace_table = g_hash_table_lookup (image->name_cache, name_space);
3982
3983         if (nspace_table)
3984                 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
3985
3986         mono_loader_unlock ();
3987
3988         if (!token)
3989                 return NULL;
3990
3991         if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
3992                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
3993                 guint32 cols [MONO_EXP_TYPE_SIZE];
3994                 guint32 idx, impl;
3995
3996                 idx = mono_metadata_token_index (token);
3997
3998                 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
3999
4000                 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
4001                 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
4002                         loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
4003                         if (!loaded_image)
4004                                 return NULL;
4005                         class = mono_class_from_name (loaded_image, name_space, name);
4006                         if (nested)
4007                                 return return_nested_in (class, nested);
4008                         return class;
4009                 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
4010                         MonoAssembly **references = image->references;
4011                         if (!references [idx - 1])
4012                                 mono_assembly_load_reference (image, idx - 1);
4013                         g_assert (references == image->references);
4014                         g_assert (references [idx - 1]);
4015                         if (references [idx - 1] == (gpointer)-1)
4016                                 return NULL;                    
4017                         else
4018                                 /* FIXME: Cycle detection */
4019                                 return mono_class_from_name (references [idx - 1]->image, name_space, name);
4020                 } else {
4021                         g_error ("not yet implemented");
4022                 }
4023         }
4024
4025         token = MONO_TOKEN_TYPE_DEF | token;
4026
4027         class = mono_class_get (image, token);
4028         if (nested)
4029                 return return_nested_in (class, nested);
4030         return class;
4031 }
4032
4033 gboolean
4034 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc, 
4035                            gboolean check_interfaces)
4036 {
4037         g_assert (klassc->idepth > 0);
4038         if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
4039                 if ((klassc->interface_id <= klass->max_interface_id) &&
4040                         (klass->interface_offsets [klassc->interface_id] >= 0))
4041                         return TRUE;
4042         } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
4043                 int i;
4044
4045                 for (i = 0; i < klass->interface_count; i ++) {
4046                         MonoClass *ic =  klass->interfaces [i];
4047                         if (ic == klassc)
4048                                 return TRUE;
4049                 }
4050         } else {
4051                 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
4052                         return TRUE;
4053         }
4054
4055         /* 
4056          * MS.NET thinks interfaces are a subclass of Object, so we think it as
4057          * well.
4058          */
4059         if (klassc == mono_defaults.object_class)
4060                 return TRUE;
4061
4062         return FALSE;
4063 }
4064
4065 gboolean
4066 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
4067 {
4068         if (!klass->inited)
4069                 mono_class_init (klass);
4070
4071         if (!oklass->inited)
4072                 mono_class_init (oklass);
4073
4074         if (MONO_CLASS_IS_INTERFACE (klass)) {
4075                 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
4076                         return FALSE;
4077
4078                 /* interface_offsets might not be set for dynamic classes */
4079                 if (oklass->reflection_info && !oklass->interface_offsets)
4080                         /* 
4081                          * oklass might be a generic type parameter but they have 
4082                          * interface_offsets set.
4083                          */
4084                         return mono_reflection_call_is_assignable_to (oklass, klass);
4085
4086                 if ((klass->interface_id <= oklass->max_interface_id) &&
4087                     (oklass->interface_offsets [klass->interface_id] != -1))
4088                         return TRUE;
4089         } else if (klass->rank) {
4090                 MonoClass *eclass, *eoclass;
4091
4092                 if (oklass->rank != klass->rank)
4093                         return FALSE;
4094
4095                 /* vectors vs. one dimensional arrays */
4096                 if (oklass->byval_arg.type != klass->byval_arg.type)
4097                         return FALSE;
4098
4099                 eclass = klass->cast_class;
4100                 eoclass = oklass->cast_class;
4101
4102                 /* 
4103                  * a is b does not imply a[] is b[] when a is a valuetype, and
4104                  * b is a reference type.
4105                  */
4106
4107                 if (eoclass->valuetype) {
4108                         if ((eclass == mono_defaults.enum_class) || 
4109                                 (eclass == mono_defaults.enum_class->parent) ||
4110                                 (eclass == mono_defaults.object_class))
4111                                 return FALSE;
4112                 }
4113
4114                 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
4115         } else if (mono_class_is_nullable (klass))
4116                 return (mono_class_is_assignable_from (klass->cast_class, oklass));
4117         else if (klass == mono_defaults.object_class)
4118                 return TRUE;
4119
4120         return mono_class_has_parent (oklass, klass);
4121 }       
4122
4123 /*
4124  * mono_class_get_cctor:
4125  *
4126  *   Returns the static constructor of @klass if it exists, NULL otherwise.
4127  */
4128 MonoMethod*
4129 mono_class_get_cctor (MonoClass *klass)
4130 {
4131         MonoCachedClassInfo cached_info;
4132
4133         if (!klass->has_cctor)
4134                 return NULL;
4135
4136         if (mono_class_get_cached_class_info (klass, &cached_info))
4137                 return mono_get_method (klass->image, cached_info.cctor_token, klass);
4138
4139         return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
4140 }
4141
4142 /*
4143  * mono_class_get_finalizer:
4144  *
4145  *   Returns the finalizer method of @klass if it exists, NULL otherwise.
4146  */
4147 MonoMethod*
4148 mono_class_get_finalizer (MonoClass *klass)
4149 {
4150         MonoCachedClassInfo cached_info;
4151
4152         if (!klass->inited)
4153                 mono_class_init (klass);
4154         if (!klass->has_finalize)
4155                 return NULL;
4156
4157         if (mono_class_get_cached_class_info (klass, &cached_info))
4158                 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
4159         else {
4160                 mono_class_setup_vtable (klass);
4161                 return klass->vtable [finalize_slot];
4162         }
4163 }
4164
4165 /*
4166  * mono_class_needs_cctor_run:
4167  *
4168  *  Determines whenever the class has a static constructor and whenever it
4169  * needs to be called when executing CALLER.
4170  */
4171 gboolean
4172 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
4173 {
4174         MonoMethod *method;
4175
4176         method = mono_class_get_cctor (klass);
4177         if (method)
4178                 return (method == caller) ? FALSE : TRUE;
4179         else
4180                 return TRUE;
4181 }
4182
4183 /**
4184  * mono_class_array_element_size:
4185  * @klass: 
4186  *
4187  * Returns: the number of bytes an element of type @klass
4188  * uses when stored into an array.
4189  */
4190 gint32
4191 mono_class_array_element_size (MonoClass *klass)
4192 {
4193         MonoType *type = &klass->byval_arg;
4194         
4195 handle_enum:
4196         switch (type->type) {
4197         case MONO_TYPE_I1:
4198         case MONO_TYPE_U1:
4199         case MONO_TYPE_BOOLEAN:
4200                 return 1;
4201         case MONO_TYPE_I2:
4202         case MONO_TYPE_U2:
4203         case MONO_TYPE_CHAR:
4204                 return 2;
4205         case MONO_TYPE_I4:
4206         case MONO_TYPE_U4:
4207         case MONO_TYPE_R4:
4208                 return 4;
4209         case MONO_TYPE_I:
4210         case MONO_TYPE_U:
4211         case MONO_TYPE_PTR:
4212         case MONO_TYPE_CLASS:
4213         case MONO_TYPE_STRING:
4214         case MONO_TYPE_OBJECT:
4215         case MONO_TYPE_SZARRAY:
4216         case MONO_TYPE_ARRAY: 
4217         case MONO_TYPE_VAR:
4218         case MONO_TYPE_MVAR:   
4219                 return sizeof (gpointer);
4220         case MONO_TYPE_I8:
4221         case MONO_TYPE_U8:
4222         case MONO_TYPE_R8:
4223                 return 8;
4224         case MONO_TYPE_VALUETYPE:
4225                 if (type->data.klass->enumtype) {
4226                         type = type->data.klass->enum_basetype;
4227                         klass = klass->element_class;
4228                         goto handle_enum;
4229                 }
4230                 return mono_class_instance_size (klass) - sizeof (MonoObject);
4231         case MONO_TYPE_GENERICINST:
4232                 type = &type->data.generic_class->container_class->byval_arg;
4233                 goto handle_enum;
4234         default:
4235                 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
4236         }
4237         return -1;
4238 }
4239
4240 /**
4241  * mono_array_element_size:
4242  * @ac: pointer to a #MonoArrayClass
4243  *
4244  * Returns: the size of single array element.
4245  */
4246 gint32
4247 mono_array_element_size (MonoClass *ac)
4248 {
4249         return mono_class_array_element_size (ac->element_class);
4250 }
4251
4252 gpointer
4253 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
4254               MonoGenericContext *context)
4255 {
4256         if (image->dynamic) {
4257                 MonoClass *tmp_handle_class;
4258                 gpointer obj = mono_lookup_dynamic_token_class (image, token, &tmp_handle_class);
4259
4260                 g_assert (tmp_handle_class);
4261                 if (handle_class)
4262                         *handle_class = tmp_handle_class;
4263
4264                 if (tmp_handle_class == mono_defaults.typehandle_class)
4265                         return &((MonoClass*)obj)->byval_arg;
4266                 else
4267                         return obj;
4268         }
4269
4270         switch (token & 0xff000000) {
4271         case MONO_TOKEN_TYPE_DEF:
4272         case MONO_TOKEN_TYPE_REF:
4273         case MONO_TOKEN_TYPE_SPEC: {
4274                 MonoClass *class;
4275                 if (handle_class)
4276                         *handle_class = mono_defaults.typehandle_class;
4277                 class = mono_class_get_full (image, token, context);
4278                 if (!class)
4279                         return NULL;
4280                 mono_class_init (class);
4281                 /* We return a MonoType* as handle */
4282                 return &class->byval_arg;
4283         }
4284         case MONO_TOKEN_FIELD_DEF: {
4285                 MonoClass *class;
4286                 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
4287                 if (handle_class)
4288                         *handle_class = mono_defaults.fieldhandle_class;
4289                 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
4290                 if (!class)
4291                         return NULL;
4292                 mono_class_init (class);
4293                 return mono_class_get_field (class, token);
4294         }
4295         case MONO_TOKEN_METHOD_DEF: {
4296                 MonoMethod *meth;
4297                 meth = mono_get_method_full (image, token, NULL, context);
4298                 if (handle_class)
4299                         *handle_class = mono_defaults.methodhandle_class;
4300                 return meth;
4301         }
4302         case MONO_TOKEN_MEMBER_REF: {
4303                 guint32 cols [MONO_MEMBERREF_SIZE];
4304                 const char *sig;
4305                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
4306                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
4307                 mono_metadata_decode_blob_size (sig, &sig);
4308                 if (*sig == 0x6) { /* it's a field */
4309                         MonoClass *klass;
4310                         MonoClassField *field;
4311                         field = mono_field_from_token (image, token, &klass, context);
4312                         if (handle_class)
4313                                 *handle_class = mono_defaults.fieldhandle_class;
4314                         return field;
4315                 } else {
4316                         MonoMethod *meth;
4317                         meth = mono_get_method_full (image, token, NULL, context);
4318                         if (handle_class)
4319                                 *handle_class = mono_defaults.methodhandle_class;
4320                         return meth;
4321                 }
4322         }
4323         default:
4324                 g_warning ("Unknown token 0x%08x in ldtoken", token);
4325                 break;
4326         }
4327         return NULL;
4328 }
4329
4330 /**
4331  * This function might need to call runtime functions so it can't be part
4332  * of the metadata library.
4333  */
4334 static MonoLookupDynamicToken lookup_dynamic = NULL;
4335
4336 void
4337 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
4338 {
4339         lookup_dynamic = func;
4340 }
4341
4342 gpointer
4343 mono_lookup_dynamic_token (MonoImage *image, guint32 token)
4344 {
4345         MonoClass *handle_class;
4346
4347         return lookup_dynamic (image, token, &handle_class);
4348 }
4349
4350 gpointer
4351 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, MonoClass **handle_class)
4352 {
4353         return lookup_dynamic (image, token, handle_class);
4354 }
4355
4356 static MonoGetCachedClassInfo get_cached_class_info = NULL;
4357
4358 void
4359 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
4360 {
4361         get_cached_class_info = func;
4362 }
4363
4364 static gboolean
4365 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
4366 {
4367         if (!get_cached_class_info)
4368                 return FALSE;
4369         else
4370                 return get_cached_class_info (klass, res);
4371 }
4372
4373 MonoImage*
4374 mono_class_get_image (MonoClass *klass)
4375 {
4376         return klass->image;
4377 }
4378
4379 /**
4380  * mono_class_get_element_class:
4381  * @klass: the MonoClass to act on
4382  *
4383  * Returns: the element class of an array or an enumeration.
4384  */
4385 MonoClass*
4386 mono_class_get_element_class (MonoClass *klass)
4387 {
4388         return klass->element_class;
4389 }
4390
4391 /**
4392  * mono_class_is_valuetype:
4393  * @klass: the MonoClass to act on
4394  *
4395  * Returns: true if the MonoClass represents a ValueType.
4396  */
4397 gboolean
4398 mono_class_is_valuetype (MonoClass *klass)
4399 {
4400         return klass->valuetype;
4401 }
4402
4403 /**
4404  * mono_class_is_enum:
4405  * @klass: the MonoClass to act on
4406  *
4407  * Returns: true if the MonoClass represents an enumeration.
4408  */
4409 gboolean
4410 mono_class_is_enum (MonoClass *klass)
4411 {
4412         return klass->enumtype;
4413 }
4414
4415 /**
4416  * mono_class_enum_basetype:
4417  * @klass: the MonoClass to act on
4418  *
4419  * Returns: the underlying type representation for an enumeration.
4420  */
4421 MonoType*
4422 mono_class_enum_basetype (MonoClass *klass)
4423 {
4424         return klass->enum_basetype;
4425 }
4426
4427 /**
4428  * mono_class_get_parent
4429  * @klass: the MonoClass to act on
4430  *
4431  * Returns: the parent class for this class.
4432  */
4433 MonoClass*
4434 mono_class_get_parent (MonoClass *klass)
4435 {
4436         return klass->parent;
4437 }
4438
4439 /**
4440  * mono_class_get_nesting_type;
4441  * @klass: the MonoClass to act on
4442  *
4443  * Returns: the container type where this type is nested or NULL if this type is not a nested type.
4444  */
4445 MonoClass*
4446 mono_class_get_nesting_type (MonoClass *klass)
4447 {
4448         return klass->nested_in;
4449 }
4450
4451 /**
4452  * mono_class_get_rank:
4453  * @klass: the MonoClass to act on
4454  *
4455  * Returns: the rank for the array (the number of dimensions).
4456  */
4457 int
4458 mono_class_get_rank (MonoClass *klass)
4459 {
4460         return klass->rank;
4461 }
4462
4463 /**
4464  * mono_class_get_flags:
4465  * @klass: the MonoClass to act on
4466  *
4467  * The type flags from the TypeDef table from the metadata.
4468  * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
4469  * different values.
4470  *
4471  * Returns: the flags from the TypeDef table.
4472  */
4473 guint32
4474 mono_class_get_flags (MonoClass *klass)
4475 {
4476         return klass->flags;
4477 }
4478
4479 /**
4480  * mono_class_get_name
4481  * @klass: the MonoClass to act on
4482  *
4483  * Returns: the name of the class.
4484  */
4485 const char*
4486 mono_class_get_name (MonoClass *klass)
4487 {
4488         return klass->name;
4489 }
4490
4491 /**
4492  * mono_class_get_namespace:
4493  * @klass: the MonoClass to act on
4494  *
4495  * Returns: the namespace of the class.
4496  */
4497 const char*
4498 mono_class_get_namespace (MonoClass *klass)
4499 {
4500         return klass->name_space;
4501 }
4502
4503 /**
4504  * mono_class_get_type:
4505  * @klass: the MonoClass to act on
4506  *
4507  * This method returns the internal Type representation for the class.
4508  *
4509  * Returns: the MonoType from the class.
4510  */
4511 MonoType*
4512 mono_class_get_type (MonoClass *klass)
4513 {
4514         return &klass->byval_arg;
4515 }
4516
4517 /**
4518  * mono_class_get_byref_type:
4519  * @klass: the MonoClass to act on
4520  *
4521  * 
4522  */
4523 MonoType*
4524 mono_class_get_byref_type (MonoClass *klass)
4525 {
4526         return &klass->this_arg;
4527 }
4528
4529 /**
4530  * mono_class_num_fields:
4531  * @klass: the MonoClass to act on
4532  *
4533  * Returns: the number of static and instance fields in the class.
4534  */
4535 int
4536 mono_class_num_fields (MonoClass *klass)
4537 {
4538         return klass->field.count;
4539 }
4540
4541 /**
4542  * mono_class_num_methods:
4543  * @klass: the MonoClass to act on
4544  *
4545  * Returns: the number of methods in the class.
4546  */
4547 int
4548 mono_class_num_methods (MonoClass *klass)
4549 {
4550         return klass->method.count;
4551 }
4552
4553 /**
4554  * mono_class_num_properties
4555  * @klass: the MonoClass to act on
4556  *
4557  * Returns: the number of properties in the class.
4558  */
4559 int
4560 mono_class_num_properties (MonoClass *klass)
4561 {
4562         mono_class_setup_properties (klass);
4563
4564         return klass->property.count;
4565 }
4566
4567 /**
4568  * mono_class_num_events:
4569  * @klass: the MonoClass to act on
4570  *
4571  * Returns: the number of events in the class.
4572  */
4573 int
4574 mono_class_num_events (MonoClass *klass)
4575 {
4576         mono_class_setup_events (klass);
4577
4578         return klass->event.count;
4579 }
4580
4581 /**
4582  * mono_class_get_fields:
4583  * @klass: the MonoClass to act on
4584  *
4585  * This routine is an iterator routine for retrieving the fields in a class.
4586  *
4587  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4588  * iterate over all of the elements.  When no more values are
4589  * available, the return value is NULL.
4590  *
4591  * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
4592  */
4593 MonoClassField*
4594 mono_class_get_fields (MonoClass* klass, gpointer *iter)
4595 {
4596         MonoClassField* field;
4597         if (!iter)
4598                 return NULL;
4599         mono_class_setup_fields_locking (klass);
4600         if (!*iter) {
4601                 /* start from the first */
4602                 if (klass->field.count) {
4603                         return *iter = &klass->fields [0];
4604                 } else {
4605                         /* no fields */
4606                         return NULL;
4607                 }
4608         }
4609         field = *iter;
4610         field++;
4611         if (field < &klass->fields [klass->field.count]) {
4612                 return *iter = field;
4613         }
4614         return NULL;
4615 }
4616
4617 /**
4618  * mono_class_get_methods
4619  * @klass: the MonoClass to act on
4620  *
4621  * This routine is an iterator routine for retrieving the fields in a class.
4622  *
4623  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4624  * iterate over all of the elements.  When no more values are
4625  * available, the return value is NULL.
4626  *
4627  * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
4628  */
4629 MonoMethod*
4630 mono_class_get_methods (MonoClass* klass, gpointer *iter)
4631 {
4632         MonoMethod** method;
4633         if (!iter)
4634                 return NULL;
4635         if (!klass->inited)
4636                 mono_class_init (klass);
4637         if (!*iter) {
4638                 mono_class_setup_methods (klass);
4639                 /* start from the first */
4640                 if (klass->method.count) {
4641                         *iter = &klass->methods [0];
4642                         return klass->methods [0];
4643                 } else {
4644                         /* no method */
4645                         return NULL;
4646                 }
4647         }
4648         method = *iter;
4649         method++;
4650         if (method < &klass->methods [klass->method.count]) {
4651                 *iter = method;
4652                 return *method;
4653         }
4654         return NULL;
4655 }
4656
4657 /**
4658  * mono_class_get_properties:
4659  * @klass: the MonoClass to act on
4660  *
4661  * This routine is an iterator routine for retrieving the properties in a class.
4662  *
4663  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4664  * iterate over all of the elements.  When no more values are
4665  * available, the return value is NULL.
4666  *
4667  * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
4668  */
4669 MonoProperty*
4670 mono_class_get_properties (MonoClass* klass, gpointer *iter)
4671 {
4672         MonoProperty* property;
4673         if (!iter)
4674                 return NULL;
4675         if (!klass->inited)
4676                 mono_class_init (klass);
4677         if (!*iter) {
4678                 mono_class_setup_properties (klass);
4679                 /* start from the first */
4680                 if (klass->property.count) {
4681                         return *iter = &klass->properties [0];
4682                 } else {
4683                         /* no fields */
4684                         return NULL;
4685                 }
4686         }
4687         property = *iter;
4688         property++;
4689         if (property < &klass->properties [klass->property.count]) {
4690                 return *iter = property;
4691         }
4692         return NULL;
4693 }
4694
4695 /**
4696  * mono_class_get_events:
4697  * @klass: the MonoClass to act on
4698  *
4699  * This routine is an iterator routine for retrieving the properties in a class.
4700  *
4701  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4702  * iterate over all of the elements.  When no more values are
4703  * available, the return value is NULL.
4704  *
4705  * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
4706  */
4707 MonoEvent*
4708 mono_class_get_events (MonoClass* klass, gpointer *iter)
4709 {
4710         MonoEvent* event;
4711         if (!iter)
4712                 return NULL;
4713         if (!klass->inited)
4714                 mono_class_init (klass);
4715         if (!*iter) {
4716                 mono_class_setup_events (klass);
4717                 /* start from the first */
4718                 if (klass->event.count) {
4719                         return *iter = &klass->events [0];
4720                 } else {
4721                         /* no fields */
4722                         return NULL;
4723                 }
4724         }
4725         event = *iter;
4726         event++;
4727         if (event < &klass->events [klass->event.count]) {
4728                 return *iter = event;
4729         }
4730         return NULL;
4731 }
4732
4733 /**
4734  * mono_class_get_interfaces
4735  * @klass: the MonoClass to act on
4736  *
4737  * This routine is an iterator routine for retrieving the interfaces implemented by this class.
4738  *
4739  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4740  * iterate over all of the elements.  When no more values are
4741  * available, the return value is NULL.
4742  *
4743  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
4744  */
4745 MonoClass*
4746 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
4747 {
4748         MonoClass** iface;
4749         if (!iter)
4750                 return NULL;
4751         if (!klass->inited)
4752                 mono_class_init (klass);
4753         if (!*iter) {
4754                 /* start from the first */
4755                 if (klass->interface_count) {
4756                         *iter = &klass->interfaces [0];
4757                         return klass->interfaces [0];
4758                 } else {
4759                         /* no interface */
4760                         return NULL;
4761                 }
4762         }
4763         iface = *iter;
4764         iface++;
4765         if (iface < &klass->interfaces [klass->interface_count]) {
4766                 *iter = iface;
4767                 return *iface;
4768         }
4769         return NULL;
4770 }
4771
4772 /**
4773  * mono_class_get_nested_types
4774  * @klass: the MonoClass to act on
4775  *
4776  * This routine is an iterator routine for retrieving the nested types of a class.
4777  *
4778  * You must pass a gpointer that points to zero and is treated as an opaque handle to
4779  * iterate over all of the elements.  When no more values are
4780  * available, the return value is NULL.
4781  *
4782  * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
4783  */
4784 MonoClass*
4785 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
4786 {
4787         GList *item;
4788         if (!iter)
4789                 return NULL;
4790         if (!klass->inited)
4791                 mono_class_init (klass);
4792         if (!*iter) {
4793                 /* start from the first */
4794                 if (klass->nested_classes) {
4795                         *iter = klass->nested_classes;
4796                         return klass->nested_classes->data;
4797                 } else {
4798                         /* no nested types */
4799                         return NULL;
4800                 }
4801         }
4802         item = *iter;
4803         item = item->next;
4804         if (item) {
4805                 *iter = item;
4806                 return item->data;
4807         }
4808         return NULL;
4809 }
4810
4811 /**
4812  * mono_field_get_name:
4813  * @field: the MonoClassField to act on
4814  *
4815  * Returns: the name of the field.
4816  */
4817 const char*
4818 mono_field_get_name (MonoClassField *field)
4819 {
4820         return field->name;
4821 }
4822
4823 /**
4824  * mono_field_get_type:
4825  * @field: the MonoClassField to act on
4826  *
4827  * Returns: MonoType of the field.
4828  */
4829 MonoType*
4830 mono_field_get_type (MonoClassField *field)
4831 {
4832         return field->type;
4833 }
4834
4835 /**
4836  * mono_field_get_type:
4837  * @field: the MonoClassField to act on
4838  *
4839  * Returns: MonoClass where the field was defined.
4840  */
4841 MonoClass*
4842 mono_field_get_parent (MonoClassField *field)
4843 {
4844         return field->parent;
4845 }
4846
4847 /**
4848  * mono_field_get_flags;
4849  * @field: the MonoClassField to act on
4850  *
4851  * The metadata flags for a field are encoded using the
4852  * FIELD_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
4853  *
4854  * Returns: the flags for the field.
4855  */
4856 guint32
4857 mono_field_get_flags (MonoClassField *field)
4858 {
4859         return field->type->attrs;
4860 }
4861
4862 /**
4863  * mono_property_get_name: 
4864  * @prop: the MonoProperty to act on
4865  *
4866  * Returns: the name of the property
4867  */
4868 const char*
4869 mono_property_get_name (MonoProperty *prop)
4870 {
4871         return prop->name;
4872 }
4873
4874 /**
4875  * mono_property_get_set_method
4876  * @prop: the MonoProperty to act on.
4877  *
4878  * Returns: the setter method of the property (A MonoMethod)
4879  */
4880 MonoMethod*
4881 mono_property_get_set_method (MonoProperty *prop)
4882 {
4883         return prop->set;
4884 }
4885
4886 /**
4887  * mono_property_get_get_method
4888  * @prop: the MonoProperty to act on.
4889  *
4890  * Returns: the setter method of the property (A MonoMethod)
4891  */
4892 MonoMethod*
4893 mono_property_get_get_method (MonoProperty *prop)
4894 {
4895         return prop->get;
4896 }
4897
4898 /**
4899  * mono_property_get_parent:
4900  * @prop: the MonoProperty to act on.
4901  *
4902  * Returns: the MonoClass where the property was defined.
4903  */
4904 MonoClass*
4905 mono_property_get_parent (MonoProperty *prop)
4906 {
4907         return prop->parent;
4908 }
4909
4910 /**
4911  * mono_property_get_flags:
4912  * @prop: the MonoProperty to act on.
4913  *
4914  * The metadata flags for a property are encoded using the
4915  * PROPERTY_ATTRIBUTE_* constants.  See the tabledefs.h file for details.
4916  *
4917  * Returns: the flags for the property.
4918  */
4919 guint32
4920 mono_property_get_flags (MonoProperty *prop)
4921 {
4922         return prop->attrs;
4923 }
4924
4925 /**
4926  * mono_event_get_name:
4927  * @event: the MonoEvent to act on
4928  *
4929  * Returns: the name of the event.
4930  */
4931 const char*
4932 mono_event_get_name (MonoEvent *event)
4933 {
4934         return event->name;
4935 }
4936
4937 /**
4938  * mono_event_get_add_method:
4939  * @event: The MonoEvent to act on.
4940  *
4941  * Returns: the @add' method for the event (a MonoMethod).
4942  */
4943 MonoMethod*
4944 mono_event_get_add_method (MonoEvent *event)
4945 {
4946         return event->add;
4947 }
4948
4949 /**
4950  * mono_event_get_remove_method:
4951  * @event: The MonoEvent to act on.
4952  *
4953  * Returns: the @remove method for the event (a MonoMethod).
4954  */
4955 MonoMethod*
4956 mono_event_get_remove_method (MonoEvent *event)
4957 {
4958         return event->remove;
4959 }
4960
4961 /**
4962  * mono_event_get_raise_method:
4963  * @event: The MonoEvent to act on.
4964  *
4965  * Returns: the @raise method for the event (a MonoMethod).
4966  */
4967 MonoMethod*
4968 mono_event_get_raise_method (MonoEvent *event)
4969 {
4970         return event->raise;
4971 }
4972
4973 /**
4974  * mono_event_get_parent:
4975  * @event: the MonoEvent to act on.
4976  *
4977  * Returns: the MonoClass where the event is defined.
4978  */
4979 MonoClass*
4980 mono_event_get_parent (MonoEvent *event)
4981 {
4982         return event->parent;
4983 }
4984
4985 /**
4986  * mono_event_get_flags
4987  * @event: the MonoEvent to act on.
4988  *
4989  * The metadata flags for an event are encoded using the
4990  * EVENT_* constants.  See the tabledefs.h file for details.
4991  *
4992  * Returns: the flags for the event.
4993  */
4994 guint32
4995 mono_event_get_flags (MonoEvent *event)
4996 {
4997         return event->attrs;
4998 }
4999
5000 /**
5001  * mono_class_get_method_from_name:
5002  * @klass: where to look for the method
5003  * @name_space: name of the method
5004  * @param_count: number of parameters. -1 for any number.
5005  *
5006  * Obtains a MonoMethod with a given name and number of parameters.
5007  * It only works if there are no multiple signatures for any given method name.
5008  */
5009 MonoMethod *
5010 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
5011 {
5012         return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
5013 }
5014
5015 /**
5016  * mono_class_get_method_from_name_flags:
5017  * @klass: where to look for the method
5018  * @name_space: name of the method
5019  * @param_count: number of parameters. -1 for any number.
5020  * @flags: flags which must be set in the method
5021  *
5022  * Obtains a MonoMethod with a given name and number of parameters.
5023  * It only works if there are no multiple signatures for any given method name.
5024  */
5025 MonoMethod *
5026 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
5027 {
5028         MonoMethod *res = NULL;
5029         int i;
5030
5031         mono_class_init (klass);
5032
5033         if (klass->methods) {
5034                 mono_class_setup_methods (klass);
5035                 for (i = 0; i < klass->method.count; ++i) {
5036                         MonoMethod *method = klass->methods [i];
5037
5038                         if (method->name[0] == name [0] && 
5039                                 !strcmp (name, method->name) &&
5040                                 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
5041                                 ((method->flags & flags) == flags)) {
5042                                 res = method;
5043                                 break;
5044                         }
5045                 }
5046         }
5047         else {
5048                 /* Search directly in the metadata to avoid calling setup_methods () */
5049                 for (i = 0; i < klass->method.count; ++i) {
5050                         guint32 cols [MONO_METHOD_SIZE];
5051                         MonoMethod *method;
5052
5053                         mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_METHOD], klass->method.first + i, cols, MONO_METHOD_SIZE);
5054
5055                         if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
5056                                 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
5057                                 if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
5058                                         res = method;
5059                                         break;
5060                                 }
5061                         }
5062                 }
5063         }
5064
5065         return res;
5066 }
5067
5068 /**
5069  * mono_class_set_failure:
5070  * @klass: class in which the failure was detected
5071  * @ex_type: the kind of exception/error to be thrown (later)
5072  * @ex_data: exception data (specific to each type of exception/error)
5073  *
5074  * Keep a detected failure informations in the class for later processing.
5075  * Note that only the first failure is kept.
5076  */
5077 gboolean
5078 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
5079 {
5080         if (klass->exception_type)
5081                 return FALSE;
5082         klass->exception_type = ex_type;
5083         klass->exception_data = ex_data;
5084         return TRUE;
5085 }
5086
5087 /**
5088  * mono_classes_init:
5089  *
5090  * Initialize the resources used by this module.
5091  */
5092 void
5093 mono_classes_init (void)
5094 {
5095 }
5096
5097 /**
5098  * mono_classes_cleanup:
5099  *
5100  * Free the resources used by this module.
5101  */
5102 void
5103 mono_classes_cleanup (void)
5104 {
5105         IOffsetInfo *cached_info, *next;
5106
5107         if (global_interface_bitset)
5108                 mono_bitset_free (global_interface_bitset);
5109
5110         for (cached_info = cached_offset_info; cached_info;) {
5111                 next = cached_info->next;
5112
5113                 g_free (cached_info);
5114                 cached_info = next;
5115         }
5116 }
5117
5118 /**
5119  * mono_class_get_exception_for_failure:
5120  * @klass: class in which the failure was detected
5121  *
5122  * Return a constructed MonoException than the caller can then throw
5123  * using mono_raise_exception - or NULL if no failure is present (or
5124  * doesn't result in an exception).
5125  */
5126 MonoException*
5127 mono_class_get_exception_for_failure (MonoClass *klass)
5128 {
5129         switch (klass->exception_type) {
5130         case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
5131                 MonoDomain *domain = mono_domain_get ();
5132                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
5133                 MonoMethod *method = klass->exception_data;
5134                 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
5135                 MonoObject *exc = NULL;
5136                 gpointer args [4];
5137
5138                 args [0] = &error;
5139                 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
5140                 args [2] = mono_type_get_object (domain, &klass->byval_arg);
5141                 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
5142
5143                 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
5144                 return (MonoException*) exc;
5145         }
5146         case MONO_EXCEPTION_TYPE_LOAD:
5147                 return mono_exception_from_name (mono_defaults.corlib, "System", "TypeLoadException");
5148
5149         default: {
5150                 MonoLoaderError *error;
5151                 MonoException *ex;
5152                 
5153                 error = mono_loader_get_last_error ();
5154                 if (error != NULL){
5155                         ex = mono_loader_error_prepare_exception (error);
5156                         return ex;
5157                 }
5158                 
5159                 /* TODO - handle other class related failures */
5160                 return NULL;
5161         }
5162         }
5163 }