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