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