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