2 * class.c: Class management for the Mono runtime
5 * Miguel de Icaza (miguel@ximian.com)
7 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
19 #include <mono/io-layer/atomic.h>
21 #include <mono/metadata/image.h>
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/metadata.h>
24 #include <mono/metadata/metadata-internals.h>
25 #include <mono/metadata/profiler-private.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/tokentype.h>
28 #include <mono/metadata/class-internals.h>
29 #include <mono/metadata/object.h>
30 #include <mono/metadata/appdomain.h>
31 #include <mono/metadata/mono-endian.h>
32 #include <mono/metadata/debug-helpers.h>
33 #include <mono/metadata/reflection.h>
34 #include <mono/metadata/exception.h>
35 #include <mono/metadata/security-manager.h>
36 #include <mono/metadata/security-core-clr.h>
37 #include <mono/metadata/attrdefs.h>
38 #include <mono/metadata/gc-internal.h>
39 #include <mono/metadata/verify-internals.h>
40 #include <mono/metadata/mono-debug.h>
41 #include <mono/utils/mono-counters.h>
45 gboolean mono_print_vtable = FALSE;
48 * Controls whenever mono_class_init () constructs a generic vtable. This is TRUE by
49 * default to avoid breaking embedding apps, but set to FALSE by the runtime executable
52 gboolean mono_setup_vtable_in_class_init = TRUE;
55 guint32 inflated_classes, inflated_classes_size, inflated_methods_size;
56 guint32 classes_size, class_ext_size;
58 /* Function supplied by the runtime to find classes by name using information from the AOT file */
59 static MonoGetClassFromName get_class_from_name = NULL;
61 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
62 static gboolean mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res);
63 static gboolean can_access_type (MonoClass *access_klass, MonoClass *member_klass);
64 static MonoMethod* find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags);
65 static int generic_array_methods (MonoClass *class);
66 static void setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos);
68 static MonoMethod* mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter);
70 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
71 void (*mono_debugger_class_loaded_methods_func) (MonoClass *klass) = NULL;
74 * mono_class_from_typeref:
76 * @type_token: a TypeRef token
78 * Creates the MonoClass* structure representing the type defined by
79 * the typeref token valid inside @image.
80 * Returns: the MonoClass* representing the typeref token, NULL ifcould
84 mono_class_from_typeref (MonoImage *image, guint32 type_token)
86 guint32 cols [MONO_TYPEREF_SIZE];
87 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
89 const char *name, *nspace;
93 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
95 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
96 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
98 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
99 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
100 case MONO_RESOLTION_SCOPE_MODULE:
102 g_error ("null ResolutionScope not yet handled");
103 /* a typedef in disguise */
104 return mono_class_from_name (image, nspace, name);
105 case MONO_RESOLTION_SCOPE_MODULEREF:
106 module = mono_image_load_module (image, idx);
108 return mono_class_from_name (module, nspace, name);
110 char *msg = g_strdup_printf ("%s%s%s", nspace, nspace [0] ? "." : "", name);
113 human_name = mono_stringify_assembly_name (&image->assembly->aname);
114 mono_loader_set_error_type_load (msg, human_name);
120 case MONO_RESOLTION_SCOPE_TYPEREF: {
121 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
124 if (enclosing->nested_classes_inited && enclosing->ext) {
125 /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
126 for (tmp = enclosing->ext->nested_classes; tmp; tmp = tmp->next) {
128 if (strcmp (res->name, name) == 0)
132 /* Don't call mono_class_init as we might've been called by it recursively */
133 int i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, 1);
135 guint32 class_nested = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, MONO_NESTED_CLASS_NESTED);
136 guint32 string_offset = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_TYPEDEF], class_nested - 1, MONO_TYPEDEF_NAME);
137 const char *nname = mono_metadata_string_heap (enclosing->image, string_offset);
139 if (strcmp (nname, name) == 0)
140 return mono_class_create_from_typedef (enclosing->image, MONO_TOKEN_TYPE_DEF | class_nested);
142 i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, i + 1);
145 g_warning ("TypeRef ResolutionScope not yet handled (%d) for %s.%s in image %s", idx, nspace, name, image->name);
148 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
152 if (!image->references || !image->references [idx - 1])
153 mono_assembly_load_reference (image, idx - 1);
154 g_assert (image->references [idx - 1]);
156 /* If the assembly did not load, register this as a type load exception */
157 if (image->references [idx - 1] == REFERENCE_MISSING){
158 MonoAssemblyName aname;
161 mono_assembly_get_assemblyref (image, idx - 1, &aname);
162 human_name = mono_stringify_assembly_name (&aname);
163 mono_loader_set_error_assembly_load (human_name, image->assembly->ref_only);
169 return mono_class_from_name (image->references [idx - 1]->image, nspace, name);
174 mono_image_memdup (MonoImage *image, void *data, guint size)
176 void *res = mono_image_alloc (image, size);
177 memcpy (res, data, size);
181 /* Copy everything mono_metadata_free_array free. */
183 mono_dup_array_type (MonoImage *image, MonoArrayType *a)
186 a = mono_image_memdup (image, a, sizeof (MonoArrayType));
188 a->sizes = mono_image_memdup (image, a->sizes, a->numsizes * sizeof (int));
190 a->lobounds = mono_image_memdup (image, a->lobounds, a->numlobounds * sizeof (int));
192 a = g_memdup (a, sizeof (MonoArrayType));
194 a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
196 a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
201 /* Copy everything mono_metadata_free_method_signature free. */
203 mono_metadata_signature_deep_dup (MonoImage *image, MonoMethodSignature *sig)
207 sig = mono_metadata_signature_dup_full (image, sig);
209 sig->ret = mono_metadata_type_dup (image, sig->ret);
210 for (i = 0; i < sig->param_count; ++i)
211 sig->params [i] = mono_metadata_type_dup (image, sig->params [i]);
217 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
219 MonoAssembly *ta = klass->image->assembly;
221 g_string_append_printf (
222 str, ", %s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
224 ta->aname.major, ta->aname.minor, ta->aname.build, ta->aname.revision,
225 ta->aname.culture && *ta->aname.culture? ta->aname.culture: "neutral",
226 ta->aname.public_key_token [0] ? (char *)ta->aname.public_key_token : "null",
227 (ta->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
231 mono_type_name_check_byref (MonoType *type, GString *str)
234 g_string_append_c (str, '&');
238 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
239 MonoTypeNameFormat format)
243 switch (type->type) {
244 case MONO_TYPE_ARRAY: {
245 int i, rank = type->data.array->rank;
246 MonoTypeNameFormat nested_format;
248 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
249 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
251 mono_type_get_name_recurse (
252 &type->data.array->eklass->byval_arg, str, FALSE, nested_format);
253 g_string_append_c (str, '[');
255 g_string_append_c (str, '*');
256 for (i = 1; i < rank; i++)
257 g_string_append_c (str, ',');
258 g_string_append_c (str, ']');
260 mono_type_name_check_byref (type, str);
262 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
263 _mono_type_get_assembly_name (type->data.array->eklass, str);
266 case MONO_TYPE_SZARRAY: {
267 MonoTypeNameFormat nested_format;
269 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
270 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
272 mono_type_get_name_recurse (
273 &type->data.klass->byval_arg, str, FALSE, nested_format);
274 g_string_append (str, "[]");
276 mono_type_name_check_byref (type, str);
278 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
279 _mono_type_get_assembly_name (type->data.klass, str);
282 case MONO_TYPE_PTR: {
283 MonoTypeNameFormat nested_format;
285 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
286 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
288 mono_type_get_name_recurse (
289 type->data.type, str, FALSE, nested_format);
290 g_string_append_c (str, '*');
292 mono_type_name_check_byref (type, str);
294 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
295 _mono_type_get_assembly_name (mono_class_from_mono_type (type->data.type), str);
300 if (!mono_generic_param_info (type->data.generic_param))
301 g_string_append_printf (str, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", type->data.generic_param->num);
303 g_string_append (str, mono_generic_param_info (type->data.generic_param)->name);
305 mono_type_name_check_byref (type, str);
309 klass = mono_class_from_mono_type (type);
310 if (klass->nested_in) {
311 mono_type_get_name_recurse (
312 &klass->nested_in->byval_arg, str, TRUE, format);
313 if (format == MONO_TYPE_NAME_FORMAT_IL)
314 g_string_append_c (str, '.');
316 g_string_append_c (str, '+');
317 } else if (*klass->name_space) {
318 g_string_append (str, klass->name_space);
319 g_string_append_c (str, '.');
321 if (format == MONO_TYPE_NAME_FORMAT_IL) {
322 char *s = strchr (klass->name, '`');
323 int len = s ? s - klass->name : strlen (klass->name);
325 g_string_append_len (str, klass->name, len);
327 g_string_append (str, klass->name);
330 if (klass->generic_class) {
331 MonoGenericClass *gclass = klass->generic_class;
332 MonoGenericInst *inst = gclass->context.class_inst;
333 MonoTypeNameFormat nested_format;
336 nested_format = format == MONO_TYPE_NAME_FORMAT_FULL_NAME ?
337 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED : format;
339 if (format == MONO_TYPE_NAME_FORMAT_IL)
340 g_string_append_c (str, '<');
342 g_string_append_c (str, '[');
343 for (i = 0; i < inst->type_argc; i++) {
344 MonoType *t = inst->type_argv [i];
347 g_string_append_c (str, ',');
348 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
349 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
350 g_string_append_c (str, '[');
351 mono_type_get_name_recurse (inst->type_argv [i], str, FALSE, nested_format);
352 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
353 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
354 g_string_append_c (str, ']');
356 if (format == MONO_TYPE_NAME_FORMAT_IL)
357 g_string_append_c (str, '>');
359 g_string_append_c (str, ']');
360 } else if (klass->generic_container &&
361 (format != MONO_TYPE_NAME_FORMAT_FULL_NAME) &&
362 (format != MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)) {
365 if (format == MONO_TYPE_NAME_FORMAT_IL)
366 g_string_append_c (str, '<');
368 g_string_append_c (str, '[');
369 for (i = 0; i < klass->generic_container->type_argc; i++) {
371 g_string_append_c (str, ',');
372 g_string_append (str, mono_generic_container_get_param_info (klass->generic_container, i)->name);
374 if (format == MONO_TYPE_NAME_FORMAT_IL)
375 g_string_append_c (str, '>');
377 g_string_append_c (str, ']');
380 mono_type_name_check_byref (type, str);
382 if ((format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
383 (type->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
384 _mono_type_get_assembly_name (klass, str);
390 * mono_type_get_name:
392 * @format: the format for the return string.
395 * Returns: the string representation in a number of formats:
397 * if format is MONO_TYPE_NAME_FORMAT_REFLECTION, the return string is
398 * returned in the formatrequired by System.Reflection, this is the
399 * inverse of mono_reflection_parse_type ().
401 * if format is MONO_TYPE_NAME_FORMAT_IL, it returns a syntax that can
402 * be used by the IL assembler.
404 * if format is MONO_TYPE_NAME_FORMAT_FULL_NAME
406 * if format is MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED
409 mono_type_get_name_full (MonoType *type, MonoTypeNameFormat format)
413 result = g_string_new ("");
415 mono_type_get_name_recurse (type, result, FALSE, format);
417 return g_string_free (result, FALSE);
421 * mono_type_get_full_name:
424 * Returns: the string representation for type as required by System.Reflection.
425 * The inverse of mono_reflection_parse_type ().
428 mono_type_get_full_name (MonoClass *class)
430 return mono_type_get_name_full (mono_class_get_type (class), MONO_TYPE_NAME_FORMAT_REFLECTION);
434 * mono_type_get_name:
437 * Returns: the string representation for type as it would be represented in IL code.
440 mono_type_get_name (MonoType *type)
442 return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_IL);
446 * mono_type_get_underlying_type:
449 * Returns: the MonoType for the underlying integer type if @type
450 * is an enum and byref is false, otherwise the type itself.
453 mono_type_get_underlying_type (MonoType *type)
455 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype && !type->byref)
456 return mono_class_enum_basetype (type->data.klass);
457 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype && !type->byref)
458 return mono_class_enum_basetype (type->data.generic_class->container_class);
463 * mono_class_is_open_constructed_type:
466 * Returns TRUE if type represents a generics open constructed type
467 * (not all the type parameters required for the instantiation have
471 mono_class_is_open_constructed_type (MonoType *t)
477 case MONO_TYPE_SZARRAY:
478 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
479 case MONO_TYPE_ARRAY:
480 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
482 return mono_class_is_open_constructed_type (t->data.type);
483 case MONO_TYPE_GENERICINST:
484 return t->data.generic_class->context.class_inst->is_open;
491 inflate_generic_type (MonoImage *image, MonoType *type, MonoGenericContext *context)
493 switch (type->type) {
494 case MONO_TYPE_MVAR: {
496 int num = mono_type_get_generic_param_num (type);
497 MonoGenericInst *inst = context->method_inst;
498 if (!inst || !inst->type_argv)
500 if (num >= inst->type_argc)
501 g_error ("MVAR %d (%s) cannot be expanded in this context with %d instantiations",
502 num, mono_generic_param_info (type->data.generic_param)->name, inst->type_argc);
505 * Note that the VAR/MVAR cases are different from the rest. The other cases duplicate @type,
506 * while the VAR/MVAR duplicates a type from the context. So, we need to ensure that the
507 * ->byref and ->attrs from @type are propagated to the returned type.
509 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
510 nt->byref = type->byref;
511 nt->attrs = type->attrs;
514 case MONO_TYPE_VAR: {
516 int num = mono_type_get_generic_param_num (type);
517 MonoGenericInst *inst = context->class_inst;
520 if (num >= inst->type_argc)
521 g_error ("VAR %d (%s) cannot be expanded in this context with %d instantiations",
522 num, mono_generic_param_info (type->data.generic_param)->name, inst->type_argc);
523 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
524 nt->byref = type->byref;
525 nt->attrs = type->attrs;
528 case MONO_TYPE_SZARRAY: {
529 MonoClass *eclass = type->data.klass;
530 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context);
533 nt = mono_metadata_type_dup (image, type);
534 nt->data.klass = mono_class_from_mono_type (inflated);
535 mono_metadata_free_type (inflated);
538 case MONO_TYPE_ARRAY: {
539 MonoClass *eclass = type->data.array->eklass;
540 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context);
543 nt = mono_metadata_type_dup (image, type);
544 nt->data.array = g_memdup (nt->data.array, sizeof (MonoArrayType));
545 nt->data.array->eklass = mono_class_from_mono_type (inflated);
546 mono_metadata_free_type (inflated);
549 case MONO_TYPE_GENERICINST: {
550 MonoGenericClass *gclass = type->data.generic_class;
551 MonoGenericInst *inst;
553 if (!gclass->context.class_inst->is_open)
556 inst = mono_metadata_inflate_generic_inst (gclass->context.class_inst, context);
557 if (inst != gclass->context.class_inst)
558 gclass = mono_metadata_lookup_generic_class (gclass->container_class, inst, gclass->is_dynamic);
560 if (gclass == type->data.generic_class)
563 nt = mono_metadata_type_dup (image, type);
564 nt->data.generic_class = gclass;
567 case MONO_TYPE_CLASS:
568 case MONO_TYPE_VALUETYPE: {
569 MonoClass *klass = type->data.klass;
570 MonoGenericContainer *container = klass->generic_container;
571 MonoGenericInst *inst;
572 MonoGenericClass *gclass = NULL;
578 /* We can't use context->class_inst directly, since it can have more elements */
579 inst = mono_metadata_inflate_generic_inst (container->context.class_inst, context);
580 if (inst == container->context.class_inst)
583 gclass = mono_metadata_lookup_generic_class (klass, inst, klass->image->dynamic);
585 nt = mono_metadata_type_dup (image, type);
586 nt->type = MONO_TYPE_GENERICINST;
587 nt->data.generic_class = gclass;
597 mono_generic_class_get_context (MonoGenericClass *gclass)
599 return &gclass->context;
603 mono_class_get_context (MonoClass *class)
605 return class->generic_class ? mono_generic_class_get_context (class->generic_class) : NULL;
609 * mono_class_get_generic_container:
611 * Return the generic container of KLASS which should be a generic type definition.
613 MonoGenericContainer*
614 mono_class_get_generic_container (MonoClass *klass)
616 g_assert (klass->is_generic);
618 return klass->generic_container;
622 * mono_class_get_generic_class:
624 * Return the MonoGenericClass of KLASS, which should be a generic instance.
627 mono_class_get_generic_class (MonoClass *klass)
629 g_assert (klass->is_inflated);
631 return klass->generic_class;
635 * mono_class_inflate_generic_type_with_mempool:
636 * @mempool: a mempool
638 * @context: a generics context
640 * The same as mono_class_inflate_generic_type, but allocates the MonoType
641 * from mempool if it is non-NULL. If it is NULL, the MonoType is
642 * allocated on the heap and is owned by the caller.
643 * The returned type can potentially be the same as TYPE, so it should not be
644 * modified by the caller, and it should be freed using mono_metadata_free_type ().
647 mono_class_inflate_generic_type_with_mempool (MonoImage *image, MonoType *type, MonoGenericContext *context)
649 MonoType *inflated = NULL;
652 inflated = inflate_generic_type (image, type, context);
655 MonoType *shared = mono_metadata_get_shared_type (type);
660 return mono_metadata_type_dup (image, type);
664 mono_stats.inflated_type_count++;
669 * mono_class_inflate_generic_type:
671 * @context: a generics context
673 * If @type is a generic type and @context is not NULL, instantiate it using the
674 * generics context @context.
676 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
677 * on the heap and is owned by the caller.
680 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
682 return mono_class_inflate_generic_type_with_mempool (NULL, type, context);
686 * mono_class_inflate_generic_type_no_copy:
688 * Same as inflate_generic_type_with_mempool, but return TYPE if no inflation
692 mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context)
694 MonoType *inflated = NULL;
697 inflated = inflate_generic_type (image, type, context);
702 mono_stats.inflated_type_count++;
707 * mono_class_inflate_generic_class:
709 * Inflate the class GKLASS with CONTEXT.
712 mono_class_inflate_generic_class (MonoClass *gklass, MonoGenericContext *context)
717 inflated = mono_class_inflate_generic_type (&gklass->byval_arg, context);
719 res = mono_class_from_mono_type (inflated);
720 mono_metadata_free_type (inflated);
725 static MonoGenericContext
726 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with)
728 MonoGenericInst *class_inst = NULL;
729 MonoGenericInst *method_inst = NULL;
730 MonoGenericContext res;
732 if (context->class_inst)
733 class_inst = mono_metadata_inflate_generic_inst (context->class_inst, inflate_with);
735 if (context->method_inst)
736 method_inst = mono_metadata_inflate_generic_inst (context->method_inst, inflate_with);
738 res.class_inst = class_inst;
739 res.method_inst = method_inst;
745 * mono_class_inflate_generic_method:
746 * @method: a generic method
747 * @context: a generics context
749 * Instantiate the generic method @method using the generics context @context.
751 * Returns: the new instantiated method
754 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
756 return mono_class_inflate_generic_method_full (method, NULL, context);
760 * mono_class_inflate_generic_method:
762 * Instantiate method @method with the generic context @context.
763 * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
764 * Use mono_method_signature () and mono_method_get_header () to get the correct values.
767 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
770 MonoMethodInflated *iresult, *cached;
771 MonoMethodSignature *sig;
772 MonoGenericContext tmp_context;
773 gboolean is_mb_open = FALSE;
775 /* The `method' has already been instantiated before => we need to peel out the instantiation and create a new context */
776 while (method->is_inflated) {
777 MonoGenericContext *method_context = mono_method_get_context (method);
778 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
780 tmp_context = inflate_generic_context (method_context, context);
781 context = &tmp_context;
783 if (mono_metadata_generic_context_equal (method_context, context))
786 method = imethod->declaring;
789 if (!method->is_generic && !method->klass->generic_container)
793 * The reason for this hack is to fix the behavior of inflating generic methods that come from a MethodBuilder.
794 * What happens is that instantiating a generic MethodBuilder with its own arguments should create a diferent object.
795 * This is opposite to the way non-SRE MethodInfos behave.
797 * This happens, for example, when we want to emit a recursive generic method. Given the following C# code:
799 * void Example<T> () {
803 * In Example, the method token must be encoded as: "void Example<!!0>()"
805 * The reference to the first generic argument, "!!0", must be explicit otherwise it won't be inflated
806 * properly. To get that we need to inflate the MethodBuilder with its own arguments.
808 * On the other hand, inflating a non-SRE generic method with its own arguments should
809 * return itself. For example:
811 * MethodInfo m = ... //m is a generic method definition
812 * MethodInfo res = m.MakeGenericMethod (m.GetGenericArguments ());
815 * To allow such scenarios we must allow inflation of MethodBuilder to happen in a diferent way than
816 * what happens with regular methods.
818 * There is one last touch to this madness, once a TypeBuilder is finished, IOW CreateType() is called,
819 * everything should behave like a regular type or method.
822 is_mb_open = method->is_generic &&
823 method->klass->image->dynamic && !method->klass->wastypebuilder && /* that is a MethodBuilder from an unfinished TypeBuilder */
824 context->method_inst == mono_method_get_generic_container (method)->context.method_inst; /* and it's been instantiated with its own arguments. */
826 iresult = g_new0 (MonoMethodInflated, 1);
827 iresult->context = *context;
828 iresult->declaring = method;
829 iresult->method.method.is_mb_open = is_mb_open;
831 if (!context->method_inst && method->is_generic)
832 iresult->context.method_inst = mono_method_get_generic_container (method)->context.method_inst;
834 if (!context->class_inst) {
835 g_assert (!iresult->declaring->klass->generic_class);
836 if (iresult->declaring->klass->generic_container)
837 iresult->context.class_inst = iresult->declaring->klass->generic_container->context.class_inst;
838 else if (iresult->declaring->klass->generic_class)
839 iresult->context.class_inst = iresult->declaring->klass->generic_class->context.class_inst;
843 cached = mono_method_inflated_lookup (iresult, FALSE);
845 mono_loader_unlock ();
847 return (MonoMethod*)cached;
850 mono_stats.inflated_method_count++;
852 inflated_methods_size += sizeof (MonoMethodInflated);
854 sig = mono_method_signature (method);
856 memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
858 memcpy (&iresult->method.normal, method, sizeof (MonoMethodNormal));
859 iresult->method.normal.header = NULL;
862 result = (MonoMethod *) iresult;
863 result->is_inflated = TRUE;
864 result->is_generic = FALSE;
865 result->signature = NULL;
866 result->is_mb_open = is_mb_open;
868 if (!context->method_inst) {
869 /* Set the generic_container of the result to the generic_container of method */
870 MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
872 if (generic_container) {
873 result->is_generic = 1;
874 mono_method_set_generic_container (result, generic_container);
878 if (!klass_hint || !klass_hint->generic_class ||
879 klass_hint->generic_class->container_class != method->klass ||
880 klass_hint->generic_class->context.class_inst != context->class_inst)
883 if (method->klass->generic_container)
884 result->klass = klass_hint;
886 if (!result->klass) {
887 MonoType *inflated = inflate_generic_type (NULL, &method->klass->byval_arg, context);
888 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
890 mono_metadata_free_type (inflated);
893 mono_method_inflated_lookup (iresult, TRUE);
894 mono_loader_unlock ();
899 * mono_get_inflated_method:
901 * Obsolete. We keep it around since it's mentioned in the public API.
904 mono_get_inflated_method (MonoMethod *method)
910 * mono_method_get_context_general:
912 * @uninflated: handle uninflated methods?
914 * Returns the generic context of a method or NULL if it doesn't have
915 * one. For an inflated method that's the context stored in the
916 * method. Otherwise it's in the method's generic container or in the
917 * generic container of the method's class.
920 mono_method_get_context_general (MonoMethod *method, gboolean uninflated)
922 if (method->is_inflated) {
923 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
924 return &imethod->context;
928 if (method->is_generic)
929 return &(mono_method_get_generic_container (method)->context);
930 if (method->klass->generic_container)
931 return &method->klass->generic_container->context;
936 * mono_method_get_context:
939 * Returns the generic context for method if it's inflated, otherwise
943 mono_method_get_context (MonoMethod *method)
945 return mono_method_get_context_general (method, FALSE);
949 * mono_method_get_generic_container:
951 * Returns the generic container of METHOD, which should be a generic method definition.
952 * Returns NULL if METHOD is not a generic method definition.
953 * LOCKING: Acquires the loader lock.
955 MonoGenericContainer*
956 mono_method_get_generic_container (MonoMethod *method)
958 MonoGenericContainer *container;
960 if (!method->is_generic)
963 container = mono_image_property_lookup (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER);
964 g_assert (container);
970 * mono_method_set_generic_container:
972 * Sets the generic container of METHOD to CONTAINER.
973 * LOCKING: Acquires the loader lock.
976 mono_method_set_generic_container (MonoMethod *method, MonoGenericContainer* container)
978 g_assert (method->is_generic);
980 mono_image_property_insert (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER, container);
984 * mono_class_find_enum_basetype:
985 * @class: The enum class
987 * Determine the basetype of an enum by iterating through its fields. We do this
988 * in a separate function since it is cheaper than calling mono_class_setup_fields.
991 mono_class_find_enum_basetype (MonoClass *class)
993 MonoImage *m = class->image;
994 const int top = class->field.count;
997 g_assert (class->enumtype);
1000 * Fetch all the field information.
1002 for (i = 0; i < top; i++){
1004 guint32 cols [MONO_FIELD_SIZE];
1005 int idx = class->field.first + i;
1006 MonoGenericContainer *container = NULL;
1009 /* class->field.first and idx points into the fieldptr table */
1010 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1011 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1012 mono_metadata_decode_value (sig, &sig);
1013 /* FIELD signature == 0x06 */
1014 g_assert (*sig == 0x06);
1015 if (class->generic_container)
1016 container = class->generic_container;
1017 else if (class->generic_class) {
1018 MonoClass *gklass = class->generic_class->container_class;
1020 container = gklass->generic_container;
1021 g_assert (container);
1023 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1026 if (class->generic_class) {
1027 //FIXME do we leak here?
1028 ftype = mono_class_inflate_generic_type (ftype, mono_class_get_context (class));
1029 ftype->attrs = cols [MONO_FIELD_FLAGS];
1032 if (class->enumtype && !(cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC))
1040 * mono_class_setup_fields:
1041 * @class: The class to initialize
1043 * Initializes the class->fields.
1044 * LOCKING: Assumes the loader lock is held.
1047 mono_class_setup_fields (MonoClass *class)
1049 MonoImage *m = class->image;
1050 int top = class->field.count;
1051 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1052 int i, blittable = TRUE;
1053 guint32 real_size = 0;
1054 guint32 packing_size = 0;
1055 gboolean explicit_size;
1056 MonoClassField *field;
1057 MonoGenericContainer *container = NULL;
1058 MonoClass *gklass = NULL;
1060 if (class->size_inited)
1063 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1065 * This happens when a generic instance of an unfinished generic typebuilder
1066 * is used as an element type for creating an array type. We can't initialize
1067 * the fields of this class using the fields of gklass, since gklass is not
1068 * finished yet, fields could be added to it later.
1073 if (class->generic_class) {
1074 MonoClass *gklass = class->generic_class->container_class;
1075 mono_class_setup_fields (gklass);
1076 top = gklass->field.count;
1077 class->field.first = gklass->field.first;
1078 class->field.count = gklass->field.count;
1081 class->instance_size = 0;
1083 class->sizes.class_size = 0;
1085 if (class->parent) {
1086 /* For generic instances, class->parent might not have been initialized */
1087 mono_class_init (class->parent);
1088 if (!class->parent->size_inited)
1089 mono_class_setup_fields (class->parent);
1090 class->instance_size += class->parent->instance_size;
1091 class->min_align = class->parent->min_align;
1092 /* we use |= since it may have been set already */
1093 class->has_references |= class->parent->has_references;
1094 blittable = class->parent->blittable;
1096 class->instance_size = sizeof (MonoObject);
1097 class->min_align = 1;
1100 if (class->simd_type)
1101 class->min_align = 16;
1103 /* Get the real size */
1104 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1106 if (explicit_size) {
1107 g_assert ((packing_size & 0xfffffff0) == 0);
1108 class->packing_size = packing_size;
1109 real_size += class->instance_size;
1113 if (explicit_size && real_size) {
1114 class->instance_size = MAX (real_size, class->instance_size);
1116 class->size_inited = 1;
1117 class->blittable = blittable;
1121 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1124 /* Prevent infinite loops if the class references itself */
1125 class->size_inited = 1;
1127 class->fields = mono_image_alloc0 (class->image, sizeof (MonoClassField) * top);
1129 if (class->generic_container) {
1130 container = class->generic_container;
1131 } else if (class->generic_class) {
1132 gklass = class->generic_class->container_class;
1133 container = gklass->generic_container;
1134 g_assert (container);
1136 mono_class_setup_fields (gklass);
1138 if (gklass->exception_type) {
1139 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1145 * Fetch all the field information.
1147 for (i = 0; i < top; i++){
1148 int idx = class->field.first + i;
1149 field = &class->fields [i];
1151 field->parent = class;
1153 if (class->generic_class) {
1154 MonoClassField *gfield = &gklass->fields [i];
1156 field->name = mono_field_get_name (gfield);
1157 /*This memory must come from the image mempool as we don't have a chance to free it.*/
1158 field->type = mono_class_inflate_generic_type_no_copy (class->image, gfield->type, mono_class_get_context (class));
1159 g_assert (field->type->attrs == gfield->type->attrs);
1160 if (mono_field_is_deleted (field))
1162 field->offset = gfield->offset;
1165 guint32 cols [MONO_FIELD_SIZE];
1167 /* class->field.first and idx points into the fieldptr table */
1168 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1169 /* The name is needed for fieldrefs */
1170 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
1171 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1172 mono_metadata_decode_value (sig, &sig);
1173 /* FIELD signature == 0x06 */
1174 g_assert (*sig == 0x06);
1175 field->type = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1177 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1180 if (mono_field_is_deleted (field))
1182 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1184 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1185 field->offset = offset;
1186 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1187 g_warning ("%s not initialized correctly (missing field layout info for %s)",
1188 class->name, mono_field_get_name (field));
1192 /* Only do these checks if we still think this type is blittable */
1193 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1194 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1197 MonoClass *field_class = mono_class_from_mono_type (field->type);
1199 mono_class_setup_fields (field_class);
1200 if (!field_class || !field_class->blittable)
1205 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1206 class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1207 blittable = class->element_class->blittable;
1210 /* The def_value of fields is compute lazily during vtable creation */
1213 if (class == mono_defaults.string_class)
1216 class->blittable = blittable;
1218 if (class->enumtype && !mono_class_enum_basetype (class)) {
1219 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
1222 if (explicit_size && real_size) {
1223 class->instance_size = MAX (real_size, class->instance_size);
1226 if (class->exception_type)
1228 mono_class_layout_fields (class);
1232 * mono_class_setup_fields_locking:
1233 * @class: The class to initialize
1235 * Initializes the class->fields array of fields.
1236 * Aquires the loader lock.
1239 mono_class_setup_fields_locking (MonoClass *class)
1241 mono_loader_lock ();
1242 mono_class_setup_fields (class);
1243 mono_loader_unlock ();
1247 * mono_class_has_references:
1249 * Returns whenever @klass->has_references is set, initializing it if needed.
1250 * Aquires the loader lock.
1253 mono_class_has_references (MonoClass *klass)
1255 if (klass->init_pending) {
1256 /* Be conservative */
1259 mono_class_init (klass);
1261 return klass->has_references;
1265 /* useful until we keep track of gc-references in corlib etc. */
1267 #define IS_GC_REFERENCE(t) FALSE
1269 #define IS_GC_REFERENCE(t) ((t)->type == MONO_TYPE_U && class->image == mono_defaults.corlib)
1273 * mono_type_get_basic_type_from_generic:
1276 * Returns a closed type corresponding to the possibly open type
1280 mono_type_get_basic_type_from_generic (MonoType *type)
1282 /* When we do generic sharing we let type variables stand for reference types. */
1283 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1284 return &mono_defaults.object_class->byval_arg;
1289 * mono_class_layout_fields:
1292 * Compute the placement of fields inside an object or struct, according to
1293 * the layout rules and set the following fields in @class:
1294 * - has_references (if the class contains instance references firled or structs that contain references)
1295 * - has_static_refs (same, but for static fields)
1296 * - instance_size (size of the object in memory)
1297 * - class_size (size needed for the static fields)
1298 * - size_inited (flag set when the instance_size is set)
1300 * LOCKING: this is supposed to be called with the loader lock held.
1303 mono_class_layout_fields (MonoClass *class)
1306 const int top = class->field.count;
1307 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1308 guint32 pass, passes, real_size;
1309 gboolean gc_aware_layout = FALSE;
1310 MonoClassField *field;
1313 * When we do generic sharing we need to have layout
1314 * information for open generic classes (either with a generic
1315 * context containing type variables or with a generic
1316 * container), so we don't return in that case anymore.
1320 * Enable GC aware auto layout: in this mode, reference
1321 * fields are grouped together inside objects, increasing collector
1323 * Requires that all classes whose layout is known to native code be annotated
1324 * with [StructLayout (LayoutKind.Sequential)]
1325 * Value types have gc_aware_layout disabled by default, as per
1326 * what the default is for other runtimes.
1328 /* corlib is missing [StructLayout] directives in many places */
1329 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1330 if (class->image != mono_defaults.corlib &&
1331 class->byval_arg.type != MONO_TYPE_VALUETYPE)
1332 gc_aware_layout = TRUE;
1333 /* from System.dll, used in metadata/process.h */
1334 if (strcmp (class->name, "ProcessStartInfo") == 0)
1335 gc_aware_layout = FALSE;
1338 /* Compute klass->has_references */
1340 * Process non-static fields first, since static fields might recursively
1341 * refer to the class itself.
1343 for (i = 0; i < top; i++) {
1346 field = &class->fields [i];
1348 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1349 ftype = mono_type_get_underlying_type (field->type);
1350 ftype = mono_type_get_basic_type_from_generic (ftype);
1351 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1352 class->has_references = TRUE;
1356 for (i = 0; i < top; i++) {
1359 field = &class->fields [i];
1361 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1362 ftype = mono_type_get_underlying_type (field->type);
1363 ftype = mono_type_get_basic_type_from_generic (ftype);
1364 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1365 class->has_static_refs = TRUE;
1369 for (i = 0; i < top; i++) {
1372 field = &class->fields [i];
1374 ftype = mono_type_get_underlying_type (field->type);
1375 ftype = mono_type_get_basic_type_from_generic (ftype);
1376 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1377 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1378 class->has_static_refs = TRUE;
1380 class->has_references = TRUE;
1385 * Compute field layout and total size (not considering static fields)
1389 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1390 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1392 if (gc_aware_layout)
1397 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1401 real_size = class->parent->instance_size;
1403 real_size = sizeof (MonoObject);
1405 for (pass = 0; pass < passes; ++pass) {
1406 for (i = 0; i < top; i++){
1411 field = &class->fields [i];
1413 if (mono_field_is_deleted (field))
1415 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1418 ftype = mono_type_get_underlying_type (field->type);
1419 ftype = mono_type_get_basic_type_from_generic (ftype);
1420 if (gc_aware_layout) {
1421 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1430 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1431 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1432 /* This field is a hack inserted by MCS to empty structures */
1436 size = mono_type_size (field->type, &align);
1438 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1439 align = class->packing_size ? MIN (class->packing_size, align): align;
1440 /* if the field has managed references, we need to force-align it
1443 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1444 align = MAX (align, sizeof (gpointer));
1446 class->min_align = MAX (align, class->min_align);
1447 field->offset = real_size;
1448 field->offset += align - 1;
1449 field->offset &= ~(align - 1);
1450 real_size = field->offset + size;
1453 class->instance_size = MAX (real_size, class->instance_size);
1455 if (class->instance_size & (class->min_align - 1)) {
1456 class->instance_size += class->min_align - 1;
1457 class->instance_size &= ~(class->min_align - 1);
1461 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1463 for (i = 0; i < top; i++) {
1468 field = &class->fields [i];
1471 * There must be info about all the fields in a type if it
1472 * uses explicit layout.
1475 if (mono_field_is_deleted (field))
1477 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1480 size = mono_type_size (field->type, &align);
1481 class->min_align = MAX (align, class->min_align);
1484 * When we get here, field->offset is already set by the
1485 * loader (for either runtime fields or fields loaded from metadata).
1486 * The offset is from the start of the object: this works for both
1487 * classes and valuetypes.
1489 field->offset += sizeof (MonoObject);
1490 ftype = mono_type_get_underlying_type (field->type);
1491 ftype = mono_type_get_basic_type_from_generic (ftype);
1492 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1493 if (field->offset % sizeof (gpointer)) {
1494 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1501 real_size = MAX (real_size, size + field->offset);
1503 class->instance_size = MAX (real_size, class->instance_size);
1507 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1509 * For small structs, set min_align to at least the struct size to improve
1510 * performance, and since the JIT memset/memcpy code assumes this and generates
1511 * unaligned accesses otherwise. See #78990 for a testcase.
1513 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1514 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1517 class->size_inited = 1;
1520 * Compute static field layout and size
1522 for (i = 0; i < top; i++){
1526 field = &class->fields [i];
1528 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1530 if (mono_field_is_deleted (field))
1533 size = mono_type_size (field->type, &align);
1534 field->offset = class->sizes.class_size;
1535 field->offset += align - 1;
1536 field->offset &= ~(align - 1);
1537 class->sizes.class_size = field->offset + size;
1542 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1546 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1547 method->klass = class;
1548 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1549 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1550 method->signature = sig;
1551 method->name = name;
1554 if (name [0] == '.') {
1555 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1557 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1563 * mono_class_setup_methods:
1566 * Initializes the 'methods' array in the klass.
1567 * Calling this method should be avoided if possible since it allocates a lot
1568 * of long-living MonoMethod structures.
1569 * Methods belonging to an interface are assigned a sequential slot starting
1573 mono_class_setup_methods (MonoClass *class)
1576 MonoMethod **methods;
1581 mono_loader_lock ();
1583 if (class->methods) {
1584 mono_loader_unlock ();
1588 if (class->generic_class) {
1589 MonoClass *gklass = class->generic_class->container_class;
1591 mono_class_init (gklass);
1592 mono_class_setup_methods (gklass);
1594 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1595 class->method.count = gklass->method.count;
1596 methods = g_new0 (MonoMethod *, class->method.count + 1);
1598 for (i = 0; i < class->method.count; i++) {
1599 methods [i] = mono_class_inflate_generic_method_full (
1600 gklass->methods [i], class, mono_class_get_context (class));
1602 } else if (class->rank) {
1603 MonoMethod *amethod;
1604 MonoMethodSignature *sig;
1605 int count_generic = 0, first_generic = 0;
1608 class->method.count = 3 + (class->rank > 1? 2: 1);
1610 mono_class_setup_interfaces (class);
1612 if (class->interface_count) {
1613 count_generic = generic_array_methods (class);
1614 first_generic = class->method.count;
1615 class->method.count += class->interface_count * count_generic;
1618 methods = mono_image_alloc0 (class->image, sizeof (MonoMethod*) * class->method.count);
1620 sig = mono_metadata_signature_alloc (class->image, class->rank);
1621 sig->ret = &mono_defaults.void_class->byval_arg;
1622 sig->pinvoke = TRUE;
1623 sig->hasthis = TRUE;
1624 for (i = 0; i < class->rank; ++i)
1625 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1627 amethod = create_array_method (class, ".ctor", sig);
1628 methods [method_num++] = amethod;
1629 if (class->rank > 1) {
1630 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1631 sig->ret = &mono_defaults.void_class->byval_arg;
1632 sig->pinvoke = TRUE;
1633 sig->hasthis = TRUE;
1634 for (i = 0; i < class->rank * 2; ++i)
1635 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1637 amethod = create_array_method (class, ".ctor", sig);
1638 methods [method_num++] = amethod;
1640 /* element Get (idx11, [idx2, ...]) */
1641 sig = mono_metadata_signature_alloc (class->image, class->rank);
1642 sig->ret = &class->element_class->byval_arg;
1643 sig->pinvoke = TRUE;
1644 sig->hasthis = TRUE;
1645 for (i = 0; i < class->rank; ++i)
1646 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1647 amethod = create_array_method (class, "Get", sig);
1648 methods [method_num++] = amethod;
1649 /* element& Address (idx11, [idx2, ...]) */
1650 sig = mono_metadata_signature_alloc (class->image, class->rank);
1651 sig->ret = &class->element_class->this_arg;
1652 sig->pinvoke = TRUE;
1653 sig->hasthis = TRUE;
1654 for (i = 0; i < class->rank; ++i)
1655 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1656 amethod = create_array_method (class, "Address", sig);
1657 methods [method_num++] = amethod;
1658 /* void Set (idx11, [idx2, ...], element) */
1659 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1660 sig->ret = &mono_defaults.void_class->byval_arg;
1661 sig->pinvoke = TRUE;
1662 sig->hasthis = TRUE;
1663 for (i = 0; i < class->rank; ++i)
1664 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1665 sig->params [i] = &class->element_class->byval_arg;
1666 amethod = create_array_method (class, "Set", sig);
1667 methods [method_num++] = amethod;
1669 for (i = 0; i < class->interface_count; i++)
1670 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1672 methods = mono_image_alloc (class->image, sizeof (MonoMethod*) * class->method.count);
1673 for (i = 0; i < class->method.count; ++i) {
1674 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1675 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1679 if (MONO_CLASS_IS_INTERFACE (class))
1680 for (i = 0; i < class->method.count; ++i)
1681 methods [i]->slot = i;
1683 /* Needed because of the double-checking locking pattern */
1684 mono_memory_barrier ();
1686 class->methods = methods;
1688 if (mono_debugger_class_loaded_methods_func)
1689 mono_debugger_class_loaded_methods_func (class);
1691 mono_loader_unlock ();
1695 * mono_class_get_method_by_index:
1697 * Returns class->methods [index], initializing class->methods if neccesary.
1699 * LOCKING: Acquires the loader lock.
1702 mono_class_get_method_by_index (MonoClass *class, int index)
1704 /* Avoid calling setup_methods () if possible */
1705 if (class->generic_class && !class->methods) {
1706 MonoClass *gklass = class->generic_class->container_class;
1709 m = mono_class_inflate_generic_method_full (
1710 gklass->methods [index], class, mono_class_get_context (class));
1712 * If setup_methods () is called later for this class, no duplicates are created,
1713 * since inflate_generic_method guarantees that only one instance of a method
1714 * is created for each context.
1717 mono_class_setup_methods (class);
1718 g_assert (m == class->methods [index]);
1722 mono_class_setup_methods (class);
1723 g_assert (index >= 0 && index < class->method.count);
1724 return class->methods [index];
1729 * mono_class_get_inflated_method:
1731 * Given an inflated class CLASS and a method METHOD which should be a method of
1732 * CLASS's generic definition, return the inflated method corresponding to METHOD.
1735 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
1737 MonoClass *gklass = class->generic_class->container_class;
1740 mono_class_setup_methods (gklass);
1741 for (i = 0; i < gklass->method.count; ++i) {
1742 if (gklass->methods [i] == method) {
1744 return class->methods [i];
1746 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
1754 * mono_class_get_vtable_entry:
1756 * Returns class->vtable [offset], computing it if neccesary.
1757 * LOCKING: Acquires the loader lock.
1760 mono_class_get_vtable_entry (MonoClass *class, int offset)
1764 if (class->rank == 1) {
1766 * szarrays do not overwrite any methods of Array, so we can avoid
1767 * initializing their vtables in some cases.
1769 mono_class_setup_vtable (class->parent);
1770 if (offset < class->parent->vtable_size)
1771 return class->parent->vtable [offset];
1774 if (class->generic_class) {
1775 MonoClass *gklass = class->generic_class->container_class;
1776 mono_class_setup_vtable (gklass);
1777 m = gklass->vtable [offset];
1779 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
1781 mono_class_setup_vtable (class);
1782 m = class->vtable [offset];
1789 mono_class_setup_properties (MonoClass *class)
1791 guint startm, endm, i, j;
1792 guint32 cols [MONO_PROPERTY_SIZE];
1793 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1794 MonoProperty *properties;
1797 if (class->ext && class->ext->properties)
1800 mono_loader_lock ();
1802 if (class->ext && class->ext->properties) {
1803 mono_loader_unlock ();
1807 mono_class_alloc_ext (class);
1809 if (class->generic_class) {
1810 MonoClass *gklass = class->generic_class->container_class;
1812 mono_class_init (gklass);
1813 mono_class_setup_properties (gklass);
1815 class->ext->property = gklass->ext->property;
1817 properties = g_new0 (MonoProperty, class->ext->property.count + 1);
1819 for (i = 0; i < class->ext->property.count; i++) {
1820 MonoProperty *prop = &properties [i];
1822 *prop = gklass->ext->properties [i];
1825 prop->get = mono_class_inflate_generic_method_full (
1826 prop->get, class, mono_class_get_context (class));
1828 prop->set = mono_class_inflate_generic_method_full (
1829 prop->set, class, mono_class_get_context (class));
1831 prop->parent = class;
1834 class->ext->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1835 class->ext->property.count = last - class->ext->property.first;
1837 if (class->ext->property.count)
1838 mono_class_setup_methods (class);
1840 properties = mono_image_alloc0 (class->image, sizeof (MonoProperty) * class->ext->property.count);
1841 for (i = class->ext->property.first; i < last; ++i) {
1842 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
1843 properties [i - class->ext->property.first].parent = class;
1844 properties [i - class->ext->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
1845 properties [i - class->ext->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
1847 startm = mono_metadata_methods_from_property (class->image, i, &endm);
1848 for (j = startm; j < endm; ++j) {
1851 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1853 if (class->image->uncompressed_metadata)
1854 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1855 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1857 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1859 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1860 case METHOD_SEMANTIC_SETTER:
1861 properties [i - class->ext->property.first].set = method;
1863 case METHOD_SEMANTIC_GETTER:
1864 properties [i - class->ext->property.first].get = method;
1872 /*Flush any pending writes as we do double checked locking on class->properties */
1873 mono_memory_barrier ();
1875 /* Leave this assignment as the last op in the function */
1876 class->ext->properties = properties;
1878 mono_loader_unlock ();
1882 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
1884 MonoMethod **om, **retval;
1887 for (om = methods, count = 0; *om; ++om, ++count)
1890 retval = g_new0 (MonoMethod*, count + 1);
1892 for (om = methods, count = 0; *om; ++om, ++count)
1893 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
1899 mono_class_setup_events (MonoClass *class)
1901 guint startm, endm, i, j;
1902 guint32 cols [MONO_EVENT_SIZE];
1903 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1907 if (class->ext && class->ext->events)
1910 mono_loader_lock ();
1912 if (class->ext && class->ext->events) {
1913 mono_loader_unlock ();
1917 mono_class_alloc_ext (class);
1919 if (class->generic_class) {
1920 MonoClass *gklass = class->generic_class->container_class;
1921 MonoGenericContext *context;
1923 mono_class_setup_events (gklass);
1924 class->ext->event = gklass->ext->event;
1926 class->ext->events = g_new0 (MonoEvent, class->ext->event.count);
1928 if (class->ext->event.count)
1929 context = mono_class_get_context (class);
1931 for (i = 0; i < class->ext->event.count; i++) {
1932 MonoEvent *event = &class->ext->events [i];
1933 MonoEvent *gevent = &gklass->ext->events [i];
1935 event->parent = class;
1936 event->name = gevent->name;
1937 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
1938 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
1939 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
1940 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
1941 event->attrs = gevent->attrs;
1944 mono_loader_unlock ();
1948 class->ext->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1949 class->ext->event.count = last - class->ext->event.first;
1951 if (class->ext->event.count)
1952 mono_class_setup_methods (class);
1954 events = mono_image_alloc0 (class->image, sizeof (MonoEvent) * class->ext->event.count);
1955 for (i = class->ext->event.first; i < last; ++i) {
1956 MonoEvent *event = &events [i - class->ext->event.first];
1958 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
1959 event->parent = class;
1960 event->attrs = cols [MONO_EVENT_FLAGS];
1961 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
1963 startm = mono_metadata_methods_from_event (class->image, i, &endm);
1964 for (j = startm; j < endm; ++j) {
1967 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1969 if (class->image->uncompressed_metadata)
1970 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1971 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1973 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1975 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1976 case METHOD_SEMANTIC_ADD_ON:
1977 event->add = method;
1979 case METHOD_SEMANTIC_REMOVE_ON:
1980 event->remove = method;
1982 case METHOD_SEMANTIC_FIRE:
1983 event->raise = method;
1985 case METHOD_SEMANTIC_OTHER: {
1988 if (event->other == NULL) {
1989 event->other = g_new0 (MonoMethod*, 2);
1991 while (event->other [n])
1993 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
1995 event->other [n] = method;
1996 /* NULL terminated */
1997 event->other [n + 1] = NULL;
2005 /*Flush any pending writes as we do double checked locking on class->properties */
2006 mono_memory_barrier ();
2008 /* Leave this assignment as the last op in the function */
2009 class->ext->events = events;
2011 mono_loader_unlock ();
2015 * Global pool of interface IDs, represented as a bitset.
2016 * LOCKING: this is supposed to be accessed with the loader lock held.
2018 static MonoBitSet *global_interface_bitset = NULL;
2021 * mono_unload_interface_ids:
2022 * @bitset: bit set of interface IDs
2024 * When an image is unloaded, the interface IDs associated with
2025 * the image are put back in the global pool of IDs so the numbers
2029 mono_unload_interface_ids (MonoBitSet *bitset)
2031 mono_loader_lock ();
2032 mono_bitset_sub (global_interface_bitset, bitset);
2033 mono_loader_unlock ();
2037 * mono_get_unique_iid:
2040 * Assign a unique integer ID to the interface represented by @class.
2041 * The ID will positive and as small as possible.
2042 * LOCKING: this is supposed to be called with the loader lock held.
2043 * Returns: the new ID.
2046 mono_get_unique_iid (MonoClass *class)
2050 g_assert (MONO_CLASS_IS_INTERFACE (class));
2052 if (!global_interface_bitset) {
2053 global_interface_bitset = mono_bitset_new (128, 0);
2056 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2058 int old_size = mono_bitset_size (global_interface_bitset);
2059 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2060 mono_bitset_free (global_interface_bitset);
2061 global_interface_bitset = new_set;
2064 mono_bitset_set (global_interface_bitset, iid);
2065 /* set the bit also in the per-image set */
2066 if (class->image->interface_bitset) {
2067 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2068 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2069 mono_bitset_free (class->image->interface_bitset);
2070 class->image->interface_bitset = new_set;
2073 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2075 mono_bitset_set (class->image->interface_bitset, iid);
2077 if (mono_print_vtable) {
2079 char *type_name = mono_type_full_name (&class->byval_arg);
2080 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2081 generic_id = class->generic_class->context.class_inst->id;
2082 g_assert (generic_id != 0);
2086 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2090 g_assert (iid <= 65535);
2095 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
2100 mono_class_setup_interfaces (klass);
2102 for (i = 0; i < klass->interface_count; i++) {
2103 ic = klass->interfaces [i];
2106 *res = g_ptr_array_new ();
2107 g_ptr_array_add (*res, ic);
2108 mono_class_init (ic);
2110 collect_implemented_interfaces_aux (ic, res);
2115 mono_class_get_implemented_interfaces (MonoClass *klass)
2117 GPtrArray *res = NULL;
2119 collect_implemented_interfaces_aux (klass, &res);
2124 compare_interface_ids (const void *p_key, const void *p_element) {
2125 const MonoClass *key = p_key;
2126 const MonoClass *element = *(MonoClass**) p_element;
2128 return (key->interface_id - element->interface_id);
2132 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2133 MonoClass **result = bsearch (
2135 klass->interfaces_packed,
2136 klass->interface_offsets_count,
2137 sizeof (MonoClass *),
2138 compare_interface_ids);
2140 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2147 print_implemented_interfaces (MonoClass *klass) {
2148 GPtrArray *ifaces = NULL;
2150 int ancestor_level = 0;
2152 printf ("Packed interface table for class %s has size %d\n", klass->name, klass->interface_offsets_count);
2153 for (i = 0; i < klass->interface_offsets_count; i++)
2154 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2155 klass->interfaces_packed [i]->interface_id,
2156 klass->interface_offsets_packed [i],
2157 klass->interfaces_packed [i]->method.count,
2158 klass->interfaces_packed [i]->name_space,
2159 klass->interfaces_packed [i]->name );
2160 printf ("Interface flags: ");
2161 for (i = 0; i <= klass->max_interface_id; i++)
2162 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2163 printf ("(%d,T)", i);
2165 printf ("(%d,F)", i);
2167 printf ("Dump interface flags:");
2168 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2169 printf (" %02X", klass->interface_bitmap [i]);
2171 while (klass != NULL) {
2172 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2173 ifaces = mono_class_get_implemented_interfaces (klass);
2175 for (i = 0; i < ifaces->len; i++) {
2176 MonoClass *ic = g_ptr_array_index (ifaces, i);
2177 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2178 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2180 mono_class_interface_offset (klass, ic),
2185 g_ptr_array_free (ifaces, TRUE);
2188 klass = klass->parent;
2193 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2196 args [0] = &arg0->byval_arg;
2198 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2202 array_class_get_if_rank (MonoClass *class, guint rank)
2204 return rank ? mono_array_class_get (class, rank) : class;
2208 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2210 valuetype_types [0] = eclass;
2211 if (eclass == mono_defaults.int16_class)
2212 valuetype_types [1] = mono_defaults.uint16_class;
2213 else if (eclass == mono_defaults.uint16_class)
2214 valuetype_types [1] = mono_defaults.int16_class;
2215 else if (eclass == mono_defaults.int32_class)
2216 valuetype_types [1] = mono_defaults.uint32_class;
2217 else if (eclass == mono_defaults.uint32_class)
2218 valuetype_types [1] = mono_defaults.int32_class;
2219 else if (eclass == mono_defaults.int64_class)
2220 valuetype_types [1] = mono_defaults.uint64_class;
2221 else if (eclass == mono_defaults.uint64_class)
2222 valuetype_types [1] = mono_defaults.int64_class;
2223 else if (eclass == mono_defaults.byte_class)
2224 valuetype_types [1] = mono_defaults.sbyte_class;
2225 else if (eclass == mono_defaults.sbyte_class)
2226 valuetype_types [1] = mono_defaults.byte_class;
2227 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2228 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2231 /* this won't be needed once bug #325495 is completely fixed
2232 * though we'll need something similar to know which interfaces to allow
2233 * in arrays when they'll be lazyly created
2235 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2236 * MS returns diferrent types based on which instance is called. For example:
2237 * object obj = new byte[10][];
2238 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2239 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2242 * Fixing this should kill quite some code, save some bits and improve compatbility.
2245 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2247 MonoClass *eclass = class->element_class;
2248 static MonoClass* generic_icollection_class = NULL;
2249 static MonoClass* generic_ienumerable_class = NULL;
2250 static MonoClass* generic_ienumerator_class = NULL;
2251 MonoClass *valuetype_types[2] = { NULL, NULL };
2252 MonoClass **interfaces = NULL;
2253 int i, interface_count, real_count, original_rank;
2255 gboolean internal_enumerator;
2256 gboolean eclass_is_valuetype;
2258 if (!mono_defaults.generic_ilist_class) {
2262 internal_enumerator = FALSE;
2263 eclass_is_valuetype = FALSE;
2264 original_rank = eclass->rank;
2265 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2266 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2268 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2270 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2271 original_rank = eclass->rank;
2272 eclass = eclass->element_class;
2273 internal_enumerator = TRUE;
2274 *is_enumerator = TRUE;
2282 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2283 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2285 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2287 if (!generic_icollection_class) {
2288 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2289 "System.Collections.Generic", "ICollection`1");
2290 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2291 "System.Collections.Generic", "IEnumerable`1");
2292 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2293 "System.Collections.Generic", "IEnumerator`1");
2296 mono_class_init (eclass);
2299 * Arrays in 2.0 need to implement a number of generic interfaces
2300 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2301 * on the element class). We collect the types needed to build the
2302 * instantiations in interfaces at intervals of 3, because 3 are
2303 * the generic interfaces needed to implement.
2305 if (eclass->valuetype) {
2306 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2308 /* IList, ICollection, IEnumerable */
2309 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2310 if (internal_enumerator) {
2312 if (valuetype_types [1])
2316 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2317 interfaces [0] = valuetype_types [0];
2318 if (valuetype_types [1])
2319 interfaces [3] = valuetype_types [1];
2321 eclass_is_valuetype = TRUE;
2324 int idepth = eclass->idepth;
2325 if (!internal_enumerator)
2327 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2328 /* we add object for interfaces and the supertypes for the other
2329 * types. The last of the supertypes is the element class itself which we
2330 * already created the explicit interfaces for (so we include it for IEnumerator
2331 * and exclude it for arrays).
2333 if (MONO_CLASS_IS_INTERFACE (eclass))
2336 interface_count += idepth;
2337 if (eclass->rank && eclass->element_class->valuetype) {
2338 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2339 if (valuetype_types [1])
2342 /* IList, ICollection, IEnumerable */
2343 interface_count *= 3;
2344 real_count = interface_count;
2345 if (internal_enumerator) {
2346 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2347 if (valuetype_types [1])
2350 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2351 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2352 interfaces [0] = mono_defaults.object_class;
2356 for (i = 0; i < idepth; i++) {
2357 mono_class_init (eclass->supertypes [i]);
2358 interfaces [j] = eclass->supertypes [i];
2362 if (all_interfaces) {
2363 for (i = 0; i < eclass->interface_offsets_count; i++) {
2364 interfaces [j] = eclass->interfaces_packed [i];
2368 for (i = 0; i < eclass->interface_count; i++) {
2369 interfaces [j] = eclass->interfaces [i];
2373 if (valuetype_types [1]) {
2374 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2379 /* instantiate the generic interfaces */
2380 for (i = 0; i < interface_count; i += 3) {
2381 MonoClass *iface = interfaces [i];
2383 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2384 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2385 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2387 if (internal_enumerator) {
2389 /* instantiate IEnumerator<iface> */
2390 for (i = 0; i < interface_count; i++) {
2391 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2393 j = interface_count;
2394 if (!eclass_is_valuetype) {
2395 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2396 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2399 for (i = 0; i < eclass->idepth; i++) {
2400 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2404 for (i = 0; i < eclass->interface_offsets_count; i++) {
2405 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2409 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2411 if (valuetype_types [1])
2412 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2416 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2417 for (i = 0; i < real_count; ++i) {
2418 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2419 g_print ("%s implements %s\n", type_name, name);
2430 find_array_interface (MonoClass *klass, const char *name)
2433 for (i = 0; i < klass->interface_count; ++i) {
2434 if (strcmp (klass->interfaces [i]->name, name) == 0)
2441 * LOCKING: this is supposed to be called with the loader lock held.
2444 setup_interface_offsets (MonoClass *class, int cur_slot)
2448 MonoClass **interfaces_full;
2449 int *interface_offsets_full;
2451 int interface_offsets_count;
2452 MonoClass **array_interfaces;
2453 int num_array_interfaces;
2454 int is_enumerator = FALSE;
2457 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
2458 * implicit interfaces have the property that they are assigned the same slot in the
2459 * vtables for compatible interfaces
2461 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
2463 /* compute maximum number of slots and maximum interface id */
2465 for (k = class; k ; k = k->parent) {
2466 for (i = 0; i < k->interface_count; i++) {
2467 ic = k->interfaces [i];
2470 mono_class_init (ic);
2472 if (max_iid < ic->interface_id)
2473 max_iid = ic->interface_id;
2475 ifaces = mono_class_get_implemented_interfaces (k);
2477 for (i = 0; i < ifaces->len; ++i) {
2478 ic = g_ptr_array_index (ifaces, i);
2479 if (max_iid < ic->interface_id)
2480 max_iid = ic->interface_id;
2482 g_ptr_array_free (ifaces, TRUE);
2485 for (i = 0; i < num_array_interfaces; ++i) {
2486 ic = array_interfaces [i];
2487 mono_class_init (ic);
2488 if (max_iid < ic->interface_id)
2489 max_iid = ic->interface_id;
2492 if (MONO_CLASS_IS_INTERFACE (class)) {
2493 if (max_iid < class->interface_id)
2494 max_iid = class->interface_id;
2496 class->max_interface_id = max_iid;
2497 /* compute vtable offset for interfaces */
2498 interfaces_full = g_malloc (sizeof (MonoClass*) * (max_iid + 1));
2499 interface_offsets_full = g_malloc (sizeof (int) * (max_iid + 1));
2501 for (i = 0; i <= max_iid; i++) {
2502 interfaces_full [i] = NULL;
2503 interface_offsets_full [i] = -1;
2506 ifaces = mono_class_get_implemented_interfaces (class);
2508 for (i = 0; i < ifaces->len; ++i) {
2509 ic = g_ptr_array_index (ifaces, i);
2510 interfaces_full [ic->interface_id] = ic;
2511 interface_offsets_full [ic->interface_id] = cur_slot;
2512 cur_slot += ic->method.count;
2514 g_ptr_array_free (ifaces, TRUE);
2517 for (k = class->parent; k ; k = k->parent) {
2518 ifaces = mono_class_get_implemented_interfaces (k);
2520 for (i = 0; i < ifaces->len; ++i) {
2521 ic = g_ptr_array_index (ifaces, i);
2523 if (interface_offsets_full [ic->interface_id] == -1) {
2524 int io = mono_class_interface_offset (k, ic);
2528 interfaces_full [ic->interface_id] = ic;
2529 interface_offsets_full [ic->interface_id] = io;
2532 g_ptr_array_free (ifaces, TRUE);
2536 if (MONO_CLASS_IS_INTERFACE (class)) {
2537 interfaces_full [class->interface_id] = class;
2538 interface_offsets_full [class->interface_id] = cur_slot;
2541 if (num_array_interfaces) {
2542 if (is_enumerator) {
2543 int ienumerator_offset;
2544 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
2545 ienumerator_offset = interface_offsets_full [class->interfaces [ienumerator_idx]->interface_id];
2546 for (i = 0; i < num_array_interfaces; ++i) {
2547 ic = array_interfaces [i];
2548 interfaces_full [ic->interface_id] = ic;
2549 if (strcmp (ic->name, "IEnumerator`1") == 0)
2550 interface_offsets_full [ic->interface_id] = ienumerator_offset;
2552 g_assert_not_reached ();
2553 /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, interface_offsets_full [ic->interface_id], class->interfaces [0]->name);*/
2556 int ilist_offset, icollection_offset, ienumerable_offset;
2557 int ilist_iface_idx = find_array_interface (class, "IList`1");
2558 int icollection_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "ICollection`1");
2559 int ienumerable_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "IEnumerable`1");
2560 ilist_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interface_id];
2561 icollection_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [icollection_iface_idx]->interface_id];
2562 ienumerable_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [ienumerable_iface_idx]->interface_id];
2563 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
2564 for (i = 0; i < num_array_interfaces; ++i) {
2565 ic = array_interfaces [i];
2566 interfaces_full [ic->interface_id] = ic;
2567 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
2568 interface_offsets_full [ic->interface_id] = ilist_offset;
2569 else if (strcmp (ic->name, "ICollection`1") == 0)
2570 interface_offsets_full [ic->interface_id] = icollection_offset;
2571 else if (strcmp (ic->name, "IEnumerable`1") == 0)
2572 interface_offsets_full [ic->interface_id] = ienumerable_offset;
2574 g_assert_not_reached ();
2575 /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, interface_offsets_full [ic->interface_id], class->interfaces [0]->name);*/
2580 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2581 if (interface_offsets_full [i] != -1) {
2582 interface_offsets_count ++;
2587 * We might get called twice: once from mono_class_init () then once from
2588 * mono_class_setup_vtable ().
2590 if (class->interfaces_packed) {
2591 g_assert (class->interface_offsets_count == interface_offsets_count);
2593 class->interface_offsets_count = interface_offsets_count;
2594 class->interfaces_packed = mono_image_alloc (class->image, sizeof (MonoClass*) * interface_offsets_count);
2595 class->interface_offsets_packed = mono_image_alloc (class->image, sizeof (guint16) * interface_offsets_count);
2596 class->interface_bitmap = mono_image_alloc0 (class->image, (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0));
2597 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2598 if (interface_offsets_full [i] != -1) {
2599 class->interface_bitmap [i >> 3] |= (1 << (i & 7));
2600 class->interfaces_packed [interface_offsets_count] = interfaces_full [i];
2601 class->interface_offsets_packed [interface_offsets_count] = interface_offsets_full [i];
2602 /*if (num_array_interfaces)
2603 g_print ("type %s has %s offset at %d\n", mono_type_get_name_full (&class->byval_arg, 0), mono_type_get_name_full (&interfaces_full [i]->byval_arg, 0), interface_offsets_full [i]);*/
2604 interface_offsets_count ++;
2609 g_free (interfaces_full);
2610 g_free (interface_offsets_full);
2611 g_free (array_interfaces);
2613 //printf ("JUST DONE: ");
2614 //print_implemented_interfaces (class);
2620 * Setup interface offsets for interfaces.
2622 * - class->max_interface_id
2623 * - class->interface_offsets_count
2624 * - class->interfaces_packed
2625 * - class->interface_offsets_packed
2626 * - class->interface_bitmap
2629 mono_class_setup_interface_offsets (MonoClass *class)
2631 mono_loader_lock ();
2633 setup_interface_offsets (class, 0);
2635 mono_loader_unlock ();
2639 * mono_class_setup_vtable:
2641 * Creates the generic vtable of CLASS.
2642 * Initializes the following fields in MonoClass:
2645 * Plus all the fields initialized by setup_interface_offsets ().
2646 * If there is an error during vtable construction, class->exception_type is set.
2648 * LOCKING: Acquires the loader lock.
2651 mono_class_setup_vtable (MonoClass *class)
2653 MonoMethod **overrides;
2654 MonoGenericContext *context;
2663 if (mono_debug_using_mono_debugger ())
2664 /* The debugger currently depends on this */
2665 mono_class_setup_methods (class);
2667 if (MONO_CLASS_IS_INTERFACE (class)) {
2668 /* This sets method->slot for all methods if this is an interface */
2669 mono_class_setup_methods (class);
2673 mono_loader_lock ();
2675 if (class->vtable) {
2676 mono_loader_unlock ();
2680 mono_stats.generic_vtable_count ++;
2682 if (class->generic_class) {
2683 context = mono_class_get_context (class);
2684 type_token = class->generic_class->container_class->type_token;
2686 context = (MonoGenericContext *) class->generic_container;
2687 type_token = class->type_token;
2690 if (class->image->dynamic) {
2691 if (class->generic_class) {
2692 MonoClass *gklass = class->generic_class->container_class;
2694 mono_reflection_get_dynamic_overrides (gklass, &overrides, &onum);
2695 for (i = 0; i < onum; ++i) {
2696 MonoMethod *override = overrides [(i * 2) + 1];
2697 MonoMethod *inflated = NULL;
2700 for (j = 0; j < class->method.count; ++j) {
2701 if (gklass->methods [j] == override) {
2702 inflated = class->methods [j];
2706 g_assert (inflated);
2708 overrides [(i * 2) + 1] = inflated;
2711 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
2714 /* The following call fails if there are missing methods in the type */
2715 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
2719 mono_class_setup_vtable_general (class, overrides, onum);
2723 mono_loader_unlock ();
2728 #define DEBUG_INTERFACE_VTABLE_CODE 0
2729 #define TRACE_INTERFACE_VTABLE_CODE 0
2730 #define VERIFY_INTERFACE_VTABLE_CODE 0
2732 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2733 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
2737 #define DEBUG_INTERFACE_VTABLE(stmt)
2740 #if TRACE_INTERFACE_VTABLE_CODE
2741 #define TRACE_INTERFACE_VTABLE(stmt) do {\
2745 #define TRACE_INTERFACE_VTABLE(stmt)
2748 #if VERIFY_INTERFACE_VTABLE_CODE
2749 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
2753 #define VERIFY_INTERFACE_VTABLE(stmt)
2757 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2759 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
2763 GString *res = g_string_new ("");
2765 g_string_append_c (res, '(');
2766 for (i = 0; i < sig->param_count; ++i) {
2768 g_string_append_c (res, ',');
2769 mono_type_get_desc (res, sig->params [i], include_namespace);
2771 g_string_append (res, ")=>");
2772 if (sig->ret != NULL) {
2773 mono_type_get_desc (res, sig->ret, include_namespace);
2775 g_string_append (res, "NULL");
2778 g_string_free (res, FALSE);
2782 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
2783 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
2784 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
2785 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
2793 check_interface_method_override (MonoClass *class, MonoMethod *im, MonoMethod *cm, gboolean require_newslot, gboolean interface_is_explicitly_implemented_by_class, gboolean slot_is_empty, gboolean security_enabled) {
2794 if (strcmp (im->name, cm->name) == 0) {
2795 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
2796 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
2799 if (! slot_is_empty) {
2800 if (require_newslot) {
2801 if (! interface_is_explicitly_implemented_by_class) {
2802 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
2805 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
2806 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
2810 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
2813 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2814 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
2815 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2816 TRACE_INTERFACE_VTABLE (printf ("]"));
2819 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
2820 /* CAS - SecurityAction.InheritanceDemand on interface */
2821 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2822 mono_secman_inheritancedemand_method (cm, im);
2825 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
2826 mono_security_core_clr_check_override (class, cm, im);
2827 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
2830 MonoClass *ic = im->klass;
2831 const char *ic_name_space = ic->name_space;
2832 const char *ic_name = ic->name;
2835 if (! require_newslot) {
2836 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
2839 if (cm->klass->rank == 0) {
2840 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
2843 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2844 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
2845 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2846 TRACE_INTERFACE_VTABLE (printf ("]"));
2849 if (mono_class_get_image (ic) != mono_defaults.corlib) {
2850 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
2853 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
2854 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
2857 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
2858 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
2862 subname = strstr (cm->name, ic_name_space);
2863 if (subname != cm->name) {
2864 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
2867 subname += strlen (ic_name_space);
2868 if (subname [0] != '.') {
2869 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
2873 if (strstr (subname, ic_name) != subname) {
2874 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
2877 subname += strlen (ic_name);
2878 if (subname [0] != '.') {
2879 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
2883 if (strcmp (subname, im->name) != 0) {
2884 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
2888 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
2889 /* CAS - SecurityAction.InheritanceDemand on interface */
2890 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2891 mono_secman_inheritancedemand_method (cm, im);
2894 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
2895 mono_security_core_clr_check_override (class, cm, im);
2897 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
2902 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2904 foreach_override (gpointer key, gpointer value, gpointer user_data) {
2905 MonoMethod *method = key;
2906 MonoMethod *override = value;
2907 MonoClass *method_class = mono_method_get_class (method);
2908 MonoClass *override_class = mono_method_get_class (override);
2910 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
2911 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
2912 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
2915 print_overrides (GHashTable *override_map, const char *message) {
2917 printf ("Override map \"%s\" START:\n", message);
2918 g_hash_table_foreach (override_map, foreach_override, NULL);
2919 printf ("Override map \"%s\" END.\n", message);
2921 printf ("Override map \"%s\" EMPTY.\n", message);
2925 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
2926 char *full_name = mono_type_full_name (&class->byval_arg);
2930 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
2932 if (print_interfaces) {
2933 print_implemented_interfaces (class);
2934 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
2937 if (class->parent) {
2938 parent_size = class->parent->vtable_size;
2942 for (i = 0; i < size; ++i) {
2943 MonoMethod *cm = vtable [i];
2945 char *cm_name = mono_method_full_name (cm, TRUE);
2946 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
2947 printf (" [%c][%03d][INDEX %03d] %s\n", newness, i, cm->slot, cm_name);
2956 #if VERIFY_INTERFACE_VTABLE_CODE
2958 mono_method_try_get_vtable_index (MonoMethod *method)
2960 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2961 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
2962 if (imethod->declaring->is_generic)
2963 return imethod->declaring->slot;
2965 return method->slot;
2969 mono_class_verify_vtable (MonoClass *class)
2972 char *full_name = mono_type_full_name (&class->byval_arg);
2974 printf ("*** Verifying VTable of class '%s' \n", full_name);
2978 if (!class->methods)
2981 for (i = 0; i < class->method.count; ++i) {
2982 MonoMethod *cm = class->methods [i];
2985 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
2989 full_name = mono_method_full_name (cm, TRUE);
2991 slot = mono_method_try_get_vtable_index (cm);
2993 if (slot >= class->vtable_size) {
2994 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
2998 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
2999 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3000 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3001 g_free (other_name);
3004 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3011 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3013 char *method_signature;
3015 for (index = 0; index < onum; ++index) {
3016 g_print (" at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
3017 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3019 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3020 printf ("no implementation for interface method %s::%s(%s) in class %s.%s\n",
3021 mono_type_get_name (&ic->byval_arg), im->name, method_signature, class->name_space, class->name);
3022 g_free (method_signature);
3023 mono_class_setup_methods (class);
3024 for (index = 0; index < class->method.count; ++index) {
3025 MonoMethod *cm = class->methods [index];
3026 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3028 printf ("METHOD %s(%s)\n", cm->name, method_signature);
3029 g_free (method_signature);
3034 * LOCKING: this is supposed to be called with the loader lock held.
3037 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
3040 MonoMethod **vtable;
3041 int i, max_vtsize = 0, max_iid, cur_slot = 0;
3042 GPtrArray *ifaces = NULL;
3043 GHashTable *override_map = NULL;
3044 gboolean security_enabled = mono_is_security_manager_active ();
3046 gpointer class_iter;
3047 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3048 int first_non_interface_slot;
3054 ifaces = mono_class_get_implemented_interfaces (class);
3056 for (i = 0; i < ifaces->len; i++) {
3057 MonoClass *ic = g_ptr_array_index (ifaces, i);
3058 max_vtsize += ic->method.count;
3060 g_ptr_array_free (ifaces, TRUE);
3064 if (class->parent) {
3065 mono_class_init (class->parent);
3066 mono_class_setup_vtable (class->parent);
3067 max_vtsize += class->parent->vtable_size;
3068 cur_slot = class->parent->vtable_size;
3071 max_vtsize += class->method.count;
3073 vtable = alloca (sizeof (gpointer) * max_vtsize);
3074 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3076 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3078 cur_slot = setup_interface_offsets (class, cur_slot);
3079 max_iid = class->max_interface_id;
3080 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3082 /* Optimized version for generic instances */
3083 if (class->generic_class) {
3084 MonoClass *gklass = class->generic_class->container_class;
3087 mono_class_setup_vtable (gklass);
3089 tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * gklass->vtable_size);
3090 class->vtable_size = gklass->vtable_size;
3091 for (i = 0; i < gklass->vtable_size; ++i)
3092 if (gklass->vtable [i]) {
3093 tmp [i] = mono_class_inflate_generic_method_full (gklass->vtable [i], class, mono_class_get_context (class));
3094 tmp [i]->slot = gklass->vtable [i]->slot;
3096 mono_memory_barrier ();
3097 class->vtable = tmp;
3099 /* Have to set method->slot for abstract virtual methods */
3100 if (class->methods && gklass->methods) {
3101 for (i = 0; i < class->method.count; ++i)
3102 if (class->methods [i]->slot == -1)
3103 class->methods [i]->slot = gklass->methods [i]->slot;
3109 if (class->parent && class->parent->vtable_size) {
3110 MonoClass *parent = class->parent;
3113 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
3115 // Also inherit parent interface vtables, just as a starting point.
3116 // This is needed otherwise bug-77127.exe fails when the property methods
3117 // have different names in the iterface and the class, because for child
3118 // classes the ".override" information is not used anymore.
3119 for (i = 0; i < parent->interface_offsets_count; i++) {
3120 MonoClass *parent_interface = parent->interfaces_packed [i];
3121 int interface_offset = mono_class_interface_offset (class, parent_interface);
3123 if (interface_offset >= parent->vtable_size) {
3124 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
3127 mono_class_setup_methods (parent_interface);
3128 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
3129 for (j = 0; j < parent_interface->method.count; j++) {
3130 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
3131 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
3132 parent_interface_offset + j, parent_interface_offset, j,
3133 interface_offset + j, interface_offset, j));
3140 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
3141 /* override interface methods */
3142 for (i = 0; i < onum; i++) {
3143 MonoMethod *decl = overrides [i*2];
3144 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
3146 dslot = mono_method_get_vtable_slot (decl) + mono_class_interface_offset (class, decl->klass);
3147 vtable [dslot] = overrides [i*2 + 1];
3148 vtable [dslot]->slot = dslot;
3150 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3152 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
3154 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3155 mono_security_core_clr_check_override (class, vtable [dslot], decl);
3158 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
3159 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
3161 // Loop on all implemented interfaces...
3162 for (i = 0; i < class->interface_offsets_count; i++) {
3163 MonoClass *parent = class->parent;
3165 gboolean interface_is_explicitly_implemented_by_class;
3168 ic = class->interfaces_packed [i];
3169 ic_offset = mono_class_interface_offset (class, ic);
3171 mono_class_setup_methods (ic);
3173 // Check if this interface is explicitly implemented (instead of just inherited)
3174 if (parent != NULL) {
3175 int implemented_interfaces_index;
3176 interface_is_explicitly_implemented_by_class = FALSE;
3177 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
3178 if (ic == class->interfaces [implemented_interfaces_index]) {
3179 interface_is_explicitly_implemented_by_class = TRUE;
3184 interface_is_explicitly_implemented_by_class = TRUE;
3187 // Loop on all interface methods...
3188 for (im_index = 0; im_index < ic->method.count; im_index++) {
3189 MonoMethod *im = ic->methods [im_index];
3190 int im_slot = ic_offset + im->slot;
3191 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
3193 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3196 // If there is an explicit implementation, just use it right away,
3197 // otherwise look for a matching method
3198 if (override_im == NULL) {
3203 // First look for a suitable method among the class methods
3205 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
3206 TRACE_INTERFACE_VTABLE (printf (" For slot %d ('%s'.'%s':'%s'), trying method '%s'.'%s':'%s'... [EXPLICIT IMPLEMENTATION = %d][SLOT IS NULL = %d]", im_slot, ic->name_space, ic->name, im->name, cm->klass->name_space, cm->klass->name, cm->name, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL)));
3207 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
3208 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
3209 vtable [im_slot] = cm;
3210 /* Why do we need this? */
3215 TRACE_INTERFACE_VTABLE (printf ("\n"));
3218 // If the slot is still empty, look in all the inherited virtual methods...
3219 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
3220 MonoClass *parent = class->parent;
3221 // Reverse order, so that last added methods are preferred
3222 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
3223 MonoMethod *cm = parent->vtable [cm_index];
3225 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf (" For slot %d ('%s'.'%s':'%s'), trying (ancestor) method '%s'.'%s':'%s'... ", im_slot, ic->name_space, ic->name, im->name, cm->klass->name_space, cm->klass->name, cm->name));
3226 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
3227 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
3228 vtable [im_slot] = cm;
3229 /* Why do we need this? */
3235 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
3239 g_assert (vtable [im_slot] == override_im);
3244 // If the class is not abstract, check that all its interface slots are full.
3245 // The check is done here and not directly at the end of the loop above because
3246 // it can happen (for injected generic array interfaces) that the same slot is
3247 // processed multiple times (those interfaces have overlapping slots), and it
3248 // will not always be the first pass the one that fills the slot.
3249 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3250 for (i = 0; i < class->interface_offsets_count; i++) {
3254 ic = class->interfaces_packed [i];
3255 ic_offset = mono_class_interface_offset (class, ic);
3257 for (im_index = 0; im_index < ic->method.count; im_index++) {
3258 MonoMethod *im = ic->methods [im_index];
3259 int im_slot = ic_offset + im->slot;
3261 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3264 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
3265 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
3266 if (vtable [im_slot] == NULL) {
3267 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
3268 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3270 g_hash_table_destroy (override_map);
3277 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
3279 while ((cm = mono_class_get_virtual_methods (class, &class_iter))) {
3281 * If the method is REUSE_SLOT, we must check in the
3282 * base class for a method to override.
3284 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3286 for (k = class->parent; k ; k = k->parent) {
3291 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
3292 MonoMethodSignature *cmsig, *m1sig;
3294 cmsig = mono_method_signature (cm);
3295 m1sig = mono_method_signature (m1);
3297 if (!cmsig || !m1sig) {
3298 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3302 if (!strcmp(cm->name, m1->name) &&
3303 mono_metadata_signature_equal (cmsig, m1sig)) {
3305 /* CAS - SecurityAction.InheritanceDemand */
3306 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3307 mono_secman_inheritancedemand_method (cm, m1);
3310 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3311 mono_security_core_clr_check_override (class, cm, m1);
3313 slot = mono_method_get_vtable_slot (m1);
3314 g_assert (cm->slot < max_vtsize);
3316 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3317 g_hash_table_insert (override_map, m1, cm);
3329 cm->slot = cur_slot++;
3331 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
3332 vtable [cm->slot] = cm;
3335 /* override non interface methods */
3336 for (i = 0; i < onum; i++) {
3337 MonoMethod *decl = overrides [i*2];
3338 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
3339 g_assert (decl->slot != -1);
3340 vtable [decl->slot] = overrides [i*2 + 1];
3341 overrides [i * 2 + 1]->slot = decl->slot;
3343 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3344 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
3346 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3347 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
3352 * If a method occupies more than one place in the vtable, and it is
3353 * overriden, then change the other occurances too.
3356 for (i = 0; i < max_vtsize; ++i)
3358 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
3363 g_hash_table_destroy (override_map);
3366 if (class->generic_class) {
3367 MonoClass *gklass = class->generic_class->container_class;
3369 mono_class_init (gklass);
3371 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
3373 /* Check that the vtable_size value computed in mono_class_init () is correct */
3374 if (class->vtable_size)
3375 g_assert (cur_slot == class->vtable_size);
3376 class->vtable_size = cur_slot;
3379 /* Try to share the vtable with our parent. */
3380 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
3381 mono_memory_barrier ();
3382 class->vtable = class->parent->vtable;
3384 MonoMethod **tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * class->vtable_size);
3385 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
3386 mono_memory_barrier ();
3387 class->vtable = tmp;
3390 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
3391 if (mono_print_vtable) {
3394 print_implemented_interfaces (class);
3396 for (i = 0; i <= max_iid; i++)
3397 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
3400 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
3401 class->vtable_size, icount);
3403 for (i = 0; i < class->vtable_size; ++i) {
3408 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
3409 mono_method_full_name (cm, TRUE));
3415 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
3416 class->name, max_iid);
3418 for (i = 0; i < class->interface_count; i++) {
3419 ic = class->interfaces [i];
3420 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
3421 mono_class_interface_offset (class, ic),
3422 ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
3425 for (k = class->parent; k ; k = k->parent) {
3426 for (i = 0; i < k->interface_count; i++) {
3427 ic = k->interfaces [i];
3428 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
3429 mono_class_interface_offset (class, ic),
3430 ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
3436 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
3440 * mono_method_get_vtable_slot:
3442 * Returns method->slot, computing it if neccesary.
3443 * LOCKING: Acquires the loader lock.
3446 mono_method_get_vtable_slot (MonoMethod *method)
3448 if (method->slot == -1) {
3449 mono_class_setup_vtable (method->klass);
3450 g_assert (method->slot != -1);
3452 return method->slot;
3456 * mono_method_get_vtable_index:
3459 * Returns the index into the runtime vtable to access the method or,
3460 * in the case of a virtual generic method, the virtual generic method
3464 mono_method_get_vtable_index (MonoMethod *method)
3466 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3467 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3468 if (imethod->declaring->is_generic)
3469 return mono_method_get_vtable_slot (imethod->declaring);
3471 return mono_method_get_vtable_slot (method);
3474 static MonoMethod *default_ghc = NULL;
3475 static MonoMethod *default_finalize = NULL;
3476 static int finalize_slot = -1;
3477 static int ghc_slot = -1;
3480 initialize_object_slots (MonoClass *class)
3485 if (class == mono_defaults.object_class) {
3486 mono_class_setup_vtable (class);
3487 for (i = 0; i < class->vtable_size; ++i) {
3488 MonoMethod *cm = class->vtable [i];
3490 if (!strcmp (cm->name, "GetHashCode"))
3492 else if (!strcmp (cm->name, "Finalize"))
3496 g_assert (ghc_slot > 0);
3497 default_ghc = class->vtable [ghc_slot];
3499 g_assert (finalize_slot > 0);
3500 default_finalize = class->vtable [finalize_slot];
3505 MonoMethod *array_method;
3507 } GenericArrayMethodInfo;
3509 static int generic_array_method_num = 0;
3510 static GenericArrayMethodInfo *generic_array_method_info = NULL;
3513 generic_array_methods (MonoClass *class)
3515 int i, count_generic = 0;
3516 GList *list = NULL, *tmp;
3517 if (generic_array_method_num)
3518 return generic_array_method_num;
3519 mono_class_setup_methods (class->parent);
3520 for (i = 0; i < class->parent->method.count; i++) {
3521 MonoMethod *m = class->parent->methods [i];
3522 if (!strncmp (m->name, "InternalArray__", 15)) {
3524 list = g_list_prepend (list, m);
3527 list = g_list_reverse (list);
3528 generic_array_method_info = g_malloc (sizeof (GenericArrayMethodInfo) * count_generic);
3530 for (tmp = list; tmp; tmp = tmp->next) {
3531 const char *mname, *iname;
3533 MonoMethod *m = tmp->data;
3534 generic_array_method_info [i].array_method = m;
3535 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
3536 iname = "System.Collections.Generic.ICollection`1.";
3537 mname = m->name + 27;
3538 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
3539 iname = "System.Collections.Generic.IEnumerable`1.";
3540 mname = m->name + 27;
3541 } else if (!strncmp (m->name, "InternalArray__", 15)) {
3542 iname = "System.Collections.Generic.IList`1.";
3543 mname = m->name + 15;
3545 g_assert_not_reached ();
3548 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
3549 strcpy (name, iname);
3550 strcpy (name + strlen (iname), mname);
3551 generic_array_method_info [i].name = name;
3554 /*g_print ("array generic methods: %d\n", count_generic);*/
3556 generic_array_method_num = count_generic;
3558 return generic_array_method_num;
3562 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
3564 MonoGenericContext tmp_context;
3567 tmp_context.class_inst = NULL;
3568 tmp_context.method_inst = iface->generic_class->context.class_inst;
3569 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
3571 for (i = 0; i < generic_array_method_num; i++) {
3572 MonoMethod *m = generic_array_method_info [i].array_method;
3573 MonoMethod *inflated;
3575 inflated = mono_class_inflate_generic_method (m, &tmp_context);
3576 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
3581 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
3583 int len = strlen (s1) + strlen (s2) + 2;
3584 char *s = mono_image_alloc (image, len);
3587 result = g_snprintf (s, len, "%s%c%s", s1, '\0', s2);
3588 g_assert (result == len - 1);
3594 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
3596 gpointer exception_data = NULL;
3598 switch (error->exception_type) {
3599 case MONO_EXCEPTION_TYPE_LOAD:
3600 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
3603 case MONO_EXCEPTION_MISSING_METHOD:
3604 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
3607 case MONO_EXCEPTION_MISSING_FIELD: {
3608 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
3609 const char *class_name;
3612 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
3614 class_name = error->klass->name;
3616 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
3619 g_free ((void*)class_name);
3623 case MONO_EXCEPTION_FILE_NOT_FOUND: {
3626 if (error->ref_only)
3627 msg = "Cannot resolve dependency to assembly '%s' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.";
3629 msg = "Could not load file or assembly '%s' or one of its dependencies.";
3631 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
3635 case MONO_EXCEPTION_BAD_IMAGE:
3636 exception_data = error->msg;
3640 g_assert_not_reached ();
3643 mono_class_set_failure (class, error->exception_type, exception_data);
3648 * @class: the class to initialize
3650 * Compute the instance_size, class_size and other infos that cannot be
3651 * computed at mono_class_get() time. Also compute vtable_size if possible.
3652 * Returns TRUE on success or FALSE if there was a problem in loading
3653 * the type (incorrect assemblies, missing assemblies, methods, etc).
3655 * LOCKING: Acquires the loader lock.
3658 mono_class_init (MonoClass *class)
3661 MonoCachedClassInfo cached_info;
3662 gboolean has_cached_info;
3663 int class_init_ok = TRUE;
3667 /* Double-checking locking pattern */
3669 return class->exception_type == MONO_EXCEPTION_NONE;
3671 /*g_print ("Init class %s\n", class->name);*/
3673 /* We do everything inside the lock to prevent races */
3674 mono_loader_lock ();
3676 if (class->inited) {
3677 mono_loader_unlock ();
3678 /* Somebody might have gotten in before us */
3679 return class->exception_type == MONO_EXCEPTION_NONE;
3682 if (class->init_pending) {
3683 mono_loader_unlock ();
3684 /* this indicates a cyclic dependency */
3685 g_error ("pending init %s.%s\n", class->name_space, class->name);
3688 class->init_pending = 1;
3690 /* CAS - SecurityAction.InheritanceDemand */
3691 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
3692 mono_secman_inheritancedemand_class (class, class->parent);
3695 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3696 mono_security_core_clr_check_inheritance (class);
3698 mono_stats.initialized_class_count++;
3700 if (class->generic_class && !class->generic_class->is_dynamic) {
3701 MonoClass *gklass = class->generic_class->container_class;
3703 mono_stats.generic_class_count++;
3705 class->method = gklass->method;
3706 class->field = gklass->field;
3708 mono_class_init (gklass);
3709 // FIXME: Why is this needed ?
3710 mono_class_setup_methods (gklass);
3712 if (MONO_CLASS_IS_INTERFACE (class))
3713 class->interface_id = mono_get_unique_iid (class);
3716 if (class->parent && !class->parent->inited)
3717 mono_class_init (class->parent);
3719 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
3721 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
3722 class->nested_classes_inited = TRUE;
3725 * Computes the size used by the fields, and their locations
3727 if (has_cached_info) {
3728 class->instance_size = cached_info.instance_size;
3729 class->sizes.class_size = cached_info.class_size;
3730 class->packing_size = cached_info.packing_size;
3731 class->min_align = cached_info.min_align;
3732 class->blittable = cached_info.blittable;
3733 class->has_references = cached_info.has_references;
3734 class->has_static_refs = cached_info.has_static_refs;
3735 class->no_special_static_fields = cached_info.no_special_static_fields;
3738 if (!class->size_inited){
3739 mono_class_setup_fields (class);
3740 if (class->exception_type || mono_loader_get_last_error ()){
3741 class_init_ok = FALSE;
3746 /* Initialize arrays */
3748 class->method.count = 3 + (class->rank > 1? 2: 1);
3750 if (class->interface_count) {
3751 int count_generic = generic_array_methods (class);
3752 class->method.count += class->interface_count * count_generic;
3756 mono_class_setup_supertypes (class);
3759 initialize_object_slots (class);
3762 * Initialize the rest of the data without creating a generic vtable if possible.
3763 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
3764 * also avoid computing a generic vtable.
3766 if (has_cached_info) {
3768 class->vtable_size = cached_info.vtable_size;
3769 class->has_finalize = cached_info.has_finalize;
3770 class->ghcimpl = cached_info.ghcimpl;
3771 class->has_cctor = cached_info.has_cctor;
3772 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
3773 static int szarray_vtable_size = 0;
3776 if (!szarray_vtable_size) {
3777 mono_class_setup_vtable (class);
3778 szarray_vtable_size = class->vtable_size;
3780 class->vtable_size = szarray_vtable_size;
3782 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
3783 MonoClass *gklass = class->generic_class->container_class;
3785 /* Generic instance case */
3786 class->ghcimpl = gklass->ghcimpl;
3787 class->has_finalize = gklass->has_finalize;
3788 class->has_cctor = gklass->has_cctor;
3790 mono_class_setup_vtable (gklass);
3791 if (gklass->exception_type)
3794 class->vtable_size = gklass->vtable_size;
3798 /* ghcimpl is not currently used
3800 if (class->parent) {
3801 MonoMethod *cmethod = class->vtable [ghc_slot];
3802 if (cmethod->is_inflated)
3803 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
3804 if (cmethod == default_ghc) {
3810 /* Interfaces and valuetypes are not supposed to have finalizers */
3811 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
3812 MonoMethod *cmethod = NULL;
3814 if (class->parent && class->parent->has_finalize) {
3815 class->has_finalize = 1;
3817 if (class->type_token) {
3818 cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
3819 } else if (class->parent) {
3820 /* FIXME: Optimize this */
3821 mono_class_setup_vtable (class);
3822 if (class->exception_type || mono_loader_get_last_error ())
3824 cmethod = class->vtable [finalize_slot];
3828 /* Check that this is really the finalizer method */
3829 mono_class_setup_vtable (class);
3830 if (class->exception_type || mono_loader_get_last_error ())
3833 class->has_finalize = 0;
3834 if (class->parent) {
3835 cmethod = class->vtable [finalize_slot];
3836 if (cmethod->is_inflated)
3837 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
3838 if (cmethod != default_finalize) {
3839 class->has_finalize = 1;
3846 /* C# doesn't allow interfaces to have cctors */
3847 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
3848 MonoMethod *cmethod = NULL;
3850 if (class->type_token) {
3851 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
3852 /* The find_method function ignores the 'flags' argument */
3853 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
3854 class->has_cctor = 1;
3856 mono_class_setup_methods (class);
3858 for (i = 0; i < class->method.count; ++i) {
3859 MonoMethod *method = class->methods [i];
3860 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3861 (strcmp (".cctor", method->name) == 0)) {
3862 class->has_cctor = 1;
3870 if (!mono_setup_vtable_in_class_init) {
3872 * This is an embedding API break, since the caller might assume that
3873 * mono_class_init () constructs a generic vtable, so vtable construction errors
3874 * are visible right after the mono_class_init (), and not after
3875 * mono_class_vtable ().
3877 if (class->parent) {
3878 /* This will compute class->parent->vtable_size for some classes */
3879 mono_class_init (class->parent);
3880 if (class->parent->exception_type || mono_loader_get_last_error ())
3882 if (!class->parent->vtable_size) {
3883 /* FIXME: Get rid of this somehow */
3884 mono_class_setup_vtable (class->parent);
3885 if (class->parent->exception_type || mono_loader_get_last_error ())
3888 setup_interface_offsets (class, class->parent->vtable_size);
3890 setup_interface_offsets (class, 0);
3893 mono_class_setup_vtable (class);
3895 if (MONO_CLASS_IS_INTERFACE (class))
3896 setup_interface_offsets (class, 0);
3899 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
3900 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
3901 class_init_ok = FALSE;
3907 class_init_ok = FALSE;
3910 /* Because of the double-checking locking pattern */
3911 mono_memory_barrier ();
3913 class->init_pending = 0;
3915 if (mono_loader_get_last_error ()) {
3916 if (class->exception_type == MONO_EXCEPTION_NONE)
3917 set_failure_from_loader_error (class, mono_loader_get_last_error ());
3919 mono_loader_clear_error ();
3922 mono_loader_unlock ();
3924 if (mono_debugger_class_init_func)
3925 mono_debugger_class_init_func (class);
3927 return class_init_ok;
3931 is_corlib_image (MonoImage *image)
3933 /* FIXME: allow the dynamic case for our compilers and with full trust */
3935 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
3937 return image == mono_defaults.corlib;
3941 * LOCKING: this assumes the loader lock is held
3944 mono_class_setup_mono_type (MonoClass *class)
3946 const char *name = class->name;
3947 const char *nspace = class->name_space;
3948 gboolean is_corlib = is_corlib_image (class->image);
3950 class->this_arg.byref = 1;
3951 class->this_arg.data.klass = class;
3952 class->this_arg.type = MONO_TYPE_CLASS;
3953 class->byval_arg.data.klass = class;
3954 class->byval_arg.type = MONO_TYPE_CLASS;
3956 if (is_corlib && !strcmp (nspace, "System")) {
3957 if (!strcmp (name, "ValueType")) {
3959 * do not set the valuetype bit for System.ValueType.
3960 * class->valuetype = 1;
3962 class->blittable = TRUE;
3963 } else if (!strcmp (name, "Enum")) {
3965 * do not set the valuetype bit for System.Enum.
3966 * class->valuetype = 1;
3968 class->valuetype = 0;
3969 class->enumtype = 0;
3970 } else if (!strcmp (name, "Object")) {
3971 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
3972 } else if (!strcmp (name, "String")) {
3973 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
3974 } else if (!strcmp (name, "TypedReference")) {
3975 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
3979 if (class->valuetype) {
3980 int t = MONO_TYPE_VALUETYPE;
3982 if (is_corlib && !strcmp (nspace, "System")) {
3985 if (!strcmp (name, "Boolean")) {
3986 t = MONO_TYPE_BOOLEAN;
3987 } else if (!strcmp(name, "Byte")) {
3989 class->blittable = TRUE;
3993 if (!strcmp (name, "Char")) {
3998 if (!strcmp (name, "Double")) {
4000 class->blittable = TRUE;
4004 if (!strcmp (name, "Int32")) {
4006 class->blittable = TRUE;
4007 } else if (!strcmp(name, "Int16")) {
4009 class->blittable = TRUE;
4010 } else if (!strcmp(name, "Int64")) {
4012 class->blittable = TRUE;
4013 } else if (!strcmp(name, "IntPtr")) {
4015 class->blittable = TRUE;
4019 if (!strcmp (name, "Single")) {
4021 class->blittable = TRUE;
4022 } else if (!strcmp(name, "SByte")) {
4024 class->blittable = TRUE;
4028 if (!strcmp (name, "UInt32")) {
4030 class->blittable = TRUE;
4031 } else if (!strcmp(name, "UInt16")) {
4033 class->blittable = TRUE;
4034 } else if (!strcmp(name, "UInt64")) {
4036 class->blittable = TRUE;
4037 } else if (!strcmp(name, "UIntPtr")) {
4039 class->blittable = TRUE;
4043 if (!strcmp (name, "TypedReference")) {
4044 t = MONO_TYPE_TYPEDBYREF;
4045 class->blittable = TRUE;
4049 if (!strcmp (name, "Void")) {
4057 class->this_arg.type = class->byval_arg.type = t;
4060 if (MONO_CLASS_IS_INTERFACE (class))
4061 class->interface_id = mono_get_unique_iid (class);
4066 * LOCKING: this assumes the loader lock is held
4069 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
4071 gboolean system_namespace;
4072 gboolean is_corlib = is_corlib_image (class->image);
4074 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
4076 /* if root of the hierarchy */
4077 if (system_namespace && !strcmp (class->name, "Object")) {
4078 class->parent = NULL;
4079 class->instance_size = sizeof (MonoObject);
4082 if (!strcmp (class->name, "<Module>")) {
4083 class->parent = NULL;
4084 class->instance_size = 0;
4088 if (!MONO_CLASS_IS_INTERFACE (class)) {
4089 /* Imported COM Objects always derive from __ComObject. */
4090 if (MONO_CLASS_IS_IMPORT (class)) {
4091 mono_init_com_types ();
4092 if (parent == mono_defaults.object_class)
4093 parent = mono_defaults.com_object_class;
4096 /* set the parent to something useful and safe, but mark the type as broken */
4097 parent = mono_defaults.object_class;
4098 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4101 class->parent = parent;
4103 if (parent->generic_class && !parent->name) {
4105 * If the parent is a generic instance, we may get
4106 * called before it is fully initialized, especially
4107 * before it has its name.
4112 class->marshalbyref = parent->marshalbyref;
4113 class->contextbound = parent->contextbound;
4114 class->delegate = parent->delegate;
4115 if (MONO_CLASS_IS_IMPORT (class))
4116 class->is_com_object = 1;
4118 class->is_com_object = parent->is_com_object;
4120 if (system_namespace) {
4121 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
4122 class->marshalbyref = 1;
4124 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
4125 class->contextbound = 1;
4127 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
4128 class->delegate = 1;
4131 if (class->parent->enumtype || (is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
4132 (strcmp (class->parent->name_space, "System") == 0)))
4133 class->valuetype = 1;
4134 if (is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
4135 class->valuetype = class->enumtype = 1;
4137 /*class->enumtype = class->parent->enumtype; */
4138 mono_class_setup_supertypes (class);
4140 /* initialize com types if COM interfaces are present */
4141 if (MONO_CLASS_IS_IMPORT (class))
4142 mono_init_com_types ();
4143 class->parent = NULL;
4149 * mono_class_setup_supertypes:
4152 * Build the data structure needed to make fast type checks work.
4153 * This currently sets two fields in @class:
4154 * - idepth: distance between @class and System.Object in the type
4156 * - supertypes: array of classes: each element has a class in the hierarchy
4157 * starting from @class up to System.Object
4159 * LOCKING: this assumes the loader lock is held
4162 mono_class_setup_supertypes (MonoClass *class)
4166 if (class->supertypes)
4169 if (class->parent && !class->parent->supertypes)
4170 mono_class_setup_supertypes (class->parent);
4172 class->idepth = class->parent->idepth + 1;
4176 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
4177 class->supertypes = mono_image_alloc0 (class->image, sizeof (MonoClass *) * ms);
4179 if (class->parent) {
4180 class->supertypes [class->idepth - 1] = class;
4181 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
4183 class->supertypes [0] = class;
4188 * mono_class_create_from_typedef:
4189 * @image: image where the token is valid
4190 * @type_token: typedef token
4192 * Create the MonoClass* representing the specified type token.
4193 * @type_token must be a TypeDef token.
4196 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
4198 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
4199 MonoClass *class, *parent = NULL;
4200 guint32 cols [MONO_TYPEDEF_SIZE];
4201 guint32 cols_next [MONO_TYPEDEF_SIZE];
4202 guint tidx = mono_metadata_token_index (type_token);
4203 MonoGenericContext *context = NULL;
4204 const char *name, *nspace;
4206 MonoClass **interfaces;
4207 guint32 field_last, method_last;
4208 guint32 nesting_tokeen;
4210 mono_loader_lock ();
4212 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
4213 mono_loader_unlock ();
4217 g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
4219 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
4221 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
4222 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
4224 class = mono_image_alloc0 (image, sizeof (MonoClass));
4227 class->name_space = nspace;
4229 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4231 class->image = image;
4232 class->type_token = type_token;
4233 class->flags = cols [MONO_TYPEDEF_FLAGS];
4235 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
4237 classes_size += sizeof (MonoClass);
4240 * Check whether we're a generic type definition.
4242 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
4243 if (class->generic_container) {
4244 class->is_generic = 1;
4245 class->generic_container->owner.klass = class;
4246 context = &class->generic_container->context;
4249 if (cols [MONO_TYPEDEF_EXTENDS]) {
4250 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
4252 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
4253 /*WARNING: this must satisfy mono_metadata_type_hash*/
4254 class->this_arg.byref = 1;
4255 class->this_arg.data.klass = class;
4256 class->this_arg.type = MONO_TYPE_CLASS;
4257 class->byval_arg.data.klass = class;
4258 class->byval_arg.type = MONO_TYPE_CLASS;
4260 parent = mono_class_get_full (image, parent_token, context);
4262 if (parent == NULL){
4263 mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
4264 mono_loader_unlock ();
4265 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4270 /* do this early so it's available for interfaces in setup_mono_type () */
4271 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token)))
4272 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
4274 mono_class_setup_parent (class, parent);
4276 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
4277 mono_class_setup_mono_type (class);
4279 if (!class->enumtype) {
4280 if (!mono_metadata_interfaces_from_typedef_full (
4281 image, type_token, &interfaces, &icount, context)){
4282 mono_loader_unlock ();
4283 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4287 class->interfaces = interfaces;
4288 class->interface_count = icount;
4289 class->interfaces_inited = 1;
4292 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
4296 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
4300 class->cast_class = class->element_class = class;
4302 /*g_print ("Load class %s\n", name);*/
4305 * Compute the field and method lists
4307 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
4308 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
4310 if (tt->rows > tidx){
4311 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
4312 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
4313 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
4315 field_last = image->tables [MONO_TABLE_FIELD].rows;
4316 method_last = image->tables [MONO_TABLE_METHOD].rows;
4319 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
4320 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
4321 class->field.count = field_last - class->field.first;
4323 class->field.count = 0;
4325 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
4326 class->method.count = method_last - class->method.first;
4328 class->method.count = 0;
4330 /* reserve space to store vector pointer in arrays */
4331 if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
4332 class->instance_size += 2 * sizeof (gpointer);
4333 g_assert (class->field.count == 0);
4336 if (class->enumtype) {
4337 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
4338 if (!enum_basetype) {
4339 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4340 mono_loader_unlock ();
4343 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
4347 * If we're a generic type definition, load the constraints.
4348 * We must do this after the class has been constructed to make certain recursive scenarios
4351 if (class->generic_container)
4352 mono_metadata_load_generic_param_constraints (
4353 image, type_token, class->generic_container);
4355 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
4356 if (!strncmp (name, "Vector", 6))
4357 class->simd_type = !strcmp (name + 6, "2d") || !strcmp (name + 6, "2ul") || !strcmp (name + 6, "2l") || !strcmp (name + 6, "4f") || !strcmp (name + 6, "4ui") || !strcmp (name + 6, "4i") || !strcmp (name + 6, "8s") || !strcmp (name + 6, "8us") || !strcmp (name + 6, "16b") || !strcmp (name + 6, "16sb");
4360 mono_loader_unlock ();
4362 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4367 /** is klass Nullable<T>? */
4369 mono_class_is_nullable (MonoClass *klass)
4371 return klass->generic_class != NULL &&
4372 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
4376 /** if klass is T? return T */
4378 mono_class_get_nullable_param (MonoClass *klass)
4380 g_assert (mono_class_is_nullable (klass));
4381 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4385 * Create the `MonoClass' for an instantiation of a generic type.
4386 * We only do this if we actually need it.
4389 mono_generic_class_get_class (MonoGenericClass *gclass)
4391 MonoClass *klass, *gklass;
4393 mono_loader_lock ();
4394 if (gclass->cached_class) {
4395 mono_loader_unlock ();
4396 return gclass->cached_class;
4399 gclass->cached_class = g_malloc0 (sizeof (MonoClass));
4400 klass = gclass->cached_class;
4402 gklass = gclass->container_class;
4404 if (gklass->nested_in) {
4406 * FIXME: the nested type context should include everything the
4407 * nesting context should have, but it may also have additional
4408 * generic parameters...
4410 klass->nested_in = mono_class_inflate_generic_class (gklass->nested_in,
4411 mono_generic_class_get_context (gclass));
4414 klass->name = gklass->name;
4415 klass->name_space = gklass->name_space;
4417 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4419 klass->image = gklass->image;
4420 klass->flags = gklass->flags;
4421 klass->type_token = gklass->type_token;
4422 klass->field.count = gklass->field.count;
4424 klass->is_inflated = 1;
4425 klass->generic_class = gclass;
4427 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
4428 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
4429 klass->this_arg.byref = TRUE;
4430 klass->enumtype = gklass->enumtype;
4431 klass->valuetype = gklass->valuetype;
4433 klass->cast_class = klass->element_class = klass;
4435 if (mono_class_is_nullable (klass))
4436 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
4439 * We're not interested in the nested classes of a generic instance.
4440 * We use the generic type definition to look for nested classes.
4443 if (gklass->parent) {
4444 klass->parent = mono_class_inflate_generic_class (gklass->parent, mono_generic_class_get_context (gclass));
4448 mono_class_setup_parent (klass, klass->parent);
4450 if (klass->enumtype) {
4451 klass->cast_class = gklass->cast_class;
4452 klass->element_class = gklass->element_class;
4455 if (gclass->is_dynamic) {
4458 mono_class_setup_supertypes (klass);
4460 if (klass->enumtype) {
4462 * For enums, gklass->fields might not been set, but instance_size etc. is
4463 * already set in mono_reflection_create_internal_class (). For non-enums,
4464 * these will be computed normally in mono_class_layout_fields ().
4466 klass->instance_size = gklass->instance_size;
4467 klass->sizes.class_size = gklass->sizes.class_size;
4468 klass->size_inited = 1;
4472 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4474 inflated_classes ++;
4475 inflated_classes_size += sizeof (MonoClass);
4477 mono_loader_unlock ();
4483 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
4485 MonoClass *klass, **ptr;
4490 image = mono_defaults.corlib;
4492 klass = mono_image_alloc0 (image, sizeof (MonoClass));
4493 classes_size += sizeof (MonoClass);
4496 klass->name = pinfo->name;
4498 int n = mono_generic_param_num (param);
4499 klass->name = mono_image_alloc0 (image, 16);
4500 sprintf ((char*)klass->name, "%d", n);
4503 klass->name_space = "";
4504 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4508 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
4512 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
4513 klass->parent = pinfo->constraints [0];
4515 } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
4516 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
4518 klass->parent = mono_defaults.object_class;
4521 if (count - pos > 0) {
4522 klass->interface_count = count - pos;
4523 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
4524 for (i = pos; i < count; i++)
4525 klass->interfaces [i - pos] = pinfo->constraints [i];
4528 klass->image = image;
4530 klass->inited = TRUE;
4531 klass->cast_class = klass->element_class = klass;
4532 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
4534 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
4535 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
4536 klass->this_arg.byref = TRUE;
4538 /* FIXME: shouldn't this be ->type_token? */
4539 klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
4541 mono_class_setup_supertypes (klass);
4546 #define FAST_CACHE_SIZE 1024
4547 static MonoClass *var_cache_fast [FAST_CACHE_SIZE];
4548 static MonoClass *mvar_cache_fast [FAST_CACHE_SIZE];
4549 static GHashTable *var_cache_slow;
4550 static GHashTable *mvar_cache_slow;
4553 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
4555 int n = mono_generic_param_num (param);
4558 if (n < FAST_CACHE_SIZE)
4559 return (is_mvar ? mvar_cache_fast : var_cache_fast) [n];
4560 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4561 return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
4565 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
4567 int n = mono_generic_param_num (param);
4570 if (n < FAST_CACHE_SIZE) {
4571 (is_mvar ? mvar_cache_fast : var_cache_fast) [n] = klass;
4574 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4576 ht = g_hash_table_new (NULL, NULL);
4578 mvar_cache_slow = ht;
4580 var_cache_slow = ht;
4583 g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
4587 * LOCKING: Acquires the loader lock.
4590 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
4592 MonoGenericContainer *container = mono_generic_param_owner (param);
4593 MonoGenericParamInfo *pinfo;
4596 mono_loader_lock ();
4599 pinfo = mono_generic_param_info (param);
4600 if (pinfo->pklass) {
4601 mono_loader_unlock ();
4602 return pinfo->pklass;
4608 klass = get_anon_gparam_class (param, is_mvar);
4610 mono_loader_unlock ();
4615 if (!image && container) {
4617 MonoMethod *method = container->owner.method;
4618 image = (method && method->klass) ? method->klass->image : NULL;
4620 MonoClass *klass = container->owner.klass;
4621 // FIXME: 'klass' should not be null
4622 // But, monodis creates GenericContainers without associating a owner to it
4623 image = klass ? klass->image : NULL;
4627 klass = make_generic_param_class (param, image, is_mvar, pinfo);
4629 mono_memory_barrier ();
4632 pinfo->pklass = klass;
4634 set_anon_gparam_class (param, is_mvar, klass);
4636 mono_loader_unlock ();
4638 /* FIXME: Should this go inside 'make_generic_param_klass'? */
4639 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4645 mono_ptr_class_get (MonoType *type)
4648 MonoClass *el_class;
4652 el_class = mono_class_from_mono_type (type);
4653 image = el_class->image;
4655 mono_loader_lock ();
4657 if (!image->ptr_cache)
4658 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4660 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
4661 mono_loader_unlock ();
4664 result = mono_image_alloc0 (image, sizeof (MonoClass));
4666 classes_size += sizeof (MonoClass);
4668 result->parent = NULL; /* no parent for PTR types */
4669 result->name_space = el_class->name_space;
4670 name = g_strdup_printf ("%s*", el_class->name);
4671 result->name = mono_image_strdup (image, name);
4674 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4676 result->image = el_class->image;
4677 result->inited = TRUE;
4678 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4679 /* Can pointers get boxed? */
4680 result->instance_size = sizeof (gpointer);
4681 result->cast_class = result->element_class = el_class;
4682 result->blittable = TRUE;
4684 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
4685 result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
4686 result->this_arg.byref = TRUE;
4688 mono_class_setup_supertypes (result);
4690 g_hash_table_insert (image->ptr_cache, el_class, result);
4692 mono_loader_unlock ();
4694 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4700 mono_fnptr_class_get (MonoMethodSignature *sig)
4703 static GHashTable *ptr_hash = NULL;
4705 /* FIXME: These should be allocate from a mempool as well, but which one ? */
4707 mono_loader_lock ();
4710 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
4712 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
4713 mono_loader_unlock ();
4716 result = g_new0 (MonoClass, 1);
4718 result->parent = NULL; /* no parent for PTR types */
4719 result->name_space = "System";
4720 result->name = "MonoFNPtrFakeClass";
4722 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4724 result->image = mono_defaults.corlib; /* need to fix... */
4725 result->inited = TRUE;
4726 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
4727 /* Can pointers get boxed? */
4728 result->instance_size = sizeof (gpointer);
4729 result->cast_class = result->element_class = result;
4730 result->blittable = TRUE;
4732 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
4733 result->this_arg.data.method = result->byval_arg.data.method = sig;
4734 result->this_arg.byref = TRUE;
4735 result->blittable = TRUE;
4737 mono_class_setup_supertypes (result);
4739 g_hash_table_insert (ptr_hash, sig, result);
4741 mono_loader_unlock ();
4743 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4749 mono_class_from_mono_type (MonoType *type)
4751 switch (type->type) {
4752 case MONO_TYPE_OBJECT:
4753 return type->data.klass? type->data.klass: mono_defaults.object_class;
4754 case MONO_TYPE_VOID:
4755 return type->data.klass? type->data.klass: mono_defaults.void_class;
4756 case MONO_TYPE_BOOLEAN:
4757 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
4758 case MONO_TYPE_CHAR:
4759 return type->data.klass? type->data.klass: mono_defaults.char_class;
4761 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
4763 return type->data.klass? type->data.klass: mono_defaults.byte_class;
4765 return type->data.klass? type->data.klass: mono_defaults.int16_class;
4767 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
4769 return type->data.klass? type->data.klass: mono_defaults.int32_class;
4771 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
4773 return type->data.klass? type->data.klass: mono_defaults.int_class;
4775 return type->data.klass? type->data.klass: mono_defaults.uint_class;
4777 return type->data.klass? type->data.klass: mono_defaults.int64_class;
4779 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
4781 return type->data.klass? type->data.klass: mono_defaults.single_class;
4783 return type->data.klass? type->data.klass: mono_defaults.double_class;
4784 case MONO_TYPE_STRING:
4785 return type->data.klass? type->data.klass: mono_defaults.string_class;
4786 case MONO_TYPE_TYPEDBYREF:
4787 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
4788 case MONO_TYPE_ARRAY:
4789 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
4791 return mono_ptr_class_get (type->data.type);
4792 case MONO_TYPE_FNPTR:
4793 return mono_fnptr_class_get (type->data.method);
4794 case MONO_TYPE_SZARRAY:
4795 return mono_array_class_get (type->data.klass, 1);
4796 case MONO_TYPE_CLASS:
4797 case MONO_TYPE_VALUETYPE:
4798 return type->data.klass;
4799 case MONO_TYPE_GENERICINST:
4800 return mono_generic_class_get_class (type->data.generic_class);
4802 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
4803 case MONO_TYPE_MVAR:
4804 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
4806 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
4807 g_assert_not_reached ();
4814 * mono_type_retrieve_from_typespec
4815 * @image: context where the image is created
4816 * @type_spec: typespec token
4817 * @context: the generic context used to evaluate generic instantiations in
4820 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate)
4822 MonoType *t = mono_type_create_from_typespec (image, type_spec);
4825 if (context && (context->class_inst || context->method_inst)) {
4826 MonoType *inflated = inflate_generic_type (NULL, t, context);
4829 *did_inflate = TRUE;
4836 * mono_class_create_from_typespec
4837 * @image: context where the image is created
4838 * @type_spec: typespec token
4839 * @context: the generic context used to evaluate generic instantiations in
4842 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
4845 gboolean inflated = FALSE;
4846 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated);
4849 ret = mono_class_from_mono_type (t);
4851 mono_metadata_free_type (t);
4856 * mono_bounded_array_class_get:
4857 * @element_class: element class
4858 * @rank: the dimension of the array class
4859 * @bounded: whenever the array has non-zero bounds
4861 * Returns: a class object describing the array with element type @element_type and
4865 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
4869 MonoClass *parent = NULL;
4870 GSList *list, *rootlist;
4873 gboolean corlib_type = FALSE;
4875 g_assert (rank <= 255);
4878 /* bounded only matters for one-dimensional arrays */
4881 image = eclass->image;
4883 if (rank == 1 && !bounded) {
4885 * This case is very frequent not just during compilation because of calls
4886 * from mono_class_from_mono_type (), mono_array_new (),
4887 * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
4889 EnterCriticalSection (&image->szarray_cache_lock);
4890 if (!image->szarray_cache)
4891 image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4892 class = g_hash_table_lookup (image->szarray_cache, eclass);
4893 LeaveCriticalSection (&image->szarray_cache_lock);
4897 mono_loader_lock ();
4899 mono_loader_lock ();
4901 if (!image->array_cache)
4902 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4904 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
4905 for (; list; list = list->next) {
4907 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
4908 mono_loader_unlock ();
4915 /* for the building corlib use System.Array from it */
4916 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
4917 parent = mono_class_from_name (image, "System", "Array");
4920 parent = mono_defaults.array_class;
4921 if (!parent->inited)
4922 mono_class_init (parent);
4925 class = mono_image_alloc0 (image, sizeof (MonoClass));
4927 class->image = image;
4928 class->name_space = eclass->name_space;
4929 nsize = strlen (eclass->name);
4930 name = g_malloc (nsize + 2 + rank + 1);
4931 memcpy (name, eclass->name, nsize);
4934 memset (name + nsize + 1, ',', rank - 1);
4936 name [nsize + rank] = '*';
4937 name [nsize + rank + bounded] = ']';
4938 name [nsize + rank + bounded + 1] = 0;
4939 class->name = mono_image_strdup (image, name);
4942 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4944 classes_size += sizeof (MonoClass);
4946 class->type_token = 0;
4947 /* all arrays are marked serializable and sealed, bug #42779 */
4948 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
4949 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4950 class->parent = parent;
4951 class->instance_size = mono_class_instance_size (class->parent);
4953 if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
4954 if (!eclass->reflection_info || eclass->wastypebuilder) {
4955 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
4956 g_assert (eclass->reflection_info && !eclass->wastypebuilder);
4958 /* element_size -1 is ok as this is not an instantitable type*/
4959 class->sizes.element_size = -1;
4961 class->sizes.element_size = mono_class_array_element_size (eclass);
4963 mono_class_setup_supertypes (class);
4965 if (eclass->generic_class)
4966 mono_class_init (eclass);
4967 if (!eclass->size_inited)
4968 mono_class_setup_fields (eclass);
4969 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
4973 if (eclass->enumtype)
4974 class->cast_class = eclass->element_class;
4976 class->cast_class = eclass;
4978 class->element_class = eclass;
4980 if ((rank > 1) || bounded) {
4981 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
4982 class->byval_arg.type = MONO_TYPE_ARRAY;
4983 class->byval_arg.data.array = at;
4984 at->eklass = eclass;
4986 /* FIXME: complete.... */
4988 class->byval_arg.type = MONO_TYPE_SZARRAY;
4989 class->byval_arg.data.klass = eclass;
4991 class->this_arg = class->byval_arg;
4992 class->this_arg.byref = 1;
4997 class->generic_container = eclass->generic_container;
4999 if (rank == 1 && !bounded) {
5000 MonoClass *prev_class;
5002 EnterCriticalSection (&image->szarray_cache_lock);
5003 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
5005 /* Someone got in before us */
5008 g_hash_table_insert (image->szarray_cache, eclass, class);
5009 LeaveCriticalSection (&image->szarray_cache_lock);
5011 list = g_slist_append (rootlist, class);
5012 g_hash_table_insert (image->array_cache, eclass, list);
5015 mono_loader_unlock ();
5017 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5023 * mono_array_class_get:
5024 * @element_class: element class
5025 * @rank: the dimension of the array class
5027 * Returns: a class object describing the array with element type @element_type and
5031 mono_array_class_get (MonoClass *eclass, guint32 rank)
5033 return mono_bounded_array_class_get (eclass, rank, FALSE);
5037 * mono_class_instance_size:
5040 * Returns: the size of an object instance
5043 mono_class_instance_size (MonoClass *klass)
5045 if (!klass->size_inited)
5046 mono_class_init (klass);
5048 return klass->instance_size;
5052 * mono_class_min_align:
5055 * Returns: minimm alignment requirements
5058 mono_class_min_align (MonoClass *klass)
5060 if (!klass->size_inited)
5061 mono_class_init (klass);
5063 return klass->min_align;
5067 * mono_class_value_size:
5070 * This function is used for value types, and return the
5071 * space and the alignment to store that kind of value object.
5073 * Returns: the size of a value of kind @klass
5076 mono_class_value_size (MonoClass *klass, guint32 *align)
5080 /* fixme: check disable, because we still have external revereces to
5081 * mscorlib and Dummy Objects
5083 /*g_assert (klass->valuetype);*/
5085 size = mono_class_instance_size (klass) - sizeof (MonoObject);
5088 *align = klass->min_align;
5094 * mono_class_data_size:
5097 * Returns: the size of the static class data
5100 mono_class_data_size (MonoClass *klass)
5103 mono_class_init (klass);
5105 /* in arrays, sizes.class_size is unioned with element_size
5106 * and arrays have no static fields
5110 return klass->sizes.class_size;
5114 * Auxiliary routine to mono_class_get_field
5116 * Takes a field index instead of a field token.
5118 static MonoClassField *
5119 mono_class_get_field_idx (MonoClass *class, int idx)
5121 mono_class_setup_fields_locking (class);
5124 if (class->image->uncompressed_metadata) {
5126 * class->field.first points to the FieldPtr table, while idx points into the
5127 * Field table, so we have to do a search.
5129 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
5132 for (i = 0; i < class->field.count; ++i)
5133 if (mono_field_get_name (&class->fields [i]) == name)
5134 return &class->fields [i];
5135 g_assert_not_reached ();
5137 if (class->field.count) {
5138 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
5139 return &class->fields [idx - class->field.first];
5143 class = class->parent;
5149 * mono_class_get_field:
5150 * @class: the class to lookup the field.
5151 * @field_token: the field token
5153 * Returns: A MonoClassField representing the type and offset of
5154 * the field, or a NULL value if the field does not belong to this
5158 mono_class_get_field (MonoClass *class, guint32 field_token)
5160 int idx = mono_metadata_token_index (field_token);
5162 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
5164 return mono_class_get_field_idx (class, idx - 1);
5168 * mono_class_get_field_from_name:
5169 * @klass: the class to lookup the field.
5170 * @name: the field name
5172 * Search the class @klass and it's parents for a field with the name @name.
5174 * Returns: the MonoClassField pointer of the named field or NULL
5177 mono_class_get_field_from_name (MonoClass *klass, const char *name)
5181 mono_class_setup_fields_locking (klass);
5183 for (i = 0; i < klass->field.count; ++i) {
5184 if (strcmp (name, mono_field_get_name (&klass->fields [i])) == 0)
5185 return &klass->fields [i];
5187 klass = klass->parent;
5193 * mono_class_get_field_token:
5194 * @field: the field we need the token of
5196 * Get the token of a field. Note that the tokesn is only valid for the image
5197 * the field was loaded from. Don't use this function for fields in dynamic types.
5199 * Returns: the token representing the field in the image it was loaded from.
5202 mono_class_get_field_token (MonoClassField *field)
5204 MonoClass *klass = field->parent;
5207 mono_class_setup_fields_locking (klass);
5209 for (i = 0; i < klass->field.count; ++i) {
5210 if (&klass->fields [i] == field) {
5211 int idx = klass->field.first + i + 1;
5213 if (klass->image->uncompressed_metadata)
5214 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
5215 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
5218 klass = klass->parent;
5221 g_assert_not_reached ();
5226 mono_field_get_index (MonoClassField *field)
5228 int index = field - field->parent->fields;
5230 g_assert (index >= 0 && index < field->parent->field.count);
5236 * mono_class_get_field_default_value:
5238 * Return the default value of the field as a pointer into the metadata blob.
5241 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
5244 guint32 constant_cols [MONO_CONSTANT_SIZE];
5246 MonoClass *klass = field->parent;
5248 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
5250 if (!klass->ext || !klass->ext->field_def_values) {
5251 mono_loader_lock ();
5252 mono_class_alloc_ext (klass);
5253 if (!klass->ext->field_def_values)
5254 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
5255 mono_loader_unlock ();
5258 field_index = mono_field_get_index (field);
5260 if (!klass->ext->field_def_values [field_index].data) {
5261 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
5263 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
5265 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
5266 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
5267 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
5270 *def_type = klass->ext->field_def_values [field_index].def_type;
5271 return klass->ext->field_def_values [field_index].data;
5275 mono_class_get_event_token (MonoEvent *event)
5277 MonoClass *klass = event->parent;
5282 for (i = 0; i < klass->ext->event.count; ++i) {
5283 if (&klass->ext->events [i] == event)
5284 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
5287 klass = klass->parent;
5290 g_assert_not_reached ();
5295 mono_class_get_property_from_name (MonoClass *klass, const char *name)
5299 gpointer iter = NULL;
5300 while ((p = mono_class_get_properties (klass, &iter))) {
5301 if (! strcmp (name, p->name))
5304 klass = klass->parent;
5310 mono_class_get_property_token (MonoProperty *prop)
5312 MonoClass *klass = prop->parent;
5316 gpointer iter = NULL;
5317 while ((p = mono_class_get_properties (klass, &iter))) {
5318 if (&klass->ext->properties [i] == prop)
5319 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
5323 klass = klass->parent;
5326 g_assert_not_reached ();
5331 mono_class_name_from_token (MonoImage *image, guint32 type_token)
5333 const char *name, *nspace;
5335 return g_strdup_printf ("DynamicType 0x%08x", type_token);
5337 switch (type_token & 0xff000000){
5338 case MONO_TOKEN_TYPE_DEF: {
5339 guint32 cols [MONO_TYPEDEF_SIZE];
5340 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5341 guint tidx = mono_metadata_token_index (type_token);
5343 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5344 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5345 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5346 if (strlen (nspace) == 0)
5347 return g_strdup_printf ("%s", name);
5349 return g_strdup_printf ("%s.%s", nspace, name);
5352 case MONO_TOKEN_TYPE_REF: {
5353 guint32 cols [MONO_TYPEREF_SIZE];
5354 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5356 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5357 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
5358 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
5359 if (strlen (nspace) == 0)
5360 return g_strdup_printf ("%s", name);
5362 return g_strdup_printf ("%s.%s", nspace, name);
5365 case MONO_TOKEN_TYPE_SPEC:
5366 return g_strdup_printf ("Typespec 0x%08x", type_token);
5368 g_assert_not_reached ();
5375 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
5378 return g_strdup_printf ("DynamicAssembly %s", image->name);
5380 switch (type_token & 0xff000000){
5381 case MONO_TOKEN_TYPE_DEF:
5382 return mono_stringify_assembly_name (&image->assembly->aname);
5384 case MONO_TOKEN_TYPE_REF: {
5385 MonoAssemblyName aname;
5386 guint32 cols [MONO_TYPEREF_SIZE];
5387 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5390 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5392 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
5393 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
5394 case MONO_RESOLTION_SCOPE_MODULE:
5396 return g_strdup ("");
5397 case MONO_RESOLTION_SCOPE_MODULEREF:
5399 return g_strdup ("");
5400 case MONO_RESOLTION_SCOPE_TYPEREF:
5402 return g_strdup ("");
5403 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
5404 mono_assembly_get_assemblyref (image, idx - 1, &aname);
5405 return mono_stringify_assembly_name (&aname);
5407 g_assert_not_reached ();
5411 case MONO_TOKEN_TYPE_SPEC:
5413 return g_strdup ("");
5415 g_assert_not_reached ();
5422 * mono_class_get_full:
5423 * @image: the image where the class resides
5424 * @type_token: the token for the class
5425 * @context: the generic context used to evaluate generic instantiations in
5427 * Returns: the MonoClass that represents @type_token in @image
5430 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5432 MonoClass *class = NULL;
5434 if (image->dynamic) {
5435 int table = mono_metadata_token_table (type_token);
5437 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
5438 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
5441 return mono_lookup_dynamic_token (image, type_token, context);
5444 switch (type_token & 0xff000000){
5445 case MONO_TOKEN_TYPE_DEF:
5446 class = mono_class_create_from_typedef (image, type_token);
5448 case MONO_TOKEN_TYPE_REF:
5449 class = mono_class_from_typeref (image, type_token);
5451 case MONO_TOKEN_TYPE_SPEC:
5452 class = mono_class_create_from_typespec (image, type_token, context);
5455 g_warning ("unknown token type %x", type_token & 0xff000000);
5456 g_assert_not_reached ();
5460 char *name = mono_class_name_from_token (image, type_token);
5461 char *assembly = mono_assembly_name_from_token (image, type_token);
5462 mono_loader_set_error_type_load (name, assembly);
5470 * mono_type_get_full:
5471 * @image: the image where the type resides
5472 * @type_token: the token for the type
5473 * @context: the generic context used to evaluate generic instantiations in
5475 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
5477 * Returns: the MonoType that represents @type_token in @image
5480 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5482 MonoType *type = NULL;
5483 gboolean inflated = FALSE;
5485 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
5487 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
5489 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
5490 MonoClass *class = mono_class_get_full (image, type_token, context);
5491 return class ? mono_class_get_type (class) : NULL;
5494 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated);
5497 char *name = mono_class_name_from_token (image, type_token);
5498 char *assembly = mono_assembly_name_from_token (image, type_token);
5500 mono_metadata_free_type (type);
5501 mono_loader_set_error_type_load (name, assembly);
5505 MonoType *tmp = type;
5506 type = mono_class_get_type (mono_class_from_mono_type (type));
5507 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
5508 * A MonoClass::byval_arg of a generic type definion has type CLASS.
5509 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
5511 * The long term solution is to chaise this places and make then set MonoType::type correctly.
5513 if (type->type != tmp->type)
5516 mono_metadata_free_type (tmp);
5523 mono_class_get (MonoImage *image, guint32 type_token)
5525 return mono_class_get_full (image, type_token, NULL);
5529 * mono_image_init_name_cache:
5531 * Initializes the class name cache stored in image->name_cache.
5533 * LOCKING: Acquires the loader lock.
5536 mono_image_init_name_cache (MonoImage *image)
5538 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5539 guint32 cols [MONO_TYPEDEF_SIZE];
5542 guint32 i, visib, nspace_index;
5543 GHashTable *name_cache2, *nspace_table;
5545 mono_loader_lock ();
5547 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
5549 if (image->dynamic) {
5550 mono_loader_unlock ();
5554 /* Temporary hash table to avoid lookups in the nspace_table */
5555 name_cache2 = g_hash_table_new (NULL, NULL);
5557 for (i = 1; i <= t->rows; ++i) {
5558 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5559 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5561 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5562 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5564 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5566 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5567 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5569 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
5570 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5571 if (!nspace_table) {
5572 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5573 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5574 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5577 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
5580 /* Load type names from EXPORTEDTYPES table */
5582 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5583 guint32 cols [MONO_EXP_TYPE_SIZE];
5586 for (i = 0; i < t->rows; ++i) {
5587 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
5588 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
5589 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
5591 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
5592 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5593 if (!nspace_table) {
5594 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5595 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5596 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5599 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
5603 g_hash_table_destroy (name_cache2);
5605 mono_loader_unlock ();
5609 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
5610 const char *name, guint32 index)
5612 GHashTable *nspace_table;
5613 GHashTable *name_cache;
5615 mono_loader_lock ();
5617 if (!image->name_cache)
5618 mono_image_init_name_cache (image);
5620 name_cache = image->name_cache;
5621 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
5622 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5623 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
5625 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
5627 mono_loader_unlock ();
5636 find_nocase (gpointer key, gpointer value, gpointer user_data)
5638 char *name = (char*)key;
5639 FindUserData *data = (FindUserData*)user_data;
5641 if (!data->value && (g_strcasecmp (name, (char*)data->key) == 0))
5642 data->value = value;
5646 * mono_class_from_name_case:
5647 * @image: The MonoImage where the type is looked up in
5648 * @name_space: the type namespace
5649 * @name: the type short name.
5651 * Obtains a MonoClass with a given namespace and a given name which
5652 * is located in the given MonoImage. The namespace and name
5653 * lookups are case insensitive.
5656 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
5658 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5659 guint32 cols [MONO_TYPEDEF_SIZE];
5664 if (image->dynamic) {
5666 FindUserData user_data;
5668 mono_loader_lock ();
5670 if (!image->name_cache)
5671 mono_image_init_name_cache (image);
5673 user_data.key = name_space;
5674 user_data.value = NULL;
5675 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
5677 if (user_data.value) {
5678 GHashTable *nspace_table = (GHashTable*)user_data.value;
5680 user_data.key = name;
5681 user_data.value = NULL;
5683 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
5685 if (user_data.value)
5686 token = GPOINTER_TO_UINT (user_data.value);
5689 mono_loader_unlock ();
5692 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
5698 /* add a cache if needed */
5699 for (i = 1; i <= t->rows; ++i) {
5700 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5701 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5703 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5704 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5706 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5708 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5709 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5710 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
5711 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
5717 return_nested_in (MonoClass *class, char *nested)
5720 char *s = strchr (nested, '/');
5721 gpointer iter = NULL;
5728 while ((found = mono_class_get_nested_types (class, &iter))) {
5729 if (strcmp (found->name, nested) == 0) {
5731 return return_nested_in (found, s);
5739 search_modules (MonoImage *image, const char *name_space, const char *name)
5741 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
5742 MonoImage *file_image;
5747 * The EXPORTEDTYPES table only contains public types, so have to search the
5749 * Note: image->modules contains the contents of the MODULEREF table, while
5750 * the real module list is in the FILE table.
5752 for (i = 0; i < file_table->rows; i++) {
5753 guint32 cols [MONO_FILE_SIZE];
5754 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
5755 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
5758 file_image = mono_image_load_file_for_image (image, i + 1);
5760 class = mono_class_from_name (file_image, name_space, name);
5770 * mono_class_from_name:
5771 * @image: The MonoImage where the type is looked up in
5772 * @name_space: the type namespace
5773 * @name: the type short name.
5775 * Obtains a MonoClass with a given namespace and a given name which
5776 * is located in the given MonoImage.
5779 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
5781 GHashTable *nspace_table;
5782 MonoImage *loaded_image;
5789 if ((nested = strchr (name, '/'))) {
5790 int pos = nested - name;
5791 int len = strlen (name);
5794 memcpy (buf, name, len + 1);
5796 nested = buf + pos + 1;
5800 if (get_class_from_name) {
5801 gboolean res = get_class_from_name (image, name_space, name, &class);
5804 class = search_modules (image, name_space, name);
5806 return class ? return_nested_in (class, nested) : NULL;
5812 mono_loader_lock ();
5814 if (!image->name_cache)
5815 mono_image_init_name_cache (image);
5817 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
5820 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
5822 mono_loader_unlock ();
5824 if (!token && image->dynamic && image->modules) {
5825 /* Search modules as well */
5826 for (i = 0; i < image->module_count; ++i) {
5827 MonoImage *module = image->modules [i];
5829 class = mono_class_from_name (module, name_space, name);
5836 class = search_modules (image, name_space, name);
5844 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
5845 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5846 guint32 cols [MONO_EXP_TYPE_SIZE];
5849 idx = mono_metadata_token_index (token);
5851 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
5853 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
5854 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
5855 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
5858 class = mono_class_from_name (loaded_image, name_space, name);
5860 return return_nested_in (class, nested);
5862 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
5863 MonoAssembly **references = image->references;
5864 guint32 assembly_idx;
5866 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
5868 if (!references [assembly_idx - 1])
5869 mono_assembly_load_reference (image, assembly_idx - 1);
5870 g_assert (references == image->references);
5871 g_assert (references [assembly_idx - 1]);
5872 if (references [assembly_idx - 1] == (gpointer)-1)
5875 /* FIXME: Cycle detection */
5876 return mono_class_from_name (references [assembly_idx - 1]->image, name_space, name);
5878 g_error ("not yet implemented");
5882 token = MONO_TOKEN_TYPE_DEF | token;
5884 class = mono_class_get (image, token);
5886 return return_nested_in (class, nested);
5891 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
5892 gboolean check_interfaces)
5894 g_assert (klassc->idepth > 0);
5895 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
5896 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
5898 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
5901 for (i = 0; i < klass->interface_count; i ++) {
5902 MonoClass *ic = klass->interfaces [i];
5907 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
5912 * MS.NET thinks interfaces are a subclass of Object, so we think it as
5915 if (klassc == mono_defaults.object_class)
5922 mono_class_has_variant_generic_params (MonoClass *klass)
5925 MonoGenericContainer *container;
5927 if (!klass->generic_class)
5930 container = klass->generic_class->container_class->generic_container;
5932 for (i = 0; i < container->type_argc; ++i)
5933 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
5940 * mono_class_is_assignable_from:
5941 * @klass: the class to be assigned to
5942 * @oklass: the source class
5944 * Return: true if an instance of object oklass can be assigned to an
5945 * instance of object @klass
5948 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
5951 mono_class_init (klass);
5953 if (!oklass->inited)
5954 mono_class_init (oklass);
5956 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
5957 return klass == oklass;
5959 if (MONO_CLASS_IS_INTERFACE (klass)) {
5960 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
5963 /* interface_offsets might not be set for dynamic classes */
5964 if (oklass->reflection_info && !oklass->interface_bitmap)
5966 * oklass might be a generic type parameter but they have
5967 * interface_offsets set.
5969 return mono_reflection_call_is_assignable_to (oklass, klass);
5970 if (!oklass->interface_bitmap)
5971 /* Happens with generic instances of not-yet created dynamic types */
5973 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
5976 if (mono_class_has_variant_generic_params (klass)) {
5977 if (oklass->generic_class) {
5979 gboolean match = FALSE;
5980 MonoClass *container_class1 = klass->generic_class->container_class;
5981 MonoClass *container_class2 = oklass->generic_class->container_class;
5984 * Check whenever the generic definition of oklass implements the
5985 * generic definition of klass. The IMPLEMENTS_INTERFACE stuff is not usable
5986 * here since the relevant tables are not set up.
5988 for (i = 0; i < container_class2->interface_offsets_count; ++i)
5989 if ((container_class2->interfaces_packed [i] == container_class1) || (container_class2->interfaces_packed [i]->generic_class && (container_class2->interfaces_packed [i]->generic_class->container_class == container_class1)))
5993 MonoGenericContainer *container;
5995 container = klass->generic_class->container_class->generic_container;
5998 for (i = 0; i < container->type_argc; ++i) {
5999 MonoClass *param1_class = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [i]);
6000 MonoClass *param2_class = mono_class_from_mono_type (oklass->generic_class->context.class_inst->type_argv [i]);
6002 if (param1_class->valuetype != param2_class->valuetype) {
6007 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
6008 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
6010 if (param1_class != param2_class) {
6011 if ((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_VARIANT) && mono_class_is_assignable_from (param1_class, param2_class))
6013 else if (((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_COVARIANT) && mono_class_is_assignable_from (param2_class, param1_class)))
6027 } else if (klass->rank) {
6028 MonoClass *eclass, *eoclass;
6030 if (oklass->rank != klass->rank)
6033 /* vectors vs. one dimensional arrays */
6034 if (oklass->byval_arg.type != klass->byval_arg.type)
6037 eclass = klass->cast_class;
6038 eoclass = oklass->cast_class;
6041 * a is b does not imply a[] is b[] when a is a valuetype, and
6042 * b is a reference type.
6045 if (eoclass->valuetype) {
6046 if ((eclass == mono_defaults.enum_class) ||
6047 (eclass == mono_defaults.enum_class->parent) ||
6048 (eclass == mono_defaults.object_class))
6052 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6053 } else if (mono_class_is_nullable (klass)) {
6054 if (mono_class_is_nullable (oklass))
6055 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6057 return mono_class_is_assignable_from (klass->cast_class, oklass);
6058 } else if (klass == mono_defaults.object_class)
6061 return mono_class_has_parent (oklass, klass);
6065 * mono_class_get_cctor:
6066 * @klass: A MonoClass pointer
6068 * Returns: the static constructor of @klass if it exists, NULL otherwise.
6071 mono_class_get_cctor (MonoClass *klass)
6073 MonoCachedClassInfo cached_info;
6075 if (!klass->has_cctor)
6078 if (mono_class_get_cached_class_info (klass, &cached_info))
6079 return mono_get_method (klass->image, cached_info.cctor_token, klass);
6081 if (klass->generic_class && !klass->methods)
6082 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
6084 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
6088 * mono_class_get_finalizer:
6089 * @klass: The MonoClass pointer
6091 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
6094 mono_class_get_finalizer (MonoClass *klass)
6096 MonoCachedClassInfo cached_info;
6099 mono_class_init (klass);
6100 if (!klass->has_finalize)
6103 if (mono_class_get_cached_class_info (klass, &cached_info))
6104 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
6106 mono_class_setup_vtable (klass);
6107 return klass->vtable [finalize_slot];
6112 * mono_class_needs_cctor_run:
6113 * @klass: the MonoClass pointer
6114 * @caller: a MonoMethod describing the caller
6116 * Determines whenever the class has a static constructor and whenever it
6117 * needs to be called when executing CALLER.
6120 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
6124 method = mono_class_get_cctor (klass);
6126 return (method == caller) ? FALSE : TRUE;
6132 * mono_class_array_element_size:
6135 * Returns: the number of bytes an element of type @klass
6136 * uses when stored into an array.
6139 mono_class_array_element_size (MonoClass *klass)
6141 MonoType *type = &klass->byval_arg;
6144 switch (type->type) {
6147 case MONO_TYPE_BOOLEAN:
6151 case MONO_TYPE_CHAR:
6160 case MONO_TYPE_CLASS:
6161 case MONO_TYPE_STRING:
6162 case MONO_TYPE_OBJECT:
6163 case MONO_TYPE_SZARRAY:
6164 case MONO_TYPE_ARRAY:
6166 case MONO_TYPE_MVAR:
6167 return sizeof (gpointer);
6172 case MONO_TYPE_VALUETYPE:
6173 if (type->data.klass->enumtype) {
6174 type = mono_class_enum_basetype (type->data.klass);
6175 klass = klass->element_class;
6178 return mono_class_instance_size (klass) - sizeof (MonoObject);
6179 case MONO_TYPE_GENERICINST:
6180 type = &type->data.generic_class->container_class->byval_arg;
6183 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
6189 * mono_array_element_size:
6190 * @ac: pointer to a #MonoArrayClass
6192 * Returns: the size of single array element.
6195 mono_array_element_size (MonoClass *ac)
6197 g_assert (ac->rank);
6198 return ac->sizes.element_size;
6202 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
6203 MonoGenericContext *context)
6205 if (image->dynamic) {
6206 MonoClass *tmp_handle_class;
6207 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
6209 g_assert (tmp_handle_class);
6211 *handle_class = tmp_handle_class;
6213 if (tmp_handle_class == mono_defaults.typehandle_class)
6214 return &((MonoClass*)obj)->byval_arg;
6219 switch (token & 0xff000000) {
6220 case MONO_TOKEN_TYPE_DEF:
6221 case MONO_TOKEN_TYPE_REF:
6222 case MONO_TOKEN_TYPE_SPEC: {
6225 *handle_class = mono_defaults.typehandle_class;
6226 type = mono_type_get_full (image, token, context);
6229 mono_class_init (mono_class_from_mono_type (type));
6230 /* We return a MonoType* as handle */
6233 case MONO_TOKEN_FIELD_DEF: {
6235 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
6237 *handle_class = mono_defaults.fieldhandle_class;
6238 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
6241 mono_class_init (class);
6242 return mono_class_get_field (class, token);
6244 case MONO_TOKEN_METHOD_DEF:
6245 case MONO_TOKEN_METHOD_SPEC: {
6247 meth = mono_get_method_full (image, token, NULL, context);
6249 *handle_class = mono_defaults.methodhandle_class;
6252 case MONO_TOKEN_MEMBER_REF: {
6253 guint32 cols [MONO_MEMBERREF_SIZE];
6255 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
6256 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6257 mono_metadata_decode_blob_size (sig, &sig);
6258 if (*sig == 0x6) { /* it's a field */
6260 MonoClassField *field;
6261 field = mono_field_from_token (image, token, &klass, context);
6263 *handle_class = mono_defaults.fieldhandle_class;
6267 meth = mono_get_method_full (image, token, NULL, context);
6269 *handle_class = mono_defaults.methodhandle_class;
6274 g_warning ("Unknown token 0x%08x in ldtoken", token);
6281 * This function might need to call runtime functions so it can't be part
6282 * of the metadata library.
6284 static MonoLookupDynamicToken lookup_dynamic = NULL;
6287 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
6289 lookup_dynamic = func;
6293 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
6295 MonoClass *handle_class;
6297 return lookup_dynamic (image, token, TRUE, &handle_class, context);
6301 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
6303 return lookup_dynamic (image, token, valid_token, handle_class, context);
6306 static MonoGetCachedClassInfo get_cached_class_info = NULL;
6309 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
6311 get_cached_class_info = func;
6315 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
6317 if (!get_cached_class_info)
6320 return get_cached_class_info (klass, res);
6324 mono_install_get_class_from_name (MonoGetClassFromName func)
6326 get_class_from_name = func;
6330 mono_class_get_image (MonoClass *klass)
6332 return klass->image;
6336 * mono_class_get_element_class:
6337 * @klass: the MonoClass to act on
6339 * Returns: the element class of an array or an enumeration.
6342 mono_class_get_element_class (MonoClass *klass)
6344 return klass->element_class;
6348 * mono_class_is_valuetype:
6349 * @klass: the MonoClass to act on
6351 * Returns: true if the MonoClass represents a ValueType.
6354 mono_class_is_valuetype (MonoClass *klass)
6356 return klass->valuetype;
6360 * mono_class_is_enum:
6361 * @klass: the MonoClass to act on
6363 * Returns: true if the MonoClass represents an enumeration.
6366 mono_class_is_enum (MonoClass *klass)
6368 return klass->enumtype;
6372 * mono_class_enum_basetype:
6373 * @klass: the MonoClass to act on
6375 * Returns: the underlying type representation for an enumeration.
6378 mono_class_enum_basetype (MonoClass *klass)
6380 if (klass->element_class == klass)
6384 return &klass->element_class->byval_arg;
6388 * mono_class_get_parent
6389 * @klass: the MonoClass to act on
6391 * Returns: the parent class for this class.
6394 mono_class_get_parent (MonoClass *klass)
6396 return klass->parent;
6400 * mono_class_get_nesting_type;
6401 * @klass: the MonoClass to act on
6403 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
6406 mono_class_get_nesting_type (MonoClass *klass)
6408 return klass->nested_in;
6412 * mono_class_get_rank:
6413 * @klass: the MonoClass to act on
6415 * Returns: the rank for the array (the number of dimensions).
6418 mono_class_get_rank (MonoClass *klass)
6424 * mono_class_get_flags:
6425 * @klass: the MonoClass to act on
6427 * The type flags from the TypeDef table from the metadata.
6428 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
6431 * Returns: the flags from the TypeDef table.
6434 mono_class_get_flags (MonoClass *klass)
6436 return klass->flags;
6440 * mono_class_get_name
6441 * @klass: the MonoClass to act on
6443 * Returns: the name of the class.
6446 mono_class_get_name (MonoClass *klass)
6452 * mono_class_get_namespace:
6453 * @klass: the MonoClass to act on
6455 * Returns: the namespace of the class.
6458 mono_class_get_namespace (MonoClass *klass)
6460 return klass->name_space;
6464 * mono_class_get_type:
6465 * @klass: the MonoClass to act on
6467 * This method returns the internal Type representation for the class.
6469 * Returns: the MonoType from the class.
6472 mono_class_get_type (MonoClass *klass)
6474 return &klass->byval_arg;
6478 * mono_class_get_type_token
6479 * @klass: the MonoClass to act on
6481 * This method returns type token for the class.
6483 * Returns: the type token for the class.
6486 mono_class_get_type_token (MonoClass *klass)
6488 return klass->type_token;
6492 * mono_class_get_byref_type:
6493 * @klass: the MonoClass to act on
6498 mono_class_get_byref_type (MonoClass *klass)
6500 return &klass->this_arg;
6504 * mono_class_num_fields:
6505 * @klass: the MonoClass to act on
6507 * Returns: the number of static and instance fields in the class.
6510 mono_class_num_fields (MonoClass *klass)
6512 return klass->field.count;
6516 * mono_class_num_methods:
6517 * @klass: the MonoClass to act on
6519 * Returns: the number of methods in the class.
6522 mono_class_num_methods (MonoClass *klass)
6524 return klass->method.count;
6528 * mono_class_num_properties
6529 * @klass: the MonoClass to act on
6531 * Returns: the number of properties in the class.
6534 mono_class_num_properties (MonoClass *klass)
6536 mono_class_setup_properties (klass);
6538 return klass->ext->property.count;
6542 * mono_class_num_events:
6543 * @klass: the MonoClass to act on
6545 * Returns: the number of events in the class.
6548 mono_class_num_events (MonoClass *klass)
6550 mono_class_setup_events (klass);
6552 return klass->ext->event.count;
6556 * mono_class_get_fields:
6557 * @klass: the MonoClass to act on
6559 * This routine is an iterator routine for retrieving the fields in a class.
6561 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6562 * iterate over all of the elements. When no more values are
6563 * available, the return value is NULL.
6565 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
6568 mono_class_get_fields (MonoClass* klass, gpointer *iter)
6570 MonoClassField* field;
6574 mono_class_setup_fields_locking (klass);
6575 if (klass->exception_type)
6577 /* start from the first */
6578 if (klass->field.count) {
6579 return *iter = &klass->fields [0];
6587 if (field < &klass->fields [klass->field.count]) {
6588 return *iter = field;
6594 * mono_class_get_methods
6595 * @klass: the MonoClass to act on
6597 * This routine is an iterator routine for retrieving the fields in a class.
6599 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6600 * iterate over all of the elements. When no more values are
6601 * available, the return value is NULL.
6603 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
6606 mono_class_get_methods (MonoClass* klass, gpointer *iter)
6608 MonoMethod** method;
6612 mono_class_init (klass);
6614 mono_class_setup_methods (klass);
6615 /* start from the first */
6616 if (klass->method.count) {
6617 *iter = &klass->methods [0];
6618 return klass->methods [0];
6626 if (method < &klass->methods [klass->method.count]) {
6634 * mono_class_get_virtual_methods:
6636 * Iterate over the virtual methods of KLASS.
6638 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
6641 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
6643 MonoMethod** method;
6646 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
6648 mono_class_setup_methods (klass);
6649 /* start from the first */
6650 method = &klass->methods [0];
6655 while (method < &klass->methods [klass->method.count]) {
6656 if (((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
6660 if (method < &klass->methods [klass->method.count]) {
6667 /* Search directly in metadata to avoid calling setup_methods () */
6668 MonoMethod *res = NULL;
6674 start_index = GPOINTER_TO_UINT (*iter);
6677 for (i = start_index; i < klass->method.count; ++i) {
6678 guint32 cols [MONO_METHOD_SIZE];
6680 /* class->method.first points into the methodptr table */
6681 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
6683 if (cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_VIRTUAL)
6687 if (i < klass->method.count) {
6688 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
6689 /* Add 1 here so the if (*iter) check fails */
6690 *iter = GUINT_TO_POINTER (i + 1);
6699 * mono_class_get_properties:
6700 * @klass: the MonoClass to act on
6702 * This routine is an iterator routine for retrieving the properties in a class.
6704 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6705 * iterate over all of the elements. When no more values are
6706 * available, the return value is NULL.
6708 * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
6711 mono_class_get_properties (MonoClass* klass, gpointer *iter)
6713 MonoProperty* property;
6717 mono_class_init (klass);
6719 mono_class_setup_properties (klass);
6720 /* start from the first */
6721 if (klass->ext->property.count) {
6722 return *iter = &klass->ext->properties [0];
6730 if (property < &klass->ext->properties [klass->ext->property.count]) {
6731 return *iter = property;
6737 * mono_class_get_events:
6738 * @klass: the MonoClass to act on
6740 * This routine is an iterator routine for retrieving the properties in a class.
6742 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6743 * iterate over all of the elements. When no more values are
6744 * available, the return value is NULL.
6746 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
6749 mono_class_get_events (MonoClass* klass, gpointer *iter)
6755 mono_class_init (klass);
6757 mono_class_setup_events (klass);
6758 /* start from the first */
6759 if (klass->ext->event.count) {
6760 return *iter = &klass->ext->events [0];
6768 if (event < &klass->ext->events [klass->ext->event.count]) {
6769 return *iter = event;
6775 * mono_class_get_interfaces
6776 * @klass: the MonoClass to act on
6778 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
6780 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6781 * iterate over all of the elements. When no more values are
6782 * available, the return value is NULL.
6784 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
6787 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
6794 mono_class_init (klass);
6795 if (!klass->interfaces_inited)
6796 mono_class_setup_interfaces (klass);
6797 /* start from the first */
6798 if (klass->interface_count) {
6799 *iter = &klass->interfaces [0];
6800 return klass->interfaces [0];
6808 if (iface < &klass->interfaces [klass->interface_count]) {
6816 * mono_class_get_nested_types
6817 * @klass: the MonoClass to act on
6819 * This routine is an iterator routine for retrieving the nested types of a class.
6820 * This works only if @klass is non-generic, or a generic type definition.
6822 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6823 * iterate over all of the elements. When no more values are
6824 * available, the return value is NULL.
6826 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
6829 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
6837 mono_class_init (klass);
6838 if (!klass->nested_classes_inited) {
6839 if (!klass->type_token)
6840 klass->nested_classes_inited = TRUE;
6841 mono_loader_lock ();
6842 if (!klass->nested_classes_inited) {
6843 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
6846 guint32 cols [MONO_NESTED_CLASS_SIZE];
6847 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
6848 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
6849 mono_class_alloc_ext (klass);
6850 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
6852 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
6855 mono_memory_barrier ();
6856 klass->nested_classes_inited = TRUE;
6857 mono_loader_unlock ();
6861 /* start from the first */
6862 if (klass->ext && klass->ext->nested_classes) {
6863 *iter = klass->ext->nested_classes;
6864 return klass->ext->nested_classes->data;
6866 /* no nested types */
6880 * mono_field_get_name:
6881 * @field: the MonoClassField to act on
6883 * Returns: the name of the field.
6886 mono_field_get_name (MonoClassField *field)
6892 * mono_field_get_type:
6893 * @field: the MonoClassField to act on
6895 * Returns: MonoType of the field.
6898 mono_field_get_type (MonoClassField *field)
6904 * mono_field_get_type:
6905 * @field: the MonoClassField to act on
6907 * Returns: MonoClass where the field was defined.
6910 mono_field_get_parent (MonoClassField *field)
6912 return field->parent;
6916 * mono_field_get_flags;
6917 * @field: the MonoClassField to act on
6919 * The metadata flags for a field are encoded using the
6920 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
6922 * Returns: the flags for the field.
6925 mono_field_get_flags (MonoClassField *field)
6927 return field->type->attrs;
6931 * mono_field_get_offset;
6932 * @field: the MonoClassField to act on
6934 * Returns: the field offset.
6937 mono_field_get_offset (MonoClassField *field)
6939 return field->offset;
6943 mono_field_get_rva (MonoClassField *field)
6947 MonoClass *klass = field->parent;
6949 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
6951 if (!klass->ext || !klass->ext->field_def_values) {
6952 mono_loader_lock ();
6953 mono_class_alloc_ext (klass);
6954 if (!klass->ext->field_def_values)
6955 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
6956 mono_loader_unlock ();
6959 field_index = mono_field_get_index (field);
6961 if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
6962 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
6964 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
6965 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
6968 return klass->ext->field_def_values [field_index].data;
6972 * mono_field_get_data;
6973 * @field: the MonoClassField to act on
6975 * Returns: pointer to the metadata constant value or to the field
6976 * data if it has an RVA flag.
6979 mono_field_get_data (MonoClassField *field)
6981 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
6982 MonoTypeEnum def_type;
6984 return mono_class_get_field_default_value (field, &def_type);
6985 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
6986 return mono_field_get_rva (field);
6993 * mono_property_get_name:
6994 * @prop: the MonoProperty to act on
6996 * Returns: the name of the property
6999 mono_property_get_name (MonoProperty *prop)
7005 * mono_property_get_set_method
7006 * @prop: the MonoProperty to act on.
7008 * Returns: the setter method of the property (A MonoMethod)
7011 mono_property_get_set_method (MonoProperty *prop)
7017 * mono_property_get_get_method
7018 * @prop: the MonoProperty to act on.
7020 * Returns: the setter method of the property (A MonoMethod)
7023 mono_property_get_get_method (MonoProperty *prop)
7029 * mono_property_get_parent:
7030 * @prop: the MonoProperty to act on.
7032 * Returns: the MonoClass where the property was defined.
7035 mono_property_get_parent (MonoProperty *prop)
7037 return prop->parent;
7041 * mono_property_get_flags:
7042 * @prop: the MonoProperty to act on.
7044 * The metadata flags for a property are encoded using the
7045 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
7047 * Returns: the flags for the property.
7050 mono_property_get_flags (MonoProperty *prop)
7056 * mono_event_get_name:
7057 * @event: the MonoEvent to act on
7059 * Returns: the name of the event.
7062 mono_event_get_name (MonoEvent *event)
7068 * mono_event_get_add_method:
7069 * @event: The MonoEvent to act on.
7071 * Returns: the @add' method for the event (a MonoMethod).
7074 mono_event_get_add_method (MonoEvent *event)
7080 * mono_event_get_remove_method:
7081 * @event: The MonoEvent to act on.
7083 * Returns: the @remove method for the event (a MonoMethod).
7086 mono_event_get_remove_method (MonoEvent *event)
7088 return event->remove;
7092 * mono_event_get_raise_method:
7093 * @event: The MonoEvent to act on.
7095 * Returns: the @raise method for the event (a MonoMethod).
7098 mono_event_get_raise_method (MonoEvent *event)
7100 return event->raise;
7104 * mono_event_get_parent:
7105 * @event: the MonoEvent to act on.
7107 * Returns: the MonoClass where the event is defined.
7110 mono_event_get_parent (MonoEvent *event)
7112 return event->parent;
7116 * mono_event_get_flags
7117 * @event: the MonoEvent to act on.
7119 * The metadata flags for an event are encoded using the
7120 * EVENT_* constants. See the tabledefs.h file for details.
7122 * Returns: the flags for the event.
7125 mono_event_get_flags (MonoEvent *event)
7127 return event->attrs;
7131 * mono_class_get_method_from_name:
7132 * @klass: where to look for the method
7133 * @name_space: name of the method
7134 * @param_count: number of parameters. -1 for any number.
7136 * Obtains a MonoMethod with a given name and number of parameters.
7137 * It only works if there are no multiple signatures for any given method name.
7140 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
7142 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
7146 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
7148 MonoMethod *res = NULL;
7151 /* Search directly in the metadata to avoid calling setup_methods () */
7152 for (i = 0; i < klass->method.count; ++i) {
7153 guint32 cols [MONO_METHOD_SIZE];
7156 /* class->method.first points into the methodptr table */
7157 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
7159 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
7160 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7161 if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
7172 * mono_class_get_method_from_name_flags:
7173 * @klass: where to look for the method
7174 * @name_space: name of the method
7175 * @param_count: number of parameters. -1 for any number.
7176 * @flags: flags which must be set in the method
7178 * Obtains a MonoMethod with a given name and number of parameters.
7179 * It only works if there are no multiple signatures for any given method name.
7182 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
7184 MonoMethod *res = NULL;
7187 mono_class_init (klass);
7189 if (klass->generic_class && !klass->methods) {
7190 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
7192 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
7196 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
7197 mono_class_setup_methods (klass);
7198 for (i = 0; i < klass->method.count; ++i) {
7199 MonoMethod *method = klass->methods [i];
7201 if (method->name[0] == name [0] &&
7202 !strcmp (name, method->name) &&
7203 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
7204 ((method->flags & flags) == flags)) {
7211 res = find_method_in_metadata (klass, name, param_count, flags);
7218 * mono_class_set_failure:
7219 * @klass: class in which the failure was detected
7220 * @ex_type: the kind of exception/error to be thrown (later)
7221 * @ex_data: exception data (specific to each type of exception/error)
7223 * Keep a detected failure informations in the class for later processing.
7224 * Note that only the first failure is kept.
7226 * LOCKING: Acquires the loader lock.
7229 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
7231 if (klass->exception_type)
7234 mono_loader_lock ();
7235 klass->exception_type = ex_type;
7237 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
7238 mono_loader_unlock ();
7244 * mono_class_get_exception_data:
7246 * Return the exception_data property of KLASS.
7248 * LOCKING: Acquires the loader lock.
7251 mono_class_get_exception_data (MonoClass *klass)
7253 return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
7257 * mono_classes_init:
7259 * Initialize the resources used by this module.
7262 mono_classes_init (void)
7264 mono_counters_register ("Inflated methods size",
7265 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
7266 mono_counters_register ("Inflated classes",
7267 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
7268 mono_counters_register ("Inflated classes size",
7269 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
7270 mono_counters_register ("MonoClass size",
7271 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
7272 mono_counters_register ("MonoClassExt size",
7273 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
7277 * mono_classes_cleanup:
7279 * Free the resources used by this module.
7282 mono_classes_cleanup (void)
7284 if (global_interface_bitset)
7285 mono_bitset_free (global_interface_bitset);
7289 * mono_class_get_exception_for_failure:
7290 * @klass: class in which the failure was detected
7292 * Return a constructed MonoException than the caller can then throw
7293 * using mono_raise_exception - or NULL if no failure is present (or
7294 * doesn't result in an exception).
7297 mono_class_get_exception_for_failure (MonoClass *klass)
7299 gpointer exception_data = mono_class_get_exception_data (klass);
7301 switch (klass->exception_type) {
7302 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
7303 MonoDomain *domain = mono_domain_get ();
7304 MonoSecurityManager* secman = mono_security_manager_get_methods ();
7305 MonoMethod *method = exception_data;
7306 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
7307 MonoObject *exc = NULL;
7311 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
7312 args [2] = mono_type_get_object (domain, &klass->byval_arg);
7313 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
7315 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
7316 return (MonoException*) exc;
7318 case MONO_EXCEPTION_TYPE_LOAD: {
7321 char *str = mono_type_get_full_name (klass);
7322 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
7323 name = mono_string_new (mono_domain_get (), str);
7325 ex = mono_get_exception_type_load (name, astr);
7329 case MONO_EXCEPTION_MISSING_METHOD: {
7330 char *class_name = exception_data;
7331 char *assembly_name = class_name + strlen (class_name) + 1;
7333 return mono_get_exception_missing_method (class_name, assembly_name);
7335 case MONO_EXCEPTION_MISSING_FIELD: {
7336 char *class_name = exception_data;
7337 char *member_name = class_name + strlen (class_name) + 1;
7339 return mono_get_exception_missing_field (class_name, member_name);
7341 case MONO_EXCEPTION_FILE_NOT_FOUND: {
7342 char *msg_format = exception_data;
7343 char *assembly_name = msg_format + strlen (msg_format) + 1;
7344 char *msg = g_strdup_printf (msg_format, assembly_name);
7347 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
7353 case MONO_EXCEPTION_BAD_IMAGE: {
7354 return mono_get_exception_bad_image_format (exception_data);
7357 MonoLoaderError *error;
7360 error = mono_loader_get_last_error ();
7362 ex = mono_loader_error_prepare_exception (error);
7366 /* TODO - handle other class related failures */
7373 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
7375 outer_klass = mono_class_get_generic_type_definition (outer_klass);
7376 inner_klass = mono_class_get_generic_type_definition (inner_klass);
7378 if (outer_klass == inner_klass)
7380 inner_klass = inner_klass->nested_in;
7381 } while (inner_klass);
7386 mono_class_get_generic_type_definition (MonoClass *klass)
7388 return klass->generic_class ? klass->generic_class->container_class : klass;
7392 * Check if @klass is a subtype of @parent ignoring generic instantiations.
7394 * Generic instantiations are ignored for all super types of @klass.
7396 * Visibility checks ignoring generic instantiations.
7399 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
7402 klass = mono_class_get_generic_type_definition (klass);
7403 parent = mono_class_get_generic_type_definition (parent);
7405 for (i = 0; i < klass->idepth; ++i) {
7406 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
7412 * Subtype can only access parent members with family protection if the site object
7413 * is subclass of Subtype. For example:
7414 * class A { protected int x; }
7416 * void valid_access () {
7420 * void invalid_access () {
7427 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
7429 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
7432 if (context_klass == NULL)
7434 /*if access_klass is not member_klass context_klass must be type compat*/
7435 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
7441 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
7444 if (accessing == accessed)
7446 if (!accessed || !accessing)
7448 mono_assembly_load_friends (accessed);
7449 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
7450 MonoAssemblyName *friend = tmp->data;
7451 /* Be conservative with checks */
7454 if (strcmp (accessing->aname.name, friend->name))
7456 if (friend->public_key_token [0]) {
7457 if (!accessing->aname.public_key_token [0])
7459 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
7468 * If klass is a generic type or if it is derived from a generic type, return the
7469 * MonoClass of the generic definition
7470 * Returns NULL if not found
7473 get_generic_definition_class (MonoClass *klass)
7476 if (klass->generic_class && klass->generic_class->container_class)
7477 return klass->generic_class->container_class;
7478 klass = klass->parent;
7484 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
7487 for (i = 0; i < ginst->type_argc; ++i) {
7488 MonoType *type = ginst->type_argv[i];
7489 switch (type->type) {
7490 case MONO_TYPE_SZARRAY:
7491 if (!can_access_type (access_klass, type->data.klass))
7494 case MONO_TYPE_ARRAY:
7495 if (!can_access_type (access_klass, type->data.array->eklass))
7499 if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
7502 case MONO_TYPE_CLASS:
7503 case MONO_TYPE_VALUETYPE:
7504 case MONO_TYPE_GENERICINST:
7505 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
7513 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
7517 if (access_klass->element_class && !access_klass->enumtype)
7518 access_klass = access_klass->element_class;
7520 if (member_klass->element_class && !member_klass->enumtype)
7521 member_klass = member_klass->element_class;
7523 access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
7525 if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
7528 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
7531 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
7534 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
7537 switch (access_level) {
7538 case TYPE_ATTRIBUTE_NOT_PUBLIC:
7539 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7541 case TYPE_ATTRIBUTE_PUBLIC:
7544 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
7547 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
7548 return is_nesting_type (member_klass, access_klass);
7550 case TYPE_ATTRIBUTE_NESTED_FAMILY:
7551 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7553 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
7554 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7556 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
7557 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
7558 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7560 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
7561 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
7562 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7567 /* FIXME: check visibility of type, too */
7569 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
7571 MonoClass *member_generic_def;
7572 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
7573 access_klass->generic_container) &&
7574 (member_generic_def = get_generic_definition_class (member_klass))) {
7575 MonoClass *access_container;
7577 if (access_klass->generic_container)
7578 access_container = access_klass;
7580 access_container = access_klass->generic_class->container_class;
7582 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
7586 /* Partition I 8.5.3.2 */
7587 /* the access level values are the same for fields and methods */
7588 switch (access_level) {
7589 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
7590 /* same compilation unit */
7591 return access_klass->image == member_klass->image;
7592 case FIELD_ATTRIBUTE_PRIVATE:
7593 return access_klass == member_klass;
7594 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
7595 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
7596 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
7599 case FIELD_ATTRIBUTE_ASSEMBLY:
7600 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7601 case FIELD_ATTRIBUTE_FAMILY:
7602 if (is_valid_family_access (access_klass, member_klass, context_klass))
7605 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
7606 if (is_valid_family_access (access_klass, member_klass, context_klass))
7608 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7609 case FIELD_ATTRIBUTE_PUBLIC:
7616 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
7618 /* FIXME: check all overlapping fields */
7619 int can = can_access_member (method->klass, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7621 MonoClass *nested = method->klass->nested_in;
7623 can = can_access_member (nested, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7626 nested = nested->nested_in;
7633 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
7635 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7637 MonoClass *nested = method->klass->nested_in;
7639 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7642 nested = nested->nested_in;
7647 * with generics calls to explicit interface implementations can be expressed
7648 * directly: the method is private, but we must allow it. This may be opening
7649 * a hole or the generics code should handle this differently.
7650 * Maybe just ensure the interface type is public.
7652 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
7658 * mono_method_can_access_method_full:
7659 * @method: The caller method
7660 * @called: The called method
7661 * @context_klass: The static type on stack of the owner @called object used
7663 * This function must be used with instance calls, as they have more strict family accessibility.
7664 * It can be used with static methods, but context_klass should be NULL.
7666 * Returns: TRUE if caller have proper visibility and acessibility to @called
7669 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
7671 MonoClass *access_class = method->klass;
7672 MonoClass *member_class = called->klass;
7673 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7675 MonoClass *nested = access_class->nested_in;
7677 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7680 nested = nested->nested_in;
7687 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
7690 if (called->is_inflated) {
7691 MonoMethodInflated * infl = (MonoMethodInflated*)called;
7692 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
7701 * mono_method_can_access_method_with_context:
7702 * @method: The caller method
7703 * @field: The accessed field
7704 * @context_klass: The static type on stack of the owner @field object used
7706 * This function must be used with instance fields, as they have more strict family accessibility.
7707 * It can be used with static fields, but context_klass should be NULL.
7709 * Returns: TRUE if caller have proper visibility and acessibility to @field
7712 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
7714 MonoClass *access_class = method->klass;
7715 MonoClass *member_class = field->parent;
7716 /* FIXME: check all overlapping fields */
7717 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7719 MonoClass *nested = access_class->nested_in;
7721 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7724 nested = nested->nested_in;
7731 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
7737 * mono_type_is_valid_enum_basetype:
7738 * @type: The MonoType to check
7740 * Returns: TRUE if the type can be used as the basetype of an enum
7742 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
7743 switch (type->type) {
7746 case MONO_TYPE_BOOLEAN:
7749 case MONO_TYPE_CHAR:
7762 * mono_class_is_valid_enum:
7763 * @klass: An enum class to be validated
7765 * This method verify the required properties an enum should have.
7767 * Returns: TRUE if the informed enum class is valid
7769 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
7770 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
7771 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
7773 gboolean mono_class_is_valid_enum (MonoClass *klass) {
7774 MonoClassField * field;
7775 gpointer iter = NULL;
7776 gboolean found_base_field = FALSE;
7778 g_assert (klass->enumtype);
7779 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
7780 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
7784 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
7787 while ((field = mono_class_get_fields (klass, &iter))) {
7788 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
7789 if (found_base_field)
7791 found_base_field = TRUE;
7792 if (!mono_type_is_valid_enum_basetype (field->type))
7797 if (!found_base_field)
7800 if (klass->method.count > 0)
7807 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
7809 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
7812 static gboolean gshared_supported;
7815 mono_set_generic_sharing_supported (gboolean supported)
7817 gshared_supported = supported;
7821 * mono_class_generic_sharing_enabled:
7824 * Returns whether generic sharing is enabled for class.
7826 * This is a stop-gap measure to slowly introduce generic sharing
7827 * until we have all the issues sorted out, at which time this
7828 * function will disappear and generic sharing will always be enabled.
7831 mono_class_generic_sharing_enabled (MonoClass *class)
7833 static int generic_sharing = MONO_GENERIC_SHARING_NONE;
7834 static gboolean inited = FALSE;
7839 if (gshared_supported)
7840 generic_sharing = MONO_GENERIC_SHARING_ALL;
7842 generic_sharing = MONO_GENERIC_SHARING_NONE;
7844 if ((option = g_getenv ("MONO_GENERIC_SHARING"))) {
7845 if (strcmp (option, "corlib") == 0)
7846 generic_sharing = MONO_GENERIC_SHARING_CORLIB;
7847 else if (strcmp (option, "collections") == 0)
7848 generic_sharing = MONO_GENERIC_SHARING_COLLECTIONS;
7849 else if (strcmp (option, "all") == 0)
7850 generic_sharing = MONO_GENERIC_SHARING_ALL;
7851 else if (strcmp (option, "none") == 0)
7852 generic_sharing = MONO_GENERIC_SHARING_NONE;
7854 g_warning ("Unknown generic sharing option `%s'.", option);
7857 if (!gshared_supported)
7858 generic_sharing = MONO_GENERIC_SHARING_NONE;
7863 switch (generic_sharing) {
7864 case MONO_GENERIC_SHARING_NONE:
7866 case MONO_GENERIC_SHARING_ALL:
7868 case MONO_GENERIC_SHARING_CORLIB :
7869 return class->image == mono_defaults.corlib;
7870 case MONO_GENERIC_SHARING_COLLECTIONS:
7871 if (class->image != mono_defaults.corlib)
7873 while (class->nested_in)
7874 class = class->nested_in;
7875 return g_str_has_prefix (class->name_space, "System.Collections.Generic");
7877 g_assert_not_reached ();
7882 * mono_class_setup_interface_id:
7884 * Initializes MonoClass::interface_id if required.
7886 * LOCKING: Acquires the loader lock.
7889 mono_class_setup_interface_id (MonoClass *class)
7891 mono_loader_lock ();
7892 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
7893 class->interface_id = mono_get_unique_iid (class);
7894 mono_loader_unlock ();
7898 * mono_class_alloc_ext:
7900 * Allocate klass->ext if not already done.
7901 * LOCKING: Assumes the loader lock is held.
7904 mono_class_alloc_ext (MonoClass *klass)
7907 if (klass->generic_class) {
7908 klass->ext = g_new0 (MonoClassExt, 1);
7910 klass->ext = mono_image_alloc0 (klass->image, sizeof (MonoClassExt));
7912 class_ext_size += sizeof (MonoClassExt);
7917 * mono_class_setup_interfaces:
7919 * Initialize class->interfaces/interfaces_count.
7920 * LOCKING: Acquires the loader lock.
7923 mono_class_setup_interfaces (MonoClass *klass)
7927 if (klass->interfaces_inited)
7930 mono_loader_lock ();
7932 if (klass->interfaces_inited) {
7933 mono_loader_unlock ();
7937 if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
7940 /* generic IList, ICollection, IEnumerable */
7941 klass->interface_count = 1;
7942 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
7944 args [0] = &klass->element_class->byval_arg;
7945 klass->interfaces [0] = mono_class_bind_generic_parameters (
7946 mono_defaults.generic_ilist_class, 1, args, FALSE);
7947 } else if (klass->generic_class) {
7948 MonoClass *gklass = klass->generic_class->container_class;
7950 klass->interface_count = gklass->interface_count;
7951 klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
7952 for (i = 0; i < klass->interface_count; i++)
7953 klass->interfaces [i] = mono_class_inflate_generic_class (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class));
7956 mono_memory_barrier ();
7958 klass->interfaces_inited = TRUE;
7960 mono_loader_unlock ();