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)
20 #include <mono/io-layer/atomic.h>
22 #include <mono/metadata/image.h>
23 #include <mono/metadata/assembly.h>
24 #include <mono/metadata/metadata.h>
25 #include <mono/metadata/metadata-internals.h>
26 #include <mono/metadata/profiler-private.h>
27 #include <mono/metadata/tabledefs.h>
28 #include <mono/metadata/tokentype.h>
29 #include <mono/metadata/class-internals.h>
30 #include <mono/metadata/object.h>
31 #include <mono/metadata/appdomain.h>
32 #include <mono/metadata/mono-endian.h>
33 #include <mono/metadata/debug-helpers.h>
34 #include <mono/metadata/reflection.h>
35 #include <mono/metadata/exception.h>
36 #include <mono/metadata/security-manager.h>
37 #include <mono/metadata/security-core-clr.h>
38 #include <mono/metadata/attrdefs.h>
39 #include <mono/metadata/gc-internal.h>
40 #include <mono/metadata/verify-internals.h>
41 #include <mono/metadata/mono-debug.h>
42 #include <mono/utils/mono-counters.h>
46 gboolean mono_print_vtable = FALSE;
49 * Controls whenever mono_class_init () constructs a generic vtable. This is TRUE by
50 * default to avoid breaking embedding apps, but set to FALSE by the runtime executable
53 gboolean mono_setup_vtable_in_class_init = TRUE;
56 guint32 inflated_classes_size, inflated_methods_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) {
125 /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
126 for (tmp = enclosing->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_mempool_dup (MonoMemPool *mp, void *data, guint size)
176 void *res = mono_mempool_alloc (mp, size);
177 memcpy (res, data, size);
181 /* Copy everything mono_metadata_free_array free. */
183 mono_dup_array_type (MonoMemPool *mp, MonoArrayType *a)
187 a = mono_mempool_dup (mp, a, sizeof (MonoArrayType));
189 a->sizes = mono_mempool_dup (mp, a->sizes, a->numsizes * sizeof (int));
191 a->lobounds = mono_mempool_dup (mp, a->lobounds, a->numlobounds * sizeof (int));
192 mono_loader_unlock ();
194 a = g_memdup (a, sizeof (MonoArrayType));
196 a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
198 a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
203 /* Copy everything mono_metadata_free_method_signature free. */
205 mono_metadata_signature_deep_dup (MonoMemPool *mp, MonoMethodSignature *sig)
209 sig = mono_metadata_signature_dup_full (mp, sig);
211 sig->ret = mono_metadata_type_dup (mp, sig->ret);
212 for (i = 0; i < sig->param_count; ++i)
213 sig->params [i] = mono_metadata_type_dup (mp, sig->params [i]);
219 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
221 MonoAssembly *ta = klass->image->assembly;
223 g_string_append_printf (
224 str, ", %s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
226 ta->aname.major, ta->aname.minor, ta->aname.build, ta->aname.revision,
227 ta->aname.culture && *ta->aname.culture? ta->aname.culture: "neutral",
228 ta->aname.public_key_token [0] ? (char *)ta->aname.public_key_token : "null",
229 (ta->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
233 mono_type_name_check_byref (MonoType *type, GString *str)
236 g_string_append_c (str, '&');
240 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
241 MonoTypeNameFormat format)
245 switch (type->type) {
246 case MONO_TYPE_ARRAY: {
247 int i, rank = type->data.array->rank;
248 MonoTypeNameFormat nested_format;
250 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
251 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
253 mono_type_get_name_recurse (
254 &type->data.array->eklass->byval_arg, str, FALSE, nested_format);
255 g_string_append_c (str, '[');
257 g_string_append_c (str, '*');
258 for (i = 1; i < rank; i++)
259 g_string_append_c (str, ',');
260 g_string_append_c (str, ']');
262 mono_type_name_check_byref (type, str);
264 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
265 _mono_type_get_assembly_name (type->data.array->eklass, str);
268 case MONO_TYPE_SZARRAY: {
269 MonoTypeNameFormat nested_format;
271 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
272 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
274 mono_type_get_name_recurse (
275 &type->data.klass->byval_arg, str, FALSE, nested_format);
276 g_string_append (str, "[]");
278 mono_type_name_check_byref (type, str);
280 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
281 _mono_type_get_assembly_name (type->data.klass, str);
284 case MONO_TYPE_PTR: {
285 MonoTypeNameFormat nested_format;
287 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
288 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
290 mono_type_get_name_recurse (
291 type->data.type, str, FALSE, nested_format);
292 g_string_append_c (str, '*');
294 mono_type_name_check_byref (type, str);
296 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
297 _mono_type_get_assembly_name (mono_class_from_mono_type (type->data.type), str);
302 g_assert (type->data.generic_param->name);
303 g_string_append (str, 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, klass->generic_container->type_params [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 (MonoMemPool *mempool, MonoType *type, MonoGenericContext *context)
493 switch (type->type) {
494 case MONO_TYPE_MVAR: {
496 int num = type->data.generic_param->num;
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", num, type->data.generic_param->name, inst->type_argc);
504 * Note that the VAR/MVAR cases are different from the rest. The other cases duplicate @type,
505 * while the VAR/MVAR duplicates a type from the context. So, we need to ensure that the
506 * ->byref and ->attrs from @type are propagated to the returned type.
508 nt = mono_metadata_type_dup (mempool, inst->type_argv [num]);
509 nt->byref = type->byref;
510 nt->attrs = type->attrs;
513 case MONO_TYPE_VAR: {
515 int num = type->data.generic_param->num;
516 MonoGenericInst *inst = context->class_inst;
519 if (num >= inst->type_argc)
520 g_error ("VAR %d (%s) cannot be expanded in this context with %d instantiations", num, type->data.generic_param->name, inst->type_argc);
521 nt = mono_metadata_type_dup (mempool, inst->type_argv [num]);
522 nt->byref = type->byref;
523 nt->attrs = type->attrs;
526 case MONO_TYPE_SZARRAY: {
527 MonoClass *eclass = type->data.klass;
528 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context);
531 nt = mono_metadata_type_dup (mempool, type);
532 nt->data.klass = mono_class_from_mono_type (inflated);
533 mono_metadata_free_type (inflated);
536 case MONO_TYPE_ARRAY: {
537 MonoClass *eclass = type->data.array->eklass;
538 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context);
541 nt = mono_metadata_type_dup (mempool, type);
542 nt->data.array = g_memdup (nt->data.array, sizeof (MonoArrayType));
543 nt->data.array->eklass = mono_class_from_mono_type (inflated);
544 mono_metadata_free_type (inflated);
547 case MONO_TYPE_GENERICINST: {
548 MonoGenericClass *gclass = type->data.generic_class;
549 MonoGenericInst *inst;
551 if (!gclass->context.class_inst->is_open)
554 inst = mono_metadata_inflate_generic_inst (gclass->context.class_inst, context);
555 if (inst != gclass->context.class_inst)
556 gclass = mono_metadata_lookup_generic_class (gclass->container_class, inst, gclass->is_dynamic);
558 if (gclass == type->data.generic_class)
561 nt = mono_metadata_type_dup (mempool, type);
562 nt->data.generic_class = gclass;
565 case MONO_TYPE_CLASS:
566 case MONO_TYPE_VALUETYPE: {
567 MonoClass *klass = type->data.klass;
568 MonoGenericContainer *container = klass->generic_container;
569 MonoGenericInst *inst;
570 MonoGenericClass *gclass = NULL;
576 /* We can't use context->class_inst directly, since it can have more elements */
577 inst = mono_metadata_inflate_generic_inst (container->context.class_inst, context);
578 if (inst == container->context.class_inst)
581 gclass = mono_metadata_lookup_generic_class (klass, inst, klass->image->dynamic);
583 nt = mono_metadata_type_dup (mempool, type);
584 nt->type = MONO_TYPE_GENERICINST;
585 nt->data.generic_class = gclass;
595 mono_generic_class_get_context (MonoGenericClass *gclass)
597 return &gclass->context;
601 mono_class_get_context (MonoClass *class)
603 return class->generic_class ? mono_generic_class_get_context (class->generic_class) : NULL;
607 * mono_class_inflate_generic_type_with_mempool:
608 * @mempool: a mempool
610 * @context: a generics context
612 * The same as mono_class_inflate_generic_type, but allocates the MonoType
613 * from mempool if it is non-NULL. If it is NULL, the MonoType is
614 * allocated on the heap and is owned by the caller.
615 * The returned type can potentially be the same as TYPE, so it should not be
616 * modified by the caller, and it should be freed using mono_metadata_free_type ().
619 mono_class_inflate_generic_type_with_mempool (MonoMemPool *mempool, MonoType *type, MonoGenericContext *context)
621 MonoType *inflated = NULL;
624 inflated = inflate_generic_type (mempool, type, context);
627 MonoType *shared = mono_metadata_get_shared_type (type);
632 return mono_metadata_type_dup (mempool, type);
636 mono_stats.inflated_type_count++;
641 * mono_class_inflate_generic_type:
643 * @context: a generics context
645 * If @type is a generic type and @context is not NULL, instantiate it using the
646 * generics context @context.
648 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
649 * on the heap and is owned by the caller.
652 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
654 return mono_class_inflate_generic_type_with_mempool (NULL, type, context);
658 * mono_class_inflate_generic_type_with_mempool_no_copy:
660 * Same as inflate_generic_type_with_mempool, but return TYPE if no inflation
664 mono_class_inflate_generic_type_with_mempool_no_copy (MonoMemPool *mempool, MonoType *type, MonoGenericContext *context)
666 MonoType *inflated = NULL;
669 inflated = inflate_generic_type (mempool, type, context);
674 mono_stats.inflated_type_count++;
679 * mono_class_inflate_generic_class:
681 * Inflate the class GKLASS with CONTEXT.
684 mono_class_inflate_generic_class (MonoClass *gklass, MonoGenericContext *context)
689 inflated = mono_class_inflate_generic_type (&gklass->byval_arg, context);
691 res = mono_class_from_mono_type (inflated);
692 mono_metadata_free_type (inflated);
697 static MonoGenericContext
698 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with)
700 MonoGenericInst *class_inst = NULL;
701 MonoGenericInst *method_inst = NULL;
702 MonoGenericContext res;
704 if (context->class_inst)
705 class_inst = mono_metadata_inflate_generic_inst (context->class_inst, inflate_with);
707 if (context->method_inst)
708 method_inst = mono_metadata_inflate_generic_inst (context->method_inst, inflate_with);
710 res.class_inst = class_inst;
711 res.method_inst = method_inst;
717 * mono_class_inflate_generic_method:
718 * @method: a generic method
719 * @context: a generics context
721 * Instantiate the generic method @method using the generics context @context.
723 * Returns: the new instantiated method
726 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
728 return mono_class_inflate_generic_method_full (method, NULL, context);
732 * mono_class_inflate_generic_method:
734 * Instantiate method @method with the generic context @context.
735 * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
736 * Use mono_method_signature () and mono_method_get_header () to get the correct values.
739 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
742 MonoMethodInflated *iresult, *cached;
743 MonoMethodSignature *sig;
744 MonoGenericContext tmp_context;
745 gboolean is_mb_open = FALSE;
747 /* The `method' has already been instantiated before => we need to peel out the instantiation and create a new context */
748 while (method->is_inflated) {
749 MonoGenericContext *method_context = mono_method_get_context (method);
750 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
752 tmp_context = inflate_generic_context (method_context, context);
753 context = &tmp_context;
755 if (mono_metadata_generic_context_equal (method_context, context))
758 method = imethod->declaring;
761 if (!method->is_generic && !method->klass->generic_container)
765 * The reason for this hack is to fix the behavior of inflating generic methods that come from a MethodBuilder.
766 * What happens is that instantiating a generic MethodBuilder with its own arguments should create a diferent object.
767 * This is opposite to the way non-SRE MethodInfos behave.
769 * This happens, for example, when we want to emit a recursive generic method. Given the following C# code:
771 * void Example<T> () {
775 * In Example, the method token must be encoded as: "void Example<!!0>()"
777 * The reference to the first generic argument, "!!0", must be explicit otherwise it won't be inflated
778 * properly. To get that we need to inflate the MethodBuilder with its own arguments.
780 * On the other hand, inflating a non-SRE generic method with its own arguments should
781 * return itself. For example:
783 * MethodInfo m = ... //m is a generic method definition
784 * MethodInfo res = m.MakeGenericMethod (m.GetGenericArguments ());
787 * To allow such scenarios we must allow inflation of MethodBuilder to happen in a diferent way than
788 * what happens with regular methods.
790 * There is one last touch to this madness, once a TypeBuilder is finished, IOW CreateType() is called,
791 * everything should behave like a regular type or method.
794 is_mb_open = method->is_generic &&
795 method->klass->image->dynamic && !method->klass->wastypebuilder && /* that is a MethodBuilder from an unfinished TypeBuilder */
796 context->method_inst == mono_method_get_generic_container (method)->context.method_inst; /* and it's been instantiated with its own arguments. */
798 iresult = g_new0 (MonoMethodInflated, 1);
799 iresult->context = *context;
800 iresult->declaring = method;
801 iresult->is_mb_open = is_mb_open;
803 if (!context->method_inst && method->is_generic)
804 iresult->context.method_inst = mono_method_get_generic_container (method)->context.method_inst;
806 if (!context->class_inst) {
807 g_assert (!iresult->declaring->klass->generic_class);
808 if (iresult->declaring->klass->generic_container)
809 iresult->context.class_inst = iresult->declaring->klass->generic_container->context.class_inst;
810 else if (iresult->declaring->klass->generic_class)
811 iresult->context.class_inst = iresult->declaring->klass->generic_class->context.class_inst;
815 cached = mono_method_inflated_lookup (iresult, FALSE);
817 mono_loader_unlock ();
819 return (MonoMethod*)cached;
822 mono_stats.inflated_method_count++;
824 inflated_methods_size += sizeof (MonoMethodInflated);
826 sig = mono_method_signature (method);
828 memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
830 memcpy (&iresult->method.normal, method, sizeof (MonoMethodNormal));
831 iresult->method.normal.header = NULL;
834 result = (MonoMethod *) iresult;
835 result->is_inflated = TRUE;
836 result->is_generic = FALSE;
837 result->signature = NULL;
839 if (!context->method_inst) {
840 /* Set the generic_container of the result to the generic_container of method */
841 MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
843 if (generic_container) {
844 result->is_generic = 1;
845 mono_method_set_generic_container (result, generic_container);
849 if (!klass_hint || !klass_hint->generic_class ||
850 klass_hint->generic_class->container_class != method->klass ||
851 klass_hint->generic_class->context.class_inst != context->class_inst)
854 if (method->klass->generic_container)
855 result->klass = klass_hint;
857 if (!result->klass) {
858 MonoType *inflated = inflate_generic_type (NULL, &method->klass->byval_arg, context);
859 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
861 mono_metadata_free_type (inflated);
864 mono_method_inflated_lookup (iresult, TRUE);
865 mono_loader_unlock ();
870 * mono_get_inflated_method:
872 * Obsolete. We keep it around since it's mentioned in the public API.
875 mono_get_inflated_method (MonoMethod *method)
881 mono_method_get_context (MonoMethod *method)
883 MonoMethodInflated *imethod;
884 if (!method->is_inflated)
886 imethod = (MonoMethodInflated *) method;
887 return &imethod->context;
891 * mono_method_get_generic_container:
893 * Returns the generic container of METHOD, which should be a generic method definition.
894 * Returns NULL if METHOD is not a generic method definition.
895 * LOCKING: Acquires the loader lock.
897 MonoGenericContainer*
898 mono_method_get_generic_container (MonoMethod *method)
900 MonoGenericContainer *container;
902 if (!method->is_generic)
906 container = mono_property_hash_lookup (method->klass->image->property_hash, method, MONO_METHOD_PROP_GENERIC_CONTAINER);
907 mono_loader_unlock ();
908 g_assert (container);
914 * mono_method_set_generic_container:
916 * Sets the generic container of METHOD to CONTAINER.
917 * LOCKING: Acquires the loader lock.
920 mono_method_set_generic_container (MonoMethod *method, MonoGenericContainer* container)
922 g_assert (method->is_generic);
925 mono_property_hash_insert (method->klass->image->property_hash, method, MONO_METHOD_PROP_GENERIC_CONTAINER, container);
926 mono_loader_unlock ();
930 * mono_class_find_enum_basetype:
931 * @class: The enum class
933 * Determine the basetype of an enum by iterating through its fields. We do this
934 * in a separate function since it is cheaper than calling mono_class_setup_fields.
937 mono_class_find_enum_basetype (MonoClass *class)
939 MonoImage *m = class->image;
940 const int top = class->field.count;
943 g_assert (class->enumtype);
946 * Fetch all the field information.
948 for (i = 0; i < top; i++){
950 guint32 cols [MONO_FIELD_SIZE];
951 int idx = class->field.first + i;
952 MonoGenericContainer *container = NULL;
955 /* class->field.first and idx points into the fieldptr table */
956 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
957 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
958 mono_metadata_decode_value (sig, &sig);
959 /* FIELD signature == 0x06 */
960 g_assert (*sig == 0x06);
961 if (class->generic_container)
962 container = class->generic_container;
963 else if (class->generic_class) {
964 MonoClass *gklass = class->generic_class->container_class;
966 container = gklass->generic_container;
967 g_assert (container);
969 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
972 if (class->generic_class) {
973 //FIXME do we leak here?
974 ftype = mono_class_inflate_generic_type (ftype, mono_class_get_context (class));
975 ftype->attrs = cols [MONO_FIELD_FLAGS];
978 if (class->enumtype && !(cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC))
986 * mono_class_setup_fields:
987 * @class: The class to initialize
989 * Initializes the class->fields.
990 * LOCKING: Assumes the loader lock is held.
993 mono_class_setup_fields (MonoClass *class)
995 MonoImage *m = class->image;
996 int top = class->field.count;
997 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
998 int i, blittable = TRUE;
999 guint32 real_size = 0;
1000 guint32 packing_size = 0;
1001 gboolean explicit_size;
1002 MonoClassField *field;
1003 MonoGenericContainer *container = NULL;
1004 MonoClass *gklass = NULL;
1006 if (class->size_inited)
1009 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1011 * This happens when a generic instance of an unfinished generic typebuilder
1012 * is used as an element type for creating an array type. We can't initialize
1013 * the fields of this class using the fields of gklass, since gklass is not
1014 * finished yet, fields could be added to it later.
1019 if (class->generic_class) {
1020 MonoClass *gklass = class->generic_class->container_class;
1021 mono_class_setup_fields (gklass);
1022 top = gklass->field.count;
1023 class->field.count = gklass->field.count;
1026 class->instance_size = 0;
1028 class->sizes.class_size = 0;
1030 if (class->parent) {
1031 /* For generic instances, class->parent might not have been initialized */
1032 mono_class_init (class->parent);
1033 if (!class->parent->size_inited)
1034 mono_class_setup_fields (class->parent);
1035 class->instance_size += class->parent->instance_size;
1036 class->min_align = class->parent->min_align;
1037 /* we use |= since it may have been set already */
1038 class->has_references |= class->parent->has_references;
1039 blittable = class->parent->blittable;
1041 class->instance_size = sizeof (MonoObject);
1042 class->min_align = 1;
1045 if (class->simd_type)
1046 class->min_align = 16;
1048 /* Get the real size */
1049 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1051 if (explicit_size) {
1052 g_assert ((packing_size & 0xfffffff0) == 0);
1053 class->packing_size = packing_size;
1054 real_size += class->instance_size;
1058 if (explicit_size && real_size) {
1059 class->instance_size = MAX (real_size, class->instance_size);
1061 class->size_inited = 1;
1062 class->blittable = blittable;
1066 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1069 /* Prevent infinite loops if the class references itself */
1070 class->size_inited = 1;
1072 class->fields = mono_image_alloc0 (class->image, sizeof (MonoClassField) * top);
1074 if (class->generic_container) {
1075 container = class->generic_container;
1076 } else if (class->generic_class) {
1077 gklass = class->generic_class->container_class;
1078 container = gklass->generic_container;
1079 g_assert (container);
1081 mono_class_setup_fields (gklass);
1083 if (gklass->exception_type) {
1084 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1090 * Fetch all the field information.
1092 for (i = 0; i < top; i++){
1093 int idx = class->field.first + i;
1094 field = &class->fields [i];
1096 field->parent = class;
1098 if (class->generic_class) {
1099 MonoClassField *gfield = &gklass->fields [i];
1101 field->name = mono_field_get_name (gfield);
1102 /*This memory must come from the image mempool as we don't have a chance to free it.*/
1103 field->type = mono_class_inflate_generic_type_with_mempool_no_copy (class->image->mempool, gfield->type, mono_class_get_context (class));
1104 g_assert (field->type->attrs == gfield->type->attrs);
1105 if (mono_field_is_deleted (field))
1107 field->offset = gfield->offset;
1110 guint32 cols [MONO_FIELD_SIZE];
1112 /* class->field.first and idx points into the fieldptr table */
1113 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1114 /* The name is needed for fieldrefs */
1115 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
1116 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1117 mono_metadata_decode_value (sig, &sig);
1118 /* FIELD signature == 0x06 */
1119 g_assert (*sig == 0x06);
1120 field->type = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1122 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1125 if (mono_field_is_deleted (field))
1127 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1129 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1130 field->offset = offset;
1131 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1132 g_warning ("%s not initialized correctly (missing field layout info for %s)",
1133 class->name, mono_field_get_name (field));
1137 /* Only do these checks if we still think this type is blittable */
1138 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1139 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1142 MonoClass *field_class = mono_class_from_mono_type (field->type);
1144 mono_class_setup_fields (field_class);
1145 if (!field_class || !field_class->blittable)
1150 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1151 class->enum_basetype = field->type;
1152 class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
1153 blittable = class->element_class->blittable;
1156 /* The def_value of fields is compute lazily during vtable creation */
1159 if (class == mono_defaults.string_class)
1162 class->blittable = blittable;
1164 if (class->enumtype && !mono_class_enum_basetype (class)) {
1165 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
1168 if (explicit_size && real_size) {
1169 class->instance_size = MAX (real_size, class->instance_size);
1172 if (class->exception_type)
1174 mono_class_layout_fields (class);
1178 * mono_class_setup_fields_locking:
1179 * @class: The class to initialize
1181 * Initializes the class->fields array of fields.
1182 * Aquires the loader lock.
1185 mono_class_setup_fields_locking (MonoClass *class)
1187 mono_loader_lock ();
1188 mono_class_setup_fields (class);
1189 mono_loader_unlock ();
1193 * mono_class_has_references:
1195 * Returns whenever @klass->has_references is set, initializing it if needed.
1196 * Aquires the loader lock.
1199 mono_class_has_references (MonoClass *klass)
1201 if (klass->init_pending) {
1202 /* Be conservative */
1205 mono_class_init (klass);
1207 return klass->has_references;
1211 /* useful until we keep track of gc-references in corlib etc. */
1213 #define IS_GC_REFERENCE(t) FALSE
1215 #define IS_GC_REFERENCE(t) ((t)->type == MONO_TYPE_U && class->image == mono_defaults.corlib)
1219 * mono_type_get_basic_type_from_generic:
1222 * Returns a closed type corresponding to the possibly open type
1226 mono_type_get_basic_type_from_generic (MonoType *type)
1228 /* When we do generic sharing we let type variables stand for reference types. */
1229 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1230 return &mono_defaults.object_class->byval_arg;
1235 * mono_class_layout_fields:
1238 * Compute the placement of fields inside an object or struct, according to
1239 * the layout rules and set the following fields in @class:
1240 * - has_references (if the class contains instance references firled or structs that contain references)
1241 * - has_static_refs (same, but for static fields)
1242 * - instance_size (size of the object in memory)
1243 * - class_size (size needed for the static fields)
1244 * - size_inited (flag set when the instance_size is set)
1246 * LOCKING: this is supposed to be called with the loader lock held.
1249 mono_class_layout_fields (MonoClass *class)
1252 const int top = class->field.count;
1253 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1254 guint32 pass, passes, real_size;
1255 gboolean gc_aware_layout = FALSE;
1256 MonoClassField *field;
1259 * When we do generic sharing we need to have layout
1260 * information for open generic classes (either with a generic
1261 * context containing type variables or with a generic
1262 * container), so we don't return in that case anymore.
1266 * Enable GC aware auto layout: in this mode, reference
1267 * fields are grouped together inside objects, increasing collector
1269 * Requires that all classes whose layout is known to native code be annotated
1270 * with [StructLayout (LayoutKind.Sequential)]
1271 * Value types have gc_aware_layout disabled by default, as per
1272 * what the default is for other runtimes.
1274 /* corlib is missing [StructLayout] directives in many places */
1275 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1276 if (class->image != mono_defaults.corlib &&
1277 class->byval_arg.type != MONO_TYPE_VALUETYPE)
1278 gc_aware_layout = TRUE;
1279 /* from System.dll, used in metadata/process.h */
1280 if (strcmp (class->name, "ProcessStartInfo") == 0)
1281 gc_aware_layout = FALSE;
1284 /* Compute klass->has_references */
1286 * Process non-static fields first, since static fields might recursively
1287 * refer to the class itself.
1289 for (i = 0; i < top; i++) {
1292 field = &class->fields [i];
1294 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1295 ftype = mono_type_get_underlying_type (field->type);
1296 ftype = mono_type_get_basic_type_from_generic (ftype);
1297 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1298 class->has_references = TRUE;
1302 for (i = 0; i < top; i++) {
1305 field = &class->fields [i];
1307 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1308 ftype = mono_type_get_underlying_type (field->type);
1309 ftype = mono_type_get_basic_type_from_generic (ftype);
1310 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1311 class->has_static_refs = TRUE;
1315 for (i = 0; i < top; i++) {
1318 field = &class->fields [i];
1320 ftype = mono_type_get_underlying_type (field->type);
1321 ftype = mono_type_get_basic_type_from_generic (ftype);
1322 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1323 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1324 class->has_static_refs = TRUE;
1326 class->has_references = TRUE;
1331 * Compute field layout and total size (not considering static fields)
1335 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1336 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1338 if (gc_aware_layout)
1343 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1347 real_size = class->parent->instance_size;
1349 real_size = sizeof (MonoObject);
1351 for (pass = 0; pass < passes; ++pass) {
1352 for (i = 0; i < top; i++){
1357 field = &class->fields [i];
1359 if (mono_field_is_deleted (field))
1361 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1364 ftype = mono_type_get_underlying_type (field->type);
1365 ftype = mono_type_get_basic_type_from_generic (ftype);
1366 if (gc_aware_layout) {
1367 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1376 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1377 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1378 /* This field is a hack inserted by MCS to empty structures */
1382 size = mono_type_size (field->type, &align);
1384 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1385 align = class->packing_size ? MIN (class->packing_size, align): align;
1386 /* if the field has managed references, we need to force-align it
1389 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1390 align = MAX (align, sizeof (gpointer));
1392 class->min_align = MAX (align, class->min_align);
1393 field->offset = real_size;
1394 field->offset += align - 1;
1395 field->offset &= ~(align - 1);
1396 real_size = field->offset + size;
1399 class->instance_size = MAX (real_size, class->instance_size);
1401 if (class->instance_size & (class->min_align - 1)) {
1402 class->instance_size += class->min_align - 1;
1403 class->instance_size &= ~(class->min_align - 1);
1407 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1409 for (i = 0; i < top; i++) {
1414 field = &class->fields [i];
1417 * There must be info about all the fields in a type if it
1418 * uses explicit layout.
1421 if (mono_field_is_deleted (field))
1423 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1426 size = mono_type_size (field->type, &align);
1427 class->min_align = MAX (align, class->min_align);
1430 * When we get here, field->offset is already set by the
1431 * loader (for either runtime fields or fields loaded from metadata).
1432 * The offset is from the start of the object: this works for both
1433 * classes and valuetypes.
1435 field->offset += sizeof (MonoObject);
1436 ftype = mono_type_get_underlying_type (field->type);
1437 ftype = mono_type_get_basic_type_from_generic (ftype);
1438 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1439 if (field->offset % sizeof (gpointer)) {
1440 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1447 real_size = MAX (real_size, size + field->offset);
1449 class->instance_size = MAX (real_size, class->instance_size);
1453 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1455 * For small structs, set min_align to at least the struct size to improve
1456 * performance, and since the JIT memset/memcpy code assumes this and generates
1457 * unaligned accesses otherwise. See #78990 for a testcase.
1459 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1460 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1463 class->size_inited = 1;
1466 * Compute static field layout and size
1468 for (i = 0; i < top; i++){
1472 field = &class->fields [i];
1474 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1476 if (mono_field_is_deleted (field))
1479 size = mono_type_size (field->type, &align);
1480 field->offset = class->sizes.class_size;
1481 field->offset += align - 1;
1482 field->offset &= ~(align - 1);
1483 class->sizes.class_size = field->offset + size;
1488 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1492 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1493 method->klass = class;
1494 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1495 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1496 method->signature = sig;
1497 method->name = name;
1500 if (name [0] == '.') {
1501 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1503 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1509 * mono_class_setup_methods:
1512 * Initializes the 'methods' array in the klass.
1513 * Calling this method should be avoided if possible since it allocates a lot
1514 * of long-living MonoMethod structures.
1515 * Methods belonging to an interface are assigned a sequential slot starting
1519 mono_class_setup_methods (MonoClass *class)
1522 MonoMethod **methods;
1527 mono_loader_lock ();
1529 if (class->methods) {
1530 mono_loader_unlock ();
1534 if (class->generic_class) {
1535 MonoClass *gklass = class->generic_class->container_class;
1537 mono_class_init (gklass);
1538 mono_class_setup_methods (gklass);
1540 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1541 class->method.count = gklass->method.count;
1542 methods = g_new0 (MonoMethod *, class->method.count + 1);
1544 for (i = 0; i < class->method.count; i++) {
1545 methods [i] = mono_class_inflate_generic_method_full (
1546 gklass->methods [i], class, mono_class_get_context (class));
1548 } else if (class->rank) {
1549 MonoMethod *amethod;
1550 MonoMethodSignature *sig;
1551 int count_generic = 0, first_generic = 0;
1554 class->method.count = 3 + (class->rank > 1? 2: 1);
1556 if (class->interface_count) {
1557 count_generic = generic_array_methods (class);
1558 first_generic = class->method.count;
1559 class->method.count += class->interface_count * count_generic;
1562 methods = mono_image_alloc0 (class->image, sizeof (MonoMethod*) * class->method.count);
1564 sig = mono_metadata_signature_alloc (class->image, class->rank);
1565 sig->ret = &mono_defaults.void_class->byval_arg;
1566 sig->pinvoke = TRUE;
1567 sig->hasthis = TRUE;
1568 for (i = 0; i < class->rank; ++i)
1569 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1571 amethod = create_array_method (class, ".ctor", sig);
1572 methods [method_num++] = amethod;
1573 if (class->rank > 1) {
1574 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1575 sig->ret = &mono_defaults.void_class->byval_arg;
1576 sig->pinvoke = TRUE;
1577 sig->hasthis = TRUE;
1578 for (i = 0; i < class->rank * 2; ++i)
1579 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1581 amethod = create_array_method (class, ".ctor", sig);
1582 methods [method_num++] = amethod;
1584 /* element Get (idx11, [idx2, ...]) */
1585 sig = mono_metadata_signature_alloc (class->image, class->rank);
1586 sig->ret = &class->element_class->byval_arg;
1587 sig->pinvoke = TRUE;
1588 sig->hasthis = TRUE;
1589 for (i = 0; i < class->rank; ++i)
1590 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1591 amethod = create_array_method (class, "Get", sig);
1592 methods [method_num++] = amethod;
1593 /* element& Address (idx11, [idx2, ...]) */
1594 sig = mono_metadata_signature_alloc (class->image, class->rank);
1595 sig->ret = &class->element_class->this_arg;
1596 sig->pinvoke = TRUE;
1597 sig->hasthis = TRUE;
1598 for (i = 0; i < class->rank; ++i)
1599 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1600 amethod = create_array_method (class, "Address", sig);
1601 methods [method_num++] = amethod;
1602 /* void Set (idx11, [idx2, ...], element) */
1603 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1604 sig->ret = &mono_defaults.void_class->byval_arg;
1605 sig->pinvoke = TRUE;
1606 sig->hasthis = TRUE;
1607 for (i = 0; i < class->rank; ++i)
1608 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1609 sig->params [i] = &class->element_class->byval_arg;
1610 amethod = create_array_method (class, "Set", sig);
1611 methods [method_num++] = amethod;
1613 for (i = 0; i < class->interface_count; i++)
1614 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1616 methods = mono_image_alloc (class->image, sizeof (MonoMethod*) * class->method.count);
1617 for (i = 0; i < class->method.count; ++i) {
1618 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1619 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1623 if (MONO_CLASS_IS_INTERFACE (class))
1624 for (i = 0; i < class->method.count; ++i)
1625 methods [i]->slot = i;
1627 /* Needed because of the double-checking locking pattern */
1628 mono_memory_barrier ();
1630 class->methods = methods;
1632 if (mono_debugger_class_loaded_methods_func)
1633 mono_debugger_class_loaded_methods_func (class);
1635 mono_loader_unlock ();
1639 * mono_class_get_method_by_index:
1641 * Returns class->methods [index], initializing class->methods if neccesary.
1643 * LOCKING: Acquires the loader lock.
1646 mono_class_get_method_by_index (MonoClass *class, int index)
1648 /* Avoid calling setup_methods () if possible */
1649 if (class->generic_class && !class->methods) {
1650 MonoClass *gklass = class->generic_class->container_class;
1653 m = mono_class_inflate_generic_method_full (
1654 gklass->methods [index], class, mono_class_get_context (class));
1656 * If setup_methods () is called later for this class, no duplicates are created,
1657 * since inflate_generic_method guarantees that only one instance of a method
1658 * is created for each context.
1661 mono_class_setup_methods (class);
1662 g_assert (m == class->methods [index]);
1666 mono_class_setup_methods (class);
1667 g_assert (index >= 0 && index < class->method.count);
1668 return class->methods [index];
1673 * mono_class_get_inflated_method:
1675 * Given an inflated class CLASS and a method METHOD which should be a method of
1676 * CLASS's generic definition, return the inflated method corresponding to METHOD.
1679 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
1681 MonoClass *gklass = class->generic_class->container_class;
1684 mono_class_setup_methods (gklass);
1685 for (i = 0; i < gklass->method.count; ++i) {
1686 if (gklass->methods [i] == method) {
1688 return class->methods [i];
1690 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
1698 * mono_class_get_vtable_entry:
1700 * Returns class->vtable [offset], computing it if neccesary.
1701 * LOCKING: Acquires the loader lock.
1704 mono_class_get_vtable_entry (MonoClass *class, int offset)
1706 if (class->generic_class) {
1707 MonoClass *gklass = class->generic_class->container_class;
1708 mono_class_setup_vtable (gklass);
1709 if (gklass->vtable [offset]->wrapper_type != MONO_WRAPPER_STATIC_RGCTX_INVOKE)
1710 return mono_class_inflate_generic_method_full (gklass->vtable [offset], class, mono_class_get_context (class));
1713 if (class->rank == 1) {
1715 * szarrays do not overwrite any methods of Array, so we can avoid
1716 * initializing their vtables in some cases.
1718 mono_class_setup_vtable (class->parent);
1719 if (offset < class->parent->vtable_size)
1720 return class->parent->vtable [offset];
1723 mono_class_setup_vtable (class);
1724 return class->vtable [offset];
1728 mono_class_setup_properties (MonoClass *class)
1730 guint startm, endm, i, j;
1731 guint32 cols [MONO_PROPERTY_SIZE];
1732 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1733 MonoProperty *properties;
1736 if (class->properties)
1739 mono_loader_lock ();
1741 if (class->properties) {
1742 mono_loader_unlock ();
1746 if (class->generic_class) {
1747 MonoClass *gklass = class->generic_class->container_class;
1749 mono_class_init (gklass);
1750 mono_class_setup_properties (gklass);
1752 class->property = gklass->property;
1754 properties = g_new0 (MonoProperty, class->property.count + 1);
1756 for (i = 0; i < class->property.count; i++) {
1757 MonoProperty *prop = &properties [i];
1759 *prop = gklass->properties [i];
1762 prop->get = mono_class_inflate_generic_method_full (
1763 prop->get, class, mono_class_get_context (class));
1765 prop->set = mono_class_inflate_generic_method_full (
1766 prop->set, class, mono_class_get_context (class));
1768 prop->parent = class;
1771 class->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1772 class->property.count = last - class->property.first;
1774 if (class->property.count)
1775 mono_class_setup_methods (class);
1777 properties = mono_image_alloc0 (class->image, sizeof (MonoProperty) * class->property.count);
1778 for (i = class->property.first; i < last; ++i) {
1779 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
1780 properties [i - class->property.first].parent = class;
1781 properties [i - class->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
1782 properties [i - class->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
1784 startm = mono_metadata_methods_from_property (class->image, i, &endm);
1785 for (j = startm; j < endm; ++j) {
1788 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1790 if (class->image->uncompressed_metadata)
1791 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1792 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1794 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1796 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1797 case METHOD_SEMANTIC_SETTER:
1798 properties [i - class->property.first].set = method;
1800 case METHOD_SEMANTIC_GETTER:
1801 properties [i - class->property.first].get = method;
1809 /*Flush any pending writes as we do double checked locking on class->properties */
1810 mono_memory_barrier ();
1812 /* Leave this assignment as the last op in the function */
1813 class->properties = properties;
1815 mono_loader_unlock ();
1819 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
1821 MonoMethod **om, **retval;
1824 for (om = methods, count = 0; *om; ++om, ++count)
1827 retval = g_new0 (MonoMethod*, count + 1);
1829 for (om = methods, count = 0; *om; ++om, ++count)
1830 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
1836 mono_class_setup_events (MonoClass *class)
1838 guint startm, endm, i, j;
1839 guint32 cols [MONO_EVENT_SIZE];
1840 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1847 mono_loader_lock ();
1849 if (class->events) {
1850 mono_loader_unlock ();
1854 if (class->generic_class) {
1855 MonoClass *gklass = class->generic_class->container_class;
1856 MonoGenericContext *context;
1858 mono_class_setup_events (gklass);
1859 class->event = gklass->event;
1861 class->events = g_new0 (MonoEvent, class->event.count);
1863 if (class->event.count)
1864 context = mono_class_get_context (class);
1866 for (i = 0; i < class->event.count; i++) {
1867 MonoEvent *event = &class->events [i];
1868 MonoEvent *gevent = &gklass->events [i];
1870 event->parent = class;
1871 event->name = gevent->name;
1872 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
1873 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
1874 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
1875 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
1876 event->attrs = gevent->attrs;
1879 mono_loader_unlock ();
1883 class->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1884 class->event.count = last - class->event.first;
1886 if (class->event.count)
1887 mono_class_setup_methods (class);
1889 events = mono_image_alloc0 (class->image, sizeof (MonoEvent) * class->event.count);
1890 for (i = class->event.first; i < last; ++i) {
1891 MonoEvent *event = &events [i - class->event.first];
1893 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
1894 event->parent = class;
1895 event->attrs = cols [MONO_EVENT_FLAGS];
1896 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
1898 startm = mono_metadata_methods_from_event (class->image, i, &endm);
1899 for (j = startm; j < endm; ++j) {
1902 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1904 if (class->image->uncompressed_metadata)
1905 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1906 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1908 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1910 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1911 case METHOD_SEMANTIC_ADD_ON:
1912 event->add = method;
1914 case METHOD_SEMANTIC_REMOVE_ON:
1915 event->remove = method;
1917 case METHOD_SEMANTIC_FIRE:
1918 event->raise = method;
1920 case METHOD_SEMANTIC_OTHER: {
1923 if (event->other == NULL) {
1924 event->other = g_new0 (MonoMethod*, 2);
1926 while (event->other [n])
1928 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
1930 event->other [n] = method;
1931 /* NULL terminated */
1932 event->other [n + 1] = NULL;
1940 /*Flush any pending writes as we do double checked locking on class->properties */
1941 mono_memory_barrier ();
1943 /* Leave this assignment as the last op in the function */
1944 class->events = events;
1946 mono_loader_unlock ();
1950 * Global pool of interface IDs, represented as a bitset.
1951 * LOCKING: this is supposed to be accessed with the loader lock held.
1953 static MonoBitSet *global_interface_bitset = NULL;
1956 * mono_unload_interface_ids:
1957 * @bitset: bit set of interface IDs
1959 * When an image is unloaded, the interface IDs associated with
1960 * the image are put back in the global pool of IDs so the numbers
1964 mono_unload_interface_ids (MonoBitSet *bitset)
1966 mono_loader_lock ();
1967 mono_bitset_sub (global_interface_bitset, bitset);
1968 mono_loader_unlock ();
1972 * mono_get_unique_iid:
1975 * Assign a unique integer ID to the interface represented by @class.
1976 * The ID will positive and as small as possible.
1977 * LOCKING: this is supposed to be called with the loader lock held.
1978 * Returns: the new ID.
1981 mono_get_unique_iid (MonoClass *class)
1985 g_assert (MONO_CLASS_IS_INTERFACE (class));
1987 if (!global_interface_bitset) {
1988 global_interface_bitset = mono_bitset_new (128, 0);
1991 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
1993 int old_size = mono_bitset_size (global_interface_bitset);
1994 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
1995 mono_bitset_free (global_interface_bitset);
1996 global_interface_bitset = new_set;
1999 mono_bitset_set (global_interface_bitset, iid);
2000 /* set the bit also in the per-image set */
2001 if (class->image->interface_bitset) {
2002 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2003 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2004 mono_bitset_free (class->image->interface_bitset);
2005 class->image->interface_bitset = new_set;
2008 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2010 mono_bitset_set (class->image->interface_bitset, iid);
2012 if (mono_print_vtable) {
2014 char *type_name = mono_type_full_name (&class->byval_arg);
2015 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2016 generic_id = class->generic_class->context.class_inst->id;
2017 g_assert (generic_id != 0);
2021 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2025 g_assert (iid <= 65535);
2030 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
2035 for (i = 0; i < klass->interface_count; i++) {
2036 ic = klass->interfaces [i];
2039 *res = g_ptr_array_new ();
2040 g_ptr_array_add (*res, ic);
2041 mono_class_init (ic);
2043 collect_implemented_interfaces_aux (ic, res);
2048 mono_class_get_implemented_interfaces (MonoClass *klass)
2050 GPtrArray *res = NULL;
2052 collect_implemented_interfaces_aux (klass, &res);
2057 compare_interface_ids (const void *p_key, const void *p_element) {
2058 const MonoClass *key = p_key;
2059 const MonoClass *element = *(MonoClass**) p_element;
2061 return (key->interface_id - element->interface_id);
2065 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2066 MonoClass **result = bsearch (
2068 klass->interfaces_packed,
2069 klass->interface_offsets_count,
2070 sizeof (MonoClass *),
2071 compare_interface_ids);
2073 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2080 print_implemented_interfaces (MonoClass *klass) {
2081 GPtrArray *ifaces = NULL;
2083 int ancestor_level = 0;
2085 printf ("Packed interface table for class %s has size %d\n", klass->name, klass->interface_offsets_count);
2086 for (i = 0; i < klass->interface_offsets_count; i++)
2087 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2088 klass->interfaces_packed [i]->interface_id,
2089 klass->interface_offsets_packed [i],
2090 klass->interfaces_packed [i]->method.count,
2091 klass->interfaces_packed [i]->name_space,
2092 klass->interfaces_packed [i]->name );
2093 printf ("Interface flags: ");
2094 for (i = 0; i <= klass->max_interface_id; i++)
2095 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2096 printf ("(%d,T)", i);
2098 printf ("(%d,F)", i);
2100 printf ("Dump interface flags:");
2101 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2102 printf (" %02X", klass->interface_bitmap [i]);
2104 while (klass != NULL) {
2105 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2106 ifaces = mono_class_get_implemented_interfaces (klass);
2108 for (i = 0; i < ifaces->len; i++) {
2109 MonoClass *ic = g_ptr_array_index (ifaces, i);
2110 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2111 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2113 mono_class_interface_offset (klass, ic),
2118 g_ptr_array_free (ifaces, TRUE);
2121 klass = klass->parent;
2126 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2129 args [0] = &arg0->byval_arg;
2131 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2135 array_class_get_if_rank (MonoClass *class, guint rank)
2137 return rank ? mono_array_class_get (class, rank) : class;
2141 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2143 valuetype_types [0] = eclass;
2144 if (eclass == mono_defaults.int16_class)
2145 valuetype_types [1] = mono_defaults.uint16_class;
2146 else if (eclass == mono_defaults.uint16_class)
2147 valuetype_types [1] = mono_defaults.int16_class;
2148 else if (eclass == mono_defaults.int32_class)
2149 valuetype_types [1] = mono_defaults.uint32_class;
2150 else if (eclass == mono_defaults.uint32_class)
2151 valuetype_types [1] = mono_defaults.int32_class;
2152 else if (eclass == mono_defaults.int64_class)
2153 valuetype_types [1] = mono_defaults.uint64_class;
2154 else if (eclass == mono_defaults.uint64_class)
2155 valuetype_types [1] = mono_defaults.int64_class;
2156 else if (eclass == mono_defaults.byte_class)
2157 valuetype_types [1] = mono_defaults.sbyte_class;
2158 else if (eclass == mono_defaults.sbyte_class)
2159 valuetype_types [1] = mono_defaults.byte_class;
2160 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2161 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2164 /* this won't be needed once bug #325495 is completely fixed
2165 * though we'll need something similar to know which interfaces to allow
2166 * in arrays when they'll be lazyly created
2168 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2169 * MS returns diferrent types based on which instance is called. For example:
2170 * object obj = new byte[10][];
2171 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2172 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2175 * Fixing this should kill quite some code, save some bits and improve compatbility.
2178 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2180 MonoClass *eclass = class->element_class;
2181 static MonoClass* generic_icollection_class = NULL;
2182 static MonoClass* generic_ienumerable_class = NULL;
2183 static MonoClass* generic_ienumerator_class = NULL;
2184 MonoClass *valuetype_types[2] = { NULL, NULL };
2185 MonoClass **interfaces = NULL;
2186 int i, interface_count, real_count, original_rank;
2188 gboolean internal_enumerator;
2189 gboolean eclass_is_valuetype;
2191 if (!mono_defaults.generic_ilist_class) {
2195 internal_enumerator = FALSE;
2196 eclass_is_valuetype = FALSE;
2197 original_rank = eclass->rank;
2198 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2199 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2201 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2203 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2204 original_rank = eclass->rank;
2205 eclass = eclass->element_class;
2206 internal_enumerator = TRUE;
2207 *is_enumerator = TRUE;
2215 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2216 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2218 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2220 if (!generic_icollection_class) {
2221 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2222 "System.Collections.Generic", "ICollection`1");
2223 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2224 "System.Collections.Generic", "IEnumerable`1");
2225 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2226 "System.Collections.Generic", "IEnumerator`1");
2229 mono_class_init (eclass);
2232 * Arrays in 2.0 need to implement a number of generic interfaces
2233 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2234 * on the element class). We collect the types needed to build the
2235 * instantiations in interfaces at intervals of 3, because 3 are
2236 * the generic interfaces needed to implement.
2238 if (eclass->valuetype) {
2239 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2241 /* IList, ICollection, IEnumerable */
2242 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2243 if (internal_enumerator) {
2245 if (valuetype_types [1])
2249 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2250 interfaces [0] = valuetype_types [0];
2251 if (valuetype_types [1])
2252 interfaces [3] = valuetype_types [1];
2254 eclass_is_valuetype = TRUE;
2257 int idepth = eclass->idepth;
2258 if (!internal_enumerator)
2260 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2261 /* we add object for interfaces and the supertypes for the other
2262 * types. The last of the supertypes is the element class itself which we
2263 * already created the explicit interfaces for (so we include it for IEnumerator
2264 * and exclude it for arrays).
2266 if (MONO_CLASS_IS_INTERFACE (eclass))
2269 interface_count += idepth;
2270 if (eclass->rank && eclass->element_class->valuetype) {
2271 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2272 if (valuetype_types [1])
2275 /* IList, ICollection, IEnumerable */
2276 interface_count *= 3;
2277 real_count = interface_count;
2278 if (internal_enumerator) {
2279 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2280 if (valuetype_types [1])
2283 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2284 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2285 interfaces [0] = mono_defaults.object_class;
2289 for (i = 0; i < idepth; i++) {
2290 mono_class_init (eclass->supertypes [i]);
2291 interfaces [j] = eclass->supertypes [i];
2295 if (all_interfaces) {
2296 for (i = 0; i < eclass->interface_offsets_count; i++) {
2297 interfaces [j] = eclass->interfaces_packed [i];
2301 for (i = 0; i < eclass->interface_count; i++) {
2302 interfaces [j] = eclass->interfaces [i];
2306 if (valuetype_types [1]) {
2307 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2312 /* instantiate the generic interfaces */
2313 for (i = 0; i < interface_count; i += 3) {
2314 MonoClass *iface = interfaces [i];
2316 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2317 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2318 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2320 if (internal_enumerator) {
2322 /* instantiate IEnumerator<iface> */
2323 for (i = 0; i < interface_count; i++) {
2324 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2326 j = interface_count;
2327 if (!eclass_is_valuetype) {
2328 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2329 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2332 for (i = 0; i < eclass->idepth; i++) {
2333 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2337 for (i = 0; i < eclass->interface_offsets_count; i++) {
2338 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2342 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2344 if (valuetype_types [1])
2345 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2349 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2350 for (i = 0; i < real_count; ++i) {
2351 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2352 g_print ("%s implements %s\n", type_name, name);
2363 find_array_interface (MonoClass *klass, const char *name)
2366 for (i = 0; i < klass->interface_count; ++i) {
2367 if (strcmp (klass->interfaces [i]->name, name) == 0)
2374 * LOCKING: this is supposed to be called with the loader lock held.
2377 setup_interface_offsets (MonoClass *class, int cur_slot)
2381 MonoClass **interfaces_full;
2382 int *interface_offsets_full;
2384 int interface_offsets_count;
2385 MonoClass **array_interfaces;
2386 int num_array_interfaces;
2387 int is_enumerator = FALSE;
2390 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
2391 * implicit interfaces have the property that they are assigned the same slot in the
2392 * vtables for compatible interfaces
2394 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
2396 /* compute maximum number of slots and maximum interface id */
2398 for (k = class; k ; k = k->parent) {
2399 for (i = 0; i < k->interface_count; i++) {
2400 ic = k->interfaces [i];
2403 mono_class_init (ic);
2405 if (max_iid < ic->interface_id)
2406 max_iid = ic->interface_id;
2408 ifaces = mono_class_get_implemented_interfaces (k);
2410 for (i = 0; i < ifaces->len; ++i) {
2411 ic = g_ptr_array_index (ifaces, i);
2412 if (max_iid < ic->interface_id)
2413 max_iid = ic->interface_id;
2415 g_ptr_array_free (ifaces, TRUE);
2418 for (i = 0; i < num_array_interfaces; ++i) {
2419 ic = array_interfaces [i];
2420 mono_class_init (ic);
2421 if (max_iid < ic->interface_id)
2422 max_iid = ic->interface_id;
2425 if (MONO_CLASS_IS_INTERFACE (class)) {
2426 if (max_iid < class->interface_id)
2427 max_iid = class->interface_id;
2429 class->max_interface_id = max_iid;
2430 /* compute vtable offset for interfaces */
2431 interfaces_full = g_malloc (sizeof (MonoClass*) * (max_iid + 1));
2432 interface_offsets_full = g_malloc (sizeof (int) * (max_iid + 1));
2434 for (i = 0; i <= max_iid; i++) {
2435 interfaces_full [i] = NULL;
2436 interface_offsets_full [i] = -1;
2439 ifaces = mono_class_get_implemented_interfaces (class);
2441 for (i = 0; i < ifaces->len; ++i) {
2442 ic = g_ptr_array_index (ifaces, i);
2443 interfaces_full [ic->interface_id] = ic;
2444 interface_offsets_full [ic->interface_id] = cur_slot;
2445 cur_slot += ic->method.count;
2447 g_ptr_array_free (ifaces, TRUE);
2450 for (k = class->parent; k ; k = k->parent) {
2451 ifaces = mono_class_get_implemented_interfaces (k);
2453 for (i = 0; i < ifaces->len; ++i) {
2454 ic = g_ptr_array_index (ifaces, i);
2456 if (interface_offsets_full [ic->interface_id] == -1) {
2457 int io = mono_class_interface_offset (k, ic);
2461 interfaces_full [ic->interface_id] = ic;
2462 interface_offsets_full [ic->interface_id] = io;
2465 g_ptr_array_free (ifaces, TRUE);
2469 if (MONO_CLASS_IS_INTERFACE (class)) {
2470 interfaces_full [class->interface_id] = class;
2471 interface_offsets_full [class->interface_id] = cur_slot;
2474 if (num_array_interfaces) {
2475 if (is_enumerator) {
2476 int ienumerator_offset;
2477 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
2478 ienumerator_offset = interface_offsets_full [class->interfaces [ienumerator_idx]->interface_id];
2479 for (i = 0; i < num_array_interfaces; ++i) {
2480 ic = array_interfaces [i];
2481 interfaces_full [ic->interface_id] = ic;
2482 if (strcmp (ic->name, "IEnumerator`1") == 0)
2483 interface_offsets_full [ic->interface_id] = ienumerator_offset;
2485 g_assert_not_reached ();
2486 /*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);*/
2489 int ilist_offset, icollection_offset, ienumerable_offset;
2490 int ilist_iface_idx = find_array_interface (class, "IList`1");
2491 int icollection_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "ICollection`1");
2492 int ienumerable_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "IEnumerable`1");
2493 ilist_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interface_id];
2494 icollection_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [icollection_iface_idx]->interface_id];
2495 ienumerable_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [ienumerable_iface_idx]->interface_id];
2496 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
2497 for (i = 0; i < num_array_interfaces; ++i) {
2498 ic = array_interfaces [i];
2499 interfaces_full [ic->interface_id] = ic;
2500 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
2501 interface_offsets_full [ic->interface_id] = ilist_offset;
2502 else if (strcmp (ic->name, "ICollection`1") == 0)
2503 interface_offsets_full [ic->interface_id] = icollection_offset;
2504 else if (strcmp (ic->name, "IEnumerable`1") == 0)
2505 interface_offsets_full [ic->interface_id] = ienumerable_offset;
2507 g_assert_not_reached ();
2508 /*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);*/
2513 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2514 if (interface_offsets_full [i] != -1) {
2515 interface_offsets_count ++;
2520 * We might get called twice: once from mono_class_init () then once from
2521 * mono_class_setup_vtable ().
2523 if (class->interfaces_packed) {
2524 g_assert (class->interface_offsets_count == interface_offsets_count);
2526 class->interface_offsets_count = interface_offsets_count;
2527 class->interfaces_packed = mono_image_alloc (class->image, sizeof (MonoClass*) * interface_offsets_count);
2528 class->interface_offsets_packed = mono_image_alloc (class->image, sizeof (guint16) * interface_offsets_count);
2529 class->interface_bitmap = mono_image_alloc0 (class->image, (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0));
2530 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2531 if (interface_offsets_full [i] != -1) {
2532 class->interface_bitmap [i >> 3] |= (1 << (i & 7));
2533 class->interfaces_packed [interface_offsets_count] = interfaces_full [i];
2534 class->interface_offsets_packed [interface_offsets_count] = interface_offsets_full [i];
2535 /*if (num_array_interfaces)
2536 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]);*/
2537 interface_offsets_count ++;
2542 g_free (interfaces_full);
2543 g_free (interface_offsets_full);
2544 g_free (array_interfaces);
2546 //printf ("JUST DONE: ");
2547 //print_implemented_interfaces (class);
2553 * Setup interface offsets for interfaces. Used by Ref.Emit.
2556 mono_class_setup_interface_offsets (MonoClass *class)
2558 mono_loader_lock ();
2560 setup_interface_offsets (class, 0);
2562 mono_loader_unlock ();
2566 * mono_class_setup_vtable:
2568 * Creates the generic vtable of CLASS.
2569 * Initializes the following fields in MonoClass:
2572 * Plus all the fields initialized by setup_interface_offsets ().
2573 * If there is an error during vtable construction, class->exception_type is set.
2575 * LOCKING: Acquires the loader lock.
2578 mono_class_setup_vtable (MonoClass *class)
2580 MonoMethod **overrides;
2581 MonoGenericContext *context;
2590 if (mono_debug_using_mono_debugger ())
2591 /* The debugger currently depends on this */
2592 mono_class_setup_methods (class);
2594 if (MONO_CLASS_IS_INTERFACE (class)) {
2595 /* This sets method->slot for all methods if this is an interface */
2596 mono_class_setup_methods (class);
2600 mono_loader_lock ();
2602 if (class->vtable) {
2603 mono_loader_unlock ();
2607 mono_stats.generic_vtable_count ++;
2609 if (class->generic_class) {
2610 context = mono_class_get_context (class);
2611 type_token = class->generic_class->container_class->type_token;
2613 context = (MonoGenericContext *) class->generic_container;
2614 type_token = class->type_token;
2617 if (class->image->dynamic) {
2618 if (class->generic_class) {
2619 MonoClass *gklass = class->generic_class->container_class;
2621 mono_reflection_get_dynamic_overrides (gklass, &overrides, &onum);
2622 for (i = 0; i < onum; ++i) {
2623 MonoMethod *override = overrides [(i * 2) + 1];
2624 MonoMethod *inflated = NULL;
2627 for (j = 0; j < class->method.count; ++j) {
2628 if (gklass->methods [j] == override) {
2629 inflated = class->methods [j];
2633 g_assert (inflated);
2635 overrides [(i * 2) + 1] = inflated;
2638 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
2641 /* The following call fails if there are missing methods in the type */
2642 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
2646 mono_class_setup_vtable_general (class, overrides, onum);
2650 mono_loader_unlock ();
2656 check_core_clr_override_method (MonoClass *class, MonoMethod *override, MonoMethod *base)
2658 MonoSecurityCoreCLRLevel override_level = mono_security_core_clr_method_level (override, FALSE);
2659 MonoSecurityCoreCLRLevel base_level = mono_security_core_clr_method_level (base, FALSE);
2661 if (override_level != base_level && base_level == MONO_SECURITY_CORE_CLR_CRITICAL)
2662 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
2666 #define DEBUG_INTERFACE_VTABLE_CODE 0
2667 #define TRACE_INTERFACE_VTABLE_CODE 0
2668 #define VERIFY_INTERFACE_VTABLE_CODE 0
2670 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2671 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
2675 #define DEBUG_INTERFACE_VTABLE(stmt)
2678 #if TRACE_INTERFACE_VTABLE_CODE
2679 #define TRACE_INTERFACE_VTABLE(stmt) do {\
2683 #define TRACE_INTERFACE_VTABLE(stmt)
2686 #if VERIFY_INTERFACE_VTABLE_CODE
2687 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
2691 #define VERIFY_INTERFACE_VTABLE(stmt)
2695 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2697 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
2701 GString *res = g_string_new ("");
2703 g_string_append_c (res, '(');
2704 for (i = 0; i < sig->param_count; ++i) {
2706 g_string_append_c (res, ',');
2707 mono_type_get_desc (res, sig->params [i], include_namespace);
2709 g_string_append (res, ")=>");
2710 if (sig->ret != NULL) {
2711 mono_type_get_desc (res, sig->ret, include_namespace);
2713 g_string_append (res, "NULL");
2716 g_string_free (res, FALSE);
2720 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
2721 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
2722 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
2723 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
2731 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) {
2732 if (strcmp (im->name, cm->name) == 0) {
2733 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
2734 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
2737 if (! slot_is_empty) {
2738 if (require_newslot) {
2739 if (! interface_is_explicitly_implemented_by_class) {
2740 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
2743 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
2744 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
2748 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
2751 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2752 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
2753 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2754 TRACE_INTERFACE_VTABLE (printf ("]"));
2757 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
2758 /* CAS - SecurityAction.InheritanceDemand on interface */
2759 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2760 mono_secman_inheritancedemand_method (cm, im);
2763 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
2764 check_core_clr_override_method (class, cm, im);
2765 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
2768 MonoClass *ic = im->klass;
2769 const char *ic_name_space = ic->name_space;
2770 const char *ic_name = ic->name;
2773 if (! require_newslot) {
2774 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
2777 if (cm->klass->rank == 0) {
2778 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
2781 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2782 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
2783 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2784 TRACE_INTERFACE_VTABLE (printf ("]"));
2787 if (mono_class_get_image (ic) != mono_defaults.corlib) {
2788 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
2791 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
2792 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
2795 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
2796 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
2800 subname = strstr (cm->name, ic_name_space);
2801 if (subname != cm->name) {
2802 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
2805 subname += strlen (ic_name_space);
2806 if (subname [0] != '.') {
2807 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
2811 if (strstr (subname, ic_name) != subname) {
2812 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
2815 subname += strlen (ic_name);
2816 if (subname [0] != '.') {
2817 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
2821 if (strcmp (subname, im->name) != 0) {
2822 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
2826 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
2827 /* CAS - SecurityAction.InheritanceDemand on interface */
2828 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2829 mono_secman_inheritancedemand_method (cm, im);
2832 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
2833 check_core_clr_override_method (class, cm, im);
2835 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
2840 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2842 foreach_override (gpointer key, gpointer value, gpointer user_data) {
2843 MonoMethod *method = key;
2844 MonoMethod *override = value;
2845 MonoClass *method_class = mono_method_get_class (method);
2846 MonoClass *override_class = mono_method_get_class (override);
2848 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
2849 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
2850 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
2853 print_overrides (GHashTable *override_map, const char *message) {
2855 printf ("Override map \"%s\" START:\n", message);
2856 g_hash_table_foreach (override_map, foreach_override, NULL);
2857 printf ("Override map \"%s\" END.\n", message);
2859 printf ("Override map \"%s\" EMPTY.\n", message);
2863 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
2864 char *full_name = mono_type_full_name (&class->byval_arg);
2868 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
2870 if (print_interfaces) {
2871 print_implemented_interfaces (class);
2872 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
2875 if (class->parent) {
2876 parent_size = class->parent->vtable_size;
2880 for (i = 0; i < size; ++i) {
2881 MonoMethod *cm = vtable [i];
2883 char *cm_name = mono_method_full_name (cm, TRUE);
2884 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
2885 printf (" [%c][%03d][INDEX %03d] %s\n", newness, i, cm->slot, cm_name);
2894 #if VERIFY_INTERFACE_VTABLE_CODE
2896 mono_method_try_get_vtable_index (MonoMethod *method)
2898 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2899 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
2900 if (imethod->declaring->is_generic)
2901 return imethod->declaring->slot;
2903 return method->slot;
2907 mono_class_verify_vtable (MonoClass *class)
2910 char *full_name = mono_type_full_name (&class->byval_arg);
2912 printf ("*** Verifying VTable of class '%s' \n", full_name);
2916 if (!class->methods)
2919 for (i = 0; i < class->method.count; ++i) {
2920 MonoMethod *cm = class->methods [i];
2923 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
2927 full_name = mono_method_full_name (cm, TRUE);
2929 slot = mono_method_try_get_vtable_index (cm);
2931 if (slot >= class->vtable_size) {
2932 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
2936 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot] && class->vtable [slot]->wrapper_type != MONO_WRAPPER_STATIC_RGCTX_INVOKE)) {
2937 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
2938 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
2939 g_free (other_name);
2942 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
2949 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
2951 char *method_signature;
2953 for (index = 0; index < onum; ++index) {
2954 g_print (" at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
2955 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
2957 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
2958 printf ("no implementation for interface method %s::%s(%s) in class %s.%s\n",
2959 mono_type_get_name (&ic->byval_arg), im->name, method_signature, class->name_space, class->name);
2960 g_free (method_signature);
2961 mono_class_setup_methods (class);
2962 for (index = 0; index < class->method.count; ++index) {
2963 MonoMethod *cm = class->methods [index];
2964 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
2966 printf ("METHOD %s(%s)\n", cm->name, method_signature);
2967 g_free (method_signature);
2972 * LOCKING: this is supposed to be called with the loader lock held.
2975 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
2978 MonoMethod **vtable;
2979 int i, max_vtsize = 0, max_iid, cur_slot = 0;
2980 GPtrArray *ifaces = NULL;
2981 GHashTable *override_map = NULL;
2982 gboolean security_enabled = mono_is_security_manager_active ();
2984 gpointer class_iter;
2985 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
2986 int first_non_interface_slot;
2992 ifaces = mono_class_get_implemented_interfaces (class);
2994 for (i = 0; i < ifaces->len; i++) {
2995 MonoClass *ic = g_ptr_array_index (ifaces, i);
2996 max_vtsize += ic->method.count;
2998 g_ptr_array_free (ifaces, TRUE);
3002 if (class->parent) {
3003 mono_class_init (class->parent);
3004 mono_class_setup_vtable (class->parent);
3005 max_vtsize += class->parent->vtable_size;
3006 cur_slot = class->parent->vtable_size;
3009 max_vtsize += class->method.count;
3011 vtable = alloca (sizeof (gpointer) * max_vtsize);
3012 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3014 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3016 cur_slot = setup_interface_offsets (class, cur_slot);
3017 max_iid = class->max_interface_id;
3018 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3020 /* Optimized version for generic instances */
3021 if (class->generic_class) {
3022 MonoClass *gklass = class->generic_class->container_class;
3023 gboolean usable = TRUE;
3025 mono_class_setup_vtable (gklass);
3026 for (i = 0; i < gklass->vtable_size; ++i)
3027 if (gklass->vtable [i] && gklass->vtable [i]->wrapper_type == MONO_WRAPPER_STATIC_RGCTX_INVOKE)
3031 MonoMethod **tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * gklass->vtable_size);
3032 class->vtable_size = gklass->vtable_size;
3033 for (i = 0; i < gklass->vtable_size; ++i)
3034 if (gklass->vtable [i])
3035 tmp [i] = mono_class_inflate_generic_method_full (gklass->vtable [i], class, mono_class_get_context (class));
3036 mono_memory_barrier ();
3037 class->vtable = tmp;
3039 /* Have to set method->slot for abstract virtual methods */
3040 if (class->methods && gklass->methods) {
3041 for (i = 0; i < class->method.count; ++i)
3042 if (class->methods [i]->slot == -1)
3043 class->methods [i]->slot = gklass->methods [i]->slot;
3050 if (class->parent && class->parent->vtable_size) {
3051 MonoClass *parent = class->parent;
3054 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
3056 // Also inherit parent interface vtables, just as a starting point.
3057 // This is needed otherwise bug-77127.exe fails when the property methods
3058 // have different names in the iterface and the class, because for child
3059 // classes the ".override" information is not used anymore.
3060 for (i = 0; i < parent->interface_offsets_count; i++) {
3061 MonoClass *parent_interface = parent->interfaces_packed [i];
3062 int interface_offset = mono_class_interface_offset (class, parent_interface);
3064 if (interface_offset >= parent->vtable_size) {
3065 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
3068 mono_class_setup_methods (parent_interface);
3069 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
3070 for (j = 0; j < parent_interface->method.count; j++) {
3071 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
3072 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
3073 parent_interface_offset + j, parent_interface_offset, j,
3074 interface_offset + j, interface_offset, j));
3081 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
3082 /* override interface methods */
3083 for (i = 0; i < onum; i++) {
3084 MonoMethod *decl = overrides [i*2];
3085 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
3087 dslot = mono_method_get_vtable_slot (decl) + mono_class_interface_offset (class, decl->klass);
3088 vtable [dslot] = overrides [i*2 + 1];
3089 vtable [dslot]->slot = dslot;
3091 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3093 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
3095 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3096 check_core_clr_override_method (class, vtable [dslot], decl);
3099 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
3100 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
3102 // Loop on all implemented interfaces...
3103 for (i = 0; i < class->interface_offsets_count; i++) {
3104 MonoClass *parent = class->parent;
3106 gboolean interface_is_explicitly_implemented_by_class;
3109 ic = class->interfaces_packed [i];
3110 ic_offset = mono_class_interface_offset (class, ic);
3112 mono_class_setup_methods (ic);
3114 // Check if this interface is explicitly implemented (instead of just inherited)
3115 if (parent != NULL) {
3116 int implemented_interfaces_index;
3117 interface_is_explicitly_implemented_by_class = FALSE;
3118 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
3119 if (ic == class->interfaces [implemented_interfaces_index]) {
3120 interface_is_explicitly_implemented_by_class = TRUE;
3125 interface_is_explicitly_implemented_by_class = TRUE;
3128 // Loop on all interface methods...
3129 for (im_index = 0; im_index < ic->method.count; im_index++) {
3130 MonoMethod *im = ic->methods [im_index];
3131 int im_slot = ic_offset + im->slot;
3132 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
3134 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3137 // If there is an explicit implementation, just use it right away,
3138 // otherwise look for a matching method
3139 if (override_im == NULL) {
3144 // First look for a suitable method among the class methods
3146 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
3147 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)));
3148 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
3149 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
3150 vtable [im_slot] = cm;
3151 /* Why do we need this? */
3156 TRACE_INTERFACE_VTABLE (printf ("\n"));
3159 // If the slot is still empty, look in all the inherited virtual methods...
3160 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
3161 MonoClass *parent = class->parent;
3162 // Reverse order, so that last added methods are preferred
3163 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
3164 MonoMethod *cm = parent->vtable [cm_index];
3166 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));
3167 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
3168 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
3169 vtable [im_slot] = cm;
3170 /* Why do we need this? */
3176 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
3180 g_assert (vtable [im_slot] == override_im);
3185 // If the class is not abstract, check that all its interface slots are full.
3186 // The check is done here and not directly at the end of the loop above because
3187 // it can happen (for injected generic array interfaces) that the same slot is
3188 // processed multiple times (those interfaces have overlapping slots), and it
3189 // will not always be the first pass the one that fills the slot.
3190 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3191 for (i = 0; i < class->interface_offsets_count; i++) {
3195 ic = class->interfaces_packed [i];
3196 ic_offset = mono_class_interface_offset (class, ic);
3198 for (im_index = 0; im_index < ic->method.count; im_index++) {
3199 MonoMethod *im = ic->methods [im_index];
3200 int im_slot = ic_offset + im->slot;
3202 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3205 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
3206 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
3207 if (vtable [im_slot] == NULL) {
3208 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
3209 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3211 g_hash_table_destroy (override_map);
3218 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
3220 while ((cm = mono_class_get_virtual_methods (class, &class_iter))) {
3222 * If the method is REUSE_SLOT, we must check in the
3223 * base class for a method to override.
3225 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3227 for (k = class->parent; k ; k = k->parent) {
3232 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
3233 MonoMethodSignature *cmsig, *m1sig;
3235 cmsig = mono_method_signature (cm);
3236 m1sig = mono_method_signature (m1);
3238 if (!cmsig || !m1sig) {
3239 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3243 if (!strcmp(cm->name, m1->name) &&
3244 mono_metadata_signature_equal (cmsig, m1sig)) {
3246 /* CAS - SecurityAction.InheritanceDemand */
3247 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3248 mono_secman_inheritancedemand_method (cm, m1);
3251 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3252 check_core_clr_override_method (class, cm, m1);
3254 slot = mono_method_get_vtable_slot (m1);
3255 g_assert (cm->slot < max_vtsize);
3257 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3258 g_hash_table_insert (override_map, m1, cm);
3270 cm->slot = cur_slot++;
3272 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
3273 vtable [cm->slot] = cm;
3276 /* override non interface methods */
3277 for (i = 0; i < onum; i++) {
3278 MonoMethod *decl = overrides [i*2];
3279 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
3280 g_assert (decl->slot != -1);
3281 vtable [decl->slot] = overrides [i*2 + 1];
3282 overrides [i * 2 + 1]->slot = decl->slot;
3284 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3285 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
3287 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3288 check_core_clr_override_method (class, vtable [decl->slot], decl);
3293 * If a method occupies more than one place in the vtable, and it is
3294 * overriden, then change the other occurances too.
3297 for (i = 0; i < max_vtsize; ++i)
3299 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
3304 g_hash_table_destroy (override_map);
3307 if (class->generic_class) {
3308 MonoClass *gklass = class->generic_class->container_class;
3310 mono_class_init (gklass);
3312 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
3314 /* Check that the vtable_size value computed in mono_class_init () is correct */
3315 if (class->vtable_size)
3316 g_assert (cur_slot == class->vtable_size);
3317 class->vtable_size = cur_slot;
3320 /* FIXME: only do this if the class is actually sharable */
3321 if (class->valuetype && (class->generic_class || class->generic_container) &&
3322 mono_class_generic_sharing_enabled (class)) {
3323 for (i = 0; i < max_vtsize; ++i) {
3324 if (vtable [i] && vtable [i]->wrapper_type == MONO_WRAPPER_NONE)
3325 vtable [i] = mono_marshal_get_static_rgctx_invoke (vtable [i]);
3329 /* Try to share the vtable with our parent. */
3330 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
3331 mono_memory_barrier ();
3332 class->vtable = class->parent->vtable;
3334 MonoMethod **tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * class->vtable_size);
3335 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
3336 mono_memory_barrier ();
3337 class->vtable = tmp;
3340 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
3341 if (mono_print_vtable) {
3344 print_implemented_interfaces (class);
3346 for (i = 0; i <= max_iid; i++)
3347 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
3350 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
3351 class->vtable_size, icount);
3353 for (i = 0; i < class->vtable_size; ++i) {
3358 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
3359 mono_method_full_name (cm, TRUE));
3365 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
3366 class->name, max_iid);
3368 for (i = 0; i < class->interface_count; i++) {
3369 ic = class->interfaces [i];
3370 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
3371 mono_class_interface_offset (class, ic),
3372 ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
3375 for (k = class->parent; k ; k = k->parent) {
3376 for (i = 0; i < k->interface_count; i++) {
3377 ic = k->interfaces [i];
3378 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
3379 mono_class_interface_offset (class, ic),
3380 ic->method.count, ic->interface_id, mono_type_full_name (&ic->byval_arg));
3386 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
3390 * mono_method_get_vtable_slot:
3392 * Returns method->slot, computing it if neccesary.
3393 * LOCKING: Acquires the loader lock.
3396 mono_method_get_vtable_slot (MonoMethod *method)
3398 if (method->slot == -1) {
3399 mono_class_setup_vtable (method->klass);
3400 g_assert (method->slot != -1);
3402 return method->slot;
3406 * mono_method_get_vtable_index:
3409 * Returns the index into the runtime vtable to access the method or,
3410 * in the case of a virtual generic method, the virtual generic method
3414 mono_method_get_vtable_index (MonoMethod *method)
3416 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3417 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3418 if (imethod->declaring->is_generic)
3419 return mono_method_get_vtable_slot (imethod->declaring);
3421 return mono_method_get_vtable_slot (method);
3424 static MonoMethod *default_ghc = NULL;
3425 static MonoMethod *default_finalize = NULL;
3426 static int finalize_slot = -1;
3427 static int ghc_slot = -1;
3430 initialize_object_slots (MonoClass *class)
3435 if (class == mono_defaults.object_class) {
3436 mono_class_setup_vtable (class);
3437 for (i = 0; i < class->vtable_size; ++i) {
3438 MonoMethod *cm = class->vtable [i];
3440 if (!strcmp (cm->name, "GetHashCode"))
3442 else if (!strcmp (cm->name, "Finalize"))
3446 g_assert (ghc_slot > 0);
3447 default_ghc = class->vtable [ghc_slot];
3449 g_assert (finalize_slot > 0);
3450 default_finalize = class->vtable [finalize_slot];
3455 g_list_prepend_mempool (GList* l, MonoMemPool* mp, gpointer datum)
3457 GList* n = mono_mempool_alloc (mp, sizeof (GList));
3465 MonoMethod *array_method;
3467 } GenericArrayMethodInfo;
3469 static int generic_array_method_num = 0;
3470 static GenericArrayMethodInfo *generic_array_method_info = NULL;
3473 generic_array_methods (MonoClass *class)
3475 int i, count_generic = 0;
3476 GList *list = NULL, *tmp;
3477 if (generic_array_method_num)
3478 return generic_array_method_num;
3479 mono_class_setup_methods (class->parent);
3480 for (i = 0; i < class->parent->method.count; i++) {
3481 MonoMethod *m = class->parent->methods [i];
3482 if (!strncmp (m->name, "InternalArray__", 15)) {
3484 list = g_list_prepend (list, m);
3487 list = g_list_reverse (list);
3488 generic_array_method_info = g_malloc (sizeof (GenericArrayMethodInfo) * count_generic);
3490 for (tmp = list; tmp; tmp = tmp->next) {
3491 const char *mname, *iname;
3493 MonoMethod *m = tmp->data;
3494 generic_array_method_info [i].array_method = m;
3495 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
3496 iname = "System.Collections.Generic.ICollection`1.";
3497 mname = m->name + 27;
3498 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
3499 iname = "System.Collections.Generic.IEnumerable`1.";
3500 mname = m->name + 27;
3501 } else if (!strncmp (m->name, "InternalArray__", 15)) {
3502 iname = "System.Collections.Generic.IList`1.";
3503 mname = m->name + 15;
3505 g_assert_not_reached ();
3508 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
3509 strcpy (name, iname);
3510 strcpy (name + strlen (iname), mname);
3511 generic_array_method_info [i].name = name;
3514 /*g_print ("array generic methods: %d\n", count_generic);*/
3516 generic_array_method_num = count_generic;
3518 return generic_array_method_num;
3522 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
3524 MonoGenericContext tmp_context;
3527 tmp_context.class_inst = NULL;
3528 tmp_context.method_inst = iface->generic_class->context.class_inst;
3529 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
3531 for (i = 0; i < generic_array_method_num; i++) {
3532 MonoMethod *m = generic_array_method_info [i].array_method;
3533 MonoMethod *inflated;
3535 inflated = mono_class_inflate_generic_method (m, &tmp_context);
3536 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
3541 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
3543 int len = strlen (s1) + strlen (s2) + 2;
3544 char *s = mono_image_alloc (image, len);
3547 result = g_snprintf (s, len, "%s%c%s", s1, '\0', s2);
3548 g_assert (result == len - 1);
3554 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
3556 gpointer exception_data = NULL;
3558 switch (error->exception_type) {
3559 case MONO_EXCEPTION_TYPE_LOAD:
3560 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
3563 case MONO_EXCEPTION_MISSING_METHOD:
3564 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
3567 case MONO_EXCEPTION_MISSING_FIELD: {
3568 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
3569 const char *class_name;
3572 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
3574 class_name = error->klass->name;
3576 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
3579 g_free ((void*)class_name);
3583 case MONO_EXCEPTION_FILE_NOT_FOUND: {
3586 if (error->ref_only)
3587 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.";
3589 msg = "Could not load file or assembly '%s' or one of its dependencies.";
3591 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
3595 case MONO_EXCEPTION_BAD_IMAGE:
3596 exception_data = error->msg;
3600 g_assert_not_reached ();
3603 mono_class_set_failure (class, error->exception_type, exception_data);
3607 check_core_clr_inheritance (MonoClass *class)
3609 MonoSecurityCoreCLRLevel class_level, parent_level;
3610 MonoClass *parent = class->parent;
3615 class_level = mono_security_core_clr_class_level (class);
3616 parent_level = mono_security_core_clr_class_level (parent);
3618 if (class_level < parent_level)
3619 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3624 * @class: the class to initialize
3626 * Compute the instance_size, class_size and other infos that cannot be
3627 * computed at mono_class_get() time. Also compute vtable_size if possible.
3628 * Returns TRUE on success or FALSE if there was a problem in loading
3629 * the type (incorrect assemblies, missing assemblies, methods, etc).
3631 * LOCKING: Acquires the loader lock.
3634 mono_class_init (MonoClass *class)
3637 MonoCachedClassInfo cached_info;
3638 gboolean has_cached_info;
3639 int class_init_ok = TRUE;
3643 /* Double-checking locking pattern */
3645 return class->exception_type == MONO_EXCEPTION_NONE;
3647 /*g_print ("Init class %s\n", class->name);*/
3649 /* We do everything inside the lock to prevent races */
3650 mono_loader_lock ();
3652 if (class->inited) {
3653 mono_loader_unlock ();
3654 /* Somebody might have gotten in before us */
3655 return class->exception_type == MONO_EXCEPTION_NONE;
3658 if (class->init_pending) {
3659 mono_loader_unlock ();
3660 /* this indicates a cyclic dependency */
3661 g_error ("pending init %s.%s\n", class->name_space, class->name);
3664 class->init_pending = 1;
3666 /* CAS - SecurityAction.InheritanceDemand */
3667 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
3668 mono_secman_inheritancedemand_class (class, class->parent);
3671 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3672 check_core_clr_inheritance (class);
3674 mono_stats.initialized_class_count++;
3676 if (class->generic_class && !class->generic_class->is_dynamic) {
3677 MonoClass *gklass = class->generic_class->container_class;
3679 mono_stats.generic_class_count++;
3681 class->method = gklass->method;
3682 class->field = gklass->field;
3684 mono_class_init (gklass);
3685 // FIXME: Why is this needed ?
3686 mono_class_setup_methods (gklass);
3688 if (MONO_CLASS_IS_INTERFACE (class))
3689 class->interface_id = mono_get_unique_iid (class);
3691 g_assert (class->interface_count == gklass->interface_count);
3694 if (class->parent && !class->parent->inited)
3695 mono_class_init (class->parent);
3697 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
3699 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
3700 class->nested_classes_inited = TRUE;
3703 * Computes the size used by the fields, and their locations
3705 if (has_cached_info) {
3706 class->instance_size = cached_info.instance_size;
3707 class->sizes.class_size = cached_info.class_size;
3708 class->packing_size = cached_info.packing_size;
3709 class->min_align = cached_info.min_align;
3710 class->blittable = cached_info.blittable;
3711 class->has_references = cached_info.has_references;
3712 class->has_static_refs = cached_info.has_static_refs;
3713 class->no_special_static_fields = cached_info.no_special_static_fields;
3716 if (!class->size_inited){
3717 mono_class_setup_fields (class);
3718 if (class->exception_type || mono_loader_get_last_error ()){
3719 class_init_ok = FALSE;
3724 /* Initialize arrays */
3726 class->method.count = 3 + (class->rank > 1? 2: 1);
3728 if (class->interface_count) {
3729 int count_generic = generic_array_methods (class);
3730 class->method.count += class->interface_count * count_generic;
3734 mono_class_setup_supertypes (class);
3737 initialize_object_slots (class);
3740 * Initialize the rest of the data without creating a generic vtable if possible.
3741 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
3742 * also avoid computing a generic vtable.
3744 if (has_cached_info) {
3746 class->vtable_size = cached_info.vtable_size;
3747 class->has_finalize = cached_info.has_finalize;
3748 class->ghcimpl = cached_info.ghcimpl;
3749 class->has_cctor = cached_info.has_cctor;
3750 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
3751 static int szarray_vtable_size = 0;
3754 if (!szarray_vtable_size) {
3755 mono_class_setup_vtable (class);
3756 szarray_vtable_size = class->vtable_size;
3758 class->vtable_size = szarray_vtable_size;
3760 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
3761 MonoClass *gklass = class->generic_class->container_class;
3763 /* Generic instance case */
3764 class->ghcimpl = gklass->ghcimpl;
3765 class->has_finalize = gklass->has_finalize;
3766 class->has_cctor = gklass->has_cctor;
3768 mono_class_setup_vtable (gklass);
3769 if (gklass->exception_type)
3772 class->vtable_size = gklass->vtable_size;
3776 /* ghcimpl is not currently used
3778 if (class->parent) {
3779 MonoMethod *cmethod = class->vtable [ghc_slot];
3780 if (cmethod->is_inflated)
3781 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
3782 if (cmethod == default_ghc) {
3788 /* Interfaces and valuetypes are not supposed to have finalizers */
3789 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
3790 MonoMethod *cmethod = NULL;
3792 if (class->parent && class->parent->has_finalize) {
3793 class->has_finalize = 1;
3795 if (class->type_token) {
3796 cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
3797 } else if (class->parent) {
3798 /* FIXME: Optimize this */
3799 mono_class_setup_vtable (class);
3800 if (class->exception_type || mono_loader_get_last_error ())
3802 cmethod = class->vtable [finalize_slot];
3806 /* Check that this is really the finalizer method */
3807 mono_class_setup_vtable (class);
3808 if (class->exception_type || mono_loader_get_last_error ())
3811 class->has_finalize = 0;
3812 if (class->parent) {
3813 cmethod = class->vtable [finalize_slot];
3814 if (cmethod->is_inflated)
3815 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
3816 if (cmethod != default_finalize) {
3817 class->has_finalize = 1;
3824 /* C# doesn't allow interfaces to have cctors */
3825 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
3826 MonoMethod *cmethod = NULL;
3828 if (class->type_token) {
3829 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
3830 /* The find_method function ignores the 'flags' argument */
3831 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
3832 class->has_cctor = 1;
3834 mono_class_setup_methods (class);
3836 for (i = 0; i < class->method.count; ++i) {
3837 MonoMethod *method = class->methods [i];
3838 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3839 (strcmp (".cctor", method->name) == 0)) {
3840 class->has_cctor = 1;
3848 if (!mono_setup_vtable_in_class_init) {
3850 * This is an embedding API break, since the caller might assume that
3851 * mono_class_init () constructs a generic vtable, so vtable construction errors
3852 * are visible right after the mono_class_init (), and not after
3853 * mono_class_vtable ().
3855 if (class->parent) {
3856 /* This will compute class->parent->vtable_size for some classes */
3857 mono_class_init (class->parent);
3858 if (class->parent->exception_type || mono_loader_get_last_error ())
3860 if (!class->parent->vtable_size) {
3861 /* FIXME: Get rid of this somehow */
3862 mono_class_setup_vtable (class->parent);
3863 if (class->parent->exception_type || mono_loader_get_last_error ())
3866 setup_interface_offsets (class, class->parent->vtable_size);
3868 setup_interface_offsets (class, 0);
3871 mono_class_setup_vtable (class);
3873 if (MONO_CLASS_IS_INTERFACE (class))
3874 setup_interface_offsets (class, 0);
3877 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
3878 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
3879 class_init_ok = FALSE;
3885 class_init_ok = FALSE;
3888 /* Because of the double-checking locking pattern */
3889 mono_memory_barrier ();
3891 class->init_pending = 0;
3893 if (mono_loader_get_last_error ()) {
3894 if (class->exception_type == MONO_EXCEPTION_NONE)
3895 set_failure_from_loader_error (class, mono_loader_get_last_error ());
3897 mono_loader_clear_error ();
3900 mono_loader_unlock ();
3902 if (mono_debugger_class_init_func)
3903 mono_debugger_class_init_func (class);
3905 return class_init_ok;
3909 is_corlib_image (MonoImage *image)
3911 /* FIXME: allow the dynamic case for our compilers and with full trust */
3913 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
3915 return image == mono_defaults.corlib;
3919 * LOCKING: this assumes the loader lock is held
3922 mono_class_setup_mono_type (MonoClass *class)
3924 const char *name = class->name;
3925 const char *nspace = class->name_space;
3926 gboolean is_corlib = is_corlib_image (class->image);
3928 class->this_arg.byref = 1;
3929 class->this_arg.data.klass = class;
3930 class->this_arg.type = MONO_TYPE_CLASS;
3931 class->byval_arg.data.klass = class;
3932 class->byval_arg.type = MONO_TYPE_CLASS;
3934 if (is_corlib && !strcmp (nspace, "System")) {
3935 if (!strcmp (name, "ValueType")) {
3937 * do not set the valuetype bit for System.ValueType.
3938 * class->valuetype = 1;
3940 class->blittable = TRUE;
3941 } else if (!strcmp (name, "Enum")) {
3943 * do not set the valuetype bit for System.Enum.
3944 * class->valuetype = 1;
3946 class->valuetype = 0;
3947 class->enumtype = 0;
3948 } else if (!strcmp (name, "Object")) {
3949 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
3950 } else if (!strcmp (name, "String")) {
3951 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
3952 } else if (!strcmp (name, "TypedReference")) {
3953 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
3957 if (class->valuetype) {
3958 int t = MONO_TYPE_VALUETYPE;
3960 if (is_corlib && !strcmp (nspace, "System")) {
3963 if (!strcmp (name, "Boolean")) {
3964 t = MONO_TYPE_BOOLEAN;
3965 } else if (!strcmp(name, "Byte")) {
3967 class->blittable = TRUE;
3971 if (!strcmp (name, "Char")) {
3976 if (!strcmp (name, "Double")) {
3978 class->blittable = TRUE;
3982 if (!strcmp (name, "Int32")) {
3984 class->blittable = TRUE;
3985 } else if (!strcmp(name, "Int16")) {
3987 class->blittable = TRUE;
3988 } else if (!strcmp(name, "Int64")) {
3990 class->blittable = TRUE;
3991 } else if (!strcmp(name, "IntPtr")) {
3993 class->blittable = TRUE;
3997 if (!strcmp (name, "Single")) {
3999 class->blittable = TRUE;
4000 } else if (!strcmp(name, "SByte")) {
4002 class->blittable = TRUE;
4006 if (!strcmp (name, "UInt32")) {
4008 class->blittable = TRUE;
4009 } else if (!strcmp(name, "UInt16")) {
4011 class->blittable = TRUE;
4012 } else if (!strcmp(name, "UInt64")) {
4014 class->blittable = TRUE;
4015 } else if (!strcmp(name, "UIntPtr")) {
4017 class->blittable = TRUE;
4021 if (!strcmp (name, "TypedReference")) {
4022 t = MONO_TYPE_TYPEDBYREF;
4023 class->blittable = TRUE;
4027 if (!strcmp (name, "Void")) {
4035 class->this_arg.type = class->byval_arg.type = t;
4038 if (MONO_CLASS_IS_INTERFACE (class))
4039 class->interface_id = mono_get_unique_iid (class);
4044 * LOCKING: this assumes the loader lock is held
4047 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
4049 gboolean system_namespace;
4050 gboolean is_corlib = is_corlib_image (class->image);
4052 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
4054 /* if root of the hierarchy */
4055 if (system_namespace && !strcmp (class->name, "Object")) {
4056 class->parent = NULL;
4057 class->instance_size = sizeof (MonoObject);
4060 if (!strcmp (class->name, "<Module>")) {
4061 class->parent = NULL;
4062 class->instance_size = 0;
4066 if (!MONO_CLASS_IS_INTERFACE (class)) {
4067 /* Imported COM Objects always derive from __ComObject. */
4068 if (MONO_CLASS_IS_IMPORT (class)) {
4069 mono_init_com_types ();
4070 if (parent == mono_defaults.object_class)
4071 parent = mono_defaults.com_object_class;
4074 /* set the parent to something useful and safe, but mark the type as broken */
4075 parent = mono_defaults.object_class;
4076 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4079 class->parent = parent;
4081 if (parent->generic_class && !parent->name) {
4083 * If the parent is a generic instance, we may get
4084 * called before it is fully initialized, especially
4085 * before it has its name.
4090 class->marshalbyref = parent->marshalbyref;
4091 class->contextbound = parent->contextbound;
4092 class->delegate = parent->delegate;
4093 if (MONO_CLASS_IS_IMPORT (class))
4094 class->is_com_object = 1;
4096 class->is_com_object = parent->is_com_object;
4098 if (system_namespace) {
4099 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
4100 class->marshalbyref = 1;
4102 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
4103 class->contextbound = 1;
4105 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
4106 class->delegate = 1;
4109 if (class->parent->enumtype || (is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
4110 (strcmp (class->parent->name_space, "System") == 0)))
4111 class->valuetype = 1;
4112 if (is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
4113 class->valuetype = class->enumtype = 1;
4115 /*class->enumtype = class->parent->enumtype; */
4116 mono_class_setup_supertypes (class);
4118 /* initialize com types if COM interfaces are present */
4119 if (MONO_CLASS_IS_IMPORT (class))
4120 mono_init_com_types ();
4121 class->parent = NULL;
4127 * mono_class_setup_supertypes:
4130 * Build the data structure needed to make fast type checks work.
4131 * This currently sets two fields in @class:
4132 * - idepth: distance between @class and System.Object in the type
4134 * - supertypes: array of classes: each element has a class in the hierarchy
4135 * starting from @class up to System.Object
4137 * LOCKING: this assumes the loader lock is held
4140 mono_class_setup_supertypes (MonoClass *class)
4144 if (class->supertypes)
4147 if (class->parent && !class->parent->supertypes)
4148 mono_class_setup_supertypes (class->parent);
4150 class->idepth = class->parent->idepth + 1;
4154 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
4155 class->supertypes = mono_image_alloc0 (class->image, sizeof (MonoClass *) * ms);
4157 if (class->parent) {
4158 class->supertypes [class->idepth - 1] = class;
4159 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
4161 class->supertypes [0] = class;
4166 * mono_class_create_from_typedef:
4167 * @image: image where the token is valid
4168 * @type_token: typedef token
4170 * Create the MonoClass* representing the specified type token.
4171 * @type_token must be a TypeDef token.
4174 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
4176 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
4177 MonoClass *class, *parent = NULL;
4178 guint32 cols [MONO_TYPEDEF_SIZE];
4179 guint32 cols_next [MONO_TYPEDEF_SIZE];
4180 guint tidx = mono_metadata_token_index (type_token);
4181 MonoGenericContext *context = NULL;
4182 const char *name, *nspace;
4184 MonoClass **interfaces;
4185 guint32 field_last, method_last;
4186 guint32 nesting_tokeen;
4188 mono_loader_lock ();
4190 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
4191 mono_loader_unlock ();
4195 g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
4197 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
4199 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
4200 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
4202 class = mono_image_alloc0 (image, sizeof (MonoClass));
4205 class->name_space = nspace;
4207 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4209 class->image = image;
4210 class->type_token = type_token;
4211 class->flags = cols [MONO_TYPEDEF_FLAGS];
4213 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
4216 * Check whether we're a generic type definition.
4218 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
4219 if (class->generic_container) {
4220 class->generic_container->owner.klass = class;
4221 context = &class->generic_container->context;
4224 if (cols [MONO_TYPEDEF_EXTENDS]) {
4225 parent = mono_class_get_full (
4226 image, mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]), context);
4227 if (parent == NULL){
4228 mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
4229 mono_loader_unlock ();
4230 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4235 /* do this early so it's available for interfaces in setup_mono_type () */
4236 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token)))
4237 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
4239 mono_class_setup_parent (class, parent);
4241 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
4242 mono_class_setup_mono_type (class);
4244 if (!class->enumtype) {
4245 if (!mono_metadata_interfaces_from_typedef_full (
4246 image, type_token, &interfaces, &icount, context)){
4247 mono_loader_unlock ();
4248 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4252 class->interfaces = interfaces;
4253 class->interface_count = icount;
4256 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
4260 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
4264 class->cast_class = class->element_class = class;
4266 /*g_print ("Load class %s\n", name);*/
4269 * Compute the field and method lists
4271 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
4272 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
4274 if (tt->rows > tidx){
4275 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
4276 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
4277 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
4279 field_last = image->tables [MONO_TABLE_FIELD].rows;
4280 method_last = image->tables [MONO_TABLE_METHOD].rows;
4283 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
4284 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
4285 class->field.count = field_last - class->field.first;
4287 class->field.count = 0;
4289 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
4290 class->method.count = method_last - class->method.first;
4292 class->method.count = 0;
4294 /* reserve space to store vector pointer in arrays */
4295 if (!strcmp (nspace, "System") && !strcmp (name, "Array")) {
4296 class->instance_size += 2 * sizeof (gpointer);
4297 g_assert (class->field.count == 0);
4300 if (class->enumtype) {
4301 class->enum_basetype = mono_class_find_enum_basetype (class);
4302 if (!class->enum_basetype) {
4303 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4304 mono_loader_unlock ();
4307 class->cast_class = class->element_class = mono_class_from_mono_type (class->enum_basetype);
4311 * If we're a generic type definition, load the constraints.
4312 * We must do this after the class has been constructed to make certain recursive scenarios
4315 if (class->generic_container)
4316 mono_metadata_load_generic_param_constraints (
4317 image, type_token, class->generic_container);
4319 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
4320 if (!strncmp (name, "Vector", 6))
4321 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");
4324 mono_loader_unlock ();
4326 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4331 /** is klass Nullable<T>? */
4333 mono_class_is_nullable (MonoClass *klass)
4335 return klass->generic_class != NULL &&
4336 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
4340 /** if klass is T? return T */
4342 mono_class_get_nullable_param (MonoClass *klass)
4344 g_assert (mono_class_is_nullable (klass));
4345 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4349 * Create the `MonoClass' for an instantiation of a generic type.
4350 * We only do this if we actually need it.
4353 mono_generic_class_get_class (MonoGenericClass *gclass)
4355 MonoClass *klass, *gklass;
4358 mono_loader_lock ();
4359 if (gclass->cached_class) {
4360 mono_loader_unlock ();
4361 return gclass->cached_class;
4364 gclass->cached_class = g_malloc0 (sizeof (MonoClass));
4365 klass = gclass->cached_class;
4367 gklass = gclass->container_class;
4369 if (gklass->nested_in) {
4371 * FIXME: the nested type context should include everything the
4372 * nesting context should have, but it may also have additional
4373 * generic parameters...
4375 klass->nested_in = mono_class_inflate_generic_class (gklass->nested_in,
4376 mono_generic_class_get_context (gclass));
4379 klass->name = gklass->name;
4380 klass->name_space = gklass->name_space;
4382 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4384 klass->image = gklass->image;
4385 klass->flags = gklass->flags;
4386 klass->type_token = gklass->type_token;
4387 klass->field.count = gklass->field.count;
4388 klass->property.count = gklass->property.count;
4390 klass->generic_class = gclass;
4392 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
4393 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
4394 klass->this_arg.byref = TRUE;
4395 klass->enumtype = gklass->enumtype;
4396 klass->valuetype = gklass->valuetype;
4398 klass->cast_class = klass->element_class = klass;
4400 if (mono_class_is_nullable (klass))
4401 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
4403 klass->interface_count = gklass->interface_count;
4404 klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
4405 for (i = 0; i < klass->interface_count; i++) {
4406 klass->interfaces [i] = mono_class_inflate_generic_class (gklass->interfaces [i], mono_generic_class_get_context (gclass));
4410 * We're not interested in the nested classes of a generic instance.
4411 * We use the generic type definition to look for nested classes.
4413 klass->nested_classes = NULL;
4415 if (gklass->parent) {
4416 klass->parent = mono_class_inflate_generic_class (gklass->parent, mono_generic_class_get_context (gclass));
4420 mono_class_setup_parent (klass, klass->parent);
4422 if (klass->enumtype) {
4423 klass->enum_basetype = gklass->enum_basetype;
4424 klass->cast_class = gklass->cast_class;
4427 if (gclass->is_dynamic) {
4430 mono_class_setup_supertypes (klass);
4432 if (klass->enumtype) {
4434 * For enums, gklass->fields might not been set, but instance_size etc. is
4435 * already set in mono_reflection_create_internal_class (). For non-enums,
4436 * these will be computed normally in mono_class_layout_fields ().
4438 klass->instance_size = gklass->instance_size;
4439 klass->sizes.class_size = gklass->sizes.class_size;
4440 klass->size_inited = 1;
4444 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4446 inflated_classes_size += sizeof (MonoClass);
4448 mono_loader_unlock ();
4454 * LOCKING: Acquires the loader lock.
4457 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
4459 MonoClass *klass, **ptr;
4462 mono_loader_lock ();
4464 if (param->pklass) {
4465 mono_loader_unlock ();
4466 return param->pklass;
4469 if (!image && param->owner) {
4471 MonoMethod *method = param->owner->owner.method;
4472 image = (method && method->klass) ? method->klass->image : NULL;
4474 MonoClass *klass = param->owner->owner.klass;
4475 // FIXME: 'klass' should not be null
4476 // But, monodis creates GenericContainers without associating a owner to it
4477 image = klass ? klass->image : NULL;
4482 image = mono_defaults.corlib;
4484 klass = mono_image_alloc0 (image, sizeof (MonoClass));
4487 klass->name = param->name;
4489 klass->name = mono_image_alloc0 (image, 16);
4490 sprintf ((char*)klass->name, is_mvar ? "!!%d" : "!%d", param->num);
4492 klass->name_space = "";
4493 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4495 for (count = 0, ptr = param->constraints; ptr && *ptr; ptr++, count++)
4499 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (param->constraints [0])) {
4500 klass->parent = param->constraints [0];
4502 } else if (param->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
4503 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
4505 klass->parent = mono_defaults.object_class;
4507 if (count - pos > 0) {
4508 klass->interface_count = count - pos;
4509 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
4510 for (i = pos; i < count; i++)
4511 klass->interfaces [i - pos] = param->constraints [i];
4515 image = mono_defaults.corlib;
4517 klass->image = image;
4519 klass->inited = TRUE;
4520 klass->cast_class = klass->element_class = klass;
4521 klass->enum_basetype = &klass->element_class->byval_arg;
4522 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
4524 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
4525 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
4526 klass->this_arg.byref = TRUE;
4530 guint32 cols [MONO_GENERICPARAM_SIZE];
4531 MonoTableInfo *tdef = &image->tables [MONO_TABLE_GENERICPARAM];
4534 if (is_mvar && param->owner->owner.method)
4535 i = mono_metadata_get_generic_param_row (image, param->owner->owner.method->token, &owner);
4536 else if (!is_mvar && param->owner->owner.klass)
4537 i = mono_metadata_get_generic_param_row (image, param->owner->owner.klass->type_token, &owner);
4540 mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
4542 if (cols [MONO_GENERICPARAM_NUMBER] == param->num) {
4543 klass->sizes.generic_param_token = i | MONO_TOKEN_GENERIC_PARAM;
4546 if (++i > tdef->rows)
4548 mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
4549 } while (cols [MONO_GENERICPARAM_OWNER] == owner);
4553 mono_class_setup_supertypes (klass);
4555 mono_memory_barrier ();
4557 param->pklass = klass;
4559 mono_loader_unlock ();
4561 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4567 mono_ptr_class_get (MonoType *type)
4570 MonoClass *el_class;
4574 el_class = mono_class_from_mono_type (type);
4575 image = el_class->image;
4577 mono_loader_lock ();
4579 if (!image->ptr_cache)
4580 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4582 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
4583 mono_loader_unlock ();
4586 result = mono_image_alloc0 (image, sizeof (MonoClass));
4588 result->parent = NULL; /* no parent for PTR types */
4589 result->name_space = el_class->name_space;
4590 name = g_strdup_printf ("%s*", el_class->name);
4591 result->name = mono_image_strdup (image, name);
4594 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4596 result->image = el_class->image;
4597 result->inited = TRUE;
4598 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4599 /* Can pointers get boxed? */
4600 result->instance_size = sizeof (gpointer);
4601 result->cast_class = result->element_class = el_class;
4602 result->enum_basetype = &result->element_class->byval_arg;
4603 result->blittable = TRUE;
4605 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
4606 result->this_arg.data.type = result->byval_arg.data.type = result->enum_basetype;
4607 result->this_arg.byref = TRUE;
4609 mono_class_setup_supertypes (result);
4611 g_hash_table_insert (image->ptr_cache, el_class, result);
4613 mono_loader_unlock ();
4615 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4621 mono_fnptr_class_get (MonoMethodSignature *sig)
4624 static GHashTable *ptr_hash = NULL;
4626 /* FIXME: These should be allocate from a mempool as well, but which one ? */
4628 mono_loader_lock ();
4631 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
4633 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
4634 mono_loader_unlock ();
4637 result = g_new0 (MonoClass, 1);
4639 result->parent = NULL; /* no parent for PTR types */
4640 result->name_space = "System";
4641 result->name = "MonoFNPtrFakeClass";
4643 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4645 result->image = mono_defaults.corlib; /* need to fix... */
4646 result->inited = TRUE;
4647 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
4648 /* Can pointers get boxed? */
4649 result->instance_size = sizeof (gpointer);
4650 result->cast_class = result->element_class = result;
4651 result->blittable = TRUE;
4653 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
4654 result->this_arg.data.method = result->byval_arg.data.method = sig;
4655 result->this_arg.byref = TRUE;
4656 result->enum_basetype = &result->element_class->byval_arg;
4657 result->blittable = TRUE;
4659 mono_class_setup_supertypes (result);
4661 g_hash_table_insert (ptr_hash, sig, result);
4663 mono_loader_unlock ();
4665 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4671 mono_class_from_mono_type (MonoType *type)
4673 switch (type->type) {
4674 case MONO_TYPE_OBJECT:
4675 return type->data.klass? type->data.klass: mono_defaults.object_class;
4676 case MONO_TYPE_VOID:
4677 return type->data.klass? type->data.klass: mono_defaults.void_class;
4678 case MONO_TYPE_BOOLEAN:
4679 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
4680 case MONO_TYPE_CHAR:
4681 return type->data.klass? type->data.klass: mono_defaults.char_class;
4683 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
4685 return type->data.klass? type->data.klass: mono_defaults.byte_class;
4687 return type->data.klass? type->data.klass: mono_defaults.int16_class;
4689 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
4691 return type->data.klass? type->data.klass: mono_defaults.int32_class;
4693 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
4695 return type->data.klass? type->data.klass: mono_defaults.int_class;
4697 return type->data.klass? type->data.klass: mono_defaults.uint_class;
4699 return type->data.klass? type->data.klass: mono_defaults.int64_class;
4701 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
4703 return type->data.klass? type->data.klass: mono_defaults.single_class;
4705 return type->data.klass? type->data.klass: mono_defaults.double_class;
4706 case MONO_TYPE_STRING:
4707 return type->data.klass? type->data.klass: mono_defaults.string_class;
4708 case MONO_TYPE_TYPEDBYREF:
4709 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
4710 case MONO_TYPE_ARRAY:
4711 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
4713 return mono_ptr_class_get (type->data.type);
4714 case MONO_TYPE_FNPTR:
4715 return mono_fnptr_class_get (type->data.method);
4716 case MONO_TYPE_SZARRAY:
4717 return mono_array_class_get (type->data.klass, 1);
4718 case MONO_TYPE_CLASS:
4719 case MONO_TYPE_VALUETYPE:
4720 return type->data.klass;
4721 case MONO_TYPE_GENERICINST:
4722 return mono_generic_class_get_class (type->data.generic_class);
4724 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
4725 case MONO_TYPE_MVAR:
4726 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
4728 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
4729 g_assert_not_reached ();
4736 * mono_type_retrieve_from_typespec
4737 * @image: context where the image is created
4738 * @type_spec: typespec token
4739 * @context: the generic context used to evaluate generic instantiations in
4742 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate)
4744 MonoType *t = mono_type_create_from_typespec (image, type_spec);
4747 if (context && (context->class_inst || context->method_inst)) {
4748 MonoType *inflated = inflate_generic_type (NULL, t, context);
4751 *did_inflate = TRUE;
4758 * mono_class_create_from_typespec
4759 * @image: context where the image is created
4760 * @type_spec: typespec token
4761 * @context: the generic context used to evaluate generic instantiations in
4764 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
4767 gboolean inflated = FALSE;
4768 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated);
4771 ret = mono_class_from_mono_type (t);
4773 mono_metadata_free_type (t);
4778 * mono_bounded_array_class_get:
4779 * @element_class: element class
4780 * @rank: the dimension of the array class
4781 * @bounded: whenever the array has non-zero bounds
4783 * Returns: a class object describing the array with element type @element_type and
4787 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
4791 MonoClass *parent = NULL;
4792 GSList *list, *rootlist;
4795 gboolean corlib_type = FALSE;
4797 g_assert (rank <= 255);
4800 /* bounded only matters for one-dimensional arrays */
4803 image = eclass->image;
4805 mono_loader_lock ();
4807 if (!image->array_cache)
4808 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4810 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
4811 for (; list; list = list->next) {
4813 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
4814 mono_loader_unlock ();
4820 /* for the building corlib use System.Array from it */
4821 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
4822 parent = mono_class_from_name (image, "System", "Array");
4825 parent = mono_defaults.array_class;
4826 if (!parent->inited)
4827 mono_class_init (parent);
4830 class = mono_image_alloc0 (image, sizeof (MonoClass));
4832 class->image = image;
4833 class->name_space = eclass->name_space;
4834 nsize = strlen (eclass->name);
4835 name = g_malloc (nsize + 2 + rank + 1);
4836 memcpy (name, eclass->name, nsize);
4839 memset (name + nsize + 1, ',', rank - 1);
4841 name [nsize + rank] = '*';
4842 name [nsize + rank + bounded] = ']';
4843 name [nsize + rank + bounded + 1] = 0;
4844 class->name = mono_image_strdup (image, name);
4847 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4849 class->type_token = 0;
4850 /* all arrays are marked serializable and sealed, bug #42779 */
4851 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
4852 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4853 class->parent = parent;
4854 class->instance_size = mono_class_instance_size (class->parent);
4856 if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
4857 if (!eclass->reflection_info || eclass->wastypebuilder) {
4858 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
4859 g_assert (eclass->reflection_info && !eclass->wastypebuilder);
4861 /* element_size -1 is ok as this is not an instantitable type*/
4862 class->sizes.element_size = -1;
4864 class->sizes.element_size = mono_class_array_element_size (eclass);
4866 mono_class_setup_supertypes (class);
4868 if (mono_defaults.generic_ilist_class && !bounded && rank == 1) {
4871 /* generic IList, ICollection, IEnumerable */
4872 class->interface_count = 1;
4873 class->interfaces = mono_image_alloc0 (image, sizeof (MonoClass*) * class->interface_count);
4875 args [0] = &eclass->byval_arg;
4876 class->interfaces [0] = mono_class_bind_generic_parameters (
4877 mono_defaults.generic_ilist_class, 1, args, FALSE);
4880 if (eclass->generic_class)
4881 mono_class_init (eclass);
4882 if (!eclass->size_inited)
4883 mono_class_setup_fields (eclass);
4884 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
4888 if (eclass->enumtype)
4889 class->cast_class = eclass->element_class;
4891 class->cast_class = eclass;
4893 class->element_class = eclass;
4895 if ((rank > 1) || bounded) {
4896 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
4897 class->byval_arg.type = MONO_TYPE_ARRAY;
4898 class->byval_arg.data.array = at;
4899 at->eklass = eclass;
4901 /* FIXME: complete.... */
4903 class->byval_arg.type = MONO_TYPE_SZARRAY;
4904 class->byval_arg.data.klass = eclass;
4906 class->this_arg = class->byval_arg;
4907 class->this_arg.byref = 1;
4912 class->generic_container = eclass->generic_container;
4914 list = g_slist_append (rootlist, class);
4915 g_hash_table_insert (image->array_cache, eclass, list);
4917 mono_loader_unlock ();
4919 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4925 * mono_array_class_get:
4926 * @element_class: element class
4927 * @rank: the dimension of the array class
4929 * Returns: a class object describing the array with element type @element_type and
4933 mono_array_class_get (MonoClass *eclass, guint32 rank)
4935 return mono_bounded_array_class_get (eclass, rank, FALSE);
4939 * mono_class_instance_size:
4942 * Returns: the size of an object instance
4945 mono_class_instance_size (MonoClass *klass)
4947 if (!klass->size_inited)
4948 mono_class_init (klass);
4950 return klass->instance_size;
4954 * mono_class_min_align:
4957 * Returns: minimm alignment requirements
4960 mono_class_min_align (MonoClass *klass)
4962 if (!klass->size_inited)
4963 mono_class_init (klass);
4965 return klass->min_align;
4969 * mono_class_value_size:
4972 * This function is used for value types, and return the
4973 * space and the alignment to store that kind of value object.
4975 * Returns: the size of a value of kind @klass
4978 mono_class_value_size (MonoClass *klass, guint32 *align)
4982 /* fixme: check disable, because we still have external revereces to
4983 * mscorlib and Dummy Objects
4985 /*g_assert (klass->valuetype);*/
4987 size = mono_class_instance_size (klass) - sizeof (MonoObject);
4990 *align = klass->min_align;
4996 * mono_class_data_size:
4999 * Returns: the size of the static class data
5002 mono_class_data_size (MonoClass *klass)
5005 mono_class_init (klass);
5007 /* in arrays, sizes.class_size is unioned with element_size
5008 * and arrays have no static fields
5012 return klass->sizes.class_size;
5016 * Auxiliary routine to mono_class_get_field
5018 * Takes a field index instead of a field token.
5020 static MonoClassField *
5021 mono_class_get_field_idx (MonoClass *class, int idx)
5023 mono_class_setup_fields_locking (class);
5026 if (class->image->uncompressed_metadata) {
5028 * class->field.first points to the FieldPtr table, while idx points into the
5029 * Field table, so we have to do a search.
5031 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
5034 for (i = 0; i < class->field.count; ++i)
5035 if (mono_field_get_name (&class->fields [i]) == name)
5036 return &class->fields [i];
5037 g_assert_not_reached ();
5039 if (class->field.count) {
5040 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
5041 return &class->fields [idx - class->field.first];
5045 class = class->parent;
5051 * mono_class_get_field:
5052 * @class: the class to lookup the field.
5053 * @field_token: the field token
5055 * Returns: A MonoClassField representing the type and offset of
5056 * the field, or a NULL value if the field does not belong to this
5060 mono_class_get_field (MonoClass *class, guint32 field_token)
5062 int idx = mono_metadata_token_index (field_token);
5064 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
5066 return mono_class_get_field_idx (class, idx - 1);
5070 * mono_class_get_field_from_name:
5071 * @klass: the class to lookup the field.
5072 * @name: the field name
5074 * Search the class @klass and it's parents for a field with the name @name.
5076 * Returns: the MonoClassField pointer of the named field or NULL
5079 mono_class_get_field_from_name (MonoClass *klass, const char *name)
5083 mono_class_setup_fields_locking (klass);
5085 for (i = 0; i < klass->field.count; ++i) {
5086 if (strcmp (name, mono_field_get_name (&klass->fields [i])) == 0)
5087 return &klass->fields [i];
5089 klass = klass->parent;
5095 * mono_class_get_field_token:
5096 * @field: the field we need the token of
5098 * Get the token of a field. Note that the tokesn is only valid for the image
5099 * the field was loaded from. Don't use this function for fields in dynamic types.
5101 * Returns: the token representing the field in the image it was loaded from.
5104 mono_class_get_field_token (MonoClassField *field)
5106 MonoClass *klass = field->parent;
5109 mono_class_setup_fields_locking (klass);
5111 for (i = 0; i < klass->field.count; ++i) {
5112 if (&klass->fields [i] == field) {
5113 int idx = klass->field.first + i + 1;
5115 if (klass->image->uncompressed_metadata)
5116 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
5117 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
5120 klass = klass->parent;
5123 g_assert_not_reached ();
5128 mono_field_get_index (MonoClassField *field)
5130 int index = field - field->parent->fields;
5132 g_assert (index >= 0 && index < field->parent->field.count);
5138 * mono_class_get_field_default_value:
5140 * Return the default value of the field as a pointer into the metadata blob.
5143 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
5146 guint32 constant_cols [MONO_CONSTANT_SIZE];
5148 MonoClass *klass = field->parent;
5150 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
5152 if (!klass->field_def_values) {
5153 mono_loader_lock ();
5154 if (!klass->field_def_values)
5155 klass->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
5156 mono_loader_unlock ();
5159 field_index = mono_field_get_index (field);
5161 if (!klass->field_def_values [field_index].data) {
5162 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
5164 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
5166 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
5167 klass->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
5168 klass->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
5171 *def_type = klass->field_def_values [field_index].def_type;
5172 return klass->field_def_values [field_index].data;
5176 mono_class_get_event_token (MonoEvent *event)
5178 MonoClass *klass = event->parent;
5182 for (i = 0; i < klass->event.count; ++i) {
5183 if (&klass->events [i] == event)
5184 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->event.first + i + 1);
5186 klass = klass->parent;
5189 g_assert_not_reached ();
5194 mono_class_get_property_from_name (MonoClass *klass, const char *name)
5198 gpointer iter = NULL;
5199 while ((p = mono_class_get_properties (klass, &iter))) {
5200 if (! strcmp (name, p->name))
5203 klass = klass->parent;
5209 mono_class_get_property_token (MonoProperty *prop)
5211 MonoClass *klass = prop->parent;
5215 gpointer iter = NULL;
5216 while ((p = mono_class_get_properties (klass, &iter))) {
5217 if (&klass->properties [i] == prop)
5218 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->property.first + i + 1);
5222 klass = klass->parent;
5225 g_assert_not_reached ();
5230 mono_class_name_from_token (MonoImage *image, guint32 type_token)
5232 const char *name, *nspace;
5234 return g_strdup_printf ("DynamicType 0x%08x", type_token);
5236 switch (type_token & 0xff000000){
5237 case MONO_TOKEN_TYPE_DEF: {
5238 guint32 cols [MONO_TYPEDEF_SIZE];
5239 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5240 guint tidx = mono_metadata_token_index (type_token);
5242 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5243 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5244 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5245 if (strlen (nspace) == 0)
5246 return g_strdup_printf ("%s", name);
5248 return g_strdup_printf ("%s.%s", nspace, name);
5251 case MONO_TOKEN_TYPE_REF: {
5252 guint32 cols [MONO_TYPEREF_SIZE];
5253 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5255 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5256 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
5257 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
5258 if (strlen (nspace) == 0)
5259 return g_strdup_printf ("%s", name);
5261 return g_strdup_printf ("%s.%s", nspace, name);
5264 case MONO_TOKEN_TYPE_SPEC:
5265 return g_strdup_printf ("Typespec 0x%08x", type_token);
5267 g_assert_not_reached ();
5274 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
5277 return g_strdup_printf ("DynamicAssembly %s", image->name);
5279 switch (type_token & 0xff000000){
5280 case MONO_TOKEN_TYPE_DEF:
5281 return mono_stringify_assembly_name (&image->assembly->aname);
5283 case MONO_TOKEN_TYPE_REF: {
5284 MonoAssemblyName aname;
5285 guint32 cols [MONO_TYPEREF_SIZE];
5286 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5289 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5291 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
5292 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
5293 case MONO_RESOLTION_SCOPE_MODULE:
5295 return g_strdup ("");
5296 case MONO_RESOLTION_SCOPE_MODULEREF:
5298 return g_strdup ("");
5299 case MONO_RESOLTION_SCOPE_TYPEREF:
5301 return g_strdup ("");
5302 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
5303 mono_assembly_get_assemblyref (image, idx - 1, &aname);
5304 return mono_stringify_assembly_name (&aname);
5306 g_assert_not_reached ();
5310 case MONO_TOKEN_TYPE_SPEC:
5312 return g_strdup ("");
5314 g_assert_not_reached ();
5321 * mono_class_get_full:
5322 * @image: the image where the class resides
5323 * @type_token: the token for the class
5324 * @context: the generic context used to evaluate generic instantiations in
5326 * Returns: the MonoClass that represents @type_token in @image
5329 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5331 MonoClass *class = NULL;
5333 if (image->dynamic) {
5334 int table = mono_metadata_token_table (type_token);
5336 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
5337 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
5340 return mono_lookup_dynamic_token (image, type_token, context);
5343 switch (type_token & 0xff000000){
5344 case MONO_TOKEN_TYPE_DEF:
5345 class = mono_class_create_from_typedef (image, type_token);
5347 case MONO_TOKEN_TYPE_REF:
5348 class = mono_class_from_typeref (image, type_token);
5350 case MONO_TOKEN_TYPE_SPEC:
5351 class = mono_class_create_from_typespec (image, type_token, context);
5354 g_warning ("unknown token type %x", type_token & 0xff000000);
5355 g_assert_not_reached ();
5359 char *name = mono_class_name_from_token (image, type_token);
5360 char *assembly = mono_assembly_name_from_token (image, type_token);
5361 mono_loader_set_error_type_load (name, assembly);
5369 * mono_type_get_full:
5370 * @image: the image where the type resides
5371 * @type_token: the token for the type
5372 * @context: the generic context used to evaluate generic instantiations in
5374 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
5376 * Returns: the MonoType that represents @type_token in @image
5379 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5381 MonoType *type = NULL;
5382 gboolean inflated = FALSE;
5384 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
5386 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
5388 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
5389 MonoClass *class = mono_class_get_full (image, type_token, context);
5390 return class ? mono_class_get_type (class) : NULL;
5393 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated);
5396 char *name = mono_class_name_from_token (image, type_token);
5397 char *assembly = mono_assembly_name_from_token (image, type_token);
5399 mono_metadata_free_type (type);
5400 mono_loader_set_error_type_load (name, assembly);
5404 MonoType *tmp = type;
5405 type = mono_class_get_type (mono_class_from_mono_type (type));
5406 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
5407 * A MonoClass::byval_arg of a generic type definion has type CLASS.
5408 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
5410 * The long term solution is to chaise this places and make then set MonoType::type correctly.
5412 if (type->type != tmp->type)
5415 mono_metadata_free_type (tmp);
5422 mono_class_get (MonoImage *image, guint32 type_token)
5424 return mono_class_get_full (image, type_token, NULL);
5428 * mono_image_init_name_cache:
5430 * Initializes the class name cache stored in image->name_cache.
5432 * LOCKING: Acquires the loader lock.
5435 mono_image_init_name_cache (MonoImage *image)
5437 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5438 guint32 cols [MONO_TYPEDEF_SIZE];
5441 guint32 i, visib, nspace_index;
5442 GHashTable *name_cache2, *nspace_table;
5444 mono_loader_lock ();
5446 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
5448 if (image->dynamic) {
5449 mono_loader_unlock ();
5453 /* Temporary hash table to avoid lookups in the nspace_table */
5454 name_cache2 = g_hash_table_new (NULL, NULL);
5456 for (i = 1; i <= t->rows; ++i) {
5457 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5458 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5460 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5461 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5463 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5465 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5466 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5468 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
5469 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5470 if (!nspace_table) {
5471 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5472 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5473 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5476 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
5479 /* Load type names from EXPORTEDTYPES table */
5481 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5482 guint32 cols [MONO_EXP_TYPE_SIZE];
5485 for (i = 0; i < t->rows; ++i) {
5486 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
5487 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
5488 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
5490 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
5491 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5492 if (!nspace_table) {
5493 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5494 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5495 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5498 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
5502 g_hash_table_destroy (name_cache2);
5504 mono_loader_unlock ();
5508 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
5509 const char *name, guint32 index)
5511 GHashTable *nspace_table;
5512 GHashTable *name_cache;
5514 mono_loader_lock ();
5516 if (!image->name_cache)
5517 mono_image_init_name_cache (image);
5519 name_cache = image->name_cache;
5520 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
5521 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5522 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
5524 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
5526 mono_loader_unlock ();
5535 find_nocase (gpointer key, gpointer value, gpointer user_data)
5537 char *name = (char*)key;
5538 FindUserData *data = (FindUserData*)user_data;
5540 if (!data->value && (g_strcasecmp (name, (char*)data->key) == 0))
5541 data->value = value;
5545 * mono_class_from_name_case:
5546 * @image: The MonoImage where the type is looked up in
5547 * @name_space: the type namespace
5548 * @name: the type short name.
5550 * Obtains a MonoClass with a given namespace and a given name which
5551 * is located in the given MonoImage. The namespace and name
5552 * lookups are case insensitive.
5555 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
5557 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5558 guint32 cols [MONO_TYPEDEF_SIZE];
5563 if (image->dynamic) {
5565 FindUserData user_data;
5567 mono_loader_lock ();
5569 if (!image->name_cache)
5570 mono_image_init_name_cache (image);
5572 user_data.key = name_space;
5573 user_data.value = NULL;
5574 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
5576 if (user_data.value) {
5577 GHashTable *nspace_table = (GHashTable*)user_data.value;
5579 user_data.key = name;
5580 user_data.value = NULL;
5582 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
5584 if (user_data.value)
5585 token = GPOINTER_TO_UINT (user_data.value);
5588 mono_loader_unlock ();
5591 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
5597 /* add a cache if needed */
5598 for (i = 1; i <= t->rows; ++i) {
5599 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5600 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5602 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5603 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5605 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5607 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5608 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5609 if (g_strcasecmp (n, name) == 0 && g_strcasecmp (nspace, name_space) == 0)
5610 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
5616 return_nested_in (MonoClass *class, char *nested)
5619 char *s = strchr (nested, '/');
5620 gpointer iter = NULL;
5627 while ((found = mono_class_get_nested_types (class, &iter))) {
5628 if (strcmp (found->name, nested) == 0) {
5630 return return_nested_in (found, s);
5638 search_modules (MonoImage *image, const char *name_space, const char *name)
5640 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
5641 MonoImage *file_image;
5646 * The EXPORTEDTYPES table only contains public types, so have to search the
5648 * Note: image->modules contains the contents of the MODULEREF table, while
5649 * the real module list is in the FILE table.
5651 for (i = 0; i < file_table->rows; i++) {
5652 guint32 cols [MONO_FILE_SIZE];
5653 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
5654 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
5657 file_image = mono_image_load_file_for_image (image, i + 1);
5659 class = mono_class_from_name (file_image, name_space, name);
5669 * mono_class_from_name:
5670 * @image: The MonoImage where the type is looked up in
5671 * @name_space: the type namespace
5672 * @name: the type short name.
5674 * Obtains a MonoClass with a given namespace and a given name which
5675 * is located in the given MonoImage.
5678 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
5680 GHashTable *nspace_table;
5681 MonoImage *loaded_image;
5688 if ((nested = strchr (name, '/'))) {
5689 int pos = nested - name;
5690 int len = strlen (name);
5693 memcpy (buf, name, len + 1);
5695 nested = buf + pos + 1;
5699 if (get_class_from_name) {
5700 gboolean res = get_class_from_name (image, name_space, name, &class);
5703 class = search_modules (image, name_space, name);
5705 return class ? return_nested_in (class, nested) : NULL;
5711 mono_loader_lock ();
5713 if (!image->name_cache)
5714 mono_image_init_name_cache (image);
5716 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
5719 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
5721 mono_loader_unlock ();
5723 if (!token && image->dynamic && image->modules) {
5724 /* Search modules as well */
5725 for (i = 0; i < image->module_count; ++i) {
5726 MonoImage *module = image->modules [i];
5728 class = mono_class_from_name (module, name_space, name);
5735 class = search_modules (image, name_space, name);
5743 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
5744 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5745 guint32 cols [MONO_EXP_TYPE_SIZE];
5748 idx = mono_metadata_token_index (token);
5750 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
5752 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
5753 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
5754 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
5757 class = mono_class_from_name (loaded_image, name_space, name);
5759 return return_nested_in (class, nested);
5761 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
5762 MonoAssembly **references = image->references;
5763 guint32 assembly_idx;
5765 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
5767 if (!references [assembly_idx - 1])
5768 mono_assembly_load_reference (image, assembly_idx - 1);
5769 g_assert (references == image->references);
5770 g_assert (references [assembly_idx - 1]);
5771 if (references [assembly_idx - 1] == (gpointer)-1)
5774 /* FIXME: Cycle detection */
5775 return mono_class_from_name (references [assembly_idx - 1]->image, name_space, name);
5777 g_error ("not yet implemented");
5781 token = MONO_TOKEN_TYPE_DEF | token;
5783 class = mono_class_get (image, token);
5785 return return_nested_in (class, nested);
5790 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
5791 gboolean check_interfaces)
5793 g_assert (klassc->idepth > 0);
5794 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
5795 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
5797 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
5800 for (i = 0; i < klass->interface_count; i ++) {
5801 MonoClass *ic = klass->interfaces [i];
5806 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
5811 * MS.NET thinks interfaces are a subclass of Object, so we think it as
5814 if (klassc == mono_defaults.object_class)
5821 mono_class_has_variant_generic_params (MonoClass *klass)
5824 MonoGenericContainer *container;
5826 if (!klass->generic_class)
5829 container = klass->generic_class->container_class->generic_container;
5831 for (i = 0; i < container->type_argc; ++i)
5832 if (container->type_params [i].flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
5839 * mono_class_is_assignable_from:
5840 * @klass: the class to be assigned to
5841 * @oklass: the source class
5843 * Return: true if an instance of object oklass can be assigned to an
5844 * instance of object @klass
5847 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
5850 mono_class_init (klass);
5852 if (!oklass->inited)
5853 mono_class_init (oklass);
5855 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
5856 return klass == oklass;
5858 if (MONO_CLASS_IS_INTERFACE (klass)) {
5859 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
5862 /* interface_offsets might not be set for dynamic classes */
5863 if (oklass->reflection_info && !oklass->interface_bitmap)
5865 * oklass might be a generic type parameter but they have
5866 * interface_offsets set.
5868 return mono_reflection_call_is_assignable_to (oklass, klass);
5869 if (!oklass->interface_bitmap)
5870 /* Happens with generic instances of not-yet created dynamic types */
5872 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
5875 if (mono_class_has_variant_generic_params (klass)) {
5876 if (oklass->generic_class) {
5878 gboolean match = FALSE;
5879 MonoClass *container_class1 = klass->generic_class->container_class;
5880 MonoClass *container_class2 = oklass->generic_class->container_class;
5883 * Check whenever the generic definition of oklass implements the
5884 * generic definition of klass. The IMPLEMENTS_INTERFACE stuff is not usable
5885 * here since the relevant tables are not set up.
5887 for (i = 0; i < container_class2->interface_offsets_count; ++i)
5888 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)))
5892 MonoGenericContainer *container;
5894 container = klass->generic_class->container_class->generic_container;
5897 for (i = 0; i < container->type_argc; ++i) {
5898 MonoClass *param1_class = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [i]);
5899 MonoClass *param2_class = mono_class_from_mono_type (oklass->generic_class->context.class_inst->type_argv [i]);
5901 if (param1_class->valuetype != param2_class->valuetype) {
5906 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
5907 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
5909 if (param1_class != param2_class) {
5910 if ((container->type_params [i].flags & MONO_GEN_PARAM_VARIANT) && mono_class_is_assignable_from (param1_class, param2_class))
5912 else if (((container->type_params [i].flags & MONO_GEN_PARAM_COVARIANT) && mono_class_is_assignable_from (param2_class, param1_class)))
5926 } else if (klass->rank) {
5927 MonoClass *eclass, *eoclass;
5929 if (oklass->rank != klass->rank)
5932 /* vectors vs. one dimensional arrays */
5933 if (oklass->byval_arg.type != klass->byval_arg.type)
5936 eclass = klass->cast_class;
5937 eoclass = oklass->cast_class;
5940 * a is b does not imply a[] is b[] when a is a valuetype, and
5941 * b is a reference type.
5944 if (eoclass->valuetype) {
5945 if ((eclass == mono_defaults.enum_class) ||
5946 (eclass == mono_defaults.enum_class->parent) ||
5947 (eclass == mono_defaults.object_class))
5951 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
5952 } else if (mono_class_is_nullable (klass)) {
5953 if (mono_class_is_nullable (oklass))
5954 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
5956 return mono_class_is_assignable_from (klass->cast_class, oklass);
5957 } else if (klass == mono_defaults.object_class)
5960 return mono_class_has_parent (oklass, klass);
5964 * mono_class_get_cctor:
5965 * @klass: A MonoClass pointer
5967 * Returns: the static constructor of @klass if it exists, NULL otherwise.
5970 mono_class_get_cctor (MonoClass *klass)
5972 MonoCachedClassInfo cached_info;
5974 if (!klass->has_cctor)
5977 if (mono_class_get_cached_class_info (klass, &cached_info))
5978 return mono_get_method (klass->image, cached_info.cctor_token, klass);
5980 if (klass->generic_class && !klass->methods)
5981 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
5983 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
5987 * mono_class_get_finalizer:
5988 * @klass: The MonoClass pointer
5990 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
5993 mono_class_get_finalizer (MonoClass *klass)
5995 MonoCachedClassInfo cached_info;
5998 mono_class_init (klass);
5999 if (!klass->has_finalize)
6002 if (mono_class_get_cached_class_info (klass, &cached_info))
6003 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
6005 mono_class_setup_vtable (klass);
6006 return klass->vtable [finalize_slot];
6011 * mono_class_needs_cctor_run:
6012 * @klass: the MonoClass pointer
6013 * @caller: a MonoMethod describing the caller
6015 * Determines whenever the class has a static constructor and whenever it
6016 * needs to be called when executing CALLER.
6019 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
6023 method = mono_class_get_cctor (klass);
6025 return (method == caller) ? FALSE : TRUE;
6031 * mono_class_array_element_size:
6034 * Returns: the number of bytes an element of type @klass
6035 * uses when stored into an array.
6038 mono_class_array_element_size (MonoClass *klass)
6040 MonoType *type = &klass->byval_arg;
6043 switch (type->type) {
6046 case MONO_TYPE_BOOLEAN:
6050 case MONO_TYPE_CHAR:
6059 case MONO_TYPE_CLASS:
6060 case MONO_TYPE_STRING:
6061 case MONO_TYPE_OBJECT:
6062 case MONO_TYPE_SZARRAY:
6063 case MONO_TYPE_ARRAY:
6065 case MONO_TYPE_MVAR:
6066 return sizeof (gpointer);
6071 case MONO_TYPE_VALUETYPE:
6072 if (type->data.klass->enumtype) {
6073 type = mono_class_enum_basetype (type->data.klass);
6074 klass = klass->element_class;
6077 return mono_class_instance_size (klass) - sizeof (MonoObject);
6078 case MONO_TYPE_GENERICINST:
6079 type = &type->data.generic_class->container_class->byval_arg;
6082 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
6088 * mono_array_element_size:
6089 * @ac: pointer to a #MonoArrayClass
6091 * Returns: the size of single array element.
6094 mono_array_element_size (MonoClass *ac)
6096 g_assert (ac->rank);
6097 return ac->sizes.element_size;
6101 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
6102 MonoGenericContext *context)
6104 if (image->dynamic) {
6105 MonoClass *tmp_handle_class;
6106 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
6108 g_assert (tmp_handle_class);
6110 *handle_class = tmp_handle_class;
6112 if (tmp_handle_class == mono_defaults.typehandle_class)
6113 return &((MonoClass*)obj)->byval_arg;
6118 switch (token & 0xff000000) {
6119 case MONO_TOKEN_TYPE_DEF:
6120 case MONO_TOKEN_TYPE_REF:
6121 case MONO_TOKEN_TYPE_SPEC: {
6124 *handle_class = mono_defaults.typehandle_class;
6125 type = mono_type_get_full (image, token, context);
6128 mono_class_init (mono_class_from_mono_type (type));
6129 /* We return a MonoType* as handle */
6132 case MONO_TOKEN_FIELD_DEF: {
6134 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
6136 *handle_class = mono_defaults.fieldhandle_class;
6137 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
6140 mono_class_init (class);
6141 return mono_class_get_field (class, token);
6143 case MONO_TOKEN_METHOD_DEF:
6144 case MONO_TOKEN_METHOD_SPEC: {
6146 meth = mono_get_method_full (image, token, NULL, context);
6148 *handle_class = mono_defaults.methodhandle_class;
6151 case MONO_TOKEN_MEMBER_REF: {
6152 guint32 cols [MONO_MEMBERREF_SIZE];
6154 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
6155 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6156 mono_metadata_decode_blob_size (sig, &sig);
6157 if (*sig == 0x6) { /* it's a field */
6159 MonoClassField *field;
6160 field = mono_field_from_token (image, token, &klass, context);
6162 *handle_class = mono_defaults.fieldhandle_class;
6166 meth = mono_get_method_full (image, token, NULL, context);
6168 *handle_class = mono_defaults.methodhandle_class;
6173 g_warning ("Unknown token 0x%08x in ldtoken", token);
6180 * This function might need to call runtime functions so it can't be part
6181 * of the metadata library.
6183 static MonoLookupDynamicToken lookup_dynamic = NULL;
6186 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
6188 lookup_dynamic = func;
6192 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
6194 MonoClass *handle_class;
6196 return lookup_dynamic (image, token, TRUE, &handle_class, context);
6200 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
6202 return lookup_dynamic (image, token, valid_token, handle_class, context);
6205 static MonoGetCachedClassInfo get_cached_class_info = NULL;
6208 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
6210 get_cached_class_info = func;
6214 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
6216 if (!get_cached_class_info)
6219 return get_cached_class_info (klass, res);
6223 mono_install_get_class_from_name (MonoGetClassFromName func)
6225 get_class_from_name = func;
6229 mono_class_get_image (MonoClass *klass)
6231 return klass->image;
6235 * mono_class_get_element_class:
6236 * @klass: the MonoClass to act on
6238 * Returns: the element class of an array or an enumeration.
6241 mono_class_get_element_class (MonoClass *klass)
6243 return klass->element_class;
6247 * mono_class_is_valuetype:
6248 * @klass: the MonoClass to act on
6250 * Returns: true if the MonoClass represents a ValueType.
6253 mono_class_is_valuetype (MonoClass *klass)
6255 return klass->valuetype;
6259 * mono_class_is_enum:
6260 * @klass: the MonoClass to act on
6262 * Returns: true if the MonoClass represents an enumeration.
6265 mono_class_is_enum (MonoClass *klass)
6267 return klass->enumtype;
6271 * mono_class_enum_basetype:
6272 * @klass: the MonoClass to act on
6274 * Returns: the underlying type representation for an enumeration.
6277 mono_class_enum_basetype (MonoClass *klass)
6279 return klass->enum_basetype;
6283 * mono_class_get_parent
6284 * @klass: the MonoClass to act on
6286 * Returns: the parent class for this class.
6289 mono_class_get_parent (MonoClass *klass)
6291 return klass->parent;
6295 * mono_class_get_nesting_type;
6296 * @klass: the MonoClass to act on
6298 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
6301 mono_class_get_nesting_type (MonoClass *klass)
6303 return klass->nested_in;
6307 * mono_class_get_rank:
6308 * @klass: the MonoClass to act on
6310 * Returns: the rank for the array (the number of dimensions).
6313 mono_class_get_rank (MonoClass *klass)
6319 * mono_class_get_flags:
6320 * @klass: the MonoClass to act on
6322 * The type flags from the TypeDef table from the metadata.
6323 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
6326 * Returns: the flags from the TypeDef table.
6329 mono_class_get_flags (MonoClass *klass)
6331 return klass->flags;
6335 * mono_class_get_name
6336 * @klass: the MonoClass to act on
6338 * Returns: the name of the class.
6341 mono_class_get_name (MonoClass *klass)
6347 * mono_class_get_namespace:
6348 * @klass: the MonoClass to act on
6350 * Returns: the namespace of the class.
6353 mono_class_get_namespace (MonoClass *klass)
6355 return klass->name_space;
6359 * mono_class_get_type:
6360 * @klass: the MonoClass to act on
6362 * This method returns the internal Type representation for the class.
6364 * Returns: the MonoType from the class.
6367 mono_class_get_type (MonoClass *klass)
6369 return &klass->byval_arg;
6373 * mono_class_get_type_token
6374 * @klass: the MonoClass to act on
6376 * This method returns type token for the class.
6378 * Returns: the type token for the class.
6381 mono_class_get_type_token (MonoClass *klass)
6383 return klass->type_token;
6387 * mono_class_get_byref_type:
6388 * @klass: the MonoClass to act on
6393 mono_class_get_byref_type (MonoClass *klass)
6395 return &klass->this_arg;
6399 * mono_class_num_fields:
6400 * @klass: the MonoClass to act on
6402 * Returns: the number of static and instance fields in the class.
6405 mono_class_num_fields (MonoClass *klass)
6407 return klass->field.count;
6411 * mono_class_num_methods:
6412 * @klass: the MonoClass to act on
6414 * Returns: the number of methods in the class.
6417 mono_class_num_methods (MonoClass *klass)
6419 return klass->method.count;
6423 * mono_class_num_properties
6424 * @klass: the MonoClass to act on
6426 * Returns: the number of properties in the class.
6429 mono_class_num_properties (MonoClass *klass)
6431 mono_class_setup_properties (klass);
6433 return klass->property.count;
6437 * mono_class_num_events:
6438 * @klass: the MonoClass to act on
6440 * Returns: the number of events in the class.
6443 mono_class_num_events (MonoClass *klass)
6445 mono_class_setup_events (klass);
6447 return klass->event.count;
6451 * mono_class_get_fields:
6452 * @klass: the MonoClass to act on
6454 * This routine is an iterator routine for retrieving the fields in a class.
6456 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6457 * iterate over all of the elements. When no more values are
6458 * available, the return value is NULL.
6460 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
6463 mono_class_get_fields (MonoClass* klass, gpointer *iter)
6465 MonoClassField* field;
6469 mono_class_setup_fields_locking (klass);
6470 if (klass->exception_type)
6472 /* start from the first */
6473 if (klass->field.count) {
6474 return *iter = &klass->fields [0];
6482 if (field < &klass->fields [klass->field.count]) {
6483 return *iter = field;
6489 * mono_class_get_methods
6490 * @klass: the MonoClass to act on
6492 * This routine is an iterator routine for retrieving the fields in a class.
6494 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6495 * iterate over all of the elements. When no more values are
6496 * available, the return value is NULL.
6498 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
6501 mono_class_get_methods (MonoClass* klass, gpointer *iter)
6503 MonoMethod** method;
6507 mono_class_init (klass);
6509 mono_class_setup_methods (klass);
6510 /* start from the first */
6511 if (klass->method.count) {
6512 *iter = &klass->methods [0];
6513 return klass->methods [0];
6521 if (method < &klass->methods [klass->method.count]) {
6529 * mono_class_get_virtual_methods:
6531 * Iterate over the virtual methods of KLASS.
6533 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
6536 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
6538 MonoMethod** method;
6541 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
6543 mono_class_setup_methods (klass);
6544 /* start from the first */
6545 method = &klass->methods [0];
6550 while (method < &klass->methods [klass->method.count]) {
6551 if (((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
6555 if (method < &klass->methods [klass->method.count]) {
6562 /* Search directly in metadata to avoid calling setup_methods () */
6563 MonoMethod *res = NULL;
6569 start_index = GPOINTER_TO_UINT (*iter);
6572 for (i = start_index; i < klass->method.count; ++i) {
6573 guint32 cols [MONO_METHOD_SIZE];
6575 /* class->method.first points into the methodptr table */
6576 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
6578 if (cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_VIRTUAL)
6582 if (i < klass->method.count) {
6583 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
6584 /* Add 1 here so the if (*iter) check fails */
6585 *iter = GUINT_TO_POINTER (i + 1);
6594 * mono_class_get_properties:
6595 * @klass: the MonoClass to act on
6597 * This routine is an iterator routine for retrieving the properties 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 @MonoProperty* on each invocation, or NULL when no more are available.
6606 mono_class_get_properties (MonoClass* klass, gpointer *iter)
6608 MonoProperty* property;
6612 mono_class_init (klass);
6614 mono_class_setup_properties (klass);
6615 /* start from the first */
6616 if (klass->property.count) {
6617 return *iter = &klass->properties [0];
6625 if (property < &klass->properties [klass->property.count]) {
6626 return *iter = property;
6632 * mono_class_get_events:
6633 * @klass: the MonoClass to act on
6635 * This routine is an iterator routine for retrieving the properties in a class.
6637 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6638 * iterate over all of the elements. When no more values are
6639 * available, the return value is NULL.
6641 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
6644 mono_class_get_events (MonoClass* klass, gpointer *iter)
6650 mono_class_init (klass);
6652 mono_class_setup_events (klass);
6653 /* start from the first */
6654 if (klass->event.count) {
6655 return *iter = &klass->events [0];
6663 if (event < &klass->events [klass->event.count]) {
6664 return *iter = event;
6670 * mono_class_get_interfaces
6671 * @klass: the MonoClass to act on
6673 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
6675 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6676 * iterate over all of the elements. When no more values are
6677 * available, the return value is NULL.
6679 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
6682 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
6688 mono_class_init (klass);
6690 /* start from the first */
6691 if (klass->interface_count) {
6692 *iter = &klass->interfaces [0];
6693 return klass->interfaces [0];
6701 if (iface < &klass->interfaces [klass->interface_count]) {
6709 * mono_class_get_nested_types
6710 * @klass: the MonoClass to act on
6712 * This routine is an iterator routine for retrieving the nested types of a class.
6713 * This works only if @klass is non-generic, or a generic type definition.
6715 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6716 * iterate over all of the elements. When no more values are
6717 * available, the return value is NULL.
6719 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
6722 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
6730 mono_class_init (klass);
6731 if (!klass->nested_classes_inited) {
6732 if (!klass->type_token)
6733 klass->nested_classes_inited = TRUE;
6734 mono_loader_lock ();
6735 if (!klass->nested_classes_inited) {
6736 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
6739 guint32 cols [MONO_NESTED_CLASS_SIZE];
6740 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
6741 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
6742 klass->nested_classes = g_list_prepend_mempool (klass->nested_classes, klass->image->mempool, nclass);
6744 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
6747 mono_memory_barrier ();
6748 klass->nested_classes_inited = TRUE;
6749 mono_loader_unlock ();
6753 /* start from the first */
6754 if (klass->nested_classes) {
6755 *iter = klass->nested_classes;
6756 return klass->nested_classes->data;
6758 /* no nested types */
6772 * mono_field_get_name:
6773 * @field: the MonoClassField to act on
6775 * Returns: the name of the field.
6778 mono_field_get_name (MonoClassField *field)
6784 * mono_field_get_type:
6785 * @field: the MonoClassField to act on
6787 * Returns: MonoType of the field.
6790 mono_field_get_type (MonoClassField *field)
6796 * mono_field_get_type:
6797 * @field: the MonoClassField to act on
6799 * Returns: MonoClass where the field was defined.
6802 mono_field_get_parent (MonoClassField *field)
6804 return field->parent;
6808 * mono_field_get_flags;
6809 * @field: the MonoClassField to act on
6811 * The metadata flags for a field are encoded using the
6812 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
6814 * Returns: the flags for the field.
6817 mono_field_get_flags (MonoClassField *field)
6819 return field->type->attrs;
6823 * mono_field_get_offset;
6824 * @field: the MonoClassField to act on
6826 * Returns: the field offset.
6829 mono_field_get_offset (MonoClassField *field)
6831 return field->offset;
6835 mono_field_get_rva (MonoClassField *field)
6839 MonoClass *klass = field->parent;
6841 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
6843 if (!klass->field_def_values) {
6844 mono_loader_lock ();
6845 if (!klass->field_def_values)
6846 klass->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
6847 mono_loader_unlock ();
6850 field_index = mono_field_get_index (field);
6852 if (!klass->field_def_values [field_index].data && !klass->image->dynamic) {
6853 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
6855 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
6856 klass->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
6859 return klass->field_def_values [field_index].data;
6863 * mono_field_get_data;
6864 * @field: the MonoClassField to act on
6866 * Returns: pointer to the metadata constant value or to the field
6867 * data if it has an RVA flag.
6870 mono_field_get_data (MonoClassField *field)
6872 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
6873 MonoTypeEnum def_type;
6875 return mono_class_get_field_default_value (field, &def_type);
6876 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
6877 return mono_field_get_rva (field);
6884 * mono_property_get_name:
6885 * @prop: the MonoProperty to act on
6887 * Returns: the name of the property
6890 mono_property_get_name (MonoProperty *prop)
6896 * mono_property_get_set_method
6897 * @prop: the MonoProperty to act on.
6899 * Returns: the setter method of the property (A MonoMethod)
6902 mono_property_get_set_method (MonoProperty *prop)
6908 * mono_property_get_get_method
6909 * @prop: the MonoProperty to act on.
6911 * Returns: the setter method of the property (A MonoMethod)
6914 mono_property_get_get_method (MonoProperty *prop)
6920 * mono_property_get_parent:
6921 * @prop: the MonoProperty to act on.
6923 * Returns: the MonoClass where the property was defined.
6926 mono_property_get_parent (MonoProperty *prop)
6928 return prop->parent;
6932 * mono_property_get_flags:
6933 * @prop: the MonoProperty to act on.
6935 * The metadata flags for a property are encoded using the
6936 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
6938 * Returns: the flags for the property.
6941 mono_property_get_flags (MonoProperty *prop)
6947 * mono_event_get_name:
6948 * @event: the MonoEvent to act on
6950 * Returns: the name of the event.
6953 mono_event_get_name (MonoEvent *event)
6959 * mono_event_get_add_method:
6960 * @event: The MonoEvent to act on.
6962 * Returns: the @add' method for the event (a MonoMethod).
6965 mono_event_get_add_method (MonoEvent *event)
6971 * mono_event_get_remove_method:
6972 * @event: The MonoEvent to act on.
6974 * Returns: the @remove method for the event (a MonoMethod).
6977 mono_event_get_remove_method (MonoEvent *event)
6979 return event->remove;
6983 * mono_event_get_raise_method:
6984 * @event: The MonoEvent to act on.
6986 * Returns: the @raise method for the event (a MonoMethod).
6989 mono_event_get_raise_method (MonoEvent *event)
6991 return event->raise;
6995 * mono_event_get_parent:
6996 * @event: the MonoEvent to act on.
6998 * Returns: the MonoClass where the event is defined.
7001 mono_event_get_parent (MonoEvent *event)
7003 return event->parent;
7007 * mono_event_get_flags
7008 * @event: the MonoEvent to act on.
7010 * The metadata flags for an event are encoded using the
7011 * EVENT_* constants. See the tabledefs.h file for details.
7013 * Returns: the flags for the event.
7016 mono_event_get_flags (MonoEvent *event)
7018 return event->attrs;
7022 * mono_class_get_method_from_name:
7023 * @klass: where to look for the method
7024 * @name_space: name of the method
7025 * @param_count: number of parameters. -1 for any number.
7027 * Obtains a MonoMethod with a given name and number of parameters.
7028 * It only works if there are no multiple signatures for any given method name.
7031 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
7033 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
7037 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
7039 MonoMethod *res = NULL;
7042 /* Search directly in the metadata to avoid calling setup_methods () */
7043 for (i = 0; i < klass->method.count; ++i) {
7044 guint32 cols [MONO_METHOD_SIZE];
7047 /* class->method.first points into the methodptr table */
7048 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
7050 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
7051 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7052 if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
7063 * mono_class_get_method_from_name_flags:
7064 * @klass: where to look for the method
7065 * @name_space: name of the method
7066 * @param_count: number of parameters. -1 for any number.
7067 * @flags: flags which must be set in the method
7069 * Obtains a MonoMethod with a given name and number of parameters.
7070 * It only works if there are no multiple signatures for any given method name.
7073 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
7075 MonoMethod *res = NULL;
7078 mono_class_init (klass);
7080 if (klass->generic_class && !klass->methods) {
7081 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
7083 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
7087 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
7088 mono_class_setup_methods (klass);
7089 for (i = 0; i < klass->method.count; ++i) {
7090 MonoMethod *method = klass->methods [i];
7092 if (method->name[0] == name [0] &&
7093 !strcmp (name, method->name) &&
7094 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
7095 ((method->flags & flags) == flags)) {
7102 res = find_method_in_metadata (klass, name, param_count, flags);
7109 * mono_class_set_failure:
7110 * @klass: class in which the failure was detected
7111 * @ex_type: the kind of exception/error to be thrown (later)
7112 * @ex_data: exception data (specific to each type of exception/error)
7114 * Keep a detected failure informations in the class for later processing.
7115 * Note that only the first failure is kept.
7117 * LOCKING: Acquires the loader lock.
7120 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
7122 if (klass->exception_type)
7125 mono_loader_lock ();
7126 klass->exception_type = ex_type;
7128 mono_property_hash_insert (klass->image->property_hash, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
7129 mono_loader_unlock ();
7135 * mono_class_get_exception_data:
7137 * Return the exception_data property of KLASS.
7139 * LOCKING: Acquires the loader lock.
7142 mono_class_get_exception_data (MonoClass *klass)
7146 mono_loader_lock ();
7147 res = mono_property_hash_lookup (klass->image->property_hash, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
7148 mono_loader_unlock ();
7153 * mono_classes_init:
7155 * Initialize the resources used by this module.
7158 mono_classes_init (void)
7160 mono_counters_register ("Inflated methods size",
7161 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
7162 mono_counters_register ("Inflated classes size",
7163 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
7167 * mono_classes_cleanup:
7169 * Free the resources used by this module.
7172 mono_classes_cleanup (void)
7174 if (global_interface_bitset)
7175 mono_bitset_free (global_interface_bitset);
7179 * mono_class_get_exception_for_failure:
7180 * @klass: class in which the failure was detected
7182 * Return a constructed MonoException than the caller can then throw
7183 * using mono_raise_exception - or NULL if no failure is present (or
7184 * doesn't result in an exception).
7187 mono_class_get_exception_for_failure (MonoClass *klass)
7189 gpointer exception_data = mono_class_get_exception_data (klass);
7191 switch (klass->exception_type) {
7192 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
7193 MonoDomain *domain = mono_domain_get ();
7194 MonoSecurityManager* secman = mono_security_manager_get_methods ();
7195 MonoMethod *method = exception_data;
7196 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
7197 MonoObject *exc = NULL;
7201 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
7202 args [2] = mono_type_get_object (domain, &klass->byval_arg);
7203 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
7205 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
7206 return (MonoException*) exc;
7208 case MONO_EXCEPTION_TYPE_LOAD: {
7211 char *str = mono_type_get_full_name (klass);
7212 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
7213 name = mono_string_new (mono_domain_get (), str);
7215 ex = mono_get_exception_type_load (name, astr);
7219 case MONO_EXCEPTION_MISSING_METHOD: {
7220 char *class_name = exception_data;
7221 char *assembly_name = class_name + strlen (class_name) + 1;
7223 return mono_get_exception_missing_method (class_name, assembly_name);
7225 case MONO_EXCEPTION_MISSING_FIELD: {
7226 char *class_name = exception_data;
7227 char *member_name = class_name + strlen (class_name) + 1;
7229 return mono_get_exception_missing_field (class_name, member_name);
7231 case MONO_EXCEPTION_FILE_NOT_FOUND: {
7232 char *msg_format = exception_data;
7233 char *assembly_name = msg_format + strlen (msg_format) + 1;
7234 char *msg = g_strdup_printf (msg_format, assembly_name);
7237 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
7243 case MONO_EXCEPTION_BAD_IMAGE: {
7244 return mono_get_exception_bad_image_format (exception_data);
7247 MonoLoaderError *error;
7250 error = mono_loader_get_last_error ();
7252 ex = mono_loader_error_prepare_exception (error);
7256 /* TODO - handle other class related failures */
7263 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
7265 outer_klass = mono_class_get_generic_type_definition (outer_klass);
7266 inner_klass = mono_class_get_generic_type_definition (inner_klass);
7268 if (outer_klass == inner_klass)
7270 inner_klass = inner_klass->nested_in;
7271 } while (inner_klass);
7276 mono_class_get_generic_type_definition (MonoClass *klass)
7278 return klass->generic_class ? klass->generic_class->container_class : klass;
7282 * Check if @klass is a subtype of @parent ignoring generic instantiations.
7284 * Generic instantiations are ignored for all super types of @klass.
7286 * Visibility checks ignoring generic instantiations.
7289 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
7292 klass = mono_class_get_generic_type_definition (klass);
7293 parent = mono_class_get_generic_type_definition (parent);
7295 for (i = 0; i < klass->idepth; ++i) {
7296 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
7302 * Subtype can only access parent members with family protection if the site object
7303 * is subclass of Subtype. For example:
7304 * class A { protected int x; }
7306 * void valid_access () {
7310 * void invalid_access () {
7317 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
7319 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
7322 if (context_klass == NULL)
7324 /*if access_klass is not member_klass context_klass must be type compat*/
7325 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
7331 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
7334 if (accessing == accessed)
7336 if (!accessed || !accessing)
7338 mono_assembly_load_friends (accessed);
7339 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
7340 MonoAssemblyName *friend = tmp->data;
7341 /* Be conservative with checks */
7344 if (strcmp (accessing->aname.name, friend->name))
7346 if (friend->public_key_token [0]) {
7347 if (!accessing->aname.public_key_token [0])
7349 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
7358 * If klass is a generic type or if it is derived from a generic type, return the
7359 * MonoClass of the generic definition
7360 * Returns NULL if not found
7363 get_generic_definition_class (MonoClass *klass)
7366 if (klass->generic_class && klass->generic_class->container_class)
7367 return klass->generic_class->container_class;
7368 klass = klass->parent;
7374 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
7377 for (i = 0; i < ginst->type_argc; ++i) {
7378 MonoType *type = ginst->type_argv[i];
7379 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
7381 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
7388 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
7390 int access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
7392 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
7395 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
7398 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
7401 switch (access_level) {
7402 case TYPE_ATTRIBUTE_NOT_PUBLIC:
7403 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7405 case TYPE_ATTRIBUTE_PUBLIC:
7408 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
7411 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
7412 return is_nesting_type (member_klass, access_klass);
7414 case TYPE_ATTRIBUTE_NESTED_FAMILY:
7415 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7417 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
7418 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7420 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
7421 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
7422 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7424 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
7425 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
7426 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7431 /* FIXME: check visibility of type, too */
7433 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
7435 MonoClass *member_generic_def;
7436 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
7437 access_klass->generic_container) &&
7438 (member_generic_def = get_generic_definition_class (member_klass))) {
7439 MonoClass *access_container;
7441 if (access_klass->generic_container)
7442 access_container = access_klass;
7444 access_container = access_klass->generic_class->container_class;
7446 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
7450 /* Partition I 8.5.3.2 */
7451 /* the access level values are the same for fields and methods */
7452 switch (access_level) {
7453 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
7454 /* same compilation unit */
7455 return access_klass->image == member_klass->image;
7456 case FIELD_ATTRIBUTE_PRIVATE:
7457 return access_klass == member_klass;
7458 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
7459 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
7460 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
7463 case FIELD_ATTRIBUTE_ASSEMBLY:
7464 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7465 case FIELD_ATTRIBUTE_FAMILY:
7466 if (is_valid_family_access (access_klass, member_klass, context_klass))
7469 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
7470 if (is_valid_family_access (access_klass, member_klass, context_klass))
7472 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7473 case FIELD_ATTRIBUTE_PUBLIC:
7480 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
7482 /* FIXME: check all overlapping fields */
7483 int can = can_access_member (method->klass, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7485 MonoClass *nested = method->klass->nested_in;
7487 can = can_access_member (nested, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7490 nested = nested->nested_in;
7497 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
7499 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7501 MonoClass *nested = method->klass->nested_in;
7503 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7506 nested = nested->nested_in;
7511 * with generics calls to explicit interface implementations can be expressed
7512 * directly: the method is private, but we must allow it. This may be opening
7513 * a hole or the generics code should handle this differently.
7514 * Maybe just ensure the interface type is public.
7516 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
7522 * mono_method_can_access_method_with_context:
7523 * @method: The caller method
7524 * @called: The called method
7525 * @context_klass:TThe static type on stack of the owner @called object used
7527 * This function must be used with instance calls, as they have more strict family accessibility.
7528 * It can be used with static mehthod, but context_klass should be NULL.
7530 * Returns: TRUE if caller have proper visibility and acessibility to @called
7533 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
7535 MonoClass *access_class = method->klass;
7536 MonoClass *member_class = called->klass;
7537 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7539 MonoClass *nested = access_class->nested_in;
7541 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7544 nested = nested->nested_in;
7551 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
7554 if (called->is_inflated) {
7555 MonoMethodInflated * infl = (MonoMethodInflated*)called;
7556 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
7565 * mono_method_can_access_method_with_context:
7566 * @method: The caller method
7567 * @field: The accessed field
7568 * @context_klass: The static type on stack of the owner @field object used
7570 * This function must be used with instance fields, as they have more strict family accessibility.
7571 * It can be used with static fields, but context_klass should be NULL.
7573 * Returns: TRUE if caller have proper visibility and acessibility to @field
7576 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
7578 MonoClass *access_class = method->klass;
7579 MonoClass *member_class = field->parent;
7580 /* FIXME: check all overlapping fields */
7581 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7583 MonoClass *nested = access_class->nested_in;
7585 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7588 nested = nested->nested_in;
7595 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
7601 * mono_type_is_valid_enum_basetype:
7602 * @type: The MonoType to check
7604 * Returns: TRUE if the type can be used as the basetype of an enum
7606 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
7607 switch (type->type) {
7610 case MONO_TYPE_BOOLEAN:
7613 case MONO_TYPE_CHAR:
7626 * mono_class_is_valid_enum:
7627 * @klass: An enum class to be validated
7629 * This method verify the required properties an enum should have.
7631 * Returns: TRUE if the informed enum class is valid
7633 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
7634 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
7635 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
7637 gboolean mono_class_is_valid_enum (MonoClass *klass) {
7638 MonoClassField * field;
7639 gpointer iter = NULL;
7640 gboolean found_base_field = FALSE;
7642 g_assert (klass->enumtype);
7643 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
7644 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
7648 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
7651 while ((field = mono_class_get_fields (klass, &iter))) {
7652 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
7653 if (found_base_field)
7655 found_base_field = TRUE;
7656 if (!mono_type_is_valid_enum_basetype (field->type))
7661 if (!found_base_field)
7664 if (klass->method.count > 0)
7671 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
7673 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
7677 * mono_class_generic_sharing_enabled:
7680 * Returns whether generic sharing is enabled for class.
7682 * This is a stop-gap measure to slowly introduce generic sharing
7683 * until we have all the issues sorted out, at which time this
7684 * function will disappear and generic sharing will always be enabled.
7687 mono_class_generic_sharing_enabled (MonoClass *class)
7689 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__mono_ppc__)
7690 static gboolean supported = TRUE;
7692 /* Not supported by the JIT backends */
7693 static gboolean supported = FALSE;
7695 static int generic_sharing = MONO_GENERIC_SHARING_NONE;
7696 static gboolean inited = FALSE;
7702 generic_sharing = MONO_GENERIC_SHARING_ALL;
7704 generic_sharing = MONO_GENERIC_SHARING_NONE;
7706 if ((option = g_getenv ("MONO_GENERIC_SHARING"))) {
7707 if (strcmp (option, "corlib") == 0)
7708 generic_sharing = MONO_GENERIC_SHARING_CORLIB;
7709 else if (strcmp (option, "collections") == 0)
7710 generic_sharing = MONO_GENERIC_SHARING_COLLECTIONS;
7711 else if (strcmp (option, "all") == 0)
7712 generic_sharing = MONO_GENERIC_SHARING_ALL;
7713 else if (strcmp (option, "none") == 0)
7714 generic_sharing = MONO_GENERIC_SHARING_NONE;
7716 g_warning ("Unknown generic sharing option `%s'.", option);
7720 generic_sharing = MONO_GENERIC_SHARING_NONE;
7725 switch (generic_sharing) {
7726 case MONO_GENERIC_SHARING_NONE:
7728 case MONO_GENERIC_SHARING_ALL:
7730 case MONO_GENERIC_SHARING_CORLIB :
7731 return class->image == mono_defaults.corlib;
7732 case MONO_GENERIC_SHARING_COLLECTIONS:
7733 if (class->image != mono_defaults.corlib)
7735 while (class->nested_in)
7736 class = class->nested_in;
7737 return g_str_has_prefix (class->name_space, "System.Collections.Generic");
7739 g_assert_not_reached ();
7744 * mono_class_setup_interface_id:
7746 * Initializes MonoClass::interface_id if required.
7748 * LOCKING: Acquires the loader lock.
7751 mono_class_setup_interface_id (MonoClass *class)
7753 mono_loader_lock ();
7754 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
7755 class->interface_id = mono_get_unique_iid (class);
7756 mono_loader_unlock ();