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