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