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