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