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)
9 * Copyright 2012 Xamarin Inc (http://www.xamarin.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>
43 #include <mono/utils/mono-string.h>
44 #include <mono/utils/mono-error-internals.h>
45 #include <mono/utils/mono-logger-internal.h>
46 #include <mono/utils/mono-memory-model.h>
49 gboolean mono_print_vtable = FALSE;
52 guint32 inflated_classes, inflated_classes_size, inflated_methods_size;
53 guint32 classes_size, class_ext_size;
55 /* Function supplied by the runtime to find classes by name using information from the AOT file */
56 static MonoGetClassFromName get_class_from_name = NULL;
58 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
59 static gboolean mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res);
60 static gboolean can_access_type (MonoClass *access_klass, MonoClass *member_klass);
61 static MonoMethod* find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags);
62 static int generic_array_methods (MonoClass *class);
63 static void setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos);
65 static MonoMethod* mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter);
66 static char* mono_assembly_name_from_token (MonoImage *image, guint32 type_token);
67 static void mono_field_resolve_type (MonoClassField *field, MonoError *error);
68 static guint32 mono_field_resolve_flags (MonoClassField *field);
69 static void mono_class_setup_vtable_full (MonoClass *class, GList *in_setup);
72 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
73 void (*mono_debugger_class_loaded_methods_func) (MonoClass *klass) = NULL;
76 * mono_class_from_typeref:
78 * @type_token: a TypeRef token
80 * Creates the MonoClass* structure representing the type defined by
81 * the typeref token valid inside @image.
82 * Returns: the MonoClass* representing the typeref token, NULL ifcould
86 mono_class_from_typeref (MonoImage *image, guint32 type_token)
89 guint32 cols [MONO_TYPEREF_SIZE];
90 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
92 const char *name, *nspace;
96 if (!mono_verifier_verify_typeref_row (image, (type_token & 0xffffff) - 1, &error)) {
97 mono_trace_warning (MONO_TRACE_TYPE, "Failed to resolve typeref from %s due to '%s'", image->name, mono_error_get_message (&error));
101 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
103 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
104 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
106 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
107 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
108 case MONO_RESOLTION_SCOPE_MODULE:
110 g_error ("null ResolutionScope not yet handled");
111 /* a typedef in disguise */
112 return mono_class_from_name (image, nspace, name);
113 case MONO_RESOLTION_SCOPE_MODULEREF:
114 module = mono_image_load_module (image, idx);
116 return mono_class_from_name (module, nspace, name);
118 char *msg = g_strdup_printf ("%s%s%s", nspace, nspace [0] ? "." : "", name);
121 human_name = mono_stringify_assembly_name (&image->assembly->aname);
122 mono_loader_set_error_type_load (msg, human_name);
128 case MONO_RESOLTION_SCOPE_TYPEREF: {
129 MonoClass *enclosing;
132 if (idx == mono_metadata_token_index (type_token)) {
133 mono_loader_set_error_bad_image (g_strdup_printf ("Image %s with self-referencing typeref token %08x.", image->name, type_token));
137 enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
141 if (enclosing->nested_classes_inited && enclosing->ext) {
142 /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
143 for (tmp = enclosing->ext->nested_classes; tmp; tmp = tmp->next) {
145 if (strcmp (res->name, name) == 0)
149 /* Don't call mono_class_init as we might've been called by it recursively */
150 int i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, 1);
152 guint32 class_nested = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, MONO_NESTED_CLASS_NESTED);
153 guint32 string_offset = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_TYPEDEF], class_nested - 1, MONO_TYPEDEF_NAME);
154 const char *nname = mono_metadata_string_heap (enclosing->image, string_offset);
156 if (strcmp (nname, name) == 0)
157 return mono_class_create_from_typedef (enclosing->image, MONO_TOKEN_TYPE_DEF | class_nested);
159 i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, i + 1);
162 g_warning ("TypeRef ResolutionScope not yet handled (%d) for %s.%s in image %s", idx, nspace, name, image->name);
165 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
169 if (idx > image->tables [MONO_TABLE_ASSEMBLYREF].rows) {
170 mono_loader_set_error_bad_image (g_strdup_printf ("Image %s with invalid assemblyref token %08x.", image->name, idx));
174 if (!image->references || !image->references [idx - 1])
175 mono_assembly_load_reference (image, idx - 1);
176 g_assert (image->references [idx - 1]);
178 /* If the assembly did not load, register this as a type load exception */
179 if (image->references [idx - 1] == REFERENCE_MISSING){
180 MonoAssemblyName aname;
183 mono_assembly_get_assemblyref (image, idx - 1, &aname);
184 human_name = mono_stringify_assembly_name (&aname);
185 mono_loader_set_error_assembly_load (human_name, image->assembly ? image->assembly->ref_only : FALSE);
191 return mono_class_from_name (image->references [idx - 1]->image, nspace, name);
196 mono_image_memdup (MonoImage *image, void *data, guint size)
198 void *res = mono_image_alloc (image, size);
199 memcpy (res, data, size);
203 /* Copy everything mono_metadata_free_array free. */
205 mono_dup_array_type (MonoImage *image, MonoArrayType *a)
208 a = mono_image_memdup (image, a, sizeof (MonoArrayType));
210 a->sizes = mono_image_memdup (image, a->sizes, a->numsizes * sizeof (int));
212 a->lobounds = mono_image_memdup (image, a->lobounds, a->numlobounds * sizeof (int));
214 a = g_memdup (a, sizeof (MonoArrayType));
216 a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
218 a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
223 /* Copy everything mono_metadata_free_method_signature free. */
225 mono_metadata_signature_deep_dup (MonoImage *image, MonoMethodSignature *sig)
229 sig = mono_metadata_signature_dup_full (image, sig);
231 sig->ret = mono_metadata_type_dup (image, sig->ret);
232 for (i = 0; i < sig->param_count; ++i)
233 sig->params [i] = mono_metadata_type_dup (image, sig->params [i]);
239 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
241 MonoAssembly *ta = klass->image->assembly;
244 name = mono_stringify_assembly_name (&ta->aname);
245 g_string_append_printf (str, ", %s", name);
250 mono_type_name_check_byref (MonoType *type, GString *str)
253 g_string_append_c (str, '&');
257 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
258 MonoTypeNameFormat format)
262 switch (type->type) {
263 case MONO_TYPE_ARRAY: {
264 int i, rank = type->data.array->rank;
265 MonoTypeNameFormat nested_format;
267 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
268 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
270 mono_type_get_name_recurse (
271 &type->data.array->eklass->byval_arg, str, FALSE, nested_format);
272 g_string_append_c (str, '[');
274 g_string_append_c (str, '*');
275 for (i = 1; i < rank; i++)
276 g_string_append_c (str, ',');
277 g_string_append_c (str, ']');
279 mono_type_name_check_byref (type, str);
281 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
282 _mono_type_get_assembly_name (type->data.array->eklass, str);
285 case MONO_TYPE_SZARRAY: {
286 MonoTypeNameFormat nested_format;
288 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
289 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
291 mono_type_get_name_recurse (
292 &type->data.klass->byval_arg, str, FALSE, nested_format);
293 g_string_append (str, "[]");
295 mono_type_name_check_byref (type, str);
297 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
298 _mono_type_get_assembly_name (type->data.klass, str);
301 case MONO_TYPE_PTR: {
302 MonoTypeNameFormat nested_format;
304 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
305 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
307 mono_type_get_name_recurse (
308 type->data.type, str, FALSE, nested_format);
309 g_string_append_c (str, '*');
311 mono_type_name_check_byref (type, str);
313 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
314 _mono_type_get_assembly_name (mono_class_from_mono_type (type->data.type), str);
319 if (!mono_generic_param_info (type->data.generic_param))
320 g_string_append_printf (str, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", type->data.generic_param->num);
322 g_string_append (str, mono_generic_param_info (type->data.generic_param)->name);
324 mono_type_name_check_byref (type, str);
328 klass = mono_class_from_mono_type (type);
329 if (klass->nested_in) {
330 mono_type_get_name_recurse (
331 &klass->nested_in->byval_arg, str, TRUE, format);
332 if (format == MONO_TYPE_NAME_FORMAT_IL)
333 g_string_append_c (str, '.');
335 g_string_append_c (str, '+');
336 } else if (*klass->name_space) {
337 g_string_append (str, klass->name_space);
338 g_string_append_c (str, '.');
340 if (format == MONO_TYPE_NAME_FORMAT_IL) {
341 char *s = strchr (klass->name, '`');
342 int len = s ? s - klass->name : strlen (klass->name);
344 g_string_append_len (str, klass->name, len);
346 g_string_append (str, klass->name);
349 if (klass->generic_class) {
350 MonoGenericClass *gclass = klass->generic_class;
351 MonoGenericInst *inst = gclass->context.class_inst;
352 MonoTypeNameFormat nested_format;
355 nested_format = format == MONO_TYPE_NAME_FORMAT_FULL_NAME ?
356 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED : format;
358 if (format == MONO_TYPE_NAME_FORMAT_IL)
359 g_string_append_c (str, '<');
361 g_string_append_c (str, '[');
362 for (i = 0; i < inst->type_argc; i++) {
363 MonoType *t = inst->type_argv [i];
366 g_string_append_c (str, ',');
367 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
368 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
369 g_string_append_c (str, '[');
370 mono_type_get_name_recurse (inst->type_argv [i], str, FALSE, nested_format);
371 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
372 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
373 g_string_append_c (str, ']');
375 if (format == MONO_TYPE_NAME_FORMAT_IL)
376 g_string_append_c (str, '>');
378 g_string_append_c (str, ']');
379 } else if (klass->generic_container &&
380 (format != MONO_TYPE_NAME_FORMAT_FULL_NAME) &&
381 (format != MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)) {
384 if (format == MONO_TYPE_NAME_FORMAT_IL)
385 g_string_append_c (str, '<');
387 g_string_append_c (str, '[');
388 for (i = 0; i < klass->generic_container->type_argc; i++) {
390 g_string_append_c (str, ',');
391 g_string_append (str, mono_generic_container_get_param_info (klass->generic_container, i)->name);
393 if (format == MONO_TYPE_NAME_FORMAT_IL)
394 g_string_append_c (str, '>');
396 g_string_append_c (str, ']');
399 mono_type_name_check_byref (type, str);
401 if ((format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
402 (type->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
403 _mono_type_get_assembly_name (klass, str);
409 * mono_type_get_name_full:
411 * @format: the format for the return string.
414 * Returns: the string representation in a number of formats:
416 * if format is MONO_TYPE_NAME_FORMAT_REFLECTION, the return string is
417 * returned in the formatrequired by System.Reflection, this is the
418 * inverse of mono_reflection_parse_type ().
420 * if format is MONO_TYPE_NAME_FORMAT_IL, it returns a syntax that can
421 * be used by the IL assembler.
423 * if format is MONO_TYPE_NAME_FORMAT_FULL_NAME
425 * if format is MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED
428 mono_type_get_name_full (MonoType *type, MonoTypeNameFormat format)
432 result = g_string_new ("");
434 mono_type_get_name_recurse (type, result, FALSE, format);
436 return g_string_free (result, FALSE);
440 * mono_type_get_full_name:
443 * Returns: the string representation for type as required by System.Reflection.
444 * The inverse of mono_reflection_parse_type ().
447 mono_type_get_full_name (MonoClass *class)
449 return mono_type_get_name_full (mono_class_get_type (class), MONO_TYPE_NAME_FORMAT_REFLECTION);
453 * mono_type_get_name:
456 * Returns: the string representation for type as it would be represented in IL code.
459 mono_type_get_name (MonoType *type)
461 return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_IL);
465 * mono_type_get_underlying_type:
468 * Returns: the MonoType for the underlying integer type if @type
469 * is an enum and byref is false, otherwise the type itself.
472 mono_type_get_underlying_type (MonoType *type)
474 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype && !type->byref)
475 return mono_class_enum_basetype (type->data.klass);
476 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype && !type->byref)
477 return mono_class_enum_basetype (type->data.generic_class->container_class);
482 * mono_class_is_open_constructed_type:
485 * Returns TRUE if type represents a generics open constructed type.
486 * IOW, not all type parameters required for the instantiation have
487 * been provided or it's a generic type definition.
489 * An open constructed type means it's a non realizable type. Not to
490 * be mixed up with an abstract type - we can't cast or dispatch to
491 * an open type, for example.
494 mono_class_is_open_constructed_type (MonoType *t)
500 case MONO_TYPE_SZARRAY:
501 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
502 case MONO_TYPE_ARRAY:
503 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
505 return mono_class_is_open_constructed_type (t->data.type);
506 case MONO_TYPE_GENERICINST:
507 return t->data.generic_class->context.class_inst->is_open;
508 case MONO_TYPE_CLASS:
509 case MONO_TYPE_VALUETYPE:
510 return t->data.klass->generic_container != NULL;
517 inflate_generic_type (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
519 mono_error_init (error);
521 switch (type->type) {
522 case MONO_TYPE_MVAR: {
524 int num = mono_type_get_generic_param_num (type);
525 MonoGenericInst *inst = context->method_inst;
526 if (!inst || !inst->type_argv)
528 if (num >= inst->type_argc) {
529 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
530 mono_error_set_bad_image (error, image, "MVAR %d (%s) cannot be expanded in this context with %d instantiations",
531 num, info ? info->name : "", inst->type_argc);
536 * Note that the VAR/MVAR cases are different from the rest. The other cases duplicate @type,
537 * while the VAR/MVAR duplicates a type from the context. So, we need to ensure that the
538 * ->byref and ->attrs from @type are propagated to the returned type.
540 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
541 nt->byref = type->byref;
542 nt->attrs = type->attrs;
545 case MONO_TYPE_VAR: {
547 int num = mono_type_get_generic_param_num (type);
548 MonoGenericInst *inst = context->class_inst;
551 if (num >= inst->type_argc) {
552 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
553 mono_error_set_bad_image (error, image, "VAR %d (%s) cannot be expanded in this context with %d instantiations",
554 num, info ? info->name : "", inst->type_argc);
557 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
558 nt->byref = type->byref;
559 nt->attrs = type->attrs;
562 case MONO_TYPE_SZARRAY: {
563 MonoClass *eclass = type->data.klass;
564 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
565 if (!inflated || !mono_error_ok (error))
567 nt = mono_metadata_type_dup (image, type);
568 nt->data.klass = mono_class_from_mono_type (inflated);
569 mono_metadata_free_type (inflated);
572 case MONO_TYPE_ARRAY: {
573 MonoClass *eclass = type->data.array->eklass;
574 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
575 if (!inflated || !mono_error_ok (error))
577 nt = mono_metadata_type_dup (image, type);
578 nt->data.array->eklass = mono_class_from_mono_type (inflated);
579 mono_metadata_free_type (inflated);
582 case MONO_TYPE_GENERICINST: {
583 MonoGenericClass *gclass = type->data.generic_class;
584 MonoGenericInst *inst;
586 if (!gclass->context.class_inst->is_open)
589 inst = mono_metadata_inflate_generic_inst (gclass->context.class_inst, context, error);
590 if (!mono_error_ok (error))
592 if (inst != gclass->context.class_inst)
593 gclass = mono_metadata_lookup_generic_class (gclass->container_class, inst, gclass->is_dynamic);
595 if (gclass == type->data.generic_class)
598 nt = mono_metadata_type_dup (image, type);
599 nt->data.generic_class = gclass;
602 case MONO_TYPE_CLASS:
603 case MONO_TYPE_VALUETYPE: {
604 MonoClass *klass = type->data.klass;
605 MonoGenericContainer *container = klass->generic_container;
606 MonoGenericInst *inst;
607 MonoGenericClass *gclass = NULL;
613 /* We can't use context->class_inst directly, since it can have more elements */
614 inst = mono_metadata_inflate_generic_inst (container->context.class_inst, context, error);
615 if (!mono_error_ok (error))
617 if (inst == container->context.class_inst)
620 gclass = mono_metadata_lookup_generic_class (klass, inst, klass->image->dynamic);
622 nt = mono_metadata_type_dup (image, type);
623 nt->type = MONO_TYPE_GENERICINST;
624 nt->data.generic_class = gclass;
634 mono_generic_class_get_context (MonoGenericClass *gclass)
636 return &gclass->context;
640 mono_class_get_context (MonoClass *class)
642 return class->generic_class ? mono_generic_class_get_context (class->generic_class) : NULL;
646 * mono_class_get_generic_container:
648 * Return the generic container of KLASS which should be a generic type definition.
650 MonoGenericContainer*
651 mono_class_get_generic_container (MonoClass *klass)
653 g_assert (klass->is_generic);
655 return klass->generic_container;
659 * mono_class_get_generic_class:
661 * Return the MonoGenericClass of KLASS, which should be a generic instance.
664 mono_class_get_generic_class (MonoClass *klass)
666 g_assert (klass->is_inflated);
668 return klass->generic_class;
672 * mono_class_inflate_generic_type_with_mempool:
673 * @mempool: a mempool
675 * @context: a generics context
676 * @error: error context
678 * The same as mono_class_inflate_generic_type, but allocates the MonoType
679 * from mempool if it is non-NULL. If it is NULL, the MonoType is
680 * allocated on the heap and is owned by the caller.
681 * The returned type can potentially be the same as TYPE, so it should not be
682 * modified by the caller, and it should be freed using mono_metadata_free_type ().
685 mono_class_inflate_generic_type_with_mempool (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
687 MonoType *inflated = NULL;
688 mono_error_init (error);
691 inflated = inflate_generic_type (image, type, context, error);
692 if (!mono_error_ok (error))
696 MonoType *shared = mono_metadata_get_shared_type (type);
701 return mono_metadata_type_dup (image, type);
705 mono_stats.inflated_type_count++;
710 * mono_class_inflate_generic_type:
712 * @context: a generics context
714 * If @type is a generic type and @context is not NULL, instantiate it using the
715 * generics context @context.
717 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
718 * on the heap and is owned by the caller. Returns NULL on error.
720 * @deprecated Please use mono_class_inflate_generic_type_checked instead
723 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
727 result = mono_class_inflate_generic_type_checked (type, context, &error);
729 if (!mono_error_ok (&error)) {
730 mono_error_cleanup (&error);
737 * mono_class_inflate_generic_type:
739 * @context: a generics context
740 * @error: error context to use
742 * If @type is a generic type and @context is not NULL, instantiate it using the
743 * generics context @context.
745 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
746 * on the heap and is owned by the caller.
749 mono_class_inflate_generic_type_checked (MonoType *type, MonoGenericContext *context, MonoError *error)
751 return mono_class_inflate_generic_type_with_mempool (NULL, type, context, error);
755 * mono_class_inflate_generic_type_no_copy:
757 * Same as inflate_generic_type_with_mempool, but return TYPE if no inflation
761 mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
763 MonoType *inflated = NULL;
765 mono_error_init (error);
767 inflated = inflate_generic_type (image, type, context, error);
768 if (!mono_error_ok (error))
775 mono_stats.inflated_type_count++;
780 mono_class_inflate_generic_class_checked (MonoClass *gklass, MonoGenericContext *context, MonoError *error)
785 inflated = mono_class_inflate_generic_type_checked (&gklass->byval_arg, context, error);
786 if (!mono_error_ok (error))
789 res = mono_class_from_mono_type (inflated);
790 mono_metadata_free_type (inflated);
795 * mono_class_inflate_generic_class:
797 * Inflate the class GKLASS with CONTEXT.
800 mono_class_inflate_generic_class (MonoClass *gklass, MonoGenericContext *context)
805 res = mono_class_inflate_generic_class_checked (gklass, context, &error);
806 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
813 static MonoGenericContext
814 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with, MonoError *error)
816 MonoGenericInst *class_inst = NULL;
817 MonoGenericInst *method_inst = NULL;
818 MonoGenericContext res = { NULL, NULL };
820 mono_error_init (error);
822 if (context->class_inst) {
823 class_inst = mono_metadata_inflate_generic_inst (context->class_inst, inflate_with, error);
824 if (!mono_error_ok (error))
828 if (context->method_inst) {
829 method_inst = mono_metadata_inflate_generic_inst (context->method_inst, inflate_with, error);
830 if (!mono_error_ok (error))
834 res.class_inst = class_inst;
835 res.method_inst = method_inst;
841 * mono_class_inflate_generic_method:
842 * @method: a generic method
843 * @context: a generics context
845 * Instantiate the generic method @method using the generics context @context.
847 * Returns: the new instantiated method
850 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
852 return mono_class_inflate_generic_method_full (method, NULL, context);
856 * mono_class_inflate_generic_method_full:
858 * Instantiate method @method with the generic context @context.
859 * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
860 * Use mono_method_signature () and mono_method_get_header () to get the correct values.
863 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
866 MonoMethod *res = mono_class_inflate_generic_method_full_checked (method, klass_hint, context, &error);
867 if (!mono_error_ok (&error))
868 /*FIXME do proper error handling - on this case, kill this function. */
869 g_error ("Could not inflate generic method due to %s", mono_error_get_message (&error));
875 * mono_class_inflate_generic_method_full_checked:
876 * Same as mono_class_inflate_generic_method_full but return failure using @error.
879 mono_class_inflate_generic_method_full_checked (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context, MonoError *error)
882 MonoMethodInflated *iresult, *cached;
883 MonoMethodSignature *sig;
884 MonoGenericContext tmp_context;
885 gboolean is_mb_open = FALSE;
887 mono_error_init (error);
889 /* The `method' has already been instantiated before => we need to peel out the instantiation and create a new context */
890 while (method->is_inflated) {
891 MonoGenericContext *method_context = mono_method_get_context (method);
892 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
894 tmp_context = inflate_generic_context (method_context, context, error);
895 if (!mono_error_ok (error))
897 context = &tmp_context;
899 if (mono_metadata_generic_context_equal (method_context, context))
902 method = imethod->declaring;
906 * A method only needs to be inflated if the context has argument for which it is
909 * class Foo<T> { void Bar(); } - doesn't need to be inflated if only mvars' are supplied
910 * class Foo { void Bar<T> (); } - doesn't need to be if only vars' are supplied
913 if (!((method->is_generic && context->method_inst) ||
914 (method->klass->generic_container && context->class_inst)))
918 * The reason for this hack is to fix the behavior of inflating generic methods that come from a MethodBuilder.
919 * What happens is that instantiating a generic MethodBuilder with its own arguments should create a diferent object.
920 * This is opposite to the way non-SRE MethodInfos behave.
922 * This happens, for example, when we want to emit a recursive generic method. Given the following C# code:
924 * void Example<T> () {
928 * In Example, the method token must be encoded as: "void Example<!!0>()"
930 * The reference to the first generic argument, "!!0", must be explicit otherwise it won't be inflated
931 * properly. To get that we need to inflate the MethodBuilder with its own arguments.
933 * On the other hand, inflating a non-SRE generic method with its own arguments should
934 * return itself. For example:
936 * MethodInfo m = ... //m is a generic method definition
937 * MethodInfo res = m.MakeGenericMethod (m.GetGenericArguments ());
940 * To allow such scenarios we must allow inflation of MethodBuilder to happen in a diferent way than
941 * what happens with regular methods.
943 * There is one last touch to this madness, once a TypeBuilder is finished, IOW CreateType() is called,
944 * everything should behave like a regular type or method.
947 is_mb_open = method->is_generic &&
948 method->klass->image->dynamic && !method->klass->wastypebuilder && /* that is a MethodBuilder from an unfinished TypeBuilder */
949 context->method_inst == mono_method_get_generic_container (method)->context.method_inst; /* and it's been instantiated with its own arguments. */
951 iresult = g_new0 (MonoMethodInflated, 1);
952 iresult->context = *context;
953 iresult->declaring = method;
954 iresult->method.method.is_mb_open = is_mb_open;
956 if (!context->method_inst && method->is_generic)
957 iresult->context.method_inst = mono_method_get_generic_container (method)->context.method_inst;
959 if (!context->class_inst) {
960 g_assert (!iresult->declaring->klass->generic_class);
961 if (iresult->declaring->klass->generic_container)
962 iresult->context.class_inst = iresult->declaring->klass->generic_container->context.class_inst;
963 else if (iresult->declaring->klass->generic_class)
964 iresult->context.class_inst = iresult->declaring->klass->generic_class->context.class_inst;
968 cached = mono_method_inflated_lookup (iresult, FALSE);
970 mono_loader_unlock ();
972 return (MonoMethod*)cached;
975 mono_stats.inflated_method_count++;
977 inflated_methods_size += sizeof (MonoMethodInflated);
979 sig = mono_method_signature (method);
981 char *name = mono_type_get_full_name (method->klass);
982 mono_error_set_bad_image (error, method->klass->image, "Could not resolve signature of method %s:%s", name, method->name);
988 memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
990 memcpy (&iresult->method.method, method, sizeof (MonoMethod));
993 result = (MonoMethod *) iresult;
994 result->is_inflated = TRUE;
995 result->is_generic = FALSE;
996 result->sre_method = FALSE;
997 result->signature = NULL;
998 result->is_mb_open = is_mb_open;
1000 if (!context->method_inst) {
1001 /* Set the generic_container of the result to the generic_container of method */
1002 MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
1004 if (generic_container) {
1005 result->is_generic = 1;
1006 mono_method_set_generic_container (result, generic_container);
1010 if (!klass_hint || !klass_hint->generic_class ||
1011 klass_hint->generic_class->container_class != method->klass ||
1012 klass_hint->generic_class->context.class_inst != context->class_inst)
1015 if (method->klass->generic_container)
1016 result->klass = klass_hint;
1018 if (!result->klass) {
1019 MonoType *inflated = inflate_generic_type (NULL, &method->klass->byval_arg, context, error);
1020 if (!mono_error_ok (error))
1023 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
1025 mono_metadata_free_type (inflated);
1029 * FIXME: This should hold, but it doesn't:
1031 * if (result->is_inflated && mono_method_get_context (result)->method_inst &&
1032 * mono_method_get_context (result)->method_inst == mono_method_get_generic_container (((MonoMethodInflated*)result)->declaring)->context.method_inst) {
1033 * g_assert (result->is_generic);
1036 * Fixing this here causes other things to break, hence a very
1037 * ugly hack in mini-trampolines.c - see
1038 * is_generic_method_definition().
1041 mono_method_inflated_lookup (iresult, TRUE);
1042 mono_loader_unlock ();
1046 mono_loader_unlock ();
1052 * mono_get_inflated_method:
1054 * Obsolete. We keep it around since it's mentioned in the public API.
1057 mono_get_inflated_method (MonoMethod *method)
1063 * mono_method_get_context_general:
1065 * @uninflated: handle uninflated methods?
1067 * Returns the generic context of a method or NULL if it doesn't have
1068 * one. For an inflated method that's the context stored in the
1069 * method. Otherwise it's in the method's generic container or in the
1070 * generic container of the method's class.
1073 mono_method_get_context_general (MonoMethod *method, gboolean uninflated)
1075 if (method->is_inflated) {
1076 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1077 return &imethod->context;
1081 if (method->is_generic)
1082 return &(mono_method_get_generic_container (method)->context);
1083 if (method->klass->generic_container)
1084 return &method->klass->generic_container->context;
1089 * mono_method_get_context:
1092 * Returns the generic context for method if it's inflated, otherwise
1096 mono_method_get_context (MonoMethod *method)
1098 return mono_method_get_context_general (method, FALSE);
1102 * mono_method_get_generic_container:
1104 * Returns the generic container of METHOD, which should be a generic method definition.
1105 * Returns NULL if METHOD is not a generic method definition.
1106 * LOCKING: Acquires the loader lock.
1108 MonoGenericContainer*
1109 mono_method_get_generic_container (MonoMethod *method)
1111 MonoGenericContainer *container;
1113 if (!method->is_generic)
1116 container = mono_image_property_lookup (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER);
1117 g_assert (container);
1123 * mono_method_set_generic_container:
1125 * Sets the generic container of METHOD to CONTAINER.
1126 * LOCKING: Acquires the loader lock.
1129 mono_method_set_generic_container (MonoMethod *method, MonoGenericContainer* container)
1131 g_assert (method->is_generic);
1133 mono_image_property_insert (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER, container);
1137 * mono_class_find_enum_basetype:
1138 * @class: The enum class
1140 * Determine the basetype of an enum by iterating through its fields. We do this
1141 * in a separate function since it is cheaper than calling mono_class_setup_fields.
1144 mono_class_find_enum_basetype (MonoClass *class)
1146 MonoGenericContainer *container = NULL;
1147 MonoImage *m = class->image;
1148 const int top = class->field.count;
1151 g_assert (class->enumtype);
1153 if (class->generic_container)
1154 container = class->generic_container;
1155 else if (class->generic_class) {
1156 MonoClass *gklass = class->generic_class->container_class;
1158 container = gklass->generic_container;
1159 g_assert (container);
1163 * Fetch all the field information.
1165 for (i = 0; i < top; i++){
1167 guint32 cols [MONO_FIELD_SIZE];
1168 int idx = class->field.first + i;
1171 /* class->field.first and idx points into the fieldptr table */
1172 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1174 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC) //no need to decode static fields
1177 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL))
1180 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1181 mono_metadata_decode_value (sig, &sig);
1182 /* FIELD signature == 0x06 */
1186 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1189 if (class->generic_class) {
1190 //FIXME do we leak here?
1191 ftype = mono_class_inflate_generic_type (ftype, mono_class_get_context (class));
1192 ftype->attrs = cols [MONO_FIELD_FLAGS];
1202 * Checks for MonoClass::exception_type without resolving all MonoType's into MonoClass'es
1205 mono_type_has_exceptions (MonoType *type)
1207 switch (type->type) {
1208 case MONO_TYPE_CLASS:
1209 case MONO_TYPE_VALUETYPE:
1210 case MONO_TYPE_SZARRAY:
1211 return type->data.klass->exception_type;
1212 case MONO_TYPE_ARRAY:
1213 return type->data.array->eklass->exception_type;
1214 case MONO_TYPE_GENERICINST:
1215 return mono_generic_class_get_class (type->data.generic_class)->exception_type;
1223 * Allocate memory for some data belonging to CLASS, either from its image's mempool,
1227 mono_class_alloc (MonoClass *class, int size)
1229 if (class->generic_class)
1230 return mono_image_set_alloc (class->generic_class->owner, size);
1232 return mono_image_alloc (class->image, size);
1236 mono_class_alloc0 (MonoClass *class, int size)
1240 res = mono_class_alloc (class, size);
1241 memset (res, 0, size);
1245 #define mono_class_new0(class,struct_type, n_structs) \
1246 ((struct_type *) mono_class_alloc0 ((class), ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
1249 * mono_class_setup_basic_field_info:
1250 * @class: The class to initialize
1252 * Initializes the class->fields.
1253 * LOCKING: Assumes the loader lock is held.
1256 mono_class_setup_basic_field_info (MonoClass *class)
1258 MonoClassField *field;
1266 gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1267 image = class->image;
1268 top = class->field.count;
1270 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1272 * This happens when a generic instance of an unfinished generic typebuilder
1273 * is used as an element type for creating an array type. We can't initialize
1274 * the fields of this class using the fields of gklass, since gklass is not
1275 * finished yet, fields could be added to it later.
1281 mono_class_setup_basic_field_info (gtd);
1283 top = gtd->field.count;
1284 class->field.first = gtd->field.first;
1285 class->field.count = gtd->field.count;
1288 class->fields = mono_class_alloc0 (class, sizeof (MonoClassField) * top);
1291 * Fetch all the field information.
1293 for (i = 0; i < top; i++){
1294 field = &class->fields [i];
1295 field->parent = class;
1298 field->name = mono_field_get_name (>d->fields [i]);
1300 int idx = class->field.first + i;
1301 /* class->field.first and idx points into the fieldptr table */
1302 guint32 name_idx = mono_metadata_decode_table_row_col (image, MONO_TABLE_FIELD, idx, MONO_FIELD_NAME);
1303 /* The name is needed for fieldrefs */
1304 field->name = mono_metadata_string_heap (image, name_idx);
1310 * mono_class_setup_fields:
1311 * @class: The class to initialize
1313 * Initializes the class->fields.
1314 * LOCKING: Assumes the loader lock is held.
1317 mono_class_setup_fields (MonoClass *class)
1320 MonoImage *m = class->image;
1322 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1323 int i, blittable = TRUE;
1324 guint32 real_size = 0;
1325 guint32 packing_size = 0;
1326 gboolean explicit_size;
1327 MonoClassField *field;
1328 MonoGenericContainer *container = NULL;
1329 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1331 if (class->size_inited)
1334 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1336 * This happens when a generic instance of an unfinished generic typebuilder
1337 * is used as an element type for creating an array type. We can't initialize
1338 * the fields of this class using the fields of gklass, since gklass is not
1339 * finished yet, fields could be added to it later.
1344 mono_class_setup_basic_field_info (class);
1345 top = class->field.count;
1348 mono_class_setup_fields (gtd);
1349 if (gtd->exception_type) {
1350 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1355 class->instance_size = 0;
1357 class->sizes.class_size = 0;
1359 if (class->parent) {
1360 /* For generic instances, class->parent might not have been initialized */
1361 mono_class_init (class->parent);
1362 if (!class->parent->size_inited) {
1363 mono_class_setup_fields (class->parent);
1364 if (class->parent->exception_type) {
1365 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1369 class->instance_size += class->parent->instance_size;
1370 class->min_align = class->parent->min_align;
1371 /* we use |= since it may have been set already */
1372 class->has_references |= class->parent->has_references;
1373 blittable = class->parent->blittable;
1375 class->instance_size = sizeof (MonoObject);
1376 class->min_align = 1;
1379 /* We can't really enable 16 bytes alignment until the GC supports it.
1380 The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
1381 boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
1382 Bug #506144 is an example of this issue.
1384 if (class->simd_type)
1385 class->min_align = 16;
1387 /* Get the real size */
1388 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1390 if (explicit_size) {
1391 if ((packing_size & 0xfffffff0) != 0) {
1392 char *err_msg = g_strdup_printf ("Could not load struct '%s' with packing size %d >= 16", class->name, packing_size);
1393 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
1396 class->packing_size = packing_size;
1397 real_size += class->instance_size;
1401 if (explicit_size && real_size) {
1402 class->instance_size = MAX (real_size, class->instance_size);
1404 class->size_inited = 1;
1405 class->blittable = blittable;
1406 mono_memory_barrier ();
1407 class->fields_inited = 1;
1411 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1414 /* Prevent infinite loops if the class references itself */
1415 class->size_inited = 1;
1417 if (class->generic_container) {
1418 container = class->generic_container;
1420 container = gtd->generic_container;
1421 g_assert (container);
1425 * Fetch all the field information.
1427 for (i = 0; i < top; i++){
1428 int idx = class->field.first + i;
1429 field = &class->fields [i];
1431 field->parent = class;
1434 mono_field_resolve_type (field, &error);
1435 if (!mono_error_ok (&error)) {
1436 /*mono_field_resolve_type already failed class*/
1437 mono_error_cleanup (&error);
1441 g_error ("could not resolve %s:%s\n", mono_type_get_full_name(class), field->name);
1442 g_assert (field->type);
1445 if (mono_field_is_deleted (field))
1448 MonoClassField *gfield = >d->fields [i];
1449 field->offset = gfield->offset;
1451 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1453 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1454 field->offset = offset;
1456 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1457 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Missing field layout info for %s", field->name));
1460 if (field->offset < -1) { /*-1 is used to encode special static fields */
1461 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Invalid negative field offset %d for %s", field->offset, field->name));
1467 /* Only do these checks if we still think this type is blittable */
1468 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1469 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1472 MonoClass *field_class = mono_class_from_mono_type (field->type);
1474 mono_class_setup_fields (field_class);
1475 if (field_class->exception_type) {
1476 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1480 if (!field_class || !field_class->blittable)
1485 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1486 class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1487 blittable = class->element_class->blittable;
1490 if (mono_type_has_exceptions (field->type)) {
1491 char *class_name = mono_type_get_full_name (class);
1492 char *type_name = mono_type_full_name (field->type);
1494 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1495 g_warning ("Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
1496 g_free (class_name);
1500 /* The def_value of fields is compute lazily during vtable creation */
1503 if (class == mono_defaults.string_class)
1506 class->blittable = blittable;
1508 if (class->enumtype && !mono_class_enum_basetype (class)) {
1509 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1512 if (explicit_size && real_size) {
1513 class->instance_size = MAX (real_size, class->instance_size);
1516 if (class->exception_type)
1518 mono_class_layout_fields (class);
1520 /*valuetypes can't be neither bigger than 1Mb or empty. */
1521 if (class->valuetype && (class->instance_size <= 0 || class->instance_size > (0x100000 + sizeof (MonoObject))))
1522 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1524 mono_memory_barrier ();
1525 class->fields_inited = 1;
1529 * mono_class_setup_fields_locking:
1530 * @class: The class to initialize
1532 * Initializes the class->fields array of fields.
1533 * Aquires the loader lock.
1536 mono_class_setup_fields_locking (MonoClass *class)
1538 /* This can be checked without locks */
1539 if (class->fields_inited)
1541 mono_loader_lock ();
1542 mono_class_setup_fields (class);
1543 mono_loader_unlock ();
1547 * mono_class_has_references:
1549 * Returns whenever @klass->has_references is set, initializing it if needed.
1550 * Aquires the loader lock.
1553 mono_class_has_references (MonoClass *klass)
1555 if (klass->init_pending) {
1556 /* Be conservative */
1559 mono_class_init (klass);
1561 return klass->has_references;
1566 * mono_type_get_basic_type_from_generic:
1569 * Returns a closed type corresponding to the possibly open type
1573 mono_type_get_basic_type_from_generic (MonoType *type)
1575 /* When we do generic sharing we let type variables stand for reference types. */
1576 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1577 return &mono_defaults.object_class->byval_arg;
1582 * mono_class_layout_fields:
1585 * Compute the placement of fields inside an object or struct, according to
1586 * the layout rules and set the following fields in @class:
1587 * - has_references (if the class contains instance references firled or structs that contain references)
1588 * - has_static_refs (same, but for static fields)
1589 * - instance_size (size of the object in memory)
1590 * - class_size (size needed for the static fields)
1591 * - size_inited (flag set when the instance_size is set)
1593 * LOCKING: this is supposed to be called with the loader lock held.
1596 mono_class_layout_fields (MonoClass *class)
1599 const int top = class->field.count;
1600 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1601 guint32 pass, passes, real_size;
1602 gboolean gc_aware_layout = FALSE;
1603 MonoClassField *field;
1606 * When we do generic sharing we need to have layout
1607 * information for open generic classes (either with a generic
1608 * context containing type variables or with a generic
1609 * container), so we don't return in that case anymore.
1613 * Enable GC aware auto layout: in this mode, reference
1614 * fields are grouped together inside objects, increasing collector
1616 * Requires that all classes whose layout is known to native code be annotated
1617 * with [StructLayout (LayoutKind.Sequential)]
1618 * Value types have gc_aware_layout disabled by default, as per
1619 * what the default is for other runtimes.
1621 /* corlib is missing [StructLayout] directives in many places */
1622 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1623 if (class->byval_arg.type != MONO_TYPE_VALUETYPE)
1624 gc_aware_layout = TRUE;
1627 /* Compute klass->has_references */
1629 * Process non-static fields first, since static fields might recursively
1630 * refer to the class itself.
1632 for (i = 0; i < top; i++) {
1635 field = &class->fields [i];
1637 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1638 ftype = mono_type_get_underlying_type (field->type);
1639 ftype = mono_type_get_basic_type_from_generic (ftype);
1640 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1641 class->has_references = TRUE;
1645 for (i = 0; i < top; i++) {
1648 field = &class->fields [i];
1650 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1651 ftype = mono_type_get_underlying_type (field->type);
1652 ftype = mono_type_get_basic_type_from_generic (ftype);
1653 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1654 class->has_static_refs = TRUE;
1658 for (i = 0; i < top; i++) {
1661 field = &class->fields [i];
1663 ftype = mono_type_get_underlying_type (field->type);
1664 ftype = mono_type_get_basic_type_from_generic (ftype);
1665 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1666 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1667 class->has_static_refs = TRUE;
1669 class->has_references = TRUE;
1674 * Compute field layout and total size (not considering static fields)
1678 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1679 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1681 if (gc_aware_layout)
1686 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1689 if (class->parent) {
1690 mono_class_setup_fields (class->parent);
1691 if (class->parent->exception_type) {
1692 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1695 real_size = class->parent->instance_size;
1697 real_size = sizeof (MonoObject);
1700 for (pass = 0; pass < passes; ++pass) {
1701 for (i = 0; i < top; i++){
1706 field = &class->fields [i];
1708 if (mono_field_is_deleted (field))
1710 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1713 ftype = mono_type_get_underlying_type (field->type);
1714 ftype = mono_type_get_basic_type_from_generic (ftype);
1715 if (gc_aware_layout) {
1716 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1725 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1726 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1727 /* This field is a hack inserted by MCS to empty structures */
1731 size = mono_type_size (field->type, &align);
1733 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1734 align = class->packing_size ? MIN (class->packing_size, align): align;
1735 /* if the field has managed references, we need to force-align it
1738 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1739 align = MAX (align, sizeof (gpointer));
1741 class->min_align = MAX (align, class->min_align);
1742 field->offset = real_size;
1744 field->offset += align - 1;
1745 field->offset &= ~(align - 1);
1747 /*TypeBuilders produce all sort of weird things*/
1748 g_assert (class->image->dynamic || field->offset > 0);
1749 real_size = field->offset + size;
1752 class->instance_size = MAX (real_size, class->instance_size);
1754 if (class->instance_size & (class->min_align - 1)) {
1755 class->instance_size += class->min_align - 1;
1756 class->instance_size &= ~(class->min_align - 1);
1760 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1762 for (i = 0; i < top; i++) {
1767 field = &class->fields [i];
1770 * There must be info about all the fields in a type if it
1771 * uses explicit layout.
1774 if (mono_field_is_deleted (field))
1776 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1779 size = mono_type_size (field->type, &align);
1780 class->min_align = MAX (align, class->min_align);
1783 * When we get here, field->offset is already set by the
1784 * loader (for either runtime fields or fields loaded from metadata).
1785 * The offset is from the start of the object: this works for both
1786 * classes and valuetypes.
1788 field->offset += sizeof (MonoObject);
1789 ftype = mono_type_get_underlying_type (field->type);
1790 ftype = mono_type_get_basic_type_from_generic (ftype);
1791 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1792 if (field->offset % sizeof (gpointer)) {
1793 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1800 real_size = MAX (real_size, size + field->offset);
1802 class->instance_size = MAX (real_size, class->instance_size);
1806 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1808 * For small structs, set min_align to at least the struct size to improve
1809 * performance, and since the JIT memset/memcpy code assumes this and generates
1810 * unaligned accesses otherwise. See #78990 for a testcase.
1812 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1813 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1816 class->size_inited = 1;
1819 * Compute static field layout and size
1821 for (i = 0; i < top; i++){
1825 field = &class->fields [i];
1827 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1829 if (mono_field_is_deleted (field))
1832 if (mono_type_has_exceptions (field->type)) {
1833 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1837 size = mono_type_size (field->type, &align);
1838 field->offset = class->sizes.class_size;
1839 /*align is always non-zero here*/
1840 field->offset += align - 1;
1841 field->offset &= ~(align - 1);
1842 class->sizes.class_size = field->offset + size;
1847 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1851 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1852 method->klass = class;
1853 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1854 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1855 method->signature = sig;
1856 method->name = name;
1859 if (name [0] == '.') {
1860 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1862 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1868 * mono_class_setup_methods:
1871 * Initializes the 'methods' array in the klass.
1872 * Calling this method should be avoided if possible since it allocates a lot
1873 * of long-living MonoMethod structures.
1874 * Methods belonging to an interface are assigned a sequential slot starting
1877 * On failure this function sets class->exception_type
1880 mono_class_setup_methods (MonoClass *class)
1883 MonoMethod **methods;
1888 mono_loader_lock ();
1890 if (class->methods) {
1891 mono_loader_unlock ();
1895 if (class->generic_class) {
1897 MonoClass *gklass = class->generic_class->container_class;
1899 mono_class_init (gklass);
1900 if (!gklass->exception_type)
1901 mono_class_setup_methods (gklass);
1902 if (gklass->exception_type) {
1903 /*FIXME make exception_data less opaque so it's possible to dup it here*/
1904 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
1905 mono_loader_unlock ();
1909 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1910 class->method.count = gklass->method.count;
1911 methods = mono_class_alloc0 (class, sizeof (MonoMethod*) * (class->method.count + 1));
1913 for (i = 0; i < class->method.count; i++) {
1914 methods [i] = mono_class_inflate_generic_method_full_checked (
1915 gklass->methods [i], class, mono_class_get_context (class), &error);
1916 if (!mono_error_ok (&error)) {
1917 char *method = mono_method_full_name (gklass->methods [i], TRUE);
1918 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Could not inflate method %s due to %s", method, mono_error_get_message (&error)));
1921 mono_error_cleanup (&error);
1922 mono_loader_unlock ();
1926 } else if (class->rank) {
1928 MonoMethod *amethod;
1929 MonoMethodSignature *sig;
1930 int count_generic = 0, first_generic = 0;
1933 class->method.count = 3 + (class->rank > 1? 2: 1);
1935 mono_class_setup_interfaces (class, &error);
1936 g_assert (mono_error_ok (&error)); /*FIXME can this fail for array types?*/
1938 if (class->interface_count) {
1939 count_generic = generic_array_methods (class);
1940 first_generic = class->method.count;
1941 class->method.count += class->interface_count * count_generic;
1944 methods = mono_class_alloc0 (class, sizeof (MonoMethod*) * class->method.count);
1946 sig = mono_metadata_signature_alloc (class->image, class->rank);
1947 sig->ret = &mono_defaults.void_class->byval_arg;
1948 sig->pinvoke = TRUE;
1949 sig->hasthis = TRUE;
1950 for (i = 0; i < class->rank; ++i)
1951 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1953 amethod = create_array_method (class, ".ctor", sig);
1954 methods [method_num++] = amethod;
1955 if (class->rank > 1) {
1956 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1957 sig->ret = &mono_defaults.void_class->byval_arg;
1958 sig->pinvoke = TRUE;
1959 sig->hasthis = TRUE;
1960 for (i = 0; i < class->rank * 2; ++i)
1961 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1963 amethod = create_array_method (class, ".ctor", sig);
1964 methods [method_num++] = amethod;
1966 /* element Get (idx11, [idx2, ...]) */
1967 sig = mono_metadata_signature_alloc (class->image, class->rank);
1968 sig->ret = &class->element_class->byval_arg;
1969 sig->pinvoke = TRUE;
1970 sig->hasthis = TRUE;
1971 for (i = 0; i < class->rank; ++i)
1972 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1973 amethod = create_array_method (class, "Get", sig);
1974 methods [method_num++] = amethod;
1975 /* element& Address (idx11, [idx2, ...]) */
1976 sig = mono_metadata_signature_alloc (class->image, class->rank);
1977 sig->ret = &class->element_class->this_arg;
1978 sig->pinvoke = TRUE;
1979 sig->hasthis = TRUE;
1980 for (i = 0; i < class->rank; ++i)
1981 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1982 amethod = create_array_method (class, "Address", sig);
1983 methods [method_num++] = amethod;
1984 /* void Set (idx11, [idx2, ...], element) */
1985 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1986 sig->ret = &mono_defaults.void_class->byval_arg;
1987 sig->pinvoke = TRUE;
1988 sig->hasthis = TRUE;
1989 for (i = 0; i < class->rank; ++i)
1990 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1991 sig->params [i] = &class->element_class->byval_arg;
1992 amethod = create_array_method (class, "Set", sig);
1993 methods [method_num++] = amethod;
1995 for (i = 0; i < class->interface_count; i++)
1996 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1998 methods = mono_class_alloc (class, sizeof (MonoMethod*) * class->method.count);
1999 for (i = 0; i < class->method.count; ++i) {
2000 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
2001 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
2005 if (MONO_CLASS_IS_INTERFACE (class)) {
2007 /*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
2008 for (i = 0; i < class->method.count; ++i) {
2009 if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
2010 methods [i]->slot = slot++;
2014 /* Needed because of the double-checking locking pattern */
2015 mono_memory_barrier ();
2017 class->methods = methods;
2019 if (mono_debugger_class_loaded_methods_func)
2020 mono_debugger_class_loaded_methods_func (class);
2022 mono_loader_unlock ();
2026 * mono_class_get_method_by_index:
2028 * Returns class->methods [index], initializing class->methods if neccesary.
2030 * LOCKING: Acquires the loader lock.
2033 mono_class_get_method_by_index (MonoClass *class, int index)
2035 /* Avoid calling setup_methods () if possible */
2036 if (class->generic_class && !class->methods) {
2037 MonoClass *gklass = class->generic_class->container_class;
2040 m = mono_class_inflate_generic_method_full (
2041 gklass->methods [index], class, mono_class_get_context (class));
2043 * If setup_methods () is called later for this class, no duplicates are created,
2044 * since inflate_generic_method guarantees that only one instance of a method
2045 * is created for each context.
2048 mono_class_setup_methods (class);
2049 g_assert (m == class->methods [index]);
2053 mono_class_setup_methods (class);
2054 if (class->exception_type) /*FIXME do proper error handling*/
2056 g_assert (index >= 0 && index < class->method.count);
2057 return class->methods [index];
2062 * mono_class_get_inflated_method:
2064 * Given an inflated class CLASS and a method METHOD which should be a method of
2065 * CLASS's generic definition, return the inflated method corresponding to METHOD.
2068 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
2070 MonoClass *gklass = class->generic_class->container_class;
2073 g_assert (method->klass == gklass);
2075 mono_class_setup_methods (gklass);
2076 g_assert (!gklass->exception_type); /*FIXME do proper error handling*/
2078 for (i = 0; i < gklass->method.count; ++i) {
2079 if (gklass->methods [i] == method) {
2081 return class->methods [i];
2083 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
2091 * mono_class_get_vtable_entry:
2093 * Returns class->vtable [offset], computing it if neccesary. Returns NULL on failure.
2094 * LOCKING: Acquires the loader lock.
2097 mono_class_get_vtable_entry (MonoClass *class, int offset)
2101 if (class->rank == 1) {
2103 * szarrays do not overwrite any methods of Array, so we can avoid
2104 * initializing their vtables in some cases.
2106 mono_class_setup_vtable (class->parent);
2107 if (offset < class->parent->vtable_size)
2108 return class->parent->vtable [offset];
2111 if (class->generic_class) {
2112 MonoClass *gklass = class->generic_class->container_class;
2113 mono_class_setup_vtable (gklass);
2114 m = gklass->vtable [offset];
2116 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
2118 mono_class_setup_vtable (class);
2119 if (class->exception_type)
2121 m = class->vtable [offset];
2128 * mono_class_get_vtable_size:
2130 * Return the vtable size for KLASS.
2133 mono_class_get_vtable_size (MonoClass *klass)
2135 mono_class_setup_vtable (klass);
2137 return klass->vtable_size;
2140 /*This method can fail the class.*/
2142 mono_class_setup_properties (MonoClass *class)
2144 guint startm, endm, i, j;
2145 guint32 cols [MONO_PROPERTY_SIZE];
2146 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2147 MonoProperty *properties;
2150 if (class->ext && class->ext->properties)
2153 mono_loader_lock ();
2155 if (class->ext && class->ext->properties) {
2156 mono_loader_unlock ();
2160 mono_class_alloc_ext (class);
2162 if (class->generic_class) {
2163 MonoClass *gklass = class->generic_class->container_class;
2165 mono_class_init (gklass);
2166 mono_class_setup_properties (gklass);
2167 if (gklass->exception_type) {
2168 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2169 mono_loader_unlock ();
2173 class->ext->property = gklass->ext->property;
2175 properties = mono_class_new0 (class, MonoProperty, class->ext->property.count + 1);
2177 for (i = 0; i < class->ext->property.count; i++) {
2178 MonoProperty *prop = &properties [i];
2180 *prop = gklass->ext->properties [i];
2183 prop->get = mono_class_inflate_generic_method_full (
2184 prop->get, class, mono_class_get_context (class));
2186 prop->set = mono_class_inflate_generic_method_full (
2187 prop->set, class, mono_class_get_context (class));
2189 prop->parent = class;
2192 int first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2193 int count = last - first;
2196 mono_class_setup_methods (class);
2197 if (class->exception_type) {
2198 mono_loader_unlock ();
2203 class->ext->property.first = first;
2204 class->ext->property.count = count;
2205 properties = mono_class_alloc0 (class, sizeof (MonoProperty) * count);
2206 for (i = first; i < last; ++i) {
2207 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
2208 properties [i - first].parent = class;
2209 properties [i - first].attrs = cols [MONO_PROPERTY_FLAGS];
2210 properties [i - first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
2212 startm = mono_metadata_methods_from_property (class->image, i, &endm);
2213 for (j = startm; j < endm; ++j) {
2216 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2218 if (class->image->uncompressed_metadata)
2219 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2220 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2222 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2224 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2225 case METHOD_SEMANTIC_SETTER:
2226 properties [i - first].set = method;
2228 case METHOD_SEMANTIC_GETTER:
2229 properties [i - first].get = method;
2237 /*Flush any pending writes as we do double checked locking on class->properties */
2238 mono_memory_barrier ();
2240 /* Leave this assignment as the last op in the function */
2241 class->ext->properties = properties;
2243 mono_loader_unlock ();
2247 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
2249 MonoMethod **om, **retval;
2252 for (om = methods, count = 0; *om; ++om, ++count)
2255 retval = g_new0 (MonoMethod*, count + 1);
2257 for (om = methods, count = 0; *om; ++om, ++count)
2258 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
2263 /*This method can fail the class.*/
2265 mono_class_setup_events (MonoClass *class)
2268 guint startm, endm, i, j;
2269 guint32 cols [MONO_EVENT_SIZE];
2270 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2274 if (class->ext && class->ext->events)
2277 mono_loader_lock ();
2279 if (class->ext && class->ext->events) {
2280 mono_loader_unlock ();
2284 mono_class_alloc_ext (class);
2286 if (class->generic_class) {
2287 MonoClass *gklass = class->generic_class->container_class;
2288 MonoGenericContext *context;
2290 mono_class_setup_events (gklass);
2291 if (gklass->exception_type) {
2292 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2293 mono_loader_unlock ();
2297 class->ext->event = gklass->ext->event;
2298 class->ext->events = mono_class_new0 (class, MonoEvent, class->ext->event.count);
2300 if (class->ext->event.count)
2301 context = mono_class_get_context (class);
2303 for (i = 0; i < class->ext->event.count; i++) {
2304 MonoEvent *event = &class->ext->events [i];
2305 MonoEvent *gevent = &gklass->ext->events [i];
2307 event->parent = class;
2308 event->name = gevent->name;
2309 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
2310 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
2311 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
2312 #ifndef MONO_SMALL_CONFIG
2313 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
2315 event->attrs = gevent->attrs;
2318 mono_loader_unlock ();
2322 first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2323 count = last - first;
2326 mono_class_setup_methods (class);
2327 if (class->exception_type) {
2328 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2329 mono_loader_unlock ();
2333 class->ext->event.first = first;
2334 class->ext->event.count = count;
2335 events = mono_class_alloc0 (class, sizeof (MonoEvent) * class->ext->event.count);
2336 for (i = first; i < last; ++i) {
2337 MonoEvent *event = &events [i - first];
2339 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
2340 event->parent = class;
2341 event->attrs = cols [MONO_EVENT_FLAGS];
2342 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
2344 startm = mono_metadata_methods_from_event (class->image, i, &endm);
2345 for (j = startm; j < endm; ++j) {
2348 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2350 if (class->image->uncompressed_metadata)
2351 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2352 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2354 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2356 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2357 case METHOD_SEMANTIC_ADD_ON:
2358 event->add = method;
2360 case METHOD_SEMANTIC_REMOVE_ON:
2361 event->remove = method;
2363 case METHOD_SEMANTIC_FIRE:
2364 event->raise = method;
2366 case METHOD_SEMANTIC_OTHER: {
2367 #ifndef MONO_SMALL_CONFIG
2370 if (event->other == NULL) {
2371 event->other = g_new0 (MonoMethod*, 2);
2373 while (event->other [n])
2375 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
2377 event->other [n] = method;
2378 /* NULL terminated */
2379 event->other [n + 1] = NULL;
2388 /*Flush any pending writes as we do double checked locking on class->properties */
2389 mono_memory_barrier ();
2391 /* Leave this assignment as the last op in the function */
2392 class->ext->events = events;
2394 mono_loader_unlock ();
2398 * Global pool of interface IDs, represented as a bitset.
2399 * LOCKING: this is supposed to be accessed with the loader lock held.
2401 static MonoBitSet *global_interface_bitset = NULL;
2404 * mono_unload_interface_ids:
2405 * @bitset: bit set of interface IDs
2407 * When an image is unloaded, the interface IDs associated with
2408 * the image are put back in the global pool of IDs so the numbers
2412 mono_unload_interface_ids (MonoBitSet *bitset)
2414 mono_loader_lock ();
2415 mono_bitset_sub (global_interface_bitset, bitset);
2416 mono_loader_unlock ();
2420 mono_unload_interface_id (MonoClass *class)
2422 if (global_interface_bitset && class->interface_id) {
2423 mono_loader_lock ();
2424 mono_bitset_clear (global_interface_bitset, class->interface_id);
2425 mono_loader_unlock ();
2430 * mono_get_unique_iid:
2433 * Assign a unique integer ID to the interface represented by @class.
2434 * The ID will positive and as small as possible.
2435 * LOCKING: this is supposed to be called with the loader lock held.
2436 * Returns: the new ID.
2439 mono_get_unique_iid (MonoClass *class)
2443 g_assert (MONO_CLASS_IS_INTERFACE (class));
2445 if (!global_interface_bitset) {
2446 global_interface_bitset = mono_bitset_new (128, 0);
2449 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2451 int old_size = mono_bitset_size (global_interface_bitset);
2452 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2453 mono_bitset_free (global_interface_bitset);
2454 global_interface_bitset = new_set;
2457 mono_bitset_set (global_interface_bitset, iid);
2458 /* set the bit also in the per-image set */
2459 if (!class->generic_class) {
2460 if (class->image->interface_bitset) {
2461 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2462 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2463 mono_bitset_free (class->image->interface_bitset);
2464 class->image->interface_bitset = new_set;
2467 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2469 mono_bitset_set (class->image->interface_bitset, iid);
2472 #ifndef MONO_SMALL_CONFIG
2473 if (mono_print_vtable) {
2475 char *type_name = mono_type_full_name (&class->byval_arg);
2476 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2477 generic_id = class->generic_class->context.class_inst->id;
2478 g_assert (generic_id != 0);
2482 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2487 g_assert (iid <= 65535);
2492 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res, MonoError *error)
2497 mono_class_setup_interfaces (klass, error);
2498 if (!mono_error_ok (error))
2501 for (i = 0; i < klass->interface_count; i++) {
2502 ic = klass->interfaces [i];
2505 *res = g_ptr_array_new ();
2506 g_ptr_array_add (*res, ic);
2507 mono_class_init (ic);
2508 if (ic->exception_type) {
2509 mono_error_set_type_load_class (error, ic, "Error Loading class");
2513 collect_implemented_interfaces_aux (ic, res, error);
2514 if (!mono_error_ok (error))
2520 mono_class_get_implemented_interfaces (MonoClass *klass, MonoError *error)
2522 GPtrArray *res = NULL;
2524 collect_implemented_interfaces_aux (klass, &res, error);
2525 if (!mono_error_ok (error)) {
2527 g_ptr_array_free (res, TRUE);
2534 compare_interface_ids (const void *p_key, const void *p_element) {
2535 const MonoClass *key = p_key;
2536 const MonoClass *element = *(MonoClass**) p_element;
2538 return (key->interface_id - element->interface_id);
2541 /*FIXME verify all callers if they should switch to mono_class_interface_offset_with_variance*/
2543 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2544 MonoClass **result = bsearch (
2546 klass->interfaces_packed,
2547 klass->interface_offsets_count,
2548 sizeof (MonoClass *),
2549 compare_interface_ids);
2551 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2558 * mono_class_interface_offset_with_variance:
2560 * Return the interface offset of @itf in @klass. Sets @non_exact_match to TRUE if the match required variance check
2561 * If @itf is an interface with generic variant arguments, try to find the compatible one.
2563 * Note that this function is responsible for resolving ambiguities. Right now we use whatever ordering interfaces_packed gives us.
2565 * FIXME figure out MS disambiguation rules and fix this function.
2568 mono_class_interface_offset_with_variance (MonoClass *klass, MonoClass *itf, gboolean *non_exact_match) {
2569 int i = mono_class_interface_offset (klass, itf);
2570 *non_exact_match = FALSE;
2574 if (!mono_class_has_variant_generic_params (itf))
2577 for (i = 0; i < klass->interface_offsets_count; i++) {
2578 if (mono_class_is_variant_compatible (itf, klass->interfaces_packed [i], FALSE)) {
2579 *non_exact_match = TRUE;
2580 return klass->interface_offsets_packed [i];
2588 print_implemented_interfaces (MonoClass *klass) {
2591 GPtrArray *ifaces = NULL;
2593 int ancestor_level = 0;
2595 name = mono_type_get_full_name (klass);
2596 printf ("Packed interface table for class %s has size %d\n", name, klass->interface_offsets_count);
2599 for (i = 0; i < klass->interface_offsets_count; i++)
2600 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2601 klass->interfaces_packed [i]->interface_id,
2602 klass->interface_offsets_packed [i],
2603 klass->interfaces_packed [i]->method.count,
2604 klass->interfaces_packed [i]->name_space,
2605 klass->interfaces_packed [i]->name );
2606 printf ("Interface flags: ");
2607 for (i = 0; i <= klass->max_interface_id; i++)
2608 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2609 printf ("(%d,T)", i);
2611 printf ("(%d,F)", i);
2613 printf ("Dump interface flags:");
2614 #ifdef COMPRESSED_INTERFACE_BITMAP
2616 const uint8_t* p = klass->interface_bitmap;
2617 i = klass->max_interface_id;
2619 printf (" %d x 00 %02X", p [0], p [1]);
2625 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2626 printf (" %02X", klass->interface_bitmap [i]);
2629 while (klass != NULL) {
2630 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2631 ifaces = mono_class_get_implemented_interfaces (klass, &error);
2632 if (!mono_error_ok (&error)) {
2633 printf (" Type failed due to %s\n", mono_error_get_message (&error));
2634 mono_error_cleanup (&error);
2635 } else if (ifaces) {
2636 for (i = 0; i < ifaces->len; i++) {
2637 MonoClass *ic = g_ptr_array_index (ifaces, i);
2638 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2639 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2641 mono_class_interface_offset (klass, ic),
2646 g_ptr_array_free (ifaces, TRUE);
2649 klass = klass->parent;
2654 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2657 args [0] = &arg0->byval_arg;
2659 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2663 array_class_get_if_rank (MonoClass *class, guint rank)
2665 return rank ? mono_array_class_get (class, rank) : class;
2669 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2671 valuetype_types [0] = eclass;
2672 if (eclass == mono_defaults.int16_class)
2673 valuetype_types [1] = mono_defaults.uint16_class;
2674 else if (eclass == mono_defaults.uint16_class)
2675 valuetype_types [1] = mono_defaults.int16_class;
2676 else if (eclass == mono_defaults.int32_class)
2677 valuetype_types [1] = mono_defaults.uint32_class;
2678 else if (eclass == mono_defaults.uint32_class)
2679 valuetype_types [1] = mono_defaults.int32_class;
2680 else if (eclass == mono_defaults.int64_class)
2681 valuetype_types [1] = mono_defaults.uint64_class;
2682 else if (eclass == mono_defaults.uint64_class)
2683 valuetype_types [1] = mono_defaults.int64_class;
2684 else if (eclass == mono_defaults.byte_class)
2685 valuetype_types [1] = mono_defaults.sbyte_class;
2686 else if (eclass == mono_defaults.sbyte_class)
2687 valuetype_types [1] = mono_defaults.byte_class;
2688 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2689 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2692 /* this won't be needed once bug #325495 is completely fixed
2693 * though we'll need something similar to know which interfaces to allow
2694 * in arrays when they'll be lazyly created
2696 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2697 * MS returns diferrent types based on which instance is called. For example:
2698 * object obj = new byte[10][];
2699 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2700 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2703 * Fixing this should kill quite some code, save some bits and improve compatibility.
2706 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2708 MonoClass *eclass = class->element_class;
2709 static MonoClass* generic_icollection_class = NULL;
2710 static MonoClass* generic_ienumerable_class = NULL;
2711 static MonoClass* generic_ienumerator_class = NULL;
2712 MonoClass *valuetype_types[2] = { NULL, NULL };
2713 MonoClass **interfaces = NULL;
2714 int i, interface_count, real_count, original_rank;
2716 gboolean internal_enumerator;
2717 gboolean eclass_is_valuetype;
2719 if (!mono_defaults.generic_ilist_class) {
2723 internal_enumerator = FALSE;
2724 eclass_is_valuetype = FALSE;
2725 original_rank = eclass->rank;
2726 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2727 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2729 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2731 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2732 original_rank = eclass->rank;
2734 eclass = eclass->element_class;
2735 internal_enumerator = TRUE;
2736 *is_enumerator = TRUE;
2744 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2745 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2747 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2749 if (!generic_icollection_class) {
2750 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2751 "System.Collections.Generic", "ICollection`1");
2752 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2753 "System.Collections.Generic", "IEnumerable`1");
2754 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2755 "System.Collections.Generic", "IEnumerator`1");
2758 mono_class_init (eclass);
2761 * Arrays in 2.0 need to implement a number of generic interfaces
2762 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2763 * on the element class). We collect the types needed to build the
2764 * instantiations in interfaces at intervals of 3, because 3 are
2765 * the generic interfaces needed to implement.
2767 if (eclass->valuetype) {
2768 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2770 /* IList, ICollection, IEnumerable */
2771 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2772 if (internal_enumerator) {
2774 if (valuetype_types [1])
2778 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2779 interfaces [0] = valuetype_types [0];
2780 if (valuetype_types [1])
2781 interfaces [3] = valuetype_types [1];
2783 eclass_is_valuetype = TRUE;
2786 int idepth = eclass->idepth;
2787 if (!internal_enumerator)
2790 // FIXME: This doesn't seem to work/required for generic params
2791 if (!(eclass->this_arg.type == MONO_TYPE_VAR || eclass->this_arg.type == MONO_TYPE_MVAR || (eclass->image->dynamic && !eclass->wastypebuilder)))
2792 mono_class_setup_interface_offsets (eclass);
2794 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2795 /* we add object for interfaces and the supertypes for the other
2796 * types. The last of the supertypes is the element class itself which we
2797 * already created the explicit interfaces for (so we include it for IEnumerator
2798 * and exclude it for arrays).
2800 if (MONO_CLASS_IS_INTERFACE (eclass))
2803 interface_count += idepth;
2804 if (eclass->rank && eclass->element_class->valuetype) {
2805 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2806 if (valuetype_types [1])
2809 /* IList, ICollection, IEnumerable */
2810 interface_count *= 3;
2811 real_count = interface_count;
2812 if (internal_enumerator) {
2813 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2814 if (valuetype_types [1])
2817 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2818 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2819 interfaces [0] = mono_defaults.object_class;
2823 for (i = 0; i < idepth; i++) {
2824 mono_class_init (eclass->supertypes [i]);
2825 interfaces [j] = eclass->supertypes [i];
2829 if (all_interfaces) {
2830 for (i = 0; i < eclass->interface_offsets_count; i++) {
2831 interfaces [j] = eclass->interfaces_packed [i];
2835 for (i = 0; i < eclass->interface_count; i++) {
2836 interfaces [j] = eclass->interfaces [i];
2840 if (valuetype_types [1]) {
2841 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2846 /* instantiate the generic interfaces */
2847 for (i = 0; i < interface_count; i += 3) {
2848 MonoClass *iface = interfaces [i];
2850 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2851 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2852 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2854 if (internal_enumerator) {
2856 /* instantiate IEnumerator<iface> */
2857 for (i = 0; i < interface_count; i++) {
2858 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2860 j = interface_count;
2861 if (!eclass_is_valuetype) {
2862 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2863 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2866 for (i = 0; i < eclass->idepth; i++) {
2867 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2871 for (i = 0; i < eclass->interface_offsets_count; i++) {
2872 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2876 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2878 if (valuetype_types [1])
2879 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2883 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2884 for (i = 0; i < real_count; ++i) {
2885 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2886 g_print ("%s implements %s\n", type_name, name);
2897 find_array_interface (MonoClass *klass, const char *name)
2900 for (i = 0; i < klass->interface_count; ++i) {
2901 if (strcmp (klass->interfaces [i]->name, name) == 0)
2908 * Return the number of virtual methods.
2909 * Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
2910 * Return -1 on failure.
2911 * FIXME It would be nice if this information could be cached somewhere.
2914 count_virtual_methods (MonoClass *class)
2918 class = mono_class_get_generic_type_definition (class); /*We can find this information by looking at the GTD*/
2920 if (class->methods || !MONO_CLASS_HAS_STATIC_METADATA (class)) {
2921 mono_class_setup_methods (class);
2922 if (class->exception_type)
2925 for (i = 0; i < class->method.count; ++i) {
2926 flags = class->methods [i]->flags;
2927 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2931 for (i = 0; i < class->method.count; ++i) {
2932 flags = mono_metadata_decode_table_row_col (class->image, MONO_TABLE_METHOD, class->method.first + i, MONO_METHOD_FLAGS);
2934 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2942 find_interface (int num_ifaces, MonoClass **interfaces_full, MonoClass *ic)
2950 m = (l + num_ifaces) / 2;
2951 if (interfaces_full [m] == ic)
2953 if (l == num_ifaces)
2955 if (!interfaces_full [m] || interfaces_full [m]->interface_id > ic->interface_id) {
2964 find_interface_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic)
2966 int i = find_interface (num_ifaces, interfaces_full, ic);
2968 return interface_offsets_full [i];
2973 set_interface_and_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic, int offset, mono_bool force_set)
2975 int i = find_interface (num_ifaces, interfaces_full, ic);
2979 interface_offsets_full [i] = offset;
2982 for (i = 0; i < num_ifaces; ++i) {
2983 if (interfaces_full [i]) {
2985 if (interfaces_full [i]->interface_id < ic->interface_id)
2988 while (end < num_ifaces && interfaces_full [end]) end++;
2989 memmove (interfaces_full + i + 1, interfaces_full + i, sizeof (MonoClass*) * (end - i));
2990 memmove (interface_offsets_full + i + 1, interface_offsets_full + i, sizeof (int) * (end - i));
2992 interfaces_full [i] = ic;
2993 interface_offsets_full [i] = offset;
2999 #ifdef COMPRESSED_INTERFACE_BITMAP
3002 * Compressed interface bitmap design.
3004 * Interface bitmaps take a large amount of memory, because their size is
3005 * linear with the maximum interface id assigned in the process (each interface
3006 * is assigned a unique id as it is loaded). The number of interface classes
3007 * is high because of the many implicit interfaces implemented by arrays (we'll
3008 * need to lazy-load them in the future).
3009 * Most classes implement a very small number of interfaces, so the bitmap is
3010 * sparse. This bitmap needs to be checked by interface casts, so access to the
3011 * needed bit must be fast and doable with few jit instructions.
3013 * The current compression format is as follows:
3014 * *) it is a sequence of one or more two-byte elements
3015 * *) the first byte in the element is the count of empty bitmap bytes
3016 * at the current bitmap position
3017 * *) the second byte in the element is an actual bitmap byte at the current
3020 * As an example, the following compressed bitmap bytes:
3021 * 0x07 0x01 0x00 0x7
3022 * correspond to the following bitmap:
3023 * 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x07
3025 * Each two-byte element can represent up to 2048 bitmap bits, but as few as a single
3026 * bitmap byte for non-sparse sequences. In practice the interface bitmaps created
3027 * during a gmcs bootstrap are reduced to less tha 5% of the original size.
3031 * mono_compress_bitmap:
3032 * @dest: destination buffer
3033 * @bitmap: bitmap buffer
3034 * @size: size of @bitmap in bytes
3036 * This is a mono internal function.
3037 * The @bitmap data is compressed into a format that is small but
3038 * still searchable in few instructions by the JIT and runtime.
3039 * The compressed data is stored in the buffer pointed to by the
3040 * @dest array. Passing a #NULL value for @dest allows to just compute
3041 * the size of the buffer.
3042 * This compression algorithm assumes the bits set in the bitmap are
3043 * few and far between, like in interface bitmaps.
3044 * Returns: the size of the compressed bitmap in bytes.
3047 mono_compress_bitmap (uint8_t *dest, const uint8_t *bitmap, int size)
3051 const uint8_t *end = bitmap + size;
3052 while (bitmap < end) {
3053 if (*bitmap || numz == 255) {
3077 * mono_class_interface_match:
3078 * @bitmap: a compressed bitmap buffer
3079 * @id: the index to check in the bitmap
3081 * This is a mono internal function.
3082 * Checks if a bit is set in a compressed interface bitmap. @id must
3083 * be already checked for being smaller than the maximum id encoded in the
3086 * Returns: a non-zero value if bit @id is set in the bitmap @bitmap,
3090 mono_class_interface_match (const uint8_t *bitmap, int id)
3093 id -= bitmap [0] * 8;
3097 return bitmap [1] & (1 << id);
3106 * LOCKING: this is supposed to be called with the loader lock held.
3107 * Return -1 on failure and set exception_type
3110 setup_interface_offsets (MonoClass *class, int cur_slot, gboolean overwrite)
3114 int i, j, max_iid, num_ifaces;
3115 MonoClass **interfaces_full = NULL;
3116 int *interface_offsets_full = NULL;
3118 GPtrArray **ifaces_array = NULL;
3119 int interface_offsets_count;
3120 MonoClass **array_interfaces = NULL;
3121 int num_array_interfaces;
3122 int is_enumerator = FALSE;
3124 mono_class_setup_supertypes (class);
3126 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
3127 * implicit interfaces have the property that they are assigned the same slot in the
3128 * vtables for compatible interfaces
3130 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
3132 /* compute maximum number of slots and maximum interface id */
3134 num_ifaces = num_array_interfaces; /* this can include duplicated ones */
3135 ifaces_array = g_new0 (GPtrArray *, class->idepth);
3136 for (j = 0; j < class->idepth; j++) {
3137 k = class->supertypes [j];
3138 num_ifaces += k->interface_count;
3139 for (i = 0; i < k->interface_count; i++) {
3140 ic = k->interfaces [i];
3143 mono_class_init (ic);
3145 if (max_iid < ic->interface_id)
3146 max_iid = ic->interface_id;
3148 ifaces = mono_class_get_implemented_interfaces (k, &error);
3149 if (!mono_error_ok (&error)) {
3150 char *name = mono_type_get_full_name (k);
3151 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Error getting the interfaces of %s due to %s", name, mono_error_get_message (&error)));
3153 mono_error_cleanup (&error);
3158 num_ifaces += ifaces->len;
3159 for (i = 0; i < ifaces->len; ++i) {
3160 ic = g_ptr_array_index (ifaces, i);
3161 if (max_iid < ic->interface_id)
3162 max_iid = ic->interface_id;
3164 ifaces_array [j] = ifaces;
3168 for (i = 0; i < num_array_interfaces; ++i) {
3169 ic = array_interfaces [i];
3170 mono_class_init (ic);
3171 if (max_iid < ic->interface_id)
3172 max_iid = ic->interface_id;
3175 if (MONO_CLASS_IS_INTERFACE (class)) {
3177 if (max_iid < class->interface_id)
3178 max_iid = class->interface_id;
3180 class->max_interface_id = max_iid;
3181 /* compute vtable offset for interfaces */
3182 interfaces_full = g_malloc0 (sizeof (MonoClass*) * num_ifaces);
3183 interface_offsets_full = g_malloc (sizeof (int) * num_ifaces);
3185 for (i = 0; i < num_ifaces; i++) {
3186 interface_offsets_full [i] = -1;
3189 /* skip the current class */
3190 for (j = 0; j < class->idepth - 1; j++) {
3191 k = class->supertypes [j];
3192 ifaces = ifaces_array [j];
3195 for (i = 0; i < ifaces->len; ++i) {
3197 ic = g_ptr_array_index (ifaces, i);
3199 /*Force the sharing of interface offsets between parent and subtypes.*/
3200 io = mono_class_interface_offset (k, ic);
3202 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, io, TRUE);
3207 g_assert (class == class->supertypes [class->idepth - 1]);
3208 ifaces = ifaces_array [class->idepth - 1];
3210 for (i = 0; i < ifaces->len; ++i) {
3212 ic = g_ptr_array_index (ifaces, i);
3213 if (set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, cur_slot, FALSE))
3215 count = count_virtual_methods (ic);
3217 char *name = mono_type_get_full_name (ic);
3218 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Error calculating interface offset of %s", name));
3227 if (MONO_CLASS_IS_INTERFACE (class))
3228 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, class, cur_slot, TRUE);
3230 if (num_array_interfaces) {
3231 if (is_enumerator) {
3232 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
3233 int ienumerator_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ienumerator_idx]);
3234 g_assert (ienumerator_offset >= 0);
3235 for (i = 0; i < num_array_interfaces; ++i) {
3236 ic = array_interfaces [i];
3237 if (strcmp (ic->name, "IEnumerator`1") == 0)
3238 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, ienumerator_offset, TRUE);
3240 g_assert_not_reached ();
3241 /*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);*/
3244 int ilist_offset, icollection_offset, ienumerable_offset;
3245 int ilist_iface_idx = find_array_interface (class, "IList`1");
3246 MonoClass* ilist_class = class->interfaces [ilist_iface_idx];
3247 int icollection_iface_idx = find_array_interface (ilist_class, "ICollection`1");
3248 int ienumerable_iface_idx = find_array_interface (ilist_class, "IEnumerable`1");
3249 ilist_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ilist_iface_idx]);
3250 icollection_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [icollection_iface_idx]);
3251 ienumerable_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [ienumerable_iface_idx]);
3252 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
3253 for (i = 0; i < num_array_interfaces; ++i) {
3255 ic = array_interfaces [i];
3256 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
3257 offset = ilist_offset;
3258 else if (strcmp (ic->name, "ICollection`1") == 0)
3259 offset = icollection_offset;
3260 else if (strcmp (ic->name, "IEnumerable`1") == 0)
3261 offset = ienumerable_offset;
3263 g_assert_not_reached ();
3264 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, offset, TRUE);
3265 /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, offset, class->interfaces [0]->name);*/
3270 for (interface_offsets_count = 0, i = 0; i < num_ifaces; i++) {
3271 if (interface_offsets_full [i] != -1) {
3272 interface_offsets_count ++;
3277 * We might get called multiple times:
3278 * - mono_class_init ()
3279 * - mono_class_setup_vtable ().
3280 * - mono_class_setup_interface_offsets ().
3281 * mono_class_setup_interface_offsets () passes 0 as CUR_SLOT, so the computed interface offsets will be invalid. This
3282 * means we have to overwrite those when called from other places (#4440).
3284 if (class->interfaces_packed && !overwrite) {
3285 g_assert (class->interface_offsets_count == interface_offsets_count);
3289 class->interface_offsets_count = interface_offsets_count;
3290 class->interfaces_packed = mono_class_alloc (class, sizeof (MonoClass*) * interface_offsets_count);
3291 class->interface_offsets_packed = mono_class_alloc (class, sizeof (guint16) * interface_offsets_count);
3292 bsize = (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0);
3293 #ifdef COMPRESSED_INTERFACE_BITMAP
3294 bitmap = g_malloc0 (bsize);
3296 bitmap = mono_class_alloc0 (class, bsize);
3298 for (i = 0; i < interface_offsets_count; i++) {
3299 int id = interfaces_full [i]->interface_id;
3300 bitmap [id >> 3] |= (1 << (id & 7));
3301 class->interfaces_packed [i] = interfaces_full [i];
3302 class->interface_offsets_packed [i] = interface_offsets_full [i];
3303 /*if (num_array_interfaces)
3304 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]);*/
3306 #ifdef COMPRESSED_INTERFACE_BITMAP
3307 i = mono_compress_bitmap (NULL, bitmap, bsize);
3308 class->interface_bitmap = mono_class_alloc0 (class, i);
3309 mono_compress_bitmap (class->interface_bitmap, bitmap, bsize);
3312 class->interface_bitmap = bitmap;
3317 g_free (interfaces_full);
3318 g_free (interface_offsets_full);
3319 g_free (array_interfaces);
3320 for (i = 0; i < class->idepth; i++) {
3321 ifaces = ifaces_array [i];
3323 g_ptr_array_free (ifaces, TRUE);
3325 g_free (ifaces_array);
3327 //printf ("JUST DONE: ");
3328 //print_implemented_interfaces (class);
3334 * Setup interface offsets for interfaces.
3336 * - class->max_interface_id
3337 * - class->interface_offsets_count
3338 * - class->interfaces_packed
3339 * - class->interface_offsets_packed
3340 * - class->interface_bitmap
3342 * This function can fail @class.
3345 mono_class_setup_interface_offsets (MonoClass *class)
3347 mono_loader_lock ();
3349 setup_interface_offsets (class, 0, FALSE);
3351 mono_loader_unlock ();
3354 /*Checks if @klass has @parent as one of it's parents type gtd
3358 * Bar<T> : Foo<Bar<Bar<T>>>
3362 mono_class_has_gtd_parent (MonoClass *klass, MonoClass *parent)
3364 klass = mono_class_get_generic_type_definition (klass);
3365 parent = mono_class_get_generic_type_definition (parent);
3366 mono_class_setup_supertypes (klass);
3367 mono_class_setup_supertypes (parent);
3369 return klass->idepth >= parent->idepth &&
3370 mono_class_get_generic_type_definition (klass->supertypes [parent->idepth - 1]) == parent;
3374 mono_class_check_vtable_constraints (MonoClass *class, GList *in_setup)
3376 MonoGenericInst *ginst;
3378 if (!class->generic_class) {
3379 mono_class_setup_vtable_full (class, in_setup);
3380 return class->exception_type == 0;
3383 mono_class_setup_vtable_full (mono_class_get_generic_type_definition (class), in_setup);
3384 if (class->generic_class->container_class->exception_type) {
3385 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Failed to load generic definition vtable"));
3389 ginst = class->generic_class->context.class_inst;
3390 for (i = 0; i < ginst->type_argc; ++i) {
3392 if (ginst->type_argv [i]->type != MONO_TYPE_GENERICINST)
3394 arg = mono_class_from_mono_type (ginst->type_argv [i]);
3395 /*Those 2 will be checked by mono_class_setup_vtable itself*/
3396 if (mono_class_has_gtd_parent (class, arg) || mono_class_has_gtd_parent (arg, class))
3398 if (!mono_class_check_vtable_constraints (arg, in_setup)) {
3399 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Failed to load generic parameter %d", i));
3407 * mono_class_setup_vtable:
3409 * Creates the generic vtable of CLASS.
3410 * Initializes the following fields in MonoClass:
3413 * Plus all the fields initialized by setup_interface_offsets ().
3414 * If there is an error during vtable construction, class->exception_type is set.
3416 * LOCKING: Acquires the loader lock.
3419 mono_class_setup_vtable (MonoClass *class)
3421 mono_class_setup_vtable_full (class, NULL);
3425 mono_class_setup_vtable_full (MonoClass *class, GList *in_setup)
3427 MonoMethod **overrides;
3428 MonoGenericContext *context;
3436 if (mono_debug_using_mono_debugger ())
3437 /* The debugger currently depends on this */
3438 mono_class_setup_methods (class);
3440 if (MONO_CLASS_IS_INTERFACE (class)) {
3441 /* This sets method->slot for all methods if this is an interface */
3442 mono_class_setup_methods (class);
3446 if (class->exception_type)
3449 if (g_list_find (in_setup, class))
3452 mono_loader_lock ();
3454 if (class->vtable) {
3455 mono_loader_unlock ();
3459 mono_stats.generic_vtable_count ++;
3460 in_setup = g_list_prepend (in_setup, class);
3462 if (class->generic_class) {
3463 if (!mono_class_check_vtable_constraints (class, in_setup)) {
3464 mono_loader_unlock ();
3465 g_list_remove (in_setup, class);
3469 context = mono_class_get_context (class);
3470 type_token = class->generic_class->container_class->type_token;
3472 context = (MonoGenericContext *) class->generic_container;
3473 type_token = class->type_token;
3476 if (class->image->dynamic) {
3477 /* Generic instances can have zero method overrides without causing any harm.
3478 * This is true since we don't do layout all over again for them, we simply inflate
3479 * the layout of the parent.
3481 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
3483 /* The following call fails if there are missing methods in the type */
3484 /* FIXME it's probably a good idea to avoid this for generic instances. */
3485 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
3489 mono_class_setup_vtable_general (class, overrides, onum, in_setup);
3491 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load list of method overrides"));
3495 mono_loader_unlock ();
3496 g_list_remove (in_setup, class);
3501 #define DEBUG_INTERFACE_VTABLE_CODE 0
3502 #define TRACE_INTERFACE_VTABLE_CODE 0
3503 #define VERIFY_INTERFACE_VTABLE_CODE 0
3504 #define VTABLE_SELECTOR (1)
3506 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3507 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
3508 if (!(VTABLE_SELECTOR)) break; \
3512 #define DEBUG_INTERFACE_VTABLE(stmt)
3515 #if TRACE_INTERFACE_VTABLE_CODE
3516 #define TRACE_INTERFACE_VTABLE(stmt) do {\
3517 if (!(VTABLE_SELECTOR)) break; \
3521 #define TRACE_INTERFACE_VTABLE(stmt)
3524 #if VERIFY_INTERFACE_VTABLE_CODE
3525 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
3526 if (!(VTABLE_SELECTOR)) break; \
3530 #define VERIFY_INTERFACE_VTABLE(stmt)
3534 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3536 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
3540 GString *res = g_string_new ("");
3542 g_string_append_c (res, '(');
3543 for (i = 0; i < sig->param_count; ++i) {
3545 g_string_append_c (res, ',');
3546 mono_type_get_desc (res, sig->params [i], include_namespace);
3548 g_string_append (res, ")=>");
3549 if (sig->ret != NULL) {
3550 mono_type_get_desc (res, sig->ret, include_namespace);
3552 g_string_append (res, "NULL");
3555 g_string_free (res, FALSE);
3559 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
3560 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
3561 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
3562 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
3570 is_wcf_hack_disabled (void)
3572 static gboolean disabled;
3573 static gboolean inited = FALSE;
3575 disabled = g_getenv ("MONO_DISABLE_WCF_HACK") != NULL;
3582 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) {
3583 MonoMethodSignature *cmsig, *imsig;
3584 if (strcmp (im->name, cm->name) == 0) {
3585 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
3586 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
3589 if (! slot_is_empty) {
3590 if (require_newslot) {
3591 if (! interface_is_explicitly_implemented_by_class) {
3592 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
3595 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3596 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
3600 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
3603 cmsig = mono_method_signature (cm);
3604 imsig = mono_method_signature (im);
3605 if (!cmsig || !imsig) {
3606 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not resolve the signature of a virtual method"));
3610 if (! mono_metadata_signature_equal (cmsig, imsig)) {
3611 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
3612 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3613 TRACE_INTERFACE_VTABLE (printf ("]"));
3616 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
3617 /* CAS - SecurityAction.InheritanceDemand on interface */
3618 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3619 mono_secman_inheritancedemand_method (cm, im);
3622 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3623 mono_security_core_clr_check_override (class, cm, im);
3624 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
3625 if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
3626 char *body_name = mono_method_full_name (cm, TRUE);
3627 char *decl_name = mono_method_full_name (im, TRUE);
3628 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Method %s overrides method '%s' which is not accessible", body_name, decl_name));
3636 MonoClass *ic = im->klass;
3637 const char *ic_name_space = ic->name_space;
3638 const char *ic_name = ic->name;
3641 if (! require_newslot) {
3642 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
3645 if (cm->klass->rank == 0) {
3646 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
3649 cmsig = mono_method_signature (cm);
3650 imsig = mono_method_signature (im);
3651 if (!cmsig || !imsig) {
3652 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not resolve the signature of a virtual method"));
3656 if (! mono_metadata_signature_equal (cmsig, imsig)) {
3657 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
3658 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3659 TRACE_INTERFACE_VTABLE (printf ("]"));
3662 if (mono_class_get_image (ic) != mono_defaults.corlib) {
3663 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
3666 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
3667 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
3670 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
3671 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
3675 subname = strstr (cm->name, ic_name_space);
3676 if (subname != cm->name) {
3677 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
3680 subname += strlen (ic_name_space);
3681 if (subname [0] != '.') {
3682 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
3686 if (strstr (subname, ic_name) != subname) {
3687 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
3690 subname += strlen (ic_name);
3691 if (subname [0] != '.') {
3692 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
3696 if (strcmp (subname, im->name) != 0) {
3697 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
3701 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
3702 /* CAS - SecurityAction.InheritanceDemand on interface */
3703 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3704 mono_secman_inheritancedemand_method (cm, im);
3707 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3708 mono_security_core_clr_check_override (class, cm, im);
3710 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
3711 if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
3712 char *body_name = mono_method_full_name (cm, TRUE);
3713 char *decl_name = mono_method_full_name (im, TRUE);
3714 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Method %s overrides method '%s' which is not accessible", body_name, decl_name));
3724 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3726 foreach_override (gpointer key, gpointer value, gpointer user_data) {
3727 MonoMethod *method = key;
3728 MonoMethod *override = value;
3729 MonoClass *method_class = mono_method_get_class (method);
3730 MonoClass *override_class = mono_method_get_class (override);
3732 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
3733 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
3734 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
3737 print_overrides (GHashTable *override_map, const char *message) {
3739 printf ("Override map \"%s\" START:\n", message);
3740 g_hash_table_foreach (override_map, foreach_override, NULL);
3741 printf ("Override map \"%s\" END.\n", message);
3743 printf ("Override map \"%s\" EMPTY.\n", message);
3747 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
3748 char *full_name = mono_type_full_name (&class->byval_arg);
3752 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
3754 if (print_interfaces) {
3755 print_implemented_interfaces (class);
3756 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
3759 if (class->parent) {
3760 parent_size = class->parent->vtable_size;
3764 for (i = 0; i < size; ++i) {
3765 MonoMethod *cm = vtable [i];
3766 char *cm_name = cm ? mono_method_full_name (cm, TRUE) : g_strdup ("nil");
3767 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
3769 printf (" [%c][%03d][INDEX %03d] %s [%p]\n", newness, i, cm ? cm->slot : - 1, cm_name, cm);
3777 #if VERIFY_INTERFACE_VTABLE_CODE
3779 mono_method_try_get_vtable_index (MonoMethod *method)
3781 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3782 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3783 if (imethod->declaring->is_generic)
3784 return imethod->declaring->slot;
3786 return method->slot;
3790 mono_class_verify_vtable (MonoClass *class)
3793 char *full_name = mono_type_full_name (&class->byval_arg);
3795 printf ("*** Verifying VTable of class '%s' \n", full_name);
3799 if (!class->methods)
3802 for (i = 0; i < class->method.count; ++i) {
3803 MonoMethod *cm = class->methods [i];
3806 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
3810 full_name = mono_method_full_name (cm, TRUE);
3812 slot = mono_method_try_get_vtable_index (cm);
3814 if (slot >= class->vtable_size) {
3815 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
3819 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
3820 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3821 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3822 g_free (other_name);
3825 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3832 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3834 char *method_signature;
3837 for (index = 0; index < onum; ++index) {
3838 mono_trace_warning (MONO_TRACE_TYPE, " at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
3839 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3841 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3842 type_name = mono_type_full_name (&class->byval_arg);
3843 mono_trace_warning (MONO_TRACE_TYPE, "no implementation for interface method %s::%s(%s) in class %s\n",
3844 mono_type_get_name (&ic->byval_arg), im->name, method_signature, type_name);
3845 g_free (method_signature);
3847 mono_class_setup_methods (class);
3848 if (class->exception_type) {
3849 char *name = mono_type_get_full_name (class);
3850 mono_trace_warning (MONO_TRACE_TYPE, "CLASS %s failed to resolve methods\n", name);
3854 for (index = 0; index < class->method.count; ++index) {
3855 MonoMethod *cm = class->methods [index];
3856 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3858 mono_trace_warning (MONO_TRACE_TYPE, "METHOD %s(%s)\n", cm->name, method_signature);
3859 g_free (method_signature);
3864 mono_method_get_method_definition (MonoMethod *method)
3866 while (method->is_inflated)
3867 method = ((MonoMethodInflated*)method)->declaring;
3872 verify_class_overrides (MonoClass *class, MonoMethod **overrides, int onum)
3876 for (i = 0; i < onum; ++i) {
3877 MonoMethod *decl = overrides [i * 2];
3878 MonoMethod *body = overrides [i * 2 + 1];
3880 if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (class)) {
3881 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method belongs to a different class than the declared one"));
3885 if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
3886 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3887 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must not be static to override a base type"));
3889 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must be virtual to override a base type"));
3893 if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
3894 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3895 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a static method in a base type"));
3897 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a non virtual method in a base type"));
3901 if (!mono_class_is_assignable_from_slow (decl->klass, class)) {
3902 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method overrides a class or interface that extended or implemented by this type"));
3906 body = mono_method_get_method_definition (body);
3907 decl = mono_method_get_method_definition (decl);
3909 if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (body, decl, NULL)) {
3910 char *body_name = mono_method_full_name (body, TRUE);
3911 char *decl_name = mono_method_full_name (decl, TRUE);
3912 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Method %s overrides method '%s' which is not accessible", body_name, decl_name));
3922 mono_class_need_stelemref_method (MonoClass *class)
3924 return class->rank == 1 && MONO_TYPE_IS_REFERENCE (&class->element_class->byval_arg);
3928 * LOCKING: this is supposed to be called with the loader lock held.
3931 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum, GList *in_setup)
3935 MonoMethod **vtable;
3936 int i, max_vtsize = 0, max_iid, cur_slot = 0;
3937 GPtrArray *ifaces = NULL;
3938 GHashTable *override_map = NULL;
3939 gboolean security_enabled = mono_is_security_manager_active ();
3941 gpointer class_iter;
3942 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3943 int first_non_interface_slot;
3945 GSList *virt_methods = NULL, *l;
3946 int stelemref_slot = 0;
3951 if (overrides && !verify_class_overrides (class, overrides, onum))
3954 ifaces = mono_class_get_implemented_interfaces (class, &error);
3955 if (!mono_error_ok (&error)) {
3956 char *name = mono_type_get_full_name (class);
3957 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Could not resolve %s interfaces due to %s", name, mono_error_get_message (&error)));
3959 mono_error_cleanup (&error);
3961 } else if (ifaces) {
3962 for (i = 0; i < ifaces->len; i++) {
3963 MonoClass *ic = g_ptr_array_index (ifaces, i);
3964 max_vtsize += ic->method.count;
3966 g_ptr_array_free (ifaces, TRUE);
3970 if (class->parent) {
3971 mono_class_init (class->parent);
3972 mono_class_setup_vtable_full (class->parent, in_setup);
3974 if (class->parent->exception_type) {
3975 char *name = mono_type_get_full_name (class->parent);
3976 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Parent %s failed to load", name));
3981 max_vtsize += class->parent->vtable_size;
3982 cur_slot = class->parent->vtable_size;
3985 max_vtsize += class->method.count;
3987 /*Array have a slot for stelemref*/
3988 if (mono_class_need_stelemref_method (class)) {
3989 stelemref_slot = cur_slot;
3994 vtable = alloca (sizeof (gpointer) * max_vtsize);
3995 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3997 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3999 cur_slot = setup_interface_offsets (class, cur_slot, TRUE);
4000 if (cur_slot == -1) /*setup_interface_offsets fails the type.*/
4003 max_iid = class->max_interface_id;
4004 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
4006 /* Optimized version for generic instances */
4007 if (class->generic_class) {
4009 MonoClass *gklass = class->generic_class->container_class;
4012 mono_class_setup_vtable_full (gklass, in_setup);
4013 if (gklass->exception_type != MONO_EXCEPTION_NONE) {
4014 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4018 tmp = mono_class_alloc0 (class, sizeof (gpointer) * gklass->vtable_size);
4019 class->vtable_size = gklass->vtable_size;
4020 for (i = 0; i < gklass->vtable_size; ++i)
4021 if (gklass->vtable [i]) {
4022 MonoMethod *inflated = mono_class_inflate_generic_method_full_checked (gklass->vtable [i], class, mono_class_get_context (class), &error);
4023 if (!mono_error_ok (&error)) {
4024 char *err_msg = g_strdup_printf ("Could not inflate method due to %s", mono_error_get_message (&error));
4025 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
4027 mono_error_cleanup (&error);
4031 tmp [i]->slot = gklass->vtable [i]->slot;
4033 mono_memory_barrier ();
4034 class->vtable = tmp;
4036 /* Have to set method->slot for abstract virtual methods */
4037 if (class->methods && gklass->methods) {
4038 for (i = 0; i < class->method.count; ++i)
4039 if (class->methods [i]->slot == -1)
4040 class->methods [i]->slot = gklass->methods [i]->slot;
4046 if (class->parent && class->parent->vtable_size) {
4047 MonoClass *parent = class->parent;
4050 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
4052 // Also inherit parent interface vtables, just as a starting point.
4053 // This is needed otherwise bug-77127.exe fails when the property methods
4054 // have different names in the iterface and the class, because for child
4055 // classes the ".override" information is not used anymore.
4056 for (i = 0; i < parent->interface_offsets_count; i++) {
4057 MonoClass *parent_interface = parent->interfaces_packed [i];
4058 int interface_offset = mono_class_interface_offset (class, parent_interface);
4059 /*FIXME this is now dead code as this condition will never hold true.
4060 Since interface offsets are inherited then the offset of an interface implemented
4061 by a parent will never be the out of it's vtable boundary.
4063 if (interface_offset >= parent->vtable_size) {
4064 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
4067 mono_class_setup_methods (parent_interface); /*FIXME Just kill this whole chunk of dead code*/
4068 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
4069 for (j = 0; j < parent_interface->method.count && !class->exception_type; j++) {
4070 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
4071 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
4072 parent_interface_offset + j, parent_interface_offset, j,
4073 interface_offset + j, interface_offset, j));
4080 /*Array have a slot for stelemref*/
4081 if (mono_class_need_stelemref_method (class)) {
4082 MonoMethod *method = mono_marshal_get_virtual_stelemref (class);
4084 method->slot = stelemref_slot;
4086 g_assert (method->slot == stelemref_slot);
4088 vtable [stelemref_slot] = method;
4091 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
4092 /* override interface methods */
4093 for (i = 0; i < onum; i++) {
4094 MonoMethod *decl = overrides [i*2];
4095 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
4097 dslot = mono_method_get_vtable_slot (decl);
4099 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4103 dslot += mono_class_interface_offset (class, decl->klass);
4104 vtable [dslot] = overrides [i*2 + 1];
4105 vtable [dslot]->slot = dslot;
4107 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4109 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
4111 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4112 mono_security_core_clr_check_override (class, vtable [dslot], decl);
4115 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
4116 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
4119 * Create a list of virtual methods to avoid calling
4120 * mono_class_get_virtual_methods () which is slow because of the metadata
4124 gpointer iter = NULL;
4127 virt_methods = NULL;
4128 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
4129 virt_methods = g_slist_prepend (virt_methods, cm);
4131 if (class->exception_type)
4135 // Loop on all implemented interfaces...
4136 for (i = 0; i < class->interface_offsets_count; i++) {
4137 MonoClass *parent = class->parent;
4139 gboolean interface_is_explicitly_implemented_by_class;
4142 ic = class->interfaces_packed [i];
4143 ic_offset = mono_class_interface_offset (class, ic);
4145 mono_class_setup_methods (ic);
4146 if (ic->exception_type)
4149 // Check if this interface is explicitly implemented (instead of just inherited)
4150 if (parent != NULL) {
4151 int implemented_interfaces_index;
4152 interface_is_explicitly_implemented_by_class = FALSE;
4153 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
4154 if (ic == class->interfaces [implemented_interfaces_index]) {
4155 interface_is_explicitly_implemented_by_class = TRUE;
4160 interface_is_explicitly_implemented_by_class = TRUE;
4163 // Loop on all interface methods...
4164 for (im_index = 0; im_index < ic->method.count; im_index++) {
4165 MonoMethod *im = ic->methods [im_index];
4166 int im_slot = ic_offset + im->slot;
4167 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
4169 if (im->flags & METHOD_ATTRIBUTE_STATIC)
4172 TRACE_INTERFACE_VTABLE (printf ("\tchecking iface method %s\n", mono_method_full_name (im,1)));
4174 // If there is an explicit implementation, just use it right away,
4175 // otherwise look for a matching method
4176 if (override_im == NULL) {
4181 // First look for a suitable method among the class methods
4183 for (l = virt_methods; l; l = l->next) {
4185 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)));
4186 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
4187 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
4188 vtable [im_slot] = cm;
4189 /* Why do we need this? */
4194 TRACE_INTERFACE_VTABLE (printf ("\n"));
4195 if (class->exception_type) /*Might be set by check_interface_method_override*/
4199 // If the slot is still empty, look in all the inherited virtual methods...
4200 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
4201 MonoClass *parent = class->parent;
4202 // Reverse order, so that last added methods are preferred
4203 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
4204 MonoMethod *cm = parent->vtable [cm_index];
4206 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));
4207 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
4208 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
4209 vtable [im_slot] = cm;
4210 /* Why do we need this? */
4216 if (class->exception_type) /*Might be set by check_interface_method_override*/
4218 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
4222 g_assert (vtable [im_slot] == override_im);
4227 // If the class is not abstract, check that all its interface slots are full.
4228 // The check is done here and not directly at the end of the loop above because
4229 // it can happen (for injected generic array interfaces) that the same slot is
4230 // processed multiple times (those interfaces have overlapping slots), and it
4231 // will not always be the first pass the one that fills the slot.
4232 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
4233 for (i = 0; i < class->interface_offsets_count; i++) {
4237 ic = class->interfaces_packed [i];
4238 ic_offset = mono_class_interface_offset (class, ic);
4240 for (im_index = 0; im_index < ic->method.count; im_index++) {
4241 MonoMethod *im = ic->methods [im_index];
4242 int im_slot = ic_offset + im->slot;
4244 if (im->flags & METHOD_ATTRIBUTE_STATIC)
4247 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
4248 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
4249 if (vtable [im_slot] == NULL) {
4250 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
4257 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
4259 for (l = virt_methods; l; l = l->next) {
4262 * If the method is REUSE_SLOT, we must check in the
4263 * base class for a method to override.
4265 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
4267 for (k = class->parent; k ; k = k->parent) {
4272 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
4273 MonoMethodSignature *cmsig, *m1sig;
4275 cmsig = mono_method_signature (cm);
4276 m1sig = mono_method_signature (m1);
4278 if (!cmsig || !m1sig) {
4279 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4283 if (!strcmp(cm->name, m1->name) &&
4284 mono_metadata_signature_equal (cmsig, m1sig)) {
4286 /* CAS - SecurityAction.InheritanceDemand */
4287 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
4288 mono_secman_inheritancedemand_method (cm, m1);
4291 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4292 mono_security_core_clr_check_override (class, cm, m1);
4294 slot = mono_method_get_vtable_slot (m1);
4298 if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, m1, NULL)) {
4299 char *body_name = mono_method_full_name (cm, TRUE);
4300 char *decl_name = mono_method_full_name (m1, TRUE);
4301 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Method %s overrides method '%s' which is not accessible", body_name, decl_name));
4307 g_assert (cm->slot < max_vtsize);
4309 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4310 TRACE_INTERFACE_VTABLE (printf ("adding iface override from %s [%p] to %s [%p]\n",
4311 mono_method_full_name (m1, 1), m1,
4312 mono_method_full_name (cm, 1), cm));
4313 g_hash_table_insert (override_map, m1, cm);
4317 if (k->exception_type)
4327 /*Non final newslot methods must be given a non-interface vtable slot*/
4328 if ((cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && !(cm->flags & METHOD_ATTRIBUTE_FINAL) && cm->slot >= 0)
4332 cm->slot = cur_slot++;
4334 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
4335 vtable [cm->slot] = cm;
4338 /* override non interface methods */
4339 for (i = 0; i < onum; i++) {
4340 MonoMethod *decl = overrides [i*2];
4341 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
4342 g_assert (decl->slot != -1);
4343 vtable [decl->slot] = overrides [i*2 + 1];
4344 overrides [i * 2 + 1]->slot = decl->slot;
4346 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4347 TRACE_INTERFACE_VTABLE (printf ("adding explicit override from %s [%p] to %s [%p]\n",
4348 mono_method_full_name (decl, 1), decl,
4349 mono_method_full_name (overrides [i * 2 + 1], 1), overrides [i * 2 + 1]));
4350 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
4352 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4353 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
4358 * If a method occupies more than one place in the vtable, and it is
4359 * overriden, then change the other occurances too.
4364 for (i = 0; i < max_vtsize; ++i)
4366 TRACE_INTERFACE_VTABLE (printf ("checking slot %d method %s[%p] for overrides\n", i, mono_method_full_name (vtable [i], 1), vtable [i]));
4368 cm = g_hash_table_lookup (override_map, vtable [i]);
4373 g_hash_table_destroy (override_map);
4374 override_map = NULL;
4377 g_slist_free (virt_methods);
4378 virt_methods = NULL;
4380 /* Ensure that all vtable slots are filled with concrete instance methods */
4381 if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
4382 for (i = 0; i < cur_slot; ++i) {
4383 if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
4384 char *type_name = mono_type_get_full_name (class);
4385 char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
4386 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Type %s has invalid vtable method slot %d with method %s", type_name, i, method_name));
4388 g_free (method_name);
4394 if (class->generic_class) {
4395 MonoClass *gklass = class->generic_class->container_class;
4397 mono_class_init (gklass);
4399 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
4401 /* Check that the vtable_size value computed in mono_class_init () is correct */
4402 if (class->vtable_size)
4403 g_assert (cur_slot == class->vtable_size);
4404 class->vtable_size = cur_slot;
4407 /* Try to share the vtable with our parent. */
4408 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
4409 mono_memory_barrier ();
4410 class->vtable = class->parent->vtable;
4412 MonoMethod **tmp = mono_class_alloc0 (class, sizeof (gpointer) * class->vtable_size);
4413 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
4414 mono_memory_barrier ();
4415 class->vtable = tmp;
4418 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
4419 if (mono_print_vtable) {
4422 print_implemented_interfaces (class);
4424 for (i = 0; i <= max_iid; i++)
4425 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
4428 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
4429 class->vtable_size, icount);
4431 for (i = 0; i < cur_slot; ++i) {
4436 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
4437 mono_method_full_name (cm, TRUE));
4443 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
4444 class->name, max_iid);
4446 for (i = 0; i < class->interface_count; i++) {
4447 ic = class->interfaces [i];
4448 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
4449 mono_class_interface_offset (class, ic),
4450 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
4453 for (k = class->parent; k ; k = k->parent) {
4454 for (i = 0; i < k->interface_count; i++) {
4455 ic = k->interfaces [i];
4456 printf (" parent slot offset: %03d, method count: %03d, iid: %03d %s\n",
4457 mono_class_interface_offset (class, ic),
4458 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
4464 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
4469 char *name = mono_type_get_full_name (class);
4470 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("VTable setup of type %s failed", name));
4473 g_hash_table_destroy (override_map);
4475 g_slist_free (virt_methods);
4480 * mono_method_get_vtable_slot:
4482 * Returns method->slot, computing it if neccesary. Return -1 on failure.
4483 * LOCKING: Acquires the loader lock.
4485 * FIXME Use proper MonoError machinery here.
4488 mono_method_get_vtable_slot (MonoMethod *method)
4490 if (method->slot == -1) {
4491 mono_class_setup_vtable (method->klass);
4492 if (method->klass->exception_type)
4494 g_assert (method->slot != -1);
4496 return method->slot;
4500 * mono_method_get_vtable_index:
4503 * Returns the index into the runtime vtable to access the method or,
4504 * in the case of a virtual generic method, the virtual generic method
4505 * thunk. Returns -1 on failure.
4507 * FIXME Use proper MonoError machinery here.
4510 mono_method_get_vtable_index (MonoMethod *method)
4512 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4513 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4514 if (imethod->declaring->is_generic)
4515 return mono_method_get_vtable_slot (imethod->declaring);
4517 return mono_method_get_vtable_slot (method);
4520 static MonoMethod *default_ghc = NULL;
4521 static MonoMethod *default_finalize = NULL;
4522 static int finalize_slot = -1;
4523 static int ghc_slot = -1;
4526 initialize_object_slots (MonoClass *class)
4531 if (class == mono_defaults.object_class) {
4532 mono_class_setup_vtable (class);
4533 for (i = 0; i < class->vtable_size; ++i) {
4534 MonoMethod *cm = class->vtable [i];
4536 if (!strcmp (cm->name, "GetHashCode"))
4538 else if (!strcmp (cm->name, "Finalize"))
4542 g_assert (ghc_slot > 0);
4543 default_ghc = class->vtable [ghc_slot];
4545 g_assert (finalize_slot > 0);
4546 default_finalize = class->vtable [finalize_slot];
4551 MonoMethod *array_method;
4553 } GenericArrayMethodInfo;
4555 static int generic_array_method_num = 0;
4556 static GenericArrayMethodInfo *generic_array_method_info = NULL;
4559 generic_array_methods (MonoClass *class)
4561 int i, count_generic = 0;
4562 GList *list = NULL, *tmp;
4563 if (generic_array_method_num)
4564 return generic_array_method_num;
4565 mono_class_setup_methods (class->parent); /*This is setting up System.Array*/
4566 g_assert (!class->parent->exception_type); /*So hitting this assert is a huge problem*/
4567 for (i = 0; i < class->parent->method.count; i++) {
4568 MonoMethod *m = class->parent->methods [i];
4569 if (!strncmp (m->name, "InternalArray__", 15)) {
4571 list = g_list_prepend (list, m);
4574 list = g_list_reverse (list);
4575 generic_array_method_info = mono_image_alloc (mono_defaults.corlib, sizeof (GenericArrayMethodInfo) * count_generic);
4577 for (tmp = list; tmp; tmp = tmp->next) {
4578 const char *mname, *iname;
4580 MonoMethod *m = tmp->data;
4581 generic_array_method_info [i].array_method = m;
4582 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
4583 iname = "System.Collections.Generic.ICollection`1.";
4584 mname = m->name + 27;
4585 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
4586 iname = "System.Collections.Generic.IEnumerable`1.";
4587 mname = m->name + 27;
4588 } else if (!strncmp (m->name, "InternalArray__", 15)) {
4589 iname = "System.Collections.Generic.IList`1.";
4590 mname = m->name + 15;
4592 g_assert_not_reached ();
4595 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
4596 strcpy (name, iname);
4597 strcpy (name + strlen (iname), mname);
4598 generic_array_method_info [i].name = name;
4601 /*g_print ("array generic methods: %d\n", count_generic);*/
4603 generic_array_method_num = count_generic;
4605 return generic_array_method_num;
4609 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
4611 MonoGenericContext tmp_context;
4614 tmp_context.class_inst = NULL;
4615 tmp_context.method_inst = iface->generic_class->context.class_inst;
4616 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
4618 for (i = 0; i < generic_array_method_num; i++) {
4619 MonoMethod *m = generic_array_method_info [i].array_method;
4620 MonoMethod *inflated;
4622 inflated = mono_class_inflate_generic_method (m, &tmp_context);
4623 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
4628 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
4630 int null_length = strlen ("(null)");
4631 int len = (s1 ? strlen (s1) : null_length) + (s2 ? strlen (s2) : null_length) + 2;
4632 char *s = mono_image_alloc (image, len);
4635 result = g_snprintf (s, len, "%s%c%s", s1 ? s1 : "(null)", '\0', s2 ? s2 : "(null)");
4636 g_assert (result == len - 1);
4642 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
4644 gpointer exception_data = NULL;
4646 switch (error->exception_type) {
4647 case MONO_EXCEPTION_TYPE_LOAD:
4648 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
4651 case MONO_EXCEPTION_MISSING_METHOD:
4652 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
4655 case MONO_EXCEPTION_MISSING_FIELD: {
4656 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
4657 const char *class_name;
4660 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
4662 class_name = error->klass->name;
4664 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
4667 g_free ((void*)class_name);
4671 case MONO_EXCEPTION_FILE_NOT_FOUND: {
4674 if (error->ref_only)
4675 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.";
4677 msg = "Could not load file or assembly '%s' or one of its dependencies.";
4679 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
4683 case MONO_EXCEPTION_BAD_IMAGE:
4684 exception_data = error->msg;
4688 g_assert_not_reached ();
4691 mono_class_set_failure (class, error->exception_type, exception_data);
4696 * @class: the class to initialize
4698 * Compute the instance_size, class_size and other infos that cannot be
4699 * computed at mono_class_get() time. Also compute vtable_size if possible.
4700 * Returns TRUE on success or FALSE if there was a problem in loading
4701 * the type (incorrect assemblies, missing assemblies, methods, etc).
4703 * LOCKING: Acquires the loader lock.
4706 mono_class_init (MonoClass *class)
4709 MonoCachedClassInfo cached_info;
4710 gboolean has_cached_info;
4714 /* Double-checking locking pattern */
4715 if (class->inited || class->exception_type)
4716 return class->exception_type == MONO_EXCEPTION_NONE;
4718 /*g_print ("Init class %s\n", mono_type_get_full_name (class));*/
4720 /* We do everything inside the lock to prevent races */
4721 mono_loader_lock ();
4723 if (class->inited || class->exception_type) {
4724 mono_loader_unlock ();
4725 /* Somebody might have gotten in before us */
4726 return class->exception_type == MONO_EXCEPTION_NONE;
4729 if (class->init_pending) {
4730 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Recursive type definition detected"));
4734 class->init_pending = 1;
4736 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
4737 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
4742 if (class->byval_arg.type == MONO_TYPE_ARRAY || class->byval_arg.type == MONO_TYPE_SZARRAY) {
4743 MonoClass *element_class = class->element_class;
4744 if (!element_class->inited)
4745 mono_class_init (element_class);
4746 if (element_class->exception_type != MONO_EXCEPTION_NONE) {
4747 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4752 /* CAS - SecurityAction.InheritanceDemand */
4753 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
4754 mono_secman_inheritancedemand_class (class, class->parent);
4757 mono_stats.initialized_class_count++;
4759 if (class->generic_class && !class->generic_class->is_dynamic) {
4760 MonoClass *gklass = class->generic_class->container_class;
4762 mono_stats.generic_class_count++;
4764 class->method = gklass->method;
4765 class->field = gklass->field;
4767 mono_class_init (gklass);
4768 // FIXME: Why is this needed ?
4769 if (!gklass->exception_type)
4770 mono_class_setup_methods (gklass);
4771 if (gklass->exception_type) {
4772 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Generic Type Defintion failed to init"));
4776 if (MONO_CLASS_IS_INTERFACE (class))
4777 class->interface_id = mono_get_unique_iid (class);
4780 if (class->parent && !class->parent->inited)
4781 mono_class_init (class->parent);
4783 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
4785 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
4786 class->nested_classes_inited = TRUE;
4789 * Computes the size used by the fields, and their locations
4791 if (has_cached_info) {
4792 class->instance_size = cached_info.instance_size;
4793 class->sizes.class_size = cached_info.class_size;
4794 class->packing_size = cached_info.packing_size;
4795 class->min_align = cached_info.min_align;
4796 class->blittable = cached_info.blittable;
4797 class->has_references = cached_info.has_references;
4798 class->has_static_refs = cached_info.has_static_refs;
4799 class->no_special_static_fields = cached_info.no_special_static_fields;
4802 if (!class->size_inited){
4803 mono_class_setup_fields (class);
4804 if (class->exception_type || mono_loader_get_last_error ())
4808 /* Initialize arrays */
4810 class->method.count = 3 + (class->rank > 1? 2: 1);
4812 if (class->interface_count) {
4813 int count_generic = generic_array_methods (class);
4814 class->method.count += class->interface_count * count_generic;
4818 mono_class_setup_supertypes (class);
4821 initialize_object_slots (class);
4824 * Initialize the rest of the data without creating a generic vtable if possible.
4825 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
4826 * also avoid computing a generic vtable.
4828 if (has_cached_info) {
4830 class->vtable_size = cached_info.vtable_size;
4831 class->has_finalize = cached_info.has_finalize;
4832 class->has_finalize_inited = TRUE;
4833 class->ghcimpl = cached_info.ghcimpl;
4834 class->has_cctor = cached_info.has_cctor;
4835 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
4836 /* SZARRAY can have 2 vtable layouts, with and without the stelemref method.
4837 * The first slot if for array with.
4839 static int szarray_vtable_size[2] = { 0 };
4841 int slot = MONO_TYPE_IS_REFERENCE (&class->element_class->byval_arg) ? 0 : 1;
4844 if (!szarray_vtable_size [slot]) {
4845 mono_class_setup_vtable (class);
4846 szarray_vtable_size [slot] = class->vtable_size;
4848 class->vtable_size = szarray_vtable_size[slot];
4850 class->has_finalize_inited = TRUE;
4851 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
4852 MonoClass *gklass = class->generic_class->container_class;
4854 /* Generic instance case */
4855 class->ghcimpl = gklass->ghcimpl;
4856 class->has_finalize = mono_class_has_finalizer (gklass);
4857 class->has_finalize_inited = TRUE;
4858 class->has_cctor = gklass->has_cctor;
4860 mono_class_setup_vtable (gklass);
4861 if (gklass->exception_type) {
4862 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4866 class->vtable_size = gklass->vtable_size;
4870 /* ghcimpl is not currently used
4872 if (class->parent) {
4873 MonoMethod *cmethod = class->vtable [ghc_slot];
4874 if (cmethod->is_inflated)
4875 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4876 if (cmethod == default_ghc) {
4882 /* C# doesn't allow interfaces to have cctors */
4883 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
4884 MonoMethod *cmethod = NULL;
4886 if (class->type_token) {
4887 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
4888 /* The find_method function ignores the 'flags' argument */
4889 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
4890 class->has_cctor = 1;
4892 mono_class_setup_methods (class);
4893 if (class->exception_type)
4896 for (i = 0; i < class->method.count; ++i) {
4897 MonoMethod *method = class->methods [i];
4898 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4899 (strcmp (".cctor", method->name) == 0)) {
4900 class->has_cctor = 1;
4908 if (class->parent) {
4909 int first_iface_slot;
4910 /* This will compute class->parent->vtable_size for some classes */
4911 mono_class_init (class->parent);
4912 if (class->parent->exception_type) {
4913 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4916 if (mono_loader_get_last_error ())
4918 if (!class->parent->vtable_size) {
4919 /* FIXME: Get rid of this somehow */
4920 mono_class_setup_vtable (class->parent);
4921 if (class->parent->exception_type) {
4922 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4925 if (mono_loader_get_last_error ())
4928 first_iface_slot = class->parent->vtable_size;
4929 if (mono_class_need_stelemref_method (class))
4931 setup_interface_offsets (class, first_iface_slot, TRUE);
4933 setup_interface_offsets (class, 0, TRUE);
4936 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4937 mono_security_core_clr_check_inheritance (class);
4939 if (mono_loader_get_last_error ()) {
4940 if (class->exception_type == MONO_EXCEPTION_NONE) {
4941 set_failure_from_loader_error (class, mono_loader_get_last_error ());
4943 mono_loader_clear_error ();
4946 if (class->generic_class && !mono_verifier_class_is_valid_generic_instantiation (class))
4947 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Invalid generic instantiation"));
4952 /* Because of the double-checking locking pattern */
4953 mono_memory_barrier ();
4955 class->init_pending = 0;
4957 mono_loader_unlock ();
4959 if (mono_debugger_class_init_func)
4960 mono_debugger_class_init_func (class);
4962 return class->exception_type == MONO_EXCEPTION_NONE;
4966 * mono_class_has_finalizer:
4968 * Return whenever KLASS has a finalizer, initializing klass->has_finalizer in the
4972 mono_class_has_finalizer (MonoClass *klass)
4974 if (!klass->has_finalize_inited) {
4975 MonoClass *class = klass;
4977 mono_loader_lock ();
4979 /* Interfaces and valuetypes are not supposed to have finalizers */
4980 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
4981 MonoMethod *cmethod = NULL;
4983 if (class->parent && class->parent->has_finalize) {
4984 class->has_finalize = 1;
4986 if (class->parent) {
4988 * Can't search in metadata for a method named Finalize, because that
4989 * ignores overrides.
4991 mono_class_setup_vtable (class);
4992 if (class->exception_type || mono_loader_get_last_error ())
4994 cmethod = class->vtable [finalize_slot];
4998 g_assert (class->vtable_size > finalize_slot);
5000 class->has_finalize = 0;
5001 if (class->parent) {
5002 if (cmethod->is_inflated)
5003 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
5004 if (cmethod != default_finalize) {
5005 class->has_finalize = 1;
5012 mono_memory_barrier ();
5013 klass->has_finalize_inited = TRUE;
5015 mono_loader_unlock ();
5018 return klass->has_finalize;
5021 mono_loader_unlock ();
5026 mono_is_corlib_image (MonoImage *image)
5028 /* FIXME: allow the dynamic case for our compilers and with full trust */
5030 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
5032 return image == mono_defaults.corlib;
5036 * LOCKING: this assumes the loader lock is held
5039 mono_class_setup_mono_type (MonoClass *class)
5041 const char *name = class->name;
5042 const char *nspace = class->name_space;
5043 gboolean is_corlib = mono_is_corlib_image (class->image);
5045 class->this_arg.byref = 1;
5046 class->this_arg.data.klass = class;
5047 class->this_arg.type = MONO_TYPE_CLASS;
5048 class->byval_arg.data.klass = class;
5049 class->byval_arg.type = MONO_TYPE_CLASS;
5051 if (is_corlib && !strcmp (nspace, "System")) {
5052 if (!strcmp (name, "ValueType")) {
5054 * do not set the valuetype bit for System.ValueType.
5055 * class->valuetype = 1;
5057 class->blittable = TRUE;
5058 } else if (!strcmp (name, "Enum")) {
5060 * do not set the valuetype bit for System.Enum.
5061 * class->valuetype = 1;
5063 class->valuetype = 0;
5064 class->enumtype = 0;
5065 } else if (!strcmp (name, "Object")) {
5066 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
5067 } else if (!strcmp (name, "String")) {
5068 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
5069 } else if (!strcmp (name, "TypedReference")) {
5070 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
5074 if (class->valuetype) {
5075 int t = MONO_TYPE_VALUETYPE;
5077 if (is_corlib && !strcmp (nspace, "System")) {
5080 if (!strcmp (name, "Boolean")) {
5081 t = MONO_TYPE_BOOLEAN;
5082 } else if (!strcmp(name, "Byte")) {
5084 class->blittable = TRUE;
5088 if (!strcmp (name, "Char")) {
5093 if (!strcmp (name, "Double")) {
5095 class->blittable = TRUE;
5099 if (!strcmp (name, "Int32")) {
5101 class->blittable = TRUE;
5102 } else if (!strcmp(name, "Int16")) {
5104 class->blittable = TRUE;
5105 } else if (!strcmp(name, "Int64")) {
5107 class->blittable = TRUE;
5108 } else if (!strcmp(name, "IntPtr")) {
5110 class->blittable = TRUE;
5114 if (!strcmp (name, "Single")) {
5116 class->blittable = TRUE;
5117 } else if (!strcmp(name, "SByte")) {
5119 class->blittable = TRUE;
5123 if (!strcmp (name, "UInt32")) {
5125 class->blittable = TRUE;
5126 } else if (!strcmp(name, "UInt16")) {
5128 class->blittable = TRUE;
5129 } else if (!strcmp(name, "UInt64")) {
5131 class->blittable = TRUE;
5132 } else if (!strcmp(name, "UIntPtr")) {
5134 class->blittable = TRUE;
5138 if (!strcmp (name, "TypedReference")) {
5139 t = MONO_TYPE_TYPEDBYREF;
5140 class->blittable = TRUE;
5144 if (!strcmp (name, "Void")) {
5152 class->this_arg.type = class->byval_arg.type = t;
5155 if (MONO_CLASS_IS_INTERFACE (class))
5156 class->interface_id = mono_get_unique_iid (class);
5161 * COM initialization (using mono_init_com_types) is delayed until needed.
5162 * However when a [ComImport] attribute is present on a type it will trigger
5163 * the initialization. This is not a problem unless the BCL being executed
5164 * lacks the types that COM depends on (e.g. Variant on Silverlight).
5167 init_com_from_comimport (MonoClass *class)
5169 /* we don't always allow COM initialization under the CoreCLR (e.g. Moonlight does not require it) */
5170 if ((mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)) {
5171 /* but some other CoreCLR user could requires it for their platform (i.e. trusted) code */
5172 if (!mono_security_core_clr_determine_platform_image (class->image)) {
5173 /* but it can not be made available for application (i.e. user code) since all COM calls
5174 * are considered native calls. In this case we fail with a TypeLoadException (just like
5175 * Silverlight 2 does */
5176 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5180 /* FIXME : we should add an extra checks to ensure COM can be initialized properly before continuing */
5181 mono_init_com_types ();
5185 * LOCKING: this assumes the loader lock is held
5188 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
5190 gboolean system_namespace;
5191 gboolean is_corlib = mono_is_corlib_image (class->image);
5193 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
5195 /* if root of the hierarchy */
5196 if (system_namespace && !strcmp (class->name, "Object")) {
5197 class->parent = NULL;
5198 class->instance_size = sizeof (MonoObject);
5201 if (!strcmp (class->name, "<Module>")) {
5202 class->parent = NULL;
5203 class->instance_size = 0;
5207 if (!MONO_CLASS_IS_INTERFACE (class)) {
5208 /* Imported COM Objects always derive from __ComObject. */
5209 if (MONO_CLASS_IS_IMPORT (class)) {
5210 init_com_from_comimport (class);
5211 if (parent == mono_defaults.object_class)
5212 parent = mono_defaults.com_object_class;
5215 /* set the parent to something useful and safe, but mark the type as broken */
5216 parent = mono_defaults.object_class;
5217 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5220 class->parent = parent;
5222 if (parent->generic_class && !parent->name) {
5224 * If the parent is a generic instance, we may get
5225 * called before it is fully initialized, especially
5226 * before it has its name.
5231 class->marshalbyref = parent->marshalbyref;
5232 class->contextbound = parent->contextbound;
5233 class->delegate = parent->delegate;
5234 if (MONO_CLASS_IS_IMPORT (class))
5235 class->is_com_object = 1;
5237 class->is_com_object = parent->is_com_object;
5239 if (system_namespace) {
5240 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
5241 class->marshalbyref = 1;
5243 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
5244 class->contextbound = 1;
5246 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
5247 class->delegate = 1;
5250 if (class->parent->enumtype || (mono_is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
5251 (strcmp (class->parent->name_space, "System") == 0)))
5252 class->valuetype = 1;
5253 if (mono_is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
5254 class->valuetype = class->enumtype = 1;
5256 /*class->enumtype = class->parent->enumtype; */
5258 /* initialize com types if COM interfaces are present */
5259 if (MONO_CLASS_IS_IMPORT (class))
5260 init_com_from_comimport (class);
5261 class->parent = NULL;
5267 * mono_class_setup_supertypes:
5270 * Build the data structure needed to make fast type checks work.
5271 * This currently sets two fields in @class:
5272 * - idepth: distance between @class and System.Object in the type
5274 * - supertypes: array of classes: each element has a class in the hierarchy
5275 * starting from @class up to System.Object
5277 * LOCKING: this assumes the loader lock is held
5280 mono_class_setup_supertypes (MonoClass *class)
5283 MonoClass **supertypes;
5285 if (class->supertypes)
5288 if (class->parent && !class->parent->supertypes)
5289 mono_class_setup_supertypes (class->parent);
5291 class->idepth = class->parent->idepth + 1;
5295 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
5296 supertypes = mono_class_alloc0 (class, sizeof (MonoClass *) * ms);
5298 if (class->parent) {
5299 supertypes [class->idepth - 1] = class;
5300 memcpy (supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
5302 supertypes [0] = class;
5305 mono_atomic_store_release (&class->supertypes, supertypes);
5309 * mono_class_create_from_typedef:
5310 * @image: image where the token is valid
5311 * @type_token: typedef token
5313 * Create the MonoClass* representing the specified type token.
5314 * @type_token must be a TypeDef token.
5316 * FIXME: don't return NULL on failure, just the the caller figure it out.
5319 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
5321 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5322 MonoClass *class, *parent = NULL;
5323 guint32 cols [MONO_TYPEDEF_SIZE];
5324 guint32 cols_next [MONO_TYPEDEF_SIZE];
5325 guint tidx = mono_metadata_token_index (type_token);
5326 MonoGenericContext *context = NULL;
5327 const char *name, *nspace;
5329 MonoClass **interfaces;
5330 guint32 field_last, method_last;
5331 guint32 nesting_tokeen;
5333 if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || tidx > tt->rows)
5336 mono_loader_lock ();
5338 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
5339 mono_loader_unlock ();
5343 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5345 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5346 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5348 class = mono_image_alloc0 (image, sizeof (MonoClass));
5351 class->name_space = nspace;
5353 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
5355 class->image = image;
5356 class->type_token = type_token;
5357 class->flags = cols [MONO_TYPEDEF_FLAGS];
5359 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
5361 classes_size += sizeof (MonoClass);
5364 * Check whether we're a generic type definition.
5366 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
5367 if (class->generic_container) {
5368 class->is_generic = 1;
5369 class->generic_container->owner.klass = class;
5370 context = &class->generic_container->context;
5373 if (cols [MONO_TYPEDEF_EXTENDS]) {
5375 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
5377 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
5378 /*WARNING: this must satisfy mono_metadata_type_hash*/
5379 class->this_arg.byref = 1;
5380 class->this_arg.data.klass = class;
5381 class->this_arg.type = MONO_TYPE_CLASS;
5382 class->byval_arg.data.klass = class;
5383 class->byval_arg.type = MONO_TYPE_CLASS;
5385 parent = mono_class_get_full (image, parent_token, context);
5387 if (parent == NULL){
5388 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load parent type"));
5389 mono_loader_clear_error ();
5390 goto parent_failure;
5393 for (tmp = parent; tmp; tmp = tmp->parent) {
5395 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cycle found while resolving parent"));
5396 goto parent_failure;
5398 if (class->generic_container && tmp->generic_class && tmp->generic_class->container_class == class) {
5399 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Parent extends generic instance of this type"));
5400 goto parent_failure;
5405 mono_class_setup_parent (class, parent);
5407 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
5408 mono_class_setup_mono_type (class);
5411 * This might access class->byval_arg for recursion generated by generic constraints,
5412 * so it has to come after setup_mono_type ().
5414 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token))) {
5415 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
5416 if (!class->nested_in) {
5417 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load nestedin type"));
5418 mono_loader_unlock ();
5419 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5424 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
5428 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
5432 class->cast_class = class->element_class = class;
5434 if (!class->enumtype) {
5435 if (!mono_metadata_interfaces_from_typedef_full (
5436 image, type_token, &interfaces, &icount, FALSE, context)){
5437 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load interfaces"));
5438 mono_loader_unlock ();
5439 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5443 class->interfaces = interfaces;
5444 class->interface_count = icount;
5445 class->interfaces_inited = 1;
5448 /*g_print ("Load class %s\n", name);*/
5451 * Compute the field and method lists
5453 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
5454 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
5456 if (tt->rows > tidx){
5457 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
5458 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
5459 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
5461 field_last = image->tables [MONO_TABLE_FIELD].rows;
5462 method_last = image->tables [MONO_TABLE_METHOD].rows;
5465 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
5466 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
5467 class->field.count = field_last - class->field.first;
5469 class->field.count = 0;
5471 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
5472 class->method.count = method_last - class->method.first;
5474 class->method.count = 0;
5476 /* reserve space to store vector pointer in arrays */
5477 if (mono_is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
5478 class->instance_size += 2 * sizeof (gpointer);
5479 g_assert (class->field.count == 0);
5482 if (class->enumtype) {
5483 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
5484 if (!enum_basetype) {
5485 /*set it to a default value as the whole runtime can't handle this to be null*/
5486 class->cast_class = class->element_class = mono_defaults.int32_class;
5487 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5488 mono_loader_unlock ();
5489 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5492 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
5496 * If we're a generic type definition, load the constraints.
5497 * We must do this after the class has been constructed to make certain recursive scenarios
5500 if (class->generic_container && !mono_metadata_load_generic_param_constraints_full (image, type_token, class->generic_container)){
5501 char *class_name = g_strdup_printf("%s.%s", class->name_space, class->name);
5502 char *error = concat_two_strings_with_zero (class->image, class_name, class->image->assembly_name);
5503 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, error);
5504 g_free (class_name);
5505 mono_loader_unlock ();
5506 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5510 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
5511 if (!strncmp (name, "Vector", 6))
5512 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");
5515 mono_loader_unlock ();
5517 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5522 mono_class_setup_mono_type (class);
5523 mono_loader_unlock ();
5524 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5529 /** is klass Nullable<T>? */
5531 mono_class_is_nullable (MonoClass *klass)
5533 return klass->generic_class != NULL &&
5534 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
5538 /** if klass is T? return T */
5540 mono_class_get_nullable_param (MonoClass *klass)
5542 g_assert (mono_class_is_nullable (klass));
5543 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
5547 * Create the `MonoClass' for an instantiation of a generic type.
5548 * We only do this if we actually need it.
5551 mono_generic_class_get_class (MonoGenericClass *gclass)
5553 MonoClass *klass, *gklass;
5555 if (gclass->cached_class)
5556 return gclass->cached_class;
5558 mono_loader_lock ();
5559 if (gclass->cached_class) {
5560 mono_loader_unlock ();
5561 return gclass->cached_class;
5564 klass = mono_image_set_alloc0 (gclass->owner, sizeof (MonoClass));
5566 gklass = gclass->container_class;
5568 if (gklass->nested_in) {
5569 /* The nested_in type should not be inflated since it's possible to produce a nested type with less generic arguments*/
5570 klass->nested_in = gklass->nested_in;
5573 klass->name = gklass->name;
5574 klass->name_space = gklass->name_space;
5576 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
5578 klass->image = gklass->image;
5579 klass->flags = gklass->flags;
5580 klass->type_token = gklass->type_token;
5581 klass->field.count = gklass->field.count;
5583 klass->is_inflated = 1;
5584 klass->generic_class = gclass;
5586 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
5587 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
5588 klass->this_arg.byref = TRUE;
5589 klass->enumtype = gklass->enumtype;
5590 klass->valuetype = gklass->valuetype;
5592 klass->cast_class = klass->element_class = klass;
5594 if (mono_class_is_nullable (klass))
5595 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
5598 * We're not interested in the nested classes of a generic instance.
5599 * We use the generic type definition to look for nested classes.
5602 if (gklass->parent) {
5604 klass->parent = mono_class_inflate_generic_class_checked (gklass->parent, mono_generic_class_get_context (gclass), &error);
5605 if (!mono_error_ok (&error)) {
5606 /*Set parent to something safe as the runtime doesn't handle well this kind of failure.*/
5607 klass->parent = mono_defaults.object_class;
5608 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
5609 mono_error_cleanup (&error);
5614 mono_class_setup_parent (klass, klass->parent);
5616 if (klass->enumtype) {
5617 klass->cast_class = gklass->cast_class;
5618 klass->element_class = gklass->element_class;
5621 if (gclass->is_dynamic) {
5624 mono_class_setup_supertypes (klass);
5626 if (klass->enumtype) {
5628 * For enums, gklass->fields might not been set, but instance_size etc. is
5629 * already set in mono_reflection_create_internal_class (). For non-enums,
5630 * these will be computed normally in mono_class_layout_fields ().
5632 klass->instance_size = gklass->instance_size;
5633 klass->sizes.class_size = gklass->sizes.class_size;
5634 klass->size_inited = 1;
5638 mono_memory_barrier ();
5639 gclass->cached_class = klass;
5641 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
5643 inflated_classes ++;
5644 inflated_classes_size += sizeof (MonoClass);
5646 mono_loader_unlock ();
5652 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
5654 MonoClass *klass, **ptr;
5656 MonoGenericContainer *container = mono_generic_param_owner (param);
5660 image = mono_defaults.corlib;
5662 klass = mono_image_alloc0 (image, sizeof (MonoClass));
5663 classes_size += sizeof (MonoClass);
5666 klass->name = pinfo->name;
5668 int n = mono_generic_param_num (param);
5669 klass->name = mono_image_alloc0 (image, 16);
5670 sprintf ((char*)klass->name, "%d", n);
5675 MonoMethod *omethod = container->owner.method;
5676 klass->name_space = (omethod && omethod->klass) ? omethod->klass->name_space : "";
5678 MonoClass *oklass = container->owner.klass;
5679 klass->name_space = oklass ? oklass->name_space : "";
5682 klass->name_space = "";
5685 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
5689 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
5693 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
5694 klass->parent = pinfo->constraints [0];
5696 } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
5697 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
5699 klass->parent = mono_defaults.object_class;
5702 if (count - pos > 0) {
5703 klass->interface_count = count - pos;
5704 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
5705 klass->interfaces_inited = TRUE;
5706 for (i = pos; i < count; i++)
5707 klass->interfaces [i - pos] = pinfo->constraints [i];
5710 klass->image = image;
5712 klass->inited = TRUE;
5713 klass->cast_class = klass->element_class = klass;
5714 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
5716 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
5717 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
5718 klass->this_arg.byref = TRUE;
5720 /* We don't use type_token for VAR since only classes can use it (not arrays, pointer, VARs, etc) */
5721 klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
5723 /*Init these fields to sane values*/
5724 klass->min_align = 1;
5725 klass->instance_size = sizeof (gpointer);
5726 klass->size_inited = 1;
5728 mono_class_setup_supertypes (klass);
5730 if (count - pos > 0) {
5731 mono_class_setup_vtable (klass->parent);
5732 if (klass->parent->exception_type)
5733 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Failed to setup parent interfaces"));
5735 setup_interface_offsets (klass, klass->parent->vtable_size, TRUE);
5741 #define FAST_CACHE_SIZE 16
5744 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
5746 int n = mono_generic_param_num (param);
5747 MonoImage *image = param->image;
5752 if (n < FAST_CACHE_SIZE) {
5754 return image->mvar_cache_fast ? image->mvar_cache_fast [n] : NULL;
5756 return image->var_cache_fast ? image->var_cache_fast [n] : NULL;
5758 ht = is_mvar ? image->mvar_cache_slow : image->var_cache_slow;
5759 return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
5764 * LOCKING: Acquires the loader lock.
5767 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
5769 int n = mono_generic_param_num (param);
5770 MonoImage *image = param->image;
5775 if (n < FAST_CACHE_SIZE) {
5777 /* No locking needed */
5778 if (!image->mvar_cache_fast)
5779 image->mvar_cache_fast = mono_image_alloc0 (image, sizeof (MonoClass*) * FAST_CACHE_SIZE);
5780 image->mvar_cache_fast [n] = klass;
5782 if (!image->var_cache_fast)
5783 image->var_cache_fast = mono_image_alloc0 (image, sizeof (MonoClass*) * FAST_CACHE_SIZE);
5784 image->var_cache_fast [n] = klass;
5788 ht = is_mvar ? image->mvar_cache_slow : image->var_cache_slow;
5790 mono_loader_lock ();
5791 ht = is_mvar ? image->mvar_cache_slow : image->var_cache_slow;
5793 ht = g_hash_table_new (NULL, NULL);
5794 mono_memory_barrier ();
5796 image->mvar_cache_slow = ht;
5798 image->var_cache_slow = ht;
5800 mono_loader_unlock ();
5803 g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
5807 * LOCKING: Acquires the loader lock.
5810 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
5812 MonoGenericContainer *container = mono_generic_param_owner (param);
5813 MonoGenericParamInfo *pinfo;
5816 mono_loader_lock ();
5819 pinfo = mono_generic_param_info (param);
5820 if (pinfo->pklass) {
5821 mono_loader_unlock ();
5822 return pinfo->pklass;
5828 klass = get_anon_gparam_class (param, is_mvar);
5830 mono_loader_unlock ();
5835 if (!image && container) {
5837 MonoMethod *method = container->owner.method;
5838 image = (method && method->klass) ? method->klass->image : NULL;
5840 MonoClass *klass = container->owner.klass;
5841 // FIXME: 'klass' should not be null
5842 // But, monodis creates GenericContainers without associating a owner to it
5843 image = klass ? klass->image : NULL;
5847 klass = make_generic_param_class (param, image, is_mvar, pinfo);
5849 mono_memory_barrier ();
5852 pinfo->pklass = klass;
5854 set_anon_gparam_class (param, is_mvar, klass);
5856 mono_loader_unlock ();
5858 /* FIXME: Should this go inside 'make_generic_param_klass'? */
5859 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
5865 mono_ptr_class_get (MonoType *type)
5868 MonoClass *el_class;
5872 el_class = mono_class_from_mono_type (type);
5873 image = el_class->image;
5875 mono_loader_lock ();
5877 if (!image->ptr_cache)
5878 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5880 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
5881 mono_loader_unlock ();
5884 result = mono_image_alloc0 (image, sizeof (MonoClass));
5886 classes_size += sizeof (MonoClass);
5888 result->parent = NULL; /* no parent for PTR types */
5889 result->name_space = el_class->name_space;
5890 name = g_strdup_printf ("%s*", el_class->name);
5891 result->name = mono_image_strdup (image, name);
5894 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5896 result->image = el_class->image;
5897 result->inited = TRUE;
5898 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5899 /* Can pointers get boxed? */
5900 result->instance_size = sizeof (gpointer);
5901 result->cast_class = result->element_class = el_class;
5902 result->blittable = TRUE;
5904 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
5905 result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
5906 result->this_arg.byref = TRUE;
5908 mono_class_setup_supertypes (result);
5910 g_hash_table_insert (image->ptr_cache, el_class, result);
5912 mono_loader_unlock ();
5914 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5920 mono_fnptr_class_get (MonoMethodSignature *sig)
5923 static GHashTable *ptr_hash = NULL;
5925 /* FIXME: These should be allocate from a mempool as well, but which one ? */
5927 mono_loader_lock ();
5930 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5932 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
5933 mono_loader_unlock ();
5936 result = g_new0 (MonoClass, 1);
5938 result->parent = NULL; /* no parent for PTR types */
5939 result->name_space = "System";
5940 result->name = "MonoFNPtrFakeClass";
5942 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5944 result->image = mono_defaults.corlib; /* need to fix... */
5945 result->inited = TRUE;
5946 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
5947 /* Can pointers get boxed? */
5948 result->instance_size = sizeof (gpointer);
5949 result->cast_class = result->element_class = result;
5950 result->blittable = TRUE;
5952 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
5953 result->this_arg.data.method = result->byval_arg.data.method = sig;
5954 result->this_arg.byref = TRUE;
5955 result->blittable = TRUE;
5957 mono_class_setup_supertypes (result);
5959 g_hash_table_insert (ptr_hash, sig, result);
5961 mono_loader_unlock ();
5963 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5969 mono_class_from_mono_type (MonoType *type)
5971 switch (type->type) {
5972 case MONO_TYPE_OBJECT:
5973 return type->data.klass? type->data.klass: mono_defaults.object_class;
5974 case MONO_TYPE_VOID:
5975 return type->data.klass? type->data.klass: mono_defaults.void_class;
5976 case MONO_TYPE_BOOLEAN:
5977 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
5978 case MONO_TYPE_CHAR:
5979 return type->data.klass? type->data.klass: mono_defaults.char_class;
5981 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
5983 return type->data.klass? type->data.klass: mono_defaults.byte_class;
5985 return type->data.klass? type->data.klass: mono_defaults.int16_class;
5987 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
5989 return type->data.klass? type->data.klass: mono_defaults.int32_class;
5991 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
5993 return type->data.klass? type->data.klass: mono_defaults.int_class;
5995 return type->data.klass? type->data.klass: mono_defaults.uint_class;
5997 return type->data.klass? type->data.klass: mono_defaults.int64_class;
5999 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
6001 return type->data.klass? type->data.klass: mono_defaults.single_class;
6003 return type->data.klass? type->data.klass: mono_defaults.double_class;
6004 case MONO_TYPE_STRING:
6005 return type->data.klass? type->data.klass: mono_defaults.string_class;
6006 case MONO_TYPE_TYPEDBYREF:
6007 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
6008 case MONO_TYPE_ARRAY:
6009 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
6011 return mono_ptr_class_get (type->data.type);
6012 case MONO_TYPE_FNPTR:
6013 return mono_fnptr_class_get (type->data.method);
6014 case MONO_TYPE_SZARRAY:
6015 return mono_array_class_get (type->data.klass, 1);
6016 case MONO_TYPE_CLASS:
6017 case MONO_TYPE_VALUETYPE:
6018 return type->data.klass;
6019 case MONO_TYPE_GENERICINST:
6020 return mono_generic_class_get_class (type->data.generic_class);
6022 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
6023 case MONO_TYPE_MVAR:
6024 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
6026 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
6027 g_assert_not_reached ();
6034 * mono_type_retrieve_from_typespec
6035 * @image: context where the image is created
6036 * @type_spec: typespec token
6037 * @context: the generic context used to evaluate generic instantiations in
6040 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate, MonoError *error)
6042 MonoType *t = mono_type_create_from_typespec (image, type_spec);
6044 mono_error_init (error);
6045 *did_inflate = FALSE;
6048 char *name = mono_class_name_from_token (image, type_spec);
6049 char *assembly = mono_assembly_name_from_token (image, type_spec);
6050 mono_error_set_type_load_name (error, name, assembly, "Could not resolve typespec token %08x", type_spec);
6054 if (context && (context->class_inst || context->method_inst)) {
6055 MonoType *inflated = inflate_generic_type (NULL, t, context, error);
6057 if (!mono_error_ok (error))
6062 *did_inflate = TRUE;
6069 * mono_class_create_from_typespec
6070 * @image: context where the image is created
6071 * @type_spec: typespec token
6072 * @context: the generic context used to evaluate generic instantiations in
6075 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, MonoError *error)
6078 gboolean inflated = FALSE;
6079 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated, error);
6080 if (!mono_error_ok (error))
6082 ret = mono_class_from_mono_type (t);
6084 mono_metadata_free_type (t);
6089 * mono_bounded_array_class_get:
6090 * @element_class: element class
6091 * @rank: the dimension of the array class
6092 * @bounded: whenever the array has non-zero bounds
6094 * Returns: a class object describing the array with element type @element_type and
6098 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
6102 MonoClass *parent = NULL;
6103 GSList *list, *rootlist = NULL;
6106 gboolean corlib_type = FALSE;
6108 g_assert (rank <= 255);
6111 /* bounded only matters for one-dimensional arrays */
6114 image = eclass->image;
6116 if (rank == 1 && !bounded) {
6118 * This case is very frequent not just during compilation because of calls
6119 * from mono_class_from_mono_type (), mono_array_new (),
6120 * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
6122 EnterCriticalSection (&image->szarray_cache_lock);
6123 if (!image->szarray_cache)
6124 image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
6125 class = g_hash_table_lookup (image->szarray_cache, eclass);
6126 LeaveCriticalSection (&image->szarray_cache_lock);
6130 mono_loader_lock ();
6132 mono_loader_lock ();
6134 if (!image->array_cache)
6135 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
6137 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
6138 for (; list; list = list->next) {
6140 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
6141 mono_loader_unlock ();
6148 /* for the building corlib use System.Array from it */
6149 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
6150 parent = mono_class_from_name (image, "System", "Array");
6153 parent = mono_defaults.array_class;
6154 if (!parent->inited)
6155 mono_class_init (parent);
6158 class = mono_image_alloc0 (image, sizeof (MonoClass));
6160 class->image = image;
6161 class->name_space = eclass->name_space;
6162 nsize = strlen (eclass->name);
6163 name = g_malloc (nsize + 2 + rank + 1);
6164 memcpy (name, eclass->name, nsize);
6167 memset (name + nsize + 1, ',', rank - 1);
6169 name [nsize + rank] = '*';
6170 name [nsize + rank + bounded] = ']';
6171 name [nsize + rank + bounded + 1] = 0;
6172 class->name = mono_image_strdup (image, name);
6175 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
6177 classes_size += sizeof (MonoClass);
6179 class->type_token = 0;
6180 /* all arrays are marked serializable and sealed, bug #42779 */
6181 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED | TYPE_ATTRIBUTE_PUBLIC;
6182 class->parent = parent;
6183 class->instance_size = mono_class_instance_size (class->parent);
6185 if (eclass->byval_arg.type == MONO_TYPE_TYPEDBYREF || eclass->byval_arg.type == MONO_TYPE_VOID) {
6186 /*Arrays of those two types are invalid.*/
6187 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
6188 } else if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
6189 if (!eclass->ref_info_handle || eclass->wastypebuilder) {
6190 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
6191 g_assert (eclass->ref_info_handle && !eclass->wastypebuilder);
6193 /* element_size -1 is ok as this is not an instantitable type*/
6194 class->sizes.element_size = -1;
6196 class->sizes.element_size = mono_class_array_element_size (eclass);
6198 mono_class_setup_supertypes (class);
6200 if (eclass->generic_class)
6201 mono_class_init (eclass);
6202 if (!eclass->size_inited)
6203 mono_class_setup_fields (eclass);
6204 if (eclass->exception_type) /*FIXME we fail the array type, but we have to let other fields be set.*/
6205 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
6207 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
6211 if (eclass->enumtype)
6212 class->cast_class = eclass->element_class;
6214 class->cast_class = eclass;
6216 switch (class->cast_class->byval_arg.type) {
6218 class->cast_class = mono_defaults.byte_class;
6221 class->cast_class = mono_defaults.int16_class;
6224 #if SIZEOF_VOID_P == 4
6228 class->cast_class = mono_defaults.int32_class;
6231 #if SIZEOF_VOID_P == 8
6235 class->cast_class = mono_defaults.int64_class;
6239 class->element_class = eclass;
6241 if ((rank > 1) || bounded) {
6242 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
6243 class->byval_arg.type = MONO_TYPE_ARRAY;
6244 class->byval_arg.data.array = at;
6245 at->eklass = eclass;
6247 /* FIXME: complete.... */
6249 class->byval_arg.type = MONO_TYPE_SZARRAY;
6250 class->byval_arg.data.klass = eclass;
6252 class->this_arg = class->byval_arg;
6253 class->this_arg.byref = 1;
6258 class->generic_container = eclass->generic_container;
6260 if (rank == 1 && !bounded) {
6261 MonoClass *prev_class;
6263 EnterCriticalSection (&image->szarray_cache_lock);
6264 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
6266 /* Someone got in before us */
6269 g_hash_table_insert (image->szarray_cache, eclass, class);
6270 LeaveCriticalSection (&image->szarray_cache_lock);
6272 list = g_slist_append (rootlist, class);
6273 g_hash_table_insert (image->array_cache, eclass, list);
6276 mono_loader_unlock ();
6278 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
6284 * mono_array_class_get:
6285 * @element_class: element class
6286 * @rank: the dimension of the array class
6288 * Returns: a class object describing the array with element type @element_type and
6292 mono_array_class_get (MonoClass *eclass, guint32 rank)
6294 return mono_bounded_array_class_get (eclass, rank, FALSE);
6298 * mono_class_instance_size:
6301 * Returns: the size of an object instance
6304 mono_class_instance_size (MonoClass *klass)
6306 if (!klass->size_inited)
6307 mono_class_init (klass);
6309 return klass->instance_size;
6313 * mono_class_min_align:
6316 * Returns: minimm alignment requirements
6319 mono_class_min_align (MonoClass *klass)
6321 if (!klass->size_inited)
6322 mono_class_init (klass);
6324 return klass->min_align;
6328 * mono_class_value_size:
6331 * This function is used for value types, and return the
6332 * space and the alignment to store that kind of value object.
6334 * Returns: the size of a value of kind @klass
6337 mono_class_value_size (MonoClass *klass, guint32 *align)
6341 /* fixme: check disable, because we still have external revereces to
6342 * mscorlib and Dummy Objects
6344 /*g_assert (klass->valuetype);*/
6346 size = mono_class_instance_size (klass) - sizeof (MonoObject);
6349 *align = klass->min_align;
6355 * mono_class_data_size:
6358 * Returns: the size of the static class data
6361 mono_class_data_size (MonoClass *klass)
6364 mono_class_init (klass);
6366 /* in arrays, sizes.class_size is unioned with element_size
6367 * and arrays have no static fields
6371 return klass->sizes.class_size;
6375 * Auxiliary routine to mono_class_get_field
6377 * Takes a field index instead of a field token.
6379 static MonoClassField *
6380 mono_class_get_field_idx (MonoClass *class, int idx)
6382 mono_class_setup_fields_locking (class);
6383 if (class->exception_type)
6387 if (class->image->uncompressed_metadata) {
6389 * class->field.first points to the FieldPtr table, while idx points into the
6390 * Field table, so we have to do a search.
6392 /*FIXME this is broken for types with multiple fields with the same name.*/
6393 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
6396 for (i = 0; i < class->field.count; ++i)
6397 if (mono_field_get_name (&class->fields [i]) == name)
6398 return &class->fields [i];
6399 g_assert_not_reached ();
6401 if (class->field.count) {
6402 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
6403 return &class->fields [idx - class->field.first];
6407 class = class->parent;
6413 * mono_class_get_field:
6414 * @class: the class to lookup the field.
6415 * @field_token: the field token
6417 * Returns: A MonoClassField representing the type and offset of
6418 * the field, or a NULL value if the field does not belong to this
6422 mono_class_get_field (MonoClass *class, guint32 field_token)
6424 int idx = mono_metadata_token_index (field_token);
6426 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
6428 return mono_class_get_field_idx (class, idx - 1);
6432 * mono_class_get_field_from_name:
6433 * @klass: the class to lookup the field.
6434 * @name: the field name
6436 * Search the class @klass and it's parents for a field with the name @name.
6438 * Returns: the MonoClassField pointer of the named field or NULL
6441 mono_class_get_field_from_name (MonoClass *klass, const char *name)
6443 return mono_class_get_field_from_name_full (klass, name, NULL);
6447 * mono_class_get_field_from_name_full:
6448 * @klass: the class to lookup the field.
6449 * @name: the field name
6450 * @type: the type of the fields. This optional.
6452 * Search the class @klass and it's parents for a field with the name @name and type @type.
6454 * If @klass is an inflated generic type, the type comparison is done with the equivalent field
6455 * of its generic type definition.
6457 * Returns: the MonoClassField pointer of the named field or NULL
6460 mono_class_get_field_from_name_full (MonoClass *klass, const char *name, MonoType *type)
6464 mono_class_setup_fields_locking (klass);
6465 if (klass->exception_type)
6469 for (i = 0; i < klass->field.count; ++i) {
6470 MonoClassField *field = &klass->fields [i];
6472 if (strcmp (name, mono_field_get_name (field)) != 0)
6476 MonoType *field_type = mono_metadata_get_corresponding_field_from_generic_type_definition (field)->type;
6477 if (!mono_metadata_type_equal_full (type, field_type, TRUE))
6482 klass = klass->parent;
6488 * mono_class_get_field_token:
6489 * @field: the field we need the token of
6491 * Get the token of a field. Note that the tokesn is only valid for the image
6492 * the field was loaded from. Don't use this function for fields in dynamic types.
6494 * Returns: the token representing the field in the image it was loaded from.
6497 mono_class_get_field_token (MonoClassField *field)
6499 MonoClass *klass = field->parent;
6502 mono_class_setup_fields_locking (klass);
6507 for (i = 0; i < klass->field.count; ++i) {
6508 if (&klass->fields [i] == field) {
6509 int idx = klass->field.first + i + 1;
6511 if (klass->image->uncompressed_metadata)
6512 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
6513 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
6516 klass = klass->parent;
6519 g_assert_not_reached ();
6524 mono_field_get_index (MonoClassField *field)
6526 int index = field - field->parent->fields;
6528 g_assert (index >= 0 && index < field->parent->field.count);
6534 * mono_class_get_field_default_value:
6536 * Return the default value of the field as a pointer into the metadata blob.
6539 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
6542 guint32 constant_cols [MONO_CONSTANT_SIZE];
6544 MonoClass *klass = field->parent;
6546 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
6548 if (!klass->ext || !klass->ext->field_def_values) {
6549 mono_loader_lock ();
6550 mono_class_alloc_ext (klass);
6551 if (!klass->ext->field_def_values)
6552 klass->ext->field_def_values = mono_class_alloc0 (klass, sizeof (MonoFieldDefaultValue) * klass->field.count);
6553 mono_loader_unlock ();
6556 field_index = mono_field_get_index (field);
6558 if (!klass->ext->field_def_values [field_index].data) {
6559 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
6563 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
6565 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
6566 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
6567 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
6570 *def_type = klass->ext->field_def_values [field_index].def_type;
6571 return klass->ext->field_def_values [field_index].data;
6575 mono_property_get_index (MonoProperty *prop)
6577 int index = prop - prop->parent->ext->properties;
6579 g_assert (index >= 0 && index < prop->parent->ext->property.count);
6585 * mono_class_get_property_default_value:
6587 * Return the default value of the field as a pointer into the metadata blob.
6590 mono_class_get_property_default_value (MonoProperty *property, MonoTypeEnum *def_type)
6593 guint32 constant_cols [MONO_CONSTANT_SIZE];
6594 MonoClass *klass = property->parent;
6596 g_assert (property->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT);
6598 * We don't cache here because it is not used by C# so it's quite rare, but
6599 * we still do the lookup in klass->ext because that is where the data
6600 * is stored for dynamic assemblies.
6603 if (klass->image->dynamic) {
6604 int prop_index = mono_property_get_index (property);
6605 if (klass->ext->prop_def_values && klass->ext->prop_def_values [prop_index].data) {
6606 *def_type = klass->ext->prop_def_values [prop_index].def_type;
6607 return klass->ext->prop_def_values [prop_index].data;
6611 cindex = mono_metadata_get_constant_index (klass->image, mono_class_get_property_token (property), 0);
6615 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
6616 *def_type = constant_cols [MONO_CONSTANT_TYPE];
6617 return (gpointer)mono_metadata_blob_heap (klass->image, constant_cols [MONO_CONSTANT_VALUE]);
6621 mono_class_get_event_token (MonoEvent *event)
6623 MonoClass *klass = event->parent;
6628 for (i = 0; i < klass->ext->event.count; ++i) {
6629 if (&klass->ext->events [i] == event)
6630 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
6633 klass = klass->parent;
6636 g_assert_not_reached ();
6641 mono_class_get_property_from_name (MonoClass *klass, const char *name)
6645 gpointer iter = NULL;
6646 while ((p = mono_class_get_properties (klass, &iter))) {
6647 if (! strcmp (name, p->name))
6650 klass = klass->parent;
6656 mono_class_get_property_token (MonoProperty *prop)
6658 MonoClass *klass = prop->parent;
6662 gpointer iter = NULL;
6663 while ((p = mono_class_get_properties (klass, &iter))) {
6664 if (&klass->ext->properties [i] == prop)
6665 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
6669 klass = klass->parent;
6672 g_assert_not_reached ();
6677 mono_class_name_from_token (MonoImage *image, guint32 type_token)
6679 const char *name, *nspace;
6681 return g_strdup_printf ("DynamicType 0x%08x", type_token);
6683 switch (type_token & 0xff000000){
6684 case MONO_TOKEN_TYPE_DEF: {
6685 guint32 cols [MONO_TYPEDEF_SIZE];
6686 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
6687 guint tidx = mono_metadata_token_index (type_token);
6689 if (tidx > tt->rows)
6690 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6692 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
6693 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6694 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6695 if (strlen (nspace) == 0)
6696 return g_strdup_printf ("%s", name);
6698 return g_strdup_printf ("%s.%s", nspace, name);
6701 case MONO_TOKEN_TYPE_REF: {
6703 guint32 cols [MONO_TYPEREF_SIZE];
6704 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
6705 guint tidx = mono_metadata_token_index (type_token);
6708 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6710 if (!mono_verifier_verify_typeref_row (image, tidx - 1, &error)) {
6711 char *msg = g_strdup_printf ("Invalid type token 0x%08x due to '%s'", type_token, mono_error_get_message (&error));
6712 mono_error_cleanup (&error);
6716 mono_metadata_decode_row (t, tidx-1, cols, MONO_TYPEREF_SIZE);
6717 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
6718 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
6719 if (strlen (nspace) == 0)
6720 return g_strdup_printf ("%s", name);
6722 return g_strdup_printf ("%s.%s", nspace, name);
6725 case MONO_TOKEN_TYPE_SPEC:
6726 return g_strdup_printf ("Typespec 0x%08x", type_token);
6728 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6733 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
6736 return g_strdup_printf ("DynamicAssembly %s", image->name);
6738 switch (type_token & 0xff000000){
6739 case MONO_TOKEN_TYPE_DEF:
6740 if (image->assembly)
6741 return mono_stringify_assembly_name (&image->assembly->aname);
6742 else if (image->assembly_name)
6743 return g_strdup (image->assembly_name);
6744 return g_strdup_printf ("%s", image->name ? image->name : "[Could not resolve assembly name");
6745 case MONO_TOKEN_TYPE_REF: {
6747 MonoAssemblyName aname;
6748 guint32 cols [MONO_TYPEREF_SIZE];
6749 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
6750 guint32 idx = mono_metadata_token_index (type_token);
6753 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6755 if (!mono_verifier_verify_typeref_row (image, idx - 1, &error)) {
6756 char *msg = g_strdup_printf ("Invalid type token 0x%08x due to '%s'", type_token, mono_error_get_message (&error));
6757 mono_error_cleanup (&error);
6760 mono_metadata_decode_row (t, idx-1, cols, MONO_TYPEREF_SIZE);
6762 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
6763 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
6764 case MONO_RESOLTION_SCOPE_MODULE:
6766 return g_strdup ("");
6767 case MONO_RESOLTION_SCOPE_MODULEREF:
6769 return g_strdup ("");
6770 case MONO_RESOLTION_SCOPE_TYPEREF:
6772 return g_strdup ("");
6773 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
6774 mono_assembly_get_assemblyref (image, idx - 1, &aname);
6775 return mono_stringify_assembly_name (&aname);
6777 g_assert_not_reached ();
6781 case MONO_TOKEN_TYPE_SPEC:
6783 return g_strdup ("");
6785 g_assert_not_reached ();
6792 * mono_class_get_full:
6793 * @image: the image where the class resides
6794 * @type_token: the token for the class
6795 * @context: the generic context used to evaluate generic instantiations in
6797 * Returns: the MonoClass that represents @type_token in @image
6800 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
6803 MonoClass *class = NULL;
6805 if (image->dynamic) {
6806 int table = mono_metadata_token_table (type_token);
6808 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
6809 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
6812 return mono_lookup_dynamic_token (image, type_token, context);
6815 switch (type_token & 0xff000000){
6816 case MONO_TOKEN_TYPE_DEF:
6817 class = mono_class_create_from_typedef (image, type_token);
6819 case MONO_TOKEN_TYPE_REF:
6820 class = mono_class_from_typeref (image, type_token);
6822 case MONO_TOKEN_TYPE_SPEC:
6823 class = mono_class_create_from_typespec (image, type_token, context, &error);
6824 if (!mono_error_ok (&error)) {
6825 /*FIXME don't swallow the error message*/
6826 mono_error_cleanup (&error);
6830 g_warning ("unknown token type %x", type_token & 0xff000000);
6831 g_assert_not_reached ();
6835 char *name = mono_class_name_from_token (image, type_token);
6836 char *assembly = mono_assembly_name_from_token (image, type_token);
6837 mono_loader_set_error_type_load (name, assembly);
6847 * mono_type_get_full:
6848 * @image: the image where the type resides
6849 * @type_token: the token for the type
6850 * @context: the generic context used to evaluate generic instantiations in
6852 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
6854 * Returns: the MonoType that represents @type_token in @image
6857 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
6860 MonoType *type = NULL;
6861 gboolean inflated = FALSE;
6863 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
6865 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
6867 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
6868 MonoClass *class = mono_class_get_full (image, type_token, context);
6869 return class ? mono_class_get_type (class) : NULL;
6872 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated, &error);
6874 if (!mono_error_ok (&error)) {
6875 /*FIXME don't swalloc the error message.*/
6876 char *name = mono_class_name_from_token (image, type_token);
6877 char *assembly = mono_assembly_name_from_token (image, type_token);
6879 g_warning ("Error loading type %s from %s due to %s", name, assembly, mono_error_get_message (&error));
6881 mono_error_cleanup (&error);
6882 mono_loader_set_error_type_load (name, assembly);
6887 MonoType *tmp = type;
6888 type = mono_class_get_type (mono_class_from_mono_type (type));
6889 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
6890 * A MonoClass::byval_arg of a generic type definion has type CLASS.
6891 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
6893 * The long term solution is to chaise this places and make then set MonoType::type correctly.
6895 if (type->type != tmp->type)
6898 mono_metadata_free_type (tmp);
6905 mono_class_get (MonoImage *image, guint32 type_token)
6907 return mono_class_get_full (image, type_token, NULL);
6911 * mono_image_init_name_cache:
6913 * Initializes the class name cache stored in image->name_cache.
6915 * LOCKING: Acquires the corresponding image lock.
6918 mono_image_init_name_cache (MonoImage *image)
6920 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
6921 guint32 cols [MONO_TYPEDEF_SIZE];
6924 guint32 i, visib, nspace_index;
6925 GHashTable *name_cache2, *nspace_table;
6927 mono_image_lock (image);
6929 if (image->name_cache) {
6930 mono_image_unlock (image);
6934 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
6936 if (image->dynamic) {
6937 mono_image_unlock (image);
6941 /* Temporary hash table to avoid lookups in the nspace_table */
6942 name_cache2 = g_hash_table_new (NULL, NULL);
6944 for (i = 1; i <= t->rows; ++i) {
6945 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
6946 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
6948 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
6949 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
6951 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
6953 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6954 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6956 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
6957 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6958 if (!nspace_table) {
6959 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6960 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6961 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6964 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
6967 /* Load type names from EXPORTEDTYPES table */
6969 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6970 guint32 cols [MONO_EXP_TYPE_SIZE];
6973 for (i = 0; i < t->rows; ++i) {
6974 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
6975 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
6976 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
6978 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
6979 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6980 if (!nspace_table) {
6981 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6982 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6983 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6986 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
6990 g_hash_table_destroy (name_cache2);
6991 mono_image_unlock (image);
6994 /*FIXME Only dynamic assemblies should allow this operation.*/
6996 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
6997 const char *name, guint32 index)
6999 GHashTable *nspace_table;
7000 GHashTable *name_cache;
7003 mono_image_lock (image);
7005 if (!image->name_cache)
7006 mono_image_init_name_cache (image);
7008 name_cache = image->name_cache;
7009 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
7010 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
7011 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
7014 if ((old_index = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, (char*) name))))
7015 g_error ("overrwritting old token %x on image %s for type %s::%s", old_index, image->name, nspace, name);
7017 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
7019 mono_image_unlock (image);
7028 find_nocase (gpointer key, gpointer value, gpointer user_data)
7030 char *name = (char*)key;
7031 FindUserData *data = (FindUserData*)user_data;
7033 if (!data->value && (mono_utf8_strcasecmp (name, (char*)data->key) == 0))
7034 data->value = value;
7038 * mono_class_from_name_case:
7039 * @image: The MonoImage where the type is looked up in
7040 * @name_space: the type namespace
7041 * @name: the type short name.
7043 * Obtains a MonoClass with a given namespace and a given name which
7044 * is located in the given MonoImage. The namespace and name
7045 * lookups are case insensitive.
7048 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
7050 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
7051 guint32 cols [MONO_TYPEDEF_SIZE];
7056 if (image->dynamic) {
7058 FindUserData user_data;
7060 mono_image_lock (image);
7062 if (!image->name_cache)
7063 mono_image_init_name_cache (image);
7065 user_data.key = name_space;
7066 user_data.value = NULL;
7067 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
7069 if (user_data.value) {
7070 GHashTable *nspace_table = (GHashTable*)user_data.value;
7072 user_data.key = name;
7073 user_data.value = NULL;
7075 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
7077 if (user_data.value)
7078 token = GPOINTER_TO_UINT (user_data.value);
7081 mono_image_unlock (image);
7084 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
7090 /* add a cache if needed */
7091 for (i = 1; i <= t->rows; ++i) {
7092 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
7093 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
7095 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
7096 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
7098 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
7100 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
7101 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
7102 if (mono_utf8_strcasecmp (n, name) == 0 && mono_utf8_strcasecmp (nspace, name_space) == 0)
7103 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
7109 return_nested_in (MonoClass *class, char *nested)
7112 char *s = strchr (nested, '/');
7113 gpointer iter = NULL;
7120 while ((found = mono_class_get_nested_types (class, &iter))) {
7121 if (strcmp (found->name, nested) == 0) {
7123 return return_nested_in (found, s);
7131 search_modules (MonoImage *image, const char *name_space, const char *name)
7133 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
7134 MonoImage *file_image;
7139 * The EXPORTEDTYPES table only contains public types, so have to search the
7141 * Note: image->modules contains the contents of the MODULEREF table, while
7142 * the real module list is in the FILE table.
7144 for (i = 0; i < file_table->rows; i++) {
7145 guint32 cols [MONO_FILE_SIZE];
7146 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
7147 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
7150 file_image = mono_image_load_file_for_image (image, i + 1);
7152 class = mono_class_from_name (file_image, name_space, name);
7162 * mono_class_from_name:
7163 * @image: The MonoImage where the type is looked up in
7164 * @name_space: the type namespace
7165 * @name: the type short name.
7167 * Obtains a MonoClass with a given namespace and a given name which
7168 * is located in the given MonoImage.
7171 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
7173 GHashTable *nspace_table;
7174 MonoImage *loaded_image;
7181 if ((nested = strchr (name, '/'))) {
7182 int pos = nested - name;
7183 int len = strlen (name);
7186 memcpy (buf, name, len + 1);
7188 nested = buf + pos + 1;
7192 /* FIXME: get_class_from_name () can't handle types in the EXPORTEDTYPE table */
7193 if (get_class_from_name && image->tables [MONO_TABLE_EXPORTEDTYPE].rows == 0) {
7194 gboolean res = get_class_from_name (image, name_space, name, &class);
7197 class = search_modules (image, name_space, name);
7199 return class ? return_nested_in (class, nested) : NULL;
7205 mono_image_lock (image);
7207 if (!image->name_cache)
7208 mono_image_init_name_cache (image);
7210 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
7213 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
7215 mono_image_unlock (image);
7217 if (!token && image->dynamic && image->modules) {
7218 /* Search modules as well */
7219 for (i = 0; i < image->module_count; ++i) {
7220 MonoImage *module = image->modules [i];
7222 class = mono_class_from_name (module, name_space, name);
7229 class = search_modules (image, name_space, name);
7237 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
7238 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
7239 guint32 cols [MONO_EXP_TYPE_SIZE];
7242 idx = mono_metadata_token_index (token);
7244 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
7246 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
7247 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
7248 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
7251 class = mono_class_from_name (loaded_image, name_space, name);
7253 return return_nested_in (class, nested);
7255 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
7256 guint32 assembly_idx;
7258 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
7260 mono_assembly_load_reference (image, assembly_idx - 1);
7261 g_assert (image->references [assembly_idx - 1]);
7262 if (image->references [assembly_idx - 1] == (gpointer)-1)
7265 /* FIXME: Cycle detection */
7266 return mono_class_from_name (image->references [assembly_idx - 1]->image, name_space, name);
7268 g_error ("not yet implemented");
7272 token = MONO_TOKEN_TYPE_DEF | token;
7274 class = mono_class_get (image, token);
7276 return return_nested_in (class, nested);
7280 /*FIXME test for interfaces with variant generic arguments*/
7282 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
7283 gboolean check_interfaces)
7285 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
7286 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
7288 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
7291 for (i = 0; i < klass->interface_count; i ++) {
7292 MonoClass *ic = klass->interfaces [i];
7297 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
7302 * MS.NET thinks interfaces are a subclass of Object, so we think it as
7305 if (klassc == mono_defaults.object_class)
7312 mono_type_is_generic_argument (MonoType *type)
7314 return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
7318 mono_class_has_variant_generic_params (MonoClass *klass)
7321 MonoGenericContainer *container;
7323 if (!klass->generic_class)
7326 container = klass->generic_class->container_class->generic_container;
7328 for (i = 0; i < container->type_argc; ++i)
7329 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
7336 mono_gparam_is_reference_conversible (MonoClass *target, MonoClass *candidate, gboolean check_for_reference_conv)
7338 if (target == candidate)
7341 if (check_for_reference_conv &&
7342 mono_type_is_generic_argument (&target->byval_arg) &&
7343 mono_type_is_generic_argument (&candidate->byval_arg)) {
7344 MonoGenericParam *gparam = candidate->byval_arg.data.generic_param;
7345 MonoGenericParamInfo *pinfo = mono_generic_param_info (gparam);
7347 if (!pinfo || (pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) == 0)
7350 if (!mono_class_is_assignable_from (target, candidate))
7356 * @container the generic container from the GTD
7357 * @klass: the class to be assigned to
7358 * @oklass: the source class
7360 * Both klass and oklass must be instances of the same generic interface.
7361 * Return true if @klass can be assigned to a @klass variable
7364 mono_class_is_variant_compatible (MonoClass *klass, MonoClass *oklass, gboolean check_for_reference_conv)
7367 MonoType **klass_argv, **oklass_argv;
7368 MonoClass *klass_gtd = mono_class_get_generic_type_definition (klass);
7369 MonoGenericContainer *container = klass_gtd->generic_container;
7371 if (klass == oklass)
7374 /*Viable candidates are instances of the same generic interface*/
7375 if (mono_class_get_generic_type_definition (oklass) != klass_gtd || oklass == klass_gtd)
7378 klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
7379 oklass_argv = &oklass->generic_class->context.class_inst->type_argv [0];
7381 for (j = 0; j < container->type_argc; ++j) {
7382 MonoClass *param1_class = mono_class_from_mono_type (klass_argv [j]);
7383 MonoClass *param2_class = mono_class_from_mono_type (oklass_argv [j]);
7385 if (param1_class->valuetype != param2_class->valuetype || (param1_class->valuetype && param1_class != param2_class))
7389 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
7390 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
7392 if (param1_class != param2_class) {
7393 if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_VARIANT) {
7394 if (!mono_gparam_is_reference_conversible (param1_class, param2_class, check_for_reference_conv))
7396 } else if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_COVARIANT) {
7397 if (!mono_gparam_is_reference_conversible (param2_class, param1_class, check_for_reference_conv))
7407 mono_gparam_is_assignable_from (MonoClass *target, MonoClass *candidate)
7409 MonoGenericParam *gparam, *ogparam;
7410 MonoGenericParamInfo *tinfo, *cinfo;
7411 MonoClass **candidate_class;
7412 gboolean class_constraint_satisfied, valuetype_constraint_satisfied;
7415 if (target == candidate)
7417 if (target->byval_arg.type != candidate->byval_arg.type)
7420 gparam = target->byval_arg.data.generic_param;
7421 ogparam = candidate->byval_arg.data.generic_param;
7422 tinfo = mono_generic_param_info (gparam);
7423 cinfo = mono_generic_param_info (ogparam);
7425 class_constraint_satisfied = FALSE;
7426 valuetype_constraint_satisfied = FALSE;
7428 /*candidate must have a super set of target's special constraints*/
7429 tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
7430 cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
7432 if (cinfo->constraints) {
7433 for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
7434 MonoClass *cc = *candidate_class;
7436 if (mono_type_is_reference (&cc->byval_arg) && !MONO_CLASS_IS_INTERFACE (cc))
7437 class_constraint_satisfied = TRUE;
7438 else if (!mono_type_is_reference (&cc->byval_arg) && !MONO_CLASS_IS_INTERFACE (cc))
7439 valuetype_constraint_satisfied = TRUE;
7442 class_constraint_satisfied |= (cmask & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) != 0;
7443 valuetype_constraint_satisfied |= (cmask & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) != 0;
7445 if ((tmask & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && !class_constraint_satisfied)
7447 if ((tmask & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && !valuetype_constraint_satisfied)
7449 if ((tmask & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !((cmask & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) ||
7450 valuetype_constraint_satisfied)) {
7455 /*candidate type constraints must be a superset of target's*/
7456 if (tinfo->constraints) {
7457 MonoClass **target_class;
7458 for (target_class = tinfo->constraints; *target_class; ++target_class) {
7459 MonoClass *tc = *target_class;
7462 * A constraint from @target might inflate into @candidate itself and in that case we don't need
7463 * check it's constraints since it satisfy the constraint by itself.
7465 if (mono_metadata_type_equal (&tc->byval_arg, &candidate->byval_arg))
7468 if (!cinfo->constraints)
7471 for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
7472 MonoClass *cc = *candidate_class;
7474 if (mono_class_is_assignable_from (tc, cc))
7478 * This happens when we have the following:
7480 * Bar<K> where K : IFace
7481 * Foo<T, U> where T : U where U : IFace
7483 * Bar<T> <- T here satisfy K constraint transitively through to U's constraint
7486 if (mono_type_is_generic_argument (&cc->byval_arg)) {
7487 if (mono_gparam_is_assignable_from (target, cc))
7491 if (!*candidate_class)
7496 /*candidate itself must have a constraint that satisfy target*/
7497 if (cinfo->constraints) {
7498 for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
7499 MonoClass *cc = *candidate_class;
7500 if (mono_class_is_assignable_from (target, cc))
7508 * mono_class_is_assignable_from:
7509 * @klass: the class to be assigned to
7510 * @oklass: the source class
7512 * Return: true if an instance of object oklass can be assigned to an
7513 * instance of object @klass
7516 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
7518 /*FIXME this will cause a lot of irrelevant stuff to be loaded.*/
7520 mono_class_init (klass);
7522 if (!oklass->inited)
7523 mono_class_init (oklass);
7525 if (klass->exception_type || oklass->exception_type)
7528 if (mono_type_is_generic_argument (&klass->byval_arg)) {
7529 if (!mono_type_is_generic_argument (&oklass->byval_arg))
7531 return mono_gparam_is_assignable_from (klass, oklass);
7534 if (MONO_CLASS_IS_INTERFACE (klass)) {
7535 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR)) {
7536 MonoGenericParam *gparam = oklass->byval_arg.data.generic_param;
7537 MonoClass **constraints = mono_generic_container_get_param_info (gparam->owner, gparam->num)->constraints;
7541 for (i = 0; constraints [i]; ++i) {
7542 if (mono_class_is_assignable_from (klass, constraints [i]))
7550 /* interface_offsets might not be set for dynamic classes */
7551 if (oklass->ref_info_handle && !oklass->interface_bitmap)
7553 * oklass might be a generic type parameter but they have
7554 * interface_offsets set.
7556 return mono_reflection_call_is_assignable_to (oklass, klass);
7557 if (!oklass->interface_bitmap)
7558 /* Happens with generic instances of not-yet created dynamic types */
7560 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
7563 if (mono_class_has_variant_generic_params (klass)) {
7566 mono_class_setup_interfaces (oklass, &error);
7567 if (!mono_error_ok (&error)) {
7568 mono_error_cleanup (&error);
7572 /*klass is a generic variant interface, We need to extract from oklass a list of ifaces which are viable candidates.*/
7573 for (i = 0; i < oklass->interface_offsets_count; ++i) {
7574 MonoClass *iface = oklass->interfaces_packed [i];
7576 if (mono_class_is_variant_compatible (klass, iface, FALSE))
7581 } else if (klass->delegate) {
7582 if (mono_class_has_variant_generic_params (klass) && mono_class_is_variant_compatible (klass, oklass, FALSE))
7584 }else if (klass->rank) {
7585 MonoClass *eclass, *eoclass;
7587 if (oklass->rank != klass->rank)
7590 /* vectors vs. one dimensional arrays */
7591 if (oklass->byval_arg.type != klass->byval_arg.type)
7594 eclass = klass->cast_class;
7595 eoclass = oklass->cast_class;
7598 * a is b does not imply a[] is b[] when a is a valuetype, and
7599 * b is a reference type.
7602 if (eoclass->valuetype) {
7603 if ((eclass == mono_defaults.enum_class) ||
7604 (eclass == mono_defaults.enum_class->parent) ||
7605 (eclass == mono_defaults.object_class))
7609 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
7610 } else if (mono_class_is_nullable (klass)) {
7611 if (mono_class_is_nullable (oklass))
7612 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
7614 return mono_class_is_assignable_from (klass->cast_class, oklass);
7615 } else if (klass == mono_defaults.object_class)
7618 return mono_class_has_parent (oklass, klass);
7621 /*Check if @oklass is variant compatible with @klass.*/
7623 mono_class_is_variant_compatible_slow (MonoClass *klass, MonoClass *oklass)
7626 MonoType **klass_argv, **oklass_argv;
7627 MonoClass *klass_gtd = mono_class_get_generic_type_definition (klass);
7628 MonoGenericContainer *container = klass_gtd->generic_container;
7630 /*Viable candidates are instances of the same generic interface*/
7631 if (mono_class_get_generic_type_definition (oklass) != klass_gtd || oklass == klass_gtd)
7634 klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
7635 oklass_argv = &oklass->generic_class->context.class_inst->type_argv [0];
7637 for (j = 0; j < container->type_argc; ++j) {
7638 MonoClass *param1_class = mono_class_from_mono_type (klass_argv [j]);
7639 MonoClass *param2_class = mono_class_from_mono_type (oklass_argv [j]);
7641 if (param1_class->valuetype != param2_class->valuetype)
7645 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
7646 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
7648 if (param1_class != param2_class) {
7649 if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_VARIANT) {
7650 if (!mono_class_is_assignable_from_slow (param1_class, param2_class))
7652 } else if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_COVARIANT) {
7653 if (!mono_class_is_assignable_from_slow (param2_class, param1_class))
7661 /*Check if @candidate implements the interface @target*/
7663 mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
7667 gboolean is_variant = mono_class_has_variant_generic_params (target);
7669 if (is_variant && MONO_CLASS_IS_INTERFACE (candidate)) {
7670 if (mono_class_is_variant_compatible_slow (target, candidate))
7675 if (candidate == target)
7678 /*A TypeBuilder can have more interfaces on tb->interfaces than on candidate->interfaces*/
7679 if (candidate->image->dynamic && !candidate->wastypebuilder) {
7680 MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (candidate);
7682 if (tb && tb->interfaces) {
7683 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
7684 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
7685 MonoClass *iface_class;
7687 /* we can't realize the type here since it can do pretty much anything. */
7690 iface_class = mono_class_from_mono_type (iface->type);
7691 if (iface_class == target)
7693 if (is_variant && mono_class_is_variant_compatible_slow (target, iface_class))
7695 if (mono_class_implement_interface_slow (target, iface_class))
7700 /*setup_interfaces don't mono_class_init anything*/
7701 mono_class_setup_interfaces (candidate, &error);
7702 if (!mono_error_ok (&error)) {
7703 mono_error_cleanup (&error);
7707 for (i = 0; i < candidate->interface_count; ++i) {
7708 if (candidate->interfaces [i] == target)
7711 if (is_variant && mono_class_is_variant_compatible_slow (target, candidate->interfaces [i]))
7714 if (mono_class_implement_interface_slow (target, candidate->interfaces [i]))
7718 candidate = candidate->parent;
7719 } while (candidate);
7725 * Check if @oklass can be assigned to @klass.
7726 * This function does the same as mono_class_is_assignable_from but is safe to be used from mono_class_init context.
7729 mono_class_is_assignable_from_slow (MonoClass *target, MonoClass *candidate)
7731 if (candidate == target)
7733 if (target == mono_defaults.object_class)
7736 if (mono_class_has_parent (candidate, target))
7739 /*If target is not an interface there is no need to check them.*/
7740 if (MONO_CLASS_IS_INTERFACE (target))
7741 return mono_class_implement_interface_slow (target, candidate);
7743 if (target->delegate && mono_class_has_variant_generic_params (target))
7744 return mono_class_is_variant_compatible (target, candidate, FALSE);
7746 /*FIXME properly handle nullables and arrays */
7747 /*FIXME properly handle (M)VAR */
7752 * mono_class_get_cctor:
7753 * @klass: A MonoClass pointer
7755 * Returns: the static constructor of @klass if it exists, NULL otherwise.
7758 mono_class_get_cctor (MonoClass *klass)
7760 MonoCachedClassInfo cached_info;
7762 if (klass->image->dynamic) {
7764 * has_cctor is not set for these classes because mono_class_init () is
7767 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
7770 if (!klass->has_cctor)
7773 if (mono_class_get_cached_class_info (klass, &cached_info))
7774 return mono_get_method (klass->image, cached_info.cctor_token, klass);
7776 if (klass->generic_class && !klass->methods)
7777 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
7779 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
7783 * mono_class_get_finalizer:
7784 * @klass: The MonoClass pointer
7786 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
7789 mono_class_get_finalizer (MonoClass *klass)
7791 MonoCachedClassInfo cached_info;
7794 mono_class_init (klass);
7795 if (!mono_class_has_finalizer (klass))
7798 if (mono_class_get_cached_class_info (klass, &cached_info))
7799 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
7801 mono_class_setup_vtable (klass);
7802 return klass->vtable [finalize_slot];
7807 * mono_class_needs_cctor_run:
7808 * @klass: the MonoClass pointer
7809 * @caller: a MonoMethod describing the caller
7811 * Determines whenever the class has a static constructor and whenever it
7812 * needs to be called when executing CALLER.
7815 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
7819 method = mono_class_get_cctor (klass);
7821 return (method == caller) ? FALSE : TRUE;
7827 * mono_class_array_element_size:
7830 * Returns: the number of bytes an element of type @klass
7831 * uses when stored into an array.
7834 mono_class_array_element_size (MonoClass *klass)
7836 MonoType *type = &klass->byval_arg;
7839 switch (type->type) {
7842 case MONO_TYPE_BOOLEAN:
7846 case MONO_TYPE_CHAR:
7855 case MONO_TYPE_CLASS:
7856 case MONO_TYPE_STRING:
7857 case MONO_TYPE_OBJECT:
7858 case MONO_TYPE_SZARRAY:
7859 case MONO_TYPE_ARRAY:
7861 case MONO_TYPE_MVAR:
7862 return sizeof (gpointer);
7867 case MONO_TYPE_VALUETYPE:
7868 if (type->data.klass->enumtype) {
7869 type = mono_class_enum_basetype (type->data.klass);
7870 klass = klass->element_class;
7873 return mono_class_instance_size (klass) - sizeof (MonoObject);
7874 case MONO_TYPE_GENERICINST:
7875 type = &type->data.generic_class->container_class->byval_arg;
7878 case MONO_TYPE_VOID:
7882 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
7888 * mono_array_element_size:
7889 * @ac: pointer to a #MonoArrayClass
7891 * Returns: the size of single array element.
7894 mono_array_element_size (MonoClass *ac)
7896 g_assert (ac->rank);
7897 return ac->sizes.element_size;
7901 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
7902 MonoGenericContext *context)
7904 if (image->dynamic) {
7905 MonoClass *tmp_handle_class;
7906 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
7908 g_assert (tmp_handle_class);
7910 *handle_class = tmp_handle_class;
7912 if (tmp_handle_class == mono_defaults.typehandle_class)
7913 return &((MonoClass*)obj)->byval_arg;
7918 switch (token & 0xff000000) {
7919 case MONO_TOKEN_TYPE_DEF:
7920 case MONO_TOKEN_TYPE_REF:
7921 case MONO_TOKEN_TYPE_SPEC: {
7924 *handle_class = mono_defaults.typehandle_class;
7925 type = mono_type_get_full (image, token, context);
7928 mono_class_init (mono_class_from_mono_type (type));
7929 /* We return a MonoType* as handle */
7932 case MONO_TOKEN_FIELD_DEF: {
7934 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
7938 *handle_class = mono_defaults.fieldhandle_class;
7939 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
7942 mono_class_init (class);
7943 return mono_class_get_field (class, token);
7945 case MONO_TOKEN_METHOD_DEF:
7946 case MONO_TOKEN_METHOD_SPEC: {
7948 meth = mono_get_method_full (image, token, NULL, context);
7950 *handle_class = mono_defaults.methodhandle_class;
7953 case MONO_TOKEN_MEMBER_REF: {
7954 guint32 cols [MONO_MEMBERREF_SIZE];
7956 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
7957 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
7958 mono_metadata_decode_blob_size (sig, &sig);
7959 if (*sig == 0x6) { /* it's a field */
7961 MonoClassField *field;
7962 field = mono_field_from_token (image, token, &klass, context);
7964 *handle_class = mono_defaults.fieldhandle_class;
7968 meth = mono_get_method_full (image, token, NULL, context);
7970 *handle_class = mono_defaults.methodhandle_class;
7975 g_warning ("Unknown token 0x%08x in ldtoken", token);
7982 * This function might need to call runtime functions so it can't be part
7983 * of the metadata library.
7985 static MonoLookupDynamicToken lookup_dynamic = NULL;
7988 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
7990 lookup_dynamic = func;
7994 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
7996 MonoClass *handle_class;
7998 return lookup_dynamic (image, token, TRUE, &handle_class, context);
8002 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
8004 return lookup_dynamic (image, token, valid_token, handle_class, context);
8007 static MonoGetCachedClassInfo get_cached_class_info = NULL;
8010 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
8012 get_cached_class_info = func;
8016 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
8018 if (!get_cached_class_info)
8021 return get_cached_class_info (klass, res);
8025 mono_install_get_class_from_name (MonoGetClassFromName func)
8027 get_class_from_name = func;
8031 mono_class_get_image (MonoClass *klass)
8033 return klass->image;
8037 * mono_class_get_element_class:
8038 * @klass: the MonoClass to act on
8040 * Returns: the element class of an array or an enumeration.
8043 mono_class_get_element_class (MonoClass *klass)
8045 return klass->element_class;
8049 * mono_class_is_valuetype:
8050 * @klass: the MonoClass to act on
8052 * Returns: true if the MonoClass represents a ValueType.
8055 mono_class_is_valuetype (MonoClass *klass)
8057 return klass->valuetype;
8061 * mono_class_is_enum:
8062 * @klass: the MonoClass to act on
8064 * Returns: true if the MonoClass represents an enumeration.
8067 mono_class_is_enum (MonoClass *klass)
8069 return klass->enumtype;
8073 * mono_class_enum_basetype:
8074 * @klass: the MonoClass to act on
8076 * Returns: the underlying type representation for an enumeration.
8079 mono_class_enum_basetype (MonoClass *klass)
8081 if (klass->element_class == klass)
8082 /* SRE or broken types */
8085 return &klass->element_class->byval_arg;
8089 * mono_class_get_parent
8090 * @klass: the MonoClass to act on
8092 * Returns: the parent class for this class.
8095 mono_class_get_parent (MonoClass *klass)
8097 return klass->parent;
8101 * mono_class_get_nesting_type;
8102 * @klass: the MonoClass to act on
8104 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
8107 mono_class_get_nesting_type (MonoClass *klass)
8109 return klass->nested_in;
8113 * mono_class_get_rank:
8114 * @klass: the MonoClass to act on
8116 * Returns: the rank for the array (the number of dimensions).
8119 mono_class_get_rank (MonoClass *klass)
8125 * mono_class_get_flags:
8126 * @klass: the MonoClass to act on
8128 * The type flags from the TypeDef table from the metadata.
8129 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
8132 * Returns: the flags from the TypeDef table.
8135 mono_class_get_flags (MonoClass *klass)
8137 return klass->flags;
8141 * mono_class_get_name
8142 * @klass: the MonoClass to act on
8144 * Returns: the name of the class.
8147 mono_class_get_name (MonoClass *klass)
8153 * mono_class_get_namespace:
8154 * @klass: the MonoClass to act on
8156 * Returns: the namespace of the class.
8159 mono_class_get_namespace (MonoClass *klass)
8161 return klass->name_space;
8165 * mono_class_get_type:
8166 * @klass: the MonoClass to act on
8168 * This method returns the internal Type representation for the class.
8170 * Returns: the MonoType from the class.
8173 mono_class_get_type (MonoClass *klass)
8175 return &klass->byval_arg;
8179 * mono_class_get_type_token
8180 * @klass: the MonoClass to act on
8182 * This method returns type token for the class.
8184 * Returns: the type token for the class.
8187 mono_class_get_type_token (MonoClass *klass)
8189 return klass->type_token;
8193 * mono_class_get_byref_type:
8194 * @klass: the MonoClass to act on
8199 mono_class_get_byref_type (MonoClass *klass)
8201 return &klass->this_arg;
8205 * mono_class_num_fields:
8206 * @klass: the MonoClass to act on
8208 * Returns: the number of static and instance fields in the class.
8211 mono_class_num_fields (MonoClass *klass)
8213 return klass->field.count;
8217 * mono_class_num_methods:
8218 * @klass: the MonoClass to act on
8220 * Returns: the number of methods in the class.
8223 mono_class_num_methods (MonoClass *klass)
8225 return klass->method.count;
8229 * mono_class_num_properties
8230 * @klass: the MonoClass to act on
8232 * Returns: the number of properties in the class.
8235 mono_class_num_properties (MonoClass *klass)
8237 mono_class_setup_properties (klass);
8239 return klass->ext->property.count;
8243 * mono_class_num_events:
8244 * @klass: the MonoClass to act on
8246 * Returns: the number of events in the class.
8249 mono_class_num_events (MonoClass *klass)
8251 mono_class_setup_events (klass);
8253 return klass->ext->event.count;
8257 * mono_class_get_fields:
8258 * @klass: the MonoClass to act on
8260 * This routine is an iterator routine for retrieving the fields in a class.
8262 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8263 * iterate over all of the elements. When no more values are
8264 * available, the return value is NULL.
8266 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
8269 mono_class_get_fields (MonoClass* klass, gpointer *iter)
8271 MonoClassField* field;
8275 mono_class_setup_fields_locking (klass);
8276 if (klass->exception_type)
8278 /* start from the first */
8279 if (klass->field.count) {
8280 return *iter = &klass->fields [0];
8288 if (field < &klass->fields [klass->field.count]) {
8289 return *iter = field;
8295 * mono_class_get_methods
8296 * @klass: the MonoClass to act on
8298 * This routine is an iterator routine for retrieving the fields in a class.
8300 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8301 * iterate over all of the elements. When no more values are
8302 * available, the return value is NULL.
8304 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
8307 mono_class_get_methods (MonoClass* klass, gpointer *iter)
8309 MonoMethod** method;
8313 mono_class_setup_methods (klass);
8316 * We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8317 * FIXME we should better report this error to the caller
8319 if (!klass->methods)
8321 /* start from the first */
8322 if (klass->method.count) {
8323 *iter = &klass->methods [0];
8324 return klass->methods [0];
8332 if (method < &klass->methods [klass->method.count]) {
8340 * mono_class_get_virtual_methods:
8342 * Iterate over the virtual methods of KLASS.
8344 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
8347 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
8349 MonoMethod** method;
8352 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
8354 mono_class_setup_methods (klass);
8356 * We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8357 * FIXME we should better report this error to the caller
8359 if (!klass->methods)
8361 /* start from the first */
8362 method = &klass->methods [0];
8367 while (method < &klass->methods [klass->method.count]) {
8368 if (*method && ((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
8372 if (method < &klass->methods [klass->method.count]) {
8379 /* Search directly in metadata to avoid calling setup_methods () */
8380 MonoMethod *res = NULL;
8386 start_index = GPOINTER_TO_UINT (*iter);
8389 for (i = start_index; i < klass->method.count; ++i) {
8392 /* class->method.first points into the methodptr table */
8393 flags = mono_metadata_decode_table_row_col (klass->image, MONO_TABLE_METHOD, klass->method.first + i, MONO_METHOD_FLAGS);
8395 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
8399 if (i < klass->method.count) {
8400 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
8401 /* Add 1 here so the if (*iter) check fails */
8402 *iter = GUINT_TO_POINTER (i + 1);
8411 * mono_class_get_properties:
8412 * @klass: the MonoClass to act on
8414 * This routine is an iterator routine for retrieving the properties in a class.
8416 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8417 * iterate over all of the elements. When no more values are
8418 * available, the return value is NULL.
8420 * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
8423 mono_class_get_properties (MonoClass* klass, gpointer *iter)
8425 MonoProperty* property;
8429 mono_class_setup_properties (klass);
8430 /* start from the first */
8431 if (klass->ext->property.count) {
8432 return *iter = &klass->ext->properties [0];
8440 if (property < &klass->ext->properties [klass->ext->property.count]) {
8441 return *iter = property;
8447 * mono_class_get_events:
8448 * @klass: the MonoClass to act on
8450 * This routine is an iterator routine for retrieving the properties in a class.
8452 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8453 * iterate over all of the elements. When no more values are
8454 * available, the return value is NULL.
8456 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
8459 mono_class_get_events (MonoClass* klass, gpointer *iter)
8465 mono_class_setup_events (klass);
8466 /* start from the first */
8467 if (klass->ext->event.count) {
8468 return *iter = &klass->ext->events [0];
8476 if (event < &klass->ext->events [klass->ext->event.count]) {
8477 return *iter = event;
8483 * mono_class_get_interfaces
8484 * @klass: the MonoClass to act on
8486 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
8488 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8489 * iterate over all of the elements. When no more values are
8490 * available, the return value is NULL.
8492 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
8495 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
8503 mono_class_init (klass);
8504 if (!klass->interfaces_inited) {
8505 mono_class_setup_interfaces (klass, &error);
8506 if (!mono_error_ok (&error)) {
8507 mono_error_cleanup (&error);
8511 /* start from the first */
8512 if (klass->interface_count) {
8513 *iter = &klass->interfaces [0];
8514 return klass->interfaces [0];
8522 if (iface < &klass->interfaces [klass->interface_count]) {
8530 * mono_class_get_nested_types
8531 * @klass: the MonoClass to act on
8533 * This routine is an iterator routine for retrieving the nested types of a class.
8534 * This works only if @klass is non-generic, or a generic type definition.
8536 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8537 * iterate over all of the elements. When no more values are
8538 * available, the return value is NULL.
8540 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
8543 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
8550 if (!klass->nested_classes_inited) {
8551 if (!klass->type_token)
8552 klass->nested_classes_inited = TRUE;
8553 mono_loader_lock ();
8554 if (!klass->nested_classes_inited) {
8555 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
8558 guint32 cols [MONO_NESTED_CLASS_SIZE];
8559 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
8560 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
8562 mono_loader_clear_error ();
8563 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
8566 mono_class_alloc_ext (klass);
8567 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
8569 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
8572 mono_memory_barrier ();
8573 klass->nested_classes_inited = TRUE;
8574 mono_loader_unlock ();
8578 /* start from the first */
8579 if (klass->ext && klass->ext->nested_classes) {
8580 *iter = klass->ext->nested_classes;
8581 return klass->ext->nested_classes->data;
8583 /* no nested types */
8597 * mono_field_get_name:
8598 * @field: the MonoClassField to act on
8600 * Returns: the name of the field.
8603 mono_field_get_name (MonoClassField *field)
8609 * mono_field_get_type:
8610 * @field: the MonoClassField to act on
8612 * Returns: MonoType of the field.
8615 mono_field_get_type (MonoClassField *field)
8618 MonoType *type = mono_field_get_type_checked (field, &error);
8619 if (!mono_error_ok (&error)) {
8620 mono_trace_warning (MONO_TRACE_TYPE, "Could not load field's type due to %s", mono_error_get_message (&error));
8621 mono_error_cleanup (&error);
8628 * mono_field_get_type_checked:
8629 * @field: the MonoClassField to act on
8630 * @error: used to return any erro found while retrieving @field type
8632 * Returns: MonoType of the field.
8635 mono_field_get_type_checked (MonoClassField *field, MonoError *error)
8637 mono_error_init (error);
8639 mono_field_resolve_type (field, error);
8644 * mono_field_get_parent:
8645 * @field: the MonoClassField to act on
8647 * Returns: MonoClass where the field was defined.
8650 mono_field_get_parent (MonoClassField *field)
8652 return field->parent;
8656 * mono_field_get_flags;
8657 * @field: the MonoClassField to act on
8659 * The metadata flags for a field are encoded using the
8660 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
8662 * Returns: the flags for the field.
8665 mono_field_get_flags (MonoClassField *field)
8668 return mono_field_resolve_flags (field);
8669 return field->type->attrs;
8673 * mono_field_get_offset;
8674 * @field: the MonoClassField to act on
8676 * Returns: the field offset.
8679 mono_field_get_offset (MonoClassField *field)
8681 return field->offset;
8685 mono_field_get_rva (MonoClassField *field)
8689 MonoClass *klass = field->parent;
8691 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
8693 if (!klass->ext || !klass->ext->field_def_values) {
8694 mono_loader_lock ();
8695 mono_class_alloc_ext (klass);
8696 if (!klass->ext->field_def_values)
8697 klass->ext->field_def_values = mono_class_alloc0 (klass, sizeof (MonoFieldDefaultValue) * klass->field.count);
8698 mono_loader_unlock ();
8701 field_index = mono_field_get_index (field);
8703 if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
8704 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
8706 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
8707 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
8710 return klass->ext->field_def_values [field_index].data;
8714 * mono_field_get_data;
8715 * @field: the MonoClassField to act on
8717 * Returns: pointer to the metadata constant value or to the field
8718 * data if it has an RVA flag.
8721 mono_field_get_data (MonoClassField *field)
8723 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
8724 MonoTypeEnum def_type;
8726 return mono_class_get_field_default_value (field, &def_type);
8727 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
8728 return mono_field_get_rva (field);
8735 * mono_property_get_name:
8736 * @prop: the MonoProperty to act on
8738 * Returns: the name of the property
8741 mono_property_get_name (MonoProperty *prop)
8747 * mono_property_get_set_method
8748 * @prop: the MonoProperty to act on.
8750 * Returns: the setter method of the property (A MonoMethod)
8753 mono_property_get_set_method (MonoProperty *prop)
8759 * mono_property_get_get_method
8760 * @prop: the MonoProperty to act on.
8762 * Returns: the setter method of the property (A MonoMethod)
8765 mono_property_get_get_method (MonoProperty *prop)
8771 * mono_property_get_parent:
8772 * @prop: the MonoProperty to act on.
8774 * Returns: the MonoClass where the property was defined.
8777 mono_property_get_parent (MonoProperty *prop)
8779 return prop->parent;
8783 * mono_property_get_flags:
8784 * @prop: the MonoProperty to act on.
8786 * The metadata flags for a property are encoded using the
8787 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
8789 * Returns: the flags for the property.
8792 mono_property_get_flags (MonoProperty *prop)
8798 * mono_event_get_name:
8799 * @event: the MonoEvent to act on
8801 * Returns: the name of the event.
8804 mono_event_get_name (MonoEvent *event)
8810 * mono_event_get_add_method:
8811 * @event: The MonoEvent to act on.
8813 * Returns: the @add' method for the event (a MonoMethod).
8816 mono_event_get_add_method (MonoEvent *event)
8822 * mono_event_get_remove_method:
8823 * @event: The MonoEvent to act on.
8825 * Returns: the @remove method for the event (a MonoMethod).
8828 mono_event_get_remove_method (MonoEvent *event)
8830 return event->remove;
8834 * mono_event_get_raise_method:
8835 * @event: The MonoEvent to act on.
8837 * Returns: the @raise method for the event (a MonoMethod).
8840 mono_event_get_raise_method (MonoEvent *event)
8842 return event->raise;
8846 * mono_event_get_parent:
8847 * @event: the MonoEvent to act on.
8849 * Returns: the MonoClass where the event is defined.
8852 mono_event_get_parent (MonoEvent *event)
8854 return event->parent;
8858 * mono_event_get_flags
8859 * @event: the MonoEvent to act on.
8861 * The metadata flags for an event are encoded using the
8862 * EVENT_* constants. See the tabledefs.h file for details.
8864 * Returns: the flags for the event.
8867 mono_event_get_flags (MonoEvent *event)
8869 return event->attrs;
8873 * mono_class_get_method_from_name:
8874 * @klass: where to look for the method
8875 * @name_space: name of the method
8876 * @param_count: number of parameters. -1 for any number.
8878 * Obtains a MonoMethod with a given name and number of parameters.
8879 * It only works if there are no multiple signatures for any given method name.
8882 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
8884 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
8888 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
8890 MonoMethod *res = NULL;
8893 /* Search directly in the metadata to avoid calling setup_methods () */
8894 for (i = 0; i < klass->method.count; ++i) {
8895 guint32 cols [MONO_METHOD_SIZE];
8897 MonoMethodSignature *sig;
8899 /* class->method.first points into the methodptr table */
8900 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
8902 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
8903 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
8904 if (param_count == -1) {
8908 sig = mono_method_signature (method);
8909 if (sig && sig->param_count == param_count) {
8920 * mono_class_get_method_from_name_flags:
8921 * @klass: where to look for the method
8922 * @name_space: name of the method
8923 * @param_count: number of parameters. -1 for any number.
8924 * @flags: flags which must be set in the method
8926 * Obtains a MonoMethod with a given name and number of parameters.
8927 * It only works if there are no multiple signatures for any given method name.
8930 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
8932 MonoMethod *res = NULL;
8935 mono_class_init (klass);
8937 if (klass->generic_class && !klass->methods) {
8938 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
8940 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
8944 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
8945 mono_class_setup_methods (klass);
8947 We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8948 See mono/tests/array_load_exception.il
8949 FIXME we should better report this error to the caller
8951 if (!klass->methods)
8953 for (i = 0; i < klass->method.count; ++i) {
8954 MonoMethod *method = klass->methods [i];
8956 if (method->name[0] == name [0] &&
8957 !strcmp (name, method->name) &&
8958 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
8959 ((method->flags & flags) == flags)) {
8966 res = find_method_in_metadata (klass, name, param_count, flags);
8973 * mono_class_set_failure:
8974 * @klass: class in which the failure was detected
8975 * @ex_type: the kind of exception/error to be thrown (later)
8976 * @ex_data: exception data (specific to each type of exception/error)
8978 * Keep a detected failure informations in the class for later processing.
8979 * Note that only the first failure is kept.
8981 * LOCKING: Acquires the loader lock.
8984 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
8986 if (klass->exception_type)
8989 mono_loader_lock ();
8990 klass->exception_type = ex_type;
8992 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
8993 mono_loader_unlock ();
8999 * mono_class_get_exception_data:
9001 * Return the exception_data property of KLASS.
9003 * LOCKING: Acquires the loader lock.
9006 mono_class_get_exception_data (MonoClass *klass)
9008 return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
9012 * mono_classes_init:
9014 * Initialize the resources used by this module.
9017 mono_classes_init (void)
9019 mono_counters_register ("Inflated methods size",
9020 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
9021 mono_counters_register ("Inflated classes",
9022 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
9023 mono_counters_register ("Inflated classes size",
9024 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
9025 mono_counters_register ("MonoClass size",
9026 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
9027 mono_counters_register ("MonoClassExt size",
9028 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
9032 * mono_classes_cleanup:
9034 * Free the resources used by this module.
9037 mono_classes_cleanup (void)
9039 if (global_interface_bitset)
9040 mono_bitset_free (global_interface_bitset);
9041 global_interface_bitset = NULL;
9045 * mono_class_get_exception_for_failure:
9046 * @klass: class in which the failure was detected
9048 * Return a constructed MonoException than the caller can then throw
9049 * using mono_raise_exception - or NULL if no failure is present (or
9050 * doesn't result in an exception).
9053 mono_class_get_exception_for_failure (MonoClass *klass)
9055 gpointer exception_data = mono_class_get_exception_data (klass);
9057 switch (klass->exception_type) {
9058 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
9059 MonoDomain *domain = mono_domain_get ();
9060 MonoSecurityManager* secman = mono_security_manager_get_methods ();
9061 MonoMethod *method = exception_data;
9062 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
9063 MonoObject *exc = NULL;
9067 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
9068 args [2] = mono_type_get_object (domain, &klass->byval_arg);
9069 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
9071 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
9072 return (MonoException*) exc;
9074 case MONO_EXCEPTION_TYPE_LOAD: {
9077 char *str = mono_type_get_full_name (klass);
9078 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
9079 name = mono_string_new (mono_domain_get (), str);
9081 ex = mono_get_exception_type_load (name, astr);
9085 case MONO_EXCEPTION_MISSING_METHOD: {
9086 char *class_name = exception_data;
9087 char *assembly_name = class_name + strlen (class_name) + 1;
9089 return mono_get_exception_missing_method (class_name, assembly_name);
9091 case MONO_EXCEPTION_MISSING_FIELD: {
9092 char *class_name = exception_data;
9093 char *member_name = class_name + strlen (class_name) + 1;
9095 return mono_get_exception_missing_field (class_name, member_name);
9097 case MONO_EXCEPTION_FILE_NOT_FOUND: {
9098 char *msg_format = exception_data;
9099 char *assembly_name = msg_format + strlen (msg_format) + 1;
9100 char *msg = g_strdup_printf (msg_format, assembly_name);
9103 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
9109 case MONO_EXCEPTION_BAD_IMAGE: {
9110 return mono_get_exception_bad_image_format (exception_data);
9113 MonoLoaderError *error;
9116 error = mono_loader_get_last_error ();
9118 ex = mono_loader_error_prepare_exception (error);
9122 /* TODO - handle other class related failures */
9129 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
9131 outer_klass = mono_class_get_generic_type_definition (outer_klass);
9132 inner_klass = mono_class_get_generic_type_definition (inner_klass);
9134 if (outer_klass == inner_klass)
9136 inner_klass = inner_klass->nested_in;
9137 } while (inner_klass);
9142 mono_class_get_generic_type_definition (MonoClass *klass)
9144 return klass->generic_class ? klass->generic_class->container_class : klass;
9148 * Check if @klass is a subtype of @parent ignoring generic instantiations.
9150 * Generic instantiations are ignored for all super types of @klass.
9152 * Visibility checks ignoring generic instantiations.
9155 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
9158 klass = mono_class_get_generic_type_definition (klass);
9159 parent = mono_class_get_generic_type_definition (parent);
9160 mono_class_setup_supertypes (klass);
9162 for (i = 0; i < klass->idepth; ++i) {
9163 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
9169 * Subtype can only access parent members with family protection if the site object
9170 * is subclass of Subtype. For example:
9171 * class A { protected int x; }
9173 * void valid_access () {
9177 * void invalid_access () {
9184 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
9186 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
9189 if (context_klass == NULL)
9191 /*if access_klass is not member_klass context_klass must be type compat*/
9192 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
9198 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
9201 if (accessing == accessed)
9203 if (!accessed || !accessing)
9206 /* extra safety under CoreCLR - the runtime does not verify the strongname signatures
9207 * anywhere so untrusted friends are not safe to access platform's code internals */
9208 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
9209 if (!mono_security_core_clr_can_access_internals (accessing->image, accessed->image))
9213 mono_assembly_load_friends (accessed);
9214 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
9215 MonoAssemblyName *friend = tmp->data;
9216 /* Be conservative with checks */
9219 if (strcmp (accessing->aname.name, friend->name))
9221 if (friend->public_key_token [0]) {
9222 if (!accessing->aname.public_key_token [0])
9224 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
9233 * If klass is a generic type or if it is derived from a generic type, return the
9234 * MonoClass of the generic definition
9235 * Returns NULL if not found
9238 get_generic_definition_class (MonoClass *klass)
9241 if (klass->generic_class && klass->generic_class->container_class)
9242 return klass->generic_class->container_class;
9243 klass = klass->parent;
9249 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
9252 for (i = 0; i < ginst->type_argc; ++i) {
9253 MonoType *type = ginst->type_argv[i];
9254 switch (type->type) {
9255 case MONO_TYPE_SZARRAY:
9256 if (!can_access_type (access_klass, type->data.klass))
9259 case MONO_TYPE_ARRAY:
9260 if (!can_access_type (access_klass, type->data.array->eklass))
9264 if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
9267 case MONO_TYPE_CLASS:
9268 case MONO_TYPE_VALUETYPE:
9269 case MONO_TYPE_GENERICINST:
9270 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
9278 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
9282 if (access_klass->image->assembly && access_klass->image->assembly->corlib_internal)
9285 if (access_klass->element_class && !access_klass->enumtype)
9286 access_klass = access_klass->element_class;
9288 if (member_klass->element_class && !member_klass->enumtype)
9289 member_klass = member_klass->element_class;
9291 access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
9293 if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
9296 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
9299 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
9302 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
9305 /*Non nested type with nested visibility. We just fail it.*/
9306 if (access_level >= TYPE_ATTRIBUTE_NESTED_PRIVATE && access_level <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM && member_klass->nested_in == NULL)
9309 switch (access_level) {
9310 case TYPE_ATTRIBUTE_NOT_PUBLIC:
9311 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9313 case TYPE_ATTRIBUTE_PUBLIC:
9316 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
9319 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
9320 return is_nesting_type (member_klass, access_klass);
9322 case TYPE_ATTRIBUTE_NESTED_FAMILY:
9323 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
9325 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
9326 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9328 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
9329 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
9330 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
9332 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
9333 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
9334 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
9339 /* FIXME: check visibility of type, too */
9341 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
9343 MonoClass *member_generic_def;
9344 if (access_klass->image->assembly && access_klass->image->assembly->corlib_internal)
9347 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
9348 access_klass->generic_container) &&
9349 (member_generic_def = get_generic_definition_class (member_klass))) {
9350 MonoClass *access_container;
9352 if (access_klass->generic_container)
9353 access_container = access_klass;
9355 access_container = access_klass->generic_class->container_class;
9357 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
9361 /* Partition I 8.5.3.2 */
9362 /* the access level values are the same for fields and methods */
9363 switch (access_level) {
9364 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
9365 /* same compilation unit */
9366 return access_klass->image == member_klass->image;
9367 case FIELD_ATTRIBUTE_PRIVATE:
9368 return access_klass == member_klass;
9369 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
9370 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
9371 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
9374 case FIELD_ATTRIBUTE_ASSEMBLY:
9375 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9376 case FIELD_ATTRIBUTE_FAMILY:
9377 if (is_valid_family_access (access_klass, member_klass, context_klass))
9380 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
9381 if (is_valid_family_access (access_klass, member_klass, context_klass))
9383 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9384 case FIELD_ATTRIBUTE_PUBLIC:
9391 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
9393 /* FIXME: check all overlapping fields */
9394 int can = can_access_member (method->klass, field->parent, NULL, mono_field_get_type (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9396 MonoClass *nested = method->klass->nested_in;
9398 can = can_access_member (nested, field->parent, NULL, mono_field_get_type (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9401 nested = nested->nested_in;
9408 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
9410 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9412 MonoClass *nested = method->klass->nested_in;
9414 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9417 nested = nested->nested_in;
9422 * with generics calls to explicit interface implementations can be expressed
9423 * directly: the method is private, but we must allow it. This may be opening
9424 * a hole or the generics code should handle this differently.
9425 * Maybe just ensure the interface type is public.
9427 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
9433 * mono_method_can_access_method_full:
9434 * @method: The caller method
9435 * @called: The called method
9436 * @context_klass: The static type on stack of the owner @called object used
9438 * This function must be used with instance calls, as they have more strict family accessibility.
9439 * It can be used with static methods, but context_klass should be NULL.
9441 * Returns: TRUE if caller have proper visibility and acessibility to @called
9444 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
9446 MonoClass *access_class = method->klass;
9447 MonoClass *member_class = called->klass;
9448 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9450 MonoClass *nested = access_class->nested_in;
9452 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9455 nested = nested->nested_in;
9462 can = can_access_type (access_class, member_class);
9464 MonoClass *nested = access_class->nested_in;
9466 can = can_access_type (nested, member_class);
9469 nested = nested->nested_in;
9476 if (called->is_inflated) {
9477 MonoMethodInflated * infl = (MonoMethodInflated*)called;
9478 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
9487 * mono_method_can_access_field_full:
9488 * @method: The caller method
9489 * @field: The accessed field
9490 * @context_klass: The static type on stack of the owner @field object used
9492 * This function must be used with instance fields, as they have more strict family accessibility.
9493 * It can be used with static fields, but context_klass should be NULL.
9495 * Returns: TRUE if caller have proper visibility and acessibility to @field
9498 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
9500 MonoClass *access_class = method->klass;
9501 MonoClass *member_class = field->parent;
9502 /* FIXME: check all overlapping fields */
9503 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9505 MonoClass *nested = access_class->nested_in;
9507 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9510 nested = nested->nested_in;
9517 can = can_access_type (access_class, member_class);
9519 MonoClass *nested = access_class->nested_in;
9521 can = can_access_type (nested, member_class);
9524 nested = nested->nested_in;
9534 * mono_type_is_valid_enum_basetype:
9535 * @type: The MonoType to check
9537 * Returns: TRUE if the type can be used as the basetype of an enum
9539 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
9540 switch (type->type) {
9543 case MONO_TYPE_BOOLEAN:
9546 case MONO_TYPE_CHAR:
9559 * mono_class_is_valid_enum:
9560 * @klass: An enum class to be validated
9562 * This method verify the required properties an enum should have.
9564 * Returns: TRUE if the informed enum class is valid
9566 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
9567 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
9568 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
9570 gboolean mono_class_is_valid_enum (MonoClass *klass) {
9571 MonoClassField * field;
9572 gpointer iter = NULL;
9573 gboolean found_base_field = FALSE;
9575 g_assert (klass->enumtype);
9576 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
9577 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
9581 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
9584 while ((field = mono_class_get_fields (klass, &iter))) {
9585 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
9586 if (found_base_field)
9588 found_base_field = TRUE;
9589 if (!mono_type_is_valid_enum_basetype (field->type))
9594 if (!found_base_field)
9597 if (klass->method.count > 0)
9604 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
9606 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
9610 * mono_class_setup_interface_id:
9612 * Initializes MonoClass::interface_id if required.
9614 * LOCKING: Acquires the loader lock.
9617 mono_class_setup_interface_id (MonoClass *class)
9619 mono_loader_lock ();
9620 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
9621 class->interface_id = mono_get_unique_iid (class);
9622 mono_loader_unlock ();
9626 * mono_class_alloc_ext:
9628 * Allocate klass->ext if not already done.
9629 * LOCKING: Assumes the loader lock is held.
9632 mono_class_alloc_ext (MonoClass *klass)
9635 klass->ext = mono_class_alloc0 (klass, sizeof (MonoClassExt));
9636 class_ext_size += sizeof (MonoClassExt);
9641 * mono_class_setup_interfaces:
9643 * Initialize class->interfaces/interfaces_count.
9644 * LOCKING: Acquires the loader lock.
9645 * This function can fail the type.
9648 mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
9652 mono_error_init (error);
9654 if (klass->interfaces_inited)
9657 mono_loader_lock ();
9659 if (klass->interfaces_inited) {
9660 mono_loader_unlock ();
9664 if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
9667 /* generic IList, ICollection, IEnumerable */
9668 klass->interface_count = 1;
9669 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
9671 args [0] = &klass->element_class->byval_arg;
9672 klass->interfaces [0] = mono_class_bind_generic_parameters (
9673 mono_defaults.generic_ilist_class, 1, args, FALSE);
9674 } else if (klass->generic_class) {
9675 MonoClass *gklass = klass->generic_class->container_class;
9677 klass->interface_count = gklass->interface_count;
9678 klass->interfaces = mono_class_new0 (klass, MonoClass *, klass->interface_count);
9679 for (i = 0; i < klass->interface_count; i++) {
9680 klass->interfaces [i] = mono_class_inflate_generic_class_checked (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class), error);
9681 if (!mono_error_ok (error)) {
9682 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not setup the interfaces"));
9683 klass->interfaces = NULL;
9689 mono_memory_barrier ();
9691 klass->interfaces_inited = TRUE;
9693 mono_loader_unlock ();
9697 mono_field_resolve_type (MonoClassField *field, MonoError *error)
9699 MonoClass *class = field->parent;
9700 MonoImage *image = class->image;
9701 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
9702 int field_idx = field - class->fields;
9704 mono_error_init (error);
9707 MonoClassField *gfield = >d->fields [field_idx];
9708 MonoType *gtype = mono_field_get_type_checked (gfield, error);
9709 if (!mono_error_ok (error)) {
9710 char *err_msg = g_strdup_printf ("Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
9711 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
9715 field->type = mono_class_inflate_generic_type_no_copy (image, gtype, mono_class_get_context (class), error);
9716 if (!mono_error_ok (error)) {
9717 char *err_msg = g_strdup_printf ("Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
9718 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
9723 guint32 cols [MONO_FIELD_SIZE];
9724 MonoGenericContainer *container = NULL;
9725 int idx = class->field.first + field_idx;
9727 /*FIXME, in theory we do not lazy load SRE fields*/
9728 g_assert (!image->dynamic);
9730 if (class->generic_container) {
9731 container = class->generic_container;
9733 container = gtd->generic_container;
9734 g_assert (container);
9737 /* class->field.first and idx points into the fieldptr table */
9738 mono_metadata_decode_table_row (image, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
9740 if (!mono_verifier_verify_field_signature (image, cols [MONO_FIELD_SIGNATURE], NULL)) {
9741 mono_error_set_type_load_class (error, class, "Could not verify field %s signature", field->name);
9742 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
9746 sig = mono_metadata_blob_heap (image, cols [MONO_FIELD_SIGNATURE]);
9748 mono_metadata_decode_value (sig, &sig);
9749 /* FIELD signature == 0x06 */
9750 g_assert (*sig == 0x06);
9751 field->type = mono_metadata_parse_type_full (image, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
9753 mono_error_set_type_load_class (error, class, "Could not load field %s type", field->name);
9754 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
9755 mono_loader_clear_error ();
9761 mono_field_resolve_flags (MonoClassField *field)
9763 MonoClass *class = field->parent;
9764 MonoImage *image = class->image;
9765 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
9766 int field_idx = field - class->fields;
9770 MonoClassField *gfield = >d->fields [field_idx];
9771 return mono_field_get_flags (gfield);
9773 int idx = class->field.first + field_idx;
9775 /*FIXME, in theory we do not lazy load SRE fields*/
9776 g_assert (!image->dynamic);
9778 return mono_metadata_decode_table_row_col (image, MONO_TABLE_FIELD, idx, MONO_FIELD_FLAGS);
9783 * mono_class_setup_basic_field_info:
9784 * @class: The class to initialize
9786 * Initializes the class->fields array of fields.
9787 * Aquires the loader lock.
9790 mono_class_setup_basic_field_info_locking (MonoClass *class)
9792 mono_loader_lock ();
9793 mono_class_setup_basic_field_info (class);
9794 mono_loader_unlock ();
9798 * mono_class_get_fields_lazy:
9799 * @klass: the MonoClass to act on
9801 * This routine is an iterator routine for retrieving the fields in a class.
9802 * Only minimal information about fields are loaded. Accessors must be used
9803 * for all MonoClassField returned.
9805 * You must pass a gpointer that points to zero and is treated as an opaque handle to
9806 * iterate over all of the elements. When no more values are
9807 * available, the return value is NULL.
9809 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
9812 mono_class_get_fields_lazy (MonoClass* klass, gpointer *iter)
9814 MonoClassField* field;
9818 mono_class_setup_basic_field_info_locking (klass);
9821 /* start from the first */
9822 if (klass->field.count) {
9823 return *iter = &klass->fields [0];
9831 if (field < &klass->fields [klass->field.count]) {
9832 return *iter = field;