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