2 * class.c: Class management for the Mono runtime
5 * Miguel de Icaza (miguel@ximian.com)
7 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
19 #include <mono/io-layer/atomic.h>
21 #include <mono/metadata/image.h>
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/metadata.h>
24 #include <mono/metadata/metadata-internals.h>
25 #include <mono/metadata/profiler-private.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/tokentype.h>
28 #include <mono/metadata/class-internals.h>
29 #include <mono/metadata/object.h>
30 #include <mono/metadata/appdomain.h>
31 #include <mono/metadata/mono-endian.h>
32 #include <mono/metadata/debug-helpers.h>
33 #include <mono/metadata/reflection.h>
34 #include <mono/metadata/exception.h>
35 #include <mono/metadata/security-manager.h>
36 #include <mono/metadata/security-core-clr.h>
37 #include <mono/metadata/attrdefs.h>
38 #include <mono/metadata/gc-internal.h>
39 #include <mono/metadata/verify-internals.h>
40 #include <mono/metadata/mono-debug.h>
41 #include <mono/utils/mono-counters.h>
42 #include <mono/utils/mono-string.h>
43 #include <mono/utils/mono-error-internals.h>
44 #include <mono/utils/mono-logger-internal.h>
47 gboolean mono_print_vtable = FALSE;
50 guint32 inflated_classes, inflated_classes_size, inflated_methods_size;
51 guint32 classes_size, class_ext_size;
53 /* Function supplied by the runtime to find classes by name using information from the AOT file */
54 static MonoGetClassFromName get_class_from_name = NULL;
56 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
57 static gboolean mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res);
58 static gboolean can_access_type (MonoClass *access_klass, MonoClass *member_klass);
59 static MonoMethod* find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags);
60 static int generic_array_methods (MonoClass *class);
61 static void setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos);
63 static MonoMethod* mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter);
64 static char* mono_assembly_name_from_token (MonoImage *image, guint32 type_token);
65 static void mono_field_resolve_type (MonoClassField *field, MonoError *error);
66 static guint32 mono_field_resolve_flags (MonoClassField *field);
67 static void mono_class_setup_vtable_full (MonoClass *class, GList *in_setup);
70 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
71 void (*mono_debugger_class_loaded_methods_func) (MonoClass *klass) = NULL;
74 * mono_class_from_typeref:
76 * @type_token: a TypeRef token
78 * Creates the MonoClass* structure representing the type defined by
79 * the typeref token valid inside @image.
80 * Returns: the MonoClass* representing the typeref token, NULL ifcould
84 mono_class_from_typeref (MonoImage *image, guint32 type_token)
87 guint32 cols [MONO_TYPEREF_SIZE];
88 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
90 const char *name, *nspace;
94 if (!mono_verifier_verify_typeref_row (image, (type_token & 0xffffff) - 1, &error)) {
95 mono_trace_warning (MONO_TRACE_TYPE, "Failed to resolve typeref from %s due to '%s'", image->name, mono_error_get_message (&error));
99 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
101 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
102 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
104 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
105 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
106 case MONO_RESOLTION_SCOPE_MODULE:
108 g_error ("null ResolutionScope not yet handled");
109 /* a typedef in disguise */
110 return mono_class_from_name (image, nspace, name);
111 case MONO_RESOLTION_SCOPE_MODULEREF:
112 module = mono_image_load_module (image, idx);
114 return mono_class_from_name (module, nspace, name);
116 char *msg = g_strdup_printf ("%s%s%s", nspace, nspace [0] ? "." : "", name);
119 human_name = mono_stringify_assembly_name (&image->assembly->aname);
120 mono_loader_set_error_type_load (msg, human_name);
126 case MONO_RESOLTION_SCOPE_TYPEREF: {
127 MonoClass *enclosing;
130 if (idx == mono_metadata_token_index (type_token)) {
131 mono_loader_set_error_bad_image (g_strdup_printf ("Image %s with self-referencing typeref token %08x.", image->name, type_token));
135 enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
139 if (enclosing->nested_classes_inited && enclosing->ext) {
140 /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
141 for (tmp = enclosing->ext->nested_classes; tmp; tmp = tmp->next) {
143 if (strcmp (res->name, name) == 0)
147 /* Don't call mono_class_init as we might've been called by it recursively */
148 int i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, 1);
150 guint32 class_nested = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, MONO_NESTED_CLASS_NESTED);
151 guint32 string_offset = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_TYPEDEF], class_nested - 1, MONO_TYPEDEF_NAME);
152 const char *nname = mono_metadata_string_heap (enclosing->image, string_offset);
154 if (strcmp (nname, name) == 0)
155 return mono_class_create_from_typedef (enclosing->image, MONO_TOKEN_TYPE_DEF | class_nested);
157 i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, i + 1);
160 g_warning ("TypeRef ResolutionScope not yet handled (%d) for %s.%s in image %s", idx, nspace, name, image->name);
163 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
167 if (idx > image->tables [MONO_TABLE_ASSEMBLYREF].rows) {
168 mono_loader_set_error_bad_image (g_strdup_printf ("Image %s with invalid assemblyref token %08x.", image->name, idx));
172 if (!image->references || !image->references [idx - 1])
173 mono_assembly_load_reference (image, idx - 1);
174 g_assert (image->references [idx - 1]);
176 /* If the assembly did not load, register this as a type load exception */
177 if (image->references [idx - 1] == REFERENCE_MISSING){
178 MonoAssemblyName aname;
181 mono_assembly_get_assemblyref (image, idx - 1, &aname);
182 human_name = mono_stringify_assembly_name (&aname);
183 mono_loader_set_error_assembly_load (human_name, image->assembly ? image->assembly->ref_only : FALSE);
189 return mono_class_from_name (image->references [idx - 1]->image, nspace, name);
194 mono_image_memdup (MonoImage *image, void *data, guint size)
196 void *res = mono_image_alloc (image, size);
197 memcpy (res, data, size);
201 /* Copy everything mono_metadata_free_array free. */
203 mono_dup_array_type (MonoImage *image, MonoArrayType *a)
206 a = mono_image_memdup (image, a, sizeof (MonoArrayType));
208 a->sizes = mono_image_memdup (image, a->sizes, a->numsizes * sizeof (int));
210 a->lobounds = mono_image_memdup (image, a->lobounds, a->numlobounds * sizeof (int));
212 a = g_memdup (a, sizeof (MonoArrayType));
214 a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
216 a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
221 /* Copy everything mono_metadata_free_method_signature free. */
223 mono_metadata_signature_deep_dup (MonoImage *image, MonoMethodSignature *sig)
227 sig = mono_metadata_signature_dup_full (image, sig);
229 sig->ret = mono_metadata_type_dup (image, sig->ret);
230 for (i = 0; i < sig->param_count; ++i)
231 sig->params [i] = mono_metadata_type_dup (image, sig->params [i]);
237 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
239 MonoAssembly *ta = klass->image->assembly;
242 name = mono_stringify_assembly_name (&ta->aname);
243 g_string_append_printf (str, ", %s", name);
248 mono_type_name_check_byref (MonoType *type, GString *str)
251 g_string_append_c (str, '&');
255 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
256 MonoTypeNameFormat format)
260 switch (type->type) {
261 case MONO_TYPE_ARRAY: {
262 int i, rank = type->data.array->rank;
263 MonoTypeNameFormat nested_format;
265 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
266 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
268 mono_type_get_name_recurse (
269 &type->data.array->eklass->byval_arg, str, FALSE, nested_format);
270 g_string_append_c (str, '[');
272 g_string_append_c (str, '*');
273 for (i = 1; i < rank; i++)
274 g_string_append_c (str, ',');
275 g_string_append_c (str, ']');
277 mono_type_name_check_byref (type, str);
279 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
280 _mono_type_get_assembly_name (type->data.array->eklass, str);
283 case MONO_TYPE_SZARRAY: {
284 MonoTypeNameFormat nested_format;
286 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
287 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
289 mono_type_get_name_recurse (
290 &type->data.klass->byval_arg, str, FALSE, nested_format);
291 g_string_append (str, "[]");
293 mono_type_name_check_byref (type, str);
295 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
296 _mono_type_get_assembly_name (type->data.klass, str);
299 case MONO_TYPE_PTR: {
300 MonoTypeNameFormat nested_format;
302 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
303 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
305 mono_type_get_name_recurse (
306 type->data.type, str, FALSE, nested_format);
307 g_string_append_c (str, '*');
309 mono_type_name_check_byref (type, str);
311 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
312 _mono_type_get_assembly_name (mono_class_from_mono_type (type->data.type), str);
317 if (!mono_generic_param_info (type->data.generic_param))
318 g_string_append_printf (str, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", type->data.generic_param->num);
320 g_string_append (str, mono_generic_param_info (type->data.generic_param)->name);
322 mono_type_name_check_byref (type, str);
326 klass = mono_class_from_mono_type (type);
327 if (klass->nested_in) {
328 mono_type_get_name_recurse (
329 &klass->nested_in->byval_arg, str, TRUE, format);
330 if (format == MONO_TYPE_NAME_FORMAT_IL)
331 g_string_append_c (str, '.');
333 g_string_append_c (str, '+');
334 } else if (*klass->name_space) {
335 g_string_append (str, klass->name_space);
336 g_string_append_c (str, '.');
338 if (format == MONO_TYPE_NAME_FORMAT_IL) {
339 char *s = strchr (klass->name, '`');
340 int len = s ? s - klass->name : strlen (klass->name);
342 g_string_append_len (str, klass->name, len);
344 g_string_append (str, klass->name);
347 if (klass->generic_class) {
348 MonoGenericClass *gclass = klass->generic_class;
349 MonoGenericInst *inst = gclass->context.class_inst;
350 MonoTypeNameFormat nested_format;
353 nested_format = format == MONO_TYPE_NAME_FORMAT_FULL_NAME ?
354 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED : format;
356 if (format == MONO_TYPE_NAME_FORMAT_IL)
357 g_string_append_c (str, '<');
359 g_string_append_c (str, '[');
360 for (i = 0; i < inst->type_argc; i++) {
361 MonoType *t = inst->type_argv [i];
364 g_string_append_c (str, ',');
365 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
366 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
367 g_string_append_c (str, '[');
368 mono_type_get_name_recurse (inst->type_argv [i], str, FALSE, nested_format);
369 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
370 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
371 g_string_append_c (str, ']');
373 if (format == MONO_TYPE_NAME_FORMAT_IL)
374 g_string_append_c (str, '>');
376 g_string_append_c (str, ']');
377 } else if (klass->generic_container &&
378 (format != MONO_TYPE_NAME_FORMAT_FULL_NAME) &&
379 (format != MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)) {
382 if (format == MONO_TYPE_NAME_FORMAT_IL)
383 g_string_append_c (str, '<');
385 g_string_append_c (str, '[');
386 for (i = 0; i < klass->generic_container->type_argc; i++) {
388 g_string_append_c (str, ',');
389 g_string_append (str, mono_generic_container_get_param_info (klass->generic_container, i)->name);
391 if (format == MONO_TYPE_NAME_FORMAT_IL)
392 g_string_append_c (str, '>');
394 g_string_append_c (str, ']');
397 mono_type_name_check_byref (type, str);
399 if ((format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
400 (type->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
401 _mono_type_get_assembly_name (klass, str);
407 * mono_type_get_name_full:
409 * @format: the format for the return string.
412 * Returns: the string representation in a number of formats:
414 * if format is MONO_TYPE_NAME_FORMAT_REFLECTION, the return string is
415 * returned in the formatrequired by System.Reflection, this is the
416 * inverse of mono_reflection_parse_type ().
418 * if format is MONO_TYPE_NAME_FORMAT_IL, it returns a syntax that can
419 * be used by the IL assembler.
421 * if format is MONO_TYPE_NAME_FORMAT_FULL_NAME
423 * if format is MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED
426 mono_type_get_name_full (MonoType *type, MonoTypeNameFormat format)
430 result = g_string_new ("");
432 mono_type_get_name_recurse (type, result, FALSE, format);
434 return g_string_free (result, FALSE);
438 * mono_type_get_full_name:
441 * Returns: the string representation for type as required by System.Reflection.
442 * The inverse of mono_reflection_parse_type ().
445 mono_type_get_full_name (MonoClass *class)
447 return mono_type_get_name_full (mono_class_get_type (class), MONO_TYPE_NAME_FORMAT_REFLECTION);
451 * mono_type_get_name:
454 * Returns: the string representation for type as it would be represented in IL code.
457 mono_type_get_name (MonoType *type)
459 return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_IL);
463 * mono_type_get_underlying_type:
466 * Returns: the MonoType for the underlying integer type if @type
467 * is an enum and byref is false, otherwise the type itself.
470 mono_type_get_underlying_type (MonoType *type)
472 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype && !type->byref)
473 return mono_class_enum_basetype (type->data.klass);
474 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype && !type->byref)
475 return mono_class_enum_basetype (type->data.generic_class->container_class);
480 * mono_class_is_open_constructed_type:
483 * Returns TRUE if type represents a generics open constructed type.
484 * IOW, not all type parameters required for the instantiation have
485 * been provided or it's a generic type definition.
487 * An open constructed type means it's a non realizable type. Not to
488 * be mixed up with an abstract type - we can't cast or dispatch to
489 * an open type, for example.
492 mono_class_is_open_constructed_type (MonoType *t)
498 case MONO_TYPE_SZARRAY:
499 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
500 case MONO_TYPE_ARRAY:
501 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
503 return mono_class_is_open_constructed_type (t->data.type);
504 case MONO_TYPE_GENERICINST:
505 return t->data.generic_class->context.class_inst->is_open;
506 case MONO_TYPE_CLASS:
507 case MONO_TYPE_VALUETYPE:
508 return t->data.klass->generic_container != NULL;
515 inflate_generic_type (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
517 mono_error_init (error);
519 switch (type->type) {
520 case MONO_TYPE_MVAR: {
522 int num = mono_type_get_generic_param_num (type);
523 MonoGenericInst *inst = context->method_inst;
524 if (!inst || !inst->type_argv)
526 if (num >= inst->type_argc) {
527 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
528 mono_error_set_bad_image (error, image, "MVAR %d (%s) cannot be expanded in this context with %d instantiations",
529 num, info ? info->name : "", inst->type_argc);
534 * Note that the VAR/MVAR cases are different from the rest. The other cases duplicate @type,
535 * while the VAR/MVAR duplicates a type from the context. So, we need to ensure that the
536 * ->byref and ->attrs from @type are propagated to the returned type.
538 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
539 nt->byref = type->byref;
540 nt->attrs = type->attrs;
543 case MONO_TYPE_VAR: {
545 int num = mono_type_get_generic_param_num (type);
546 MonoGenericInst *inst = context->class_inst;
549 if (num >= inst->type_argc) {
550 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
551 mono_error_set_bad_image (error, image, "VAR %d (%s) cannot be expanded in this context with %d instantiations",
552 num, info ? info->name : "", inst->type_argc);
555 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
556 nt->byref = type->byref;
557 nt->attrs = type->attrs;
560 case MONO_TYPE_SZARRAY: {
561 MonoClass *eclass = type->data.klass;
562 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
563 if (!inflated || !mono_error_ok (error))
565 nt = mono_metadata_type_dup (image, type);
566 nt->data.klass = mono_class_from_mono_type (inflated);
567 mono_metadata_free_type (inflated);
570 case MONO_TYPE_ARRAY: {
571 MonoClass *eclass = type->data.array->eklass;
572 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
573 if (!inflated || !mono_error_ok (error))
575 nt = mono_metadata_type_dup (image, type);
576 nt->data.array->eklass = mono_class_from_mono_type (inflated);
577 mono_metadata_free_type (inflated);
580 case MONO_TYPE_GENERICINST: {
581 MonoGenericClass *gclass = type->data.generic_class;
582 MonoGenericInst *inst;
584 if (!gclass->context.class_inst->is_open)
587 inst = mono_metadata_inflate_generic_inst (gclass->context.class_inst, context, error);
588 if (!mono_error_ok (error))
590 if (inst != gclass->context.class_inst)
591 gclass = mono_metadata_lookup_generic_class (gclass->container_class, inst, gclass->is_dynamic);
593 if (gclass == type->data.generic_class)
596 nt = mono_metadata_type_dup (image, type);
597 nt->data.generic_class = gclass;
600 case MONO_TYPE_CLASS:
601 case MONO_TYPE_VALUETYPE: {
602 MonoClass *klass = type->data.klass;
603 MonoGenericContainer *container = klass->generic_container;
604 MonoGenericInst *inst;
605 MonoGenericClass *gclass = NULL;
611 /* We can't use context->class_inst directly, since it can have more elements */
612 inst = mono_metadata_inflate_generic_inst (container->context.class_inst, context, error);
613 if (!mono_error_ok (error))
615 if (inst == container->context.class_inst)
618 gclass = mono_metadata_lookup_generic_class (klass, inst, klass->image->dynamic);
620 nt = mono_metadata_type_dup (image, type);
621 nt->type = MONO_TYPE_GENERICINST;
622 nt->data.generic_class = gclass;
632 mono_generic_class_get_context (MonoGenericClass *gclass)
634 return &gclass->context;
638 mono_class_get_context (MonoClass *class)
640 return class->generic_class ? mono_generic_class_get_context (class->generic_class) : NULL;
644 * mono_class_get_generic_container:
646 * Return the generic container of KLASS which should be a generic type definition.
648 MonoGenericContainer*
649 mono_class_get_generic_container (MonoClass *klass)
651 g_assert (klass->is_generic);
653 return klass->generic_container;
657 * mono_class_get_generic_class:
659 * Return the MonoGenericClass of KLASS, which should be a generic instance.
662 mono_class_get_generic_class (MonoClass *klass)
664 g_assert (klass->is_inflated);
666 return klass->generic_class;
670 * mono_class_inflate_generic_type_with_mempool:
671 * @mempool: a mempool
673 * @context: a generics context
674 * @error: error context
676 * The same as mono_class_inflate_generic_type, but allocates the MonoType
677 * from mempool if it is non-NULL. If it is NULL, the MonoType is
678 * allocated on the heap and is owned by the caller.
679 * The returned type can potentially be the same as TYPE, so it should not be
680 * modified by the caller, and it should be freed using mono_metadata_free_type ().
683 mono_class_inflate_generic_type_with_mempool (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
685 MonoType *inflated = NULL;
686 mono_error_init (error);
689 inflated = inflate_generic_type (image, type, context, error);
690 if (!mono_error_ok (error))
694 MonoType *shared = mono_metadata_get_shared_type (type);
699 return mono_metadata_type_dup (image, type);
703 mono_stats.inflated_type_count++;
708 * mono_class_inflate_generic_type:
710 * @context: a generics context
712 * If @type is a generic type and @context is not NULL, instantiate it using the
713 * generics context @context.
715 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
716 * on the heap and is owned by the caller. Returns NULL on error.
718 * @deprecated Please use mono_class_inflate_generic_type_checked instead
721 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
725 result = mono_class_inflate_generic_type_checked (type, context, &error);
727 if (!mono_error_ok (&error)) {
728 mono_error_cleanup (&error);
735 * mono_class_inflate_generic_type:
737 * @context: a generics context
738 * @error: error context to use
740 * If @type is a generic type and @context is not NULL, instantiate it using the
741 * generics context @context.
743 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
744 * on the heap and is owned by the caller.
747 mono_class_inflate_generic_type_checked (MonoType *type, MonoGenericContext *context, MonoError *error)
749 return mono_class_inflate_generic_type_with_mempool (NULL, type, context, error);
753 * mono_class_inflate_generic_type_no_copy:
755 * Same as inflate_generic_type_with_mempool, but return TYPE if no inflation
759 mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
761 MonoType *inflated = NULL;
763 mono_error_init (error);
765 inflated = inflate_generic_type (image, type, context, error);
766 if (!mono_error_ok (error))
773 mono_stats.inflated_type_count++;
778 mono_class_inflate_generic_class_checked (MonoClass *gklass, MonoGenericContext *context, MonoError *error)
783 inflated = mono_class_inflate_generic_type_checked (&gklass->byval_arg, context, error);
784 if (!mono_error_ok (error))
787 res = mono_class_from_mono_type (inflated);
788 mono_metadata_free_type (inflated);
793 * mono_class_inflate_generic_class:
795 * Inflate the class GKLASS with CONTEXT.
798 mono_class_inflate_generic_class (MonoClass *gklass, MonoGenericContext *context)
803 res = mono_class_inflate_generic_class_checked (gklass, context, &error);
804 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
811 static MonoGenericContext
812 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with, MonoError *error)
814 MonoGenericInst *class_inst = NULL;
815 MonoGenericInst *method_inst = NULL;
816 MonoGenericContext res = { NULL, NULL };
818 mono_error_init (error);
820 if (context->class_inst) {
821 class_inst = mono_metadata_inflate_generic_inst (context->class_inst, inflate_with, error);
822 if (!mono_error_ok (error))
826 if (context->method_inst) {
827 method_inst = mono_metadata_inflate_generic_inst (context->method_inst, inflate_with, error);
828 if (!mono_error_ok (error))
832 res.class_inst = class_inst;
833 res.method_inst = method_inst;
839 * mono_class_inflate_generic_method:
840 * @method: a generic method
841 * @context: a generics context
843 * Instantiate the generic method @method using the generics context @context.
845 * Returns: the new instantiated method
848 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
850 return mono_class_inflate_generic_method_full (method, NULL, context);
854 * mono_class_inflate_generic_method_full:
856 * Instantiate method @method with the generic context @context.
857 * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
858 * Use mono_method_signature () and mono_method_get_header () to get the correct values.
861 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
864 MonoMethod *res = mono_class_inflate_generic_method_full_checked (method, klass_hint, context, &error);
865 if (!mono_error_ok (&error))
866 /*FIXME do proper error handling - on this case, kill this function. */
867 g_error ("Could not inflate generic method due to %s", mono_error_get_message (&error));
873 * mono_class_inflate_generic_method_full_checked:
874 * Same as mono_class_inflate_generic_method_full but return failure using @error.
877 mono_class_inflate_generic_method_full_checked (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context, MonoError *error)
880 MonoMethodInflated *iresult, *cached;
881 MonoMethodSignature *sig;
882 MonoGenericContext tmp_context;
883 gboolean is_mb_open = FALSE;
885 mono_error_init (error);
887 /* The `method' has already been instantiated before => we need to peel out the instantiation and create a new context */
888 while (method->is_inflated) {
889 MonoGenericContext *method_context = mono_method_get_context (method);
890 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
892 tmp_context = inflate_generic_context (method_context, context, error);
893 if (!mono_error_ok (error))
895 context = &tmp_context;
897 if (mono_metadata_generic_context_equal (method_context, context))
900 method = imethod->declaring;
904 * A method only needs to be inflated if the context has argument for which it is
907 * class Foo<T> { void Bar(); } - doesn't need to be inflated if only mvars' are supplied
908 * class Foo { void Bar<T> (); } - doesn't need to be if only vars' are supplied
911 if (!((method->is_generic && context->method_inst) ||
912 (method->klass->generic_container && context->class_inst)))
916 * The reason for this hack is to fix the behavior of inflating generic methods that come from a MethodBuilder.
917 * What happens is that instantiating a generic MethodBuilder with its own arguments should create a diferent object.
918 * This is opposite to the way non-SRE MethodInfos behave.
920 * This happens, for example, when we want to emit a recursive generic method. Given the following C# code:
922 * void Example<T> () {
926 * In Example, the method token must be encoded as: "void Example<!!0>()"
928 * The reference to the first generic argument, "!!0", must be explicit otherwise it won't be inflated
929 * properly. To get that we need to inflate the MethodBuilder with its own arguments.
931 * On the other hand, inflating a non-SRE generic method with its own arguments should
932 * return itself. For example:
934 * MethodInfo m = ... //m is a generic method definition
935 * MethodInfo res = m.MakeGenericMethod (m.GetGenericArguments ());
938 * To allow such scenarios we must allow inflation of MethodBuilder to happen in a diferent way than
939 * what happens with regular methods.
941 * There is one last touch to this madness, once a TypeBuilder is finished, IOW CreateType() is called,
942 * everything should behave like a regular type or method.
945 is_mb_open = method->is_generic &&
946 method->klass->image->dynamic && !method->klass->wastypebuilder && /* that is a MethodBuilder from an unfinished TypeBuilder */
947 context->method_inst == mono_method_get_generic_container (method)->context.method_inst; /* and it's been instantiated with its own arguments. */
949 iresult = g_new0 (MonoMethodInflated, 1);
950 iresult->context = *context;
951 iresult->declaring = method;
952 iresult->method.method.is_mb_open = is_mb_open;
954 if (!context->method_inst && method->is_generic)
955 iresult->context.method_inst = mono_method_get_generic_container (method)->context.method_inst;
957 if (!context->class_inst) {
958 g_assert (!iresult->declaring->klass->generic_class);
959 if (iresult->declaring->klass->generic_container)
960 iresult->context.class_inst = iresult->declaring->klass->generic_container->context.class_inst;
961 else if (iresult->declaring->klass->generic_class)
962 iresult->context.class_inst = iresult->declaring->klass->generic_class->context.class_inst;
966 cached = mono_method_inflated_lookup (iresult, FALSE);
968 mono_loader_unlock ();
970 return (MonoMethod*)cached;
973 mono_stats.inflated_method_count++;
975 inflated_methods_size += sizeof (MonoMethodInflated);
977 sig = mono_method_signature (method);
979 char *name = mono_type_get_full_name (method->klass);
980 mono_error_set_bad_image (error, method->klass->image, "Could not resolve signature of method %s:%s", name, method->name);
986 memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
988 memcpy (&iresult->method.method, method, sizeof (MonoMethod));
991 result = (MonoMethod *) iresult;
992 result->is_inflated = TRUE;
993 result->is_generic = FALSE;
994 result->sre_method = FALSE;
995 result->signature = NULL;
996 result->is_mb_open = is_mb_open;
998 if (!context->method_inst) {
999 /* Set the generic_container of the result to the generic_container of method */
1000 MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
1002 if (generic_container) {
1003 result->is_generic = 1;
1004 mono_method_set_generic_container (result, generic_container);
1008 if (!klass_hint || !klass_hint->generic_class ||
1009 klass_hint->generic_class->container_class != method->klass ||
1010 klass_hint->generic_class->context.class_inst != context->class_inst)
1013 if (method->klass->generic_container)
1014 result->klass = klass_hint;
1016 if (!result->klass) {
1017 MonoType *inflated = inflate_generic_type (NULL, &method->klass->byval_arg, context, error);
1018 if (!mono_error_ok (error))
1021 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
1023 mono_metadata_free_type (inflated);
1027 * FIXME: This should hold, but it doesn't:
1029 * if (result->is_inflated && mono_method_get_context (result)->method_inst &&
1030 * mono_method_get_context (result)->method_inst == mono_method_get_generic_container (((MonoMethodInflated*)result)->declaring)->context.method_inst) {
1031 * g_assert (result->is_generic);
1034 * Fixing this here causes other things to break, hence a very
1035 * ugly hack in mini-trampolines.c - see
1036 * is_generic_method_definition().
1039 mono_method_inflated_lookup (iresult, TRUE);
1040 mono_loader_unlock ();
1044 mono_loader_unlock ();
1050 * mono_get_inflated_method:
1052 * Obsolete. We keep it around since it's mentioned in the public API.
1055 mono_get_inflated_method (MonoMethod *method)
1061 * mono_method_get_context_general:
1063 * @uninflated: handle uninflated methods?
1065 * Returns the generic context of a method or NULL if it doesn't have
1066 * one. For an inflated method that's the context stored in the
1067 * method. Otherwise it's in the method's generic container or in the
1068 * generic container of the method's class.
1071 mono_method_get_context_general (MonoMethod *method, gboolean uninflated)
1073 if (method->is_inflated) {
1074 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1075 return &imethod->context;
1079 if (method->is_generic)
1080 return &(mono_method_get_generic_container (method)->context);
1081 if (method->klass->generic_container)
1082 return &method->klass->generic_container->context;
1087 * mono_method_get_context:
1090 * Returns the generic context for method if it's inflated, otherwise
1094 mono_method_get_context (MonoMethod *method)
1096 return mono_method_get_context_general (method, FALSE);
1100 * mono_method_get_generic_container:
1102 * Returns the generic container of METHOD, which should be a generic method definition.
1103 * Returns NULL if METHOD is not a generic method definition.
1104 * LOCKING: Acquires the loader lock.
1106 MonoGenericContainer*
1107 mono_method_get_generic_container (MonoMethod *method)
1109 MonoGenericContainer *container;
1111 if (!method->is_generic)
1114 container = mono_image_property_lookup (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER);
1115 g_assert (container);
1121 * mono_method_set_generic_container:
1123 * Sets the generic container of METHOD to CONTAINER.
1124 * LOCKING: Acquires the loader lock.
1127 mono_method_set_generic_container (MonoMethod *method, MonoGenericContainer* container)
1129 g_assert (method->is_generic);
1131 mono_image_property_insert (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER, container);
1135 * mono_class_find_enum_basetype:
1136 * @class: The enum class
1138 * Determine the basetype of an enum by iterating through its fields. We do this
1139 * in a separate function since it is cheaper than calling mono_class_setup_fields.
1142 mono_class_find_enum_basetype (MonoClass *class)
1144 MonoGenericContainer *container = NULL;
1145 MonoImage *m = class->image;
1146 const int top = class->field.count;
1149 g_assert (class->enumtype);
1151 if (class->generic_container)
1152 container = class->generic_container;
1153 else if (class->generic_class) {
1154 MonoClass *gklass = class->generic_class->container_class;
1156 container = gklass->generic_container;
1157 g_assert (container);
1161 * Fetch all the field information.
1163 for (i = 0; i < top; i++){
1165 guint32 cols [MONO_FIELD_SIZE];
1166 int idx = class->field.first + i;
1169 /* class->field.first and idx points into the fieldptr table */
1170 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1172 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC) //no need to decode static fields
1175 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL))
1178 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1179 mono_metadata_decode_value (sig, &sig);
1180 /* FIELD signature == 0x06 */
1184 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1187 if (class->generic_class) {
1188 //FIXME do we leak here?
1189 ftype = mono_class_inflate_generic_type (ftype, mono_class_get_context (class));
1190 ftype->attrs = cols [MONO_FIELD_FLAGS];
1200 * Checks for MonoClass::exception_type without resolving all MonoType's into MonoClass'es
1203 mono_type_has_exceptions (MonoType *type)
1205 switch (type->type) {
1206 case MONO_TYPE_CLASS:
1207 case MONO_TYPE_VALUETYPE:
1208 case MONO_TYPE_SZARRAY:
1209 return type->data.klass->exception_type;
1210 case MONO_TYPE_ARRAY:
1211 return type->data.array->eklass->exception_type;
1212 case MONO_TYPE_GENERICINST:
1213 return mono_generic_class_get_class (type->data.generic_class)->exception_type;
1221 * Allocate memory for some data belonging to CLASS, either from its image's mempool,
1225 mono_class_alloc (MonoClass *class, int size)
1227 if (class->generic_class)
1228 return mono_image_set_alloc (class->generic_class->owner, size);
1230 return mono_image_alloc (class->image, size);
1234 mono_class_alloc0 (MonoClass *class, int size)
1238 res = mono_class_alloc (class, size);
1239 memset (res, 0, size);
1243 #define mono_class_new0(class,struct_type, n_structs) \
1244 ((struct_type *) mono_class_alloc0 ((class), ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
1247 * mono_class_setup_basic_field_info:
1248 * @class: The class to initialize
1250 * Initializes the class->fields.
1251 * LOCKING: Assumes the loader lock is held.
1254 mono_class_setup_basic_field_info (MonoClass *class)
1256 MonoClassField *field;
1264 gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1265 image = class->image;
1266 top = class->field.count;
1268 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1270 * This happens when a generic instance of an unfinished generic typebuilder
1271 * is used as an element type for creating an array type. We can't initialize
1272 * the fields of this class using the fields of gklass, since gklass is not
1273 * finished yet, fields could be added to it later.
1279 mono_class_setup_basic_field_info (gtd);
1281 top = gtd->field.count;
1282 class->field.first = gtd->field.first;
1283 class->field.count = gtd->field.count;
1286 class->fields = mono_class_alloc0 (class, sizeof (MonoClassField) * top);
1289 * Fetch all the field information.
1291 for (i = 0; i < top; i++){
1292 field = &class->fields [i];
1293 field->parent = class;
1296 field->name = mono_field_get_name (>d->fields [i]);
1298 int idx = class->field.first + i;
1299 /* class->field.first and idx points into the fieldptr table */
1300 guint32 name_idx = mono_metadata_decode_table_row_col (image, MONO_TABLE_FIELD, idx, MONO_FIELD_NAME);
1301 /* The name is needed for fieldrefs */
1302 field->name = mono_metadata_string_heap (image, name_idx);
1308 * mono_class_setup_fields:
1309 * @class: The class to initialize
1311 * Initializes the class->fields.
1312 * LOCKING: Assumes the loader lock is held.
1315 mono_class_setup_fields (MonoClass *class)
1318 MonoImage *m = class->image;
1320 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1321 int i, blittable = TRUE;
1322 guint32 real_size = 0;
1323 guint32 packing_size = 0;
1324 gboolean explicit_size;
1325 MonoClassField *field;
1326 MonoGenericContainer *container = NULL;
1327 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1329 if (class->size_inited)
1332 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1334 * This happens when a generic instance of an unfinished generic typebuilder
1335 * is used as an element type for creating an array type. We can't initialize
1336 * the fields of this class using the fields of gklass, since gklass is not
1337 * finished yet, fields could be added to it later.
1342 mono_class_setup_basic_field_info (class);
1343 top = class->field.count;
1346 mono_class_setup_fields (gtd);
1347 if (gtd->exception_type) {
1348 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1353 class->instance_size = 0;
1355 class->sizes.class_size = 0;
1357 if (class->parent) {
1358 /* For generic instances, class->parent might not have been initialized */
1359 mono_class_init (class->parent);
1360 if (!class->parent->size_inited) {
1361 mono_class_setup_fields (class->parent);
1362 if (class->parent->exception_type) {
1363 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1367 class->instance_size += class->parent->instance_size;
1368 class->min_align = class->parent->min_align;
1369 /* we use |= since it may have been set already */
1370 class->has_references |= class->parent->has_references;
1371 blittable = class->parent->blittable;
1373 class->instance_size = sizeof (MonoObject);
1374 class->min_align = 1;
1377 /* We can't really enable 16 bytes alignment until the GC supports it.
1378 The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
1379 boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
1380 Bug #506144 is an example of this issue.
1382 if (class->simd_type)
1383 class->min_align = 16;
1385 /* Get the real size */
1386 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1388 if (explicit_size) {
1389 g_assert ((packing_size & 0xfffffff0) == 0);
1390 class->packing_size = packing_size;
1391 real_size += class->instance_size;
1395 if (explicit_size && real_size) {
1396 class->instance_size = MAX (real_size, class->instance_size);
1398 class->size_inited = 1;
1399 class->blittable = blittable;
1403 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1406 /* Prevent infinite loops if the class references itself */
1407 class->size_inited = 1;
1409 if (class->generic_container) {
1410 container = class->generic_container;
1412 container = gtd->generic_container;
1413 g_assert (container);
1417 * Fetch all the field information.
1419 for (i = 0; i < top; i++){
1420 int idx = class->field.first + i;
1421 field = &class->fields [i];
1423 field->parent = class;
1426 mono_field_resolve_type (field, &error);
1427 if (!mono_error_ok (&error)) {
1428 /*mono_field_resolve_type already failed class*/
1429 mono_error_cleanup (&error);
1433 g_error ("could not resolve %s:%s\n", mono_type_get_full_name(class), field->name);
1434 g_assert (field->type);
1437 if (mono_field_is_deleted (field))
1440 MonoClassField *gfield = >d->fields [i];
1441 field->offset = gfield->offset;
1443 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1445 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1446 field->offset = offset;
1448 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1449 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Missing field layout info for %s", field->name));
1452 if (field->offset < -1) { /*-1 is used to encode special static fields */
1453 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Invalid negative field offset %d for %s", field->offset, field->name));
1459 /* Only do these checks if we still think this type is blittable */
1460 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1461 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1464 MonoClass *field_class = mono_class_from_mono_type (field->type);
1466 mono_class_setup_fields (field_class);
1467 if (field_class->exception_type) {
1468 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1472 if (!field_class || !field_class->blittable)
1477 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1478 class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1479 blittable = class->element_class->blittable;
1482 if (mono_type_has_exceptions (field->type)) {
1483 char *class_name = mono_type_get_full_name (class);
1484 char *type_name = mono_type_full_name (field->type);
1486 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1487 g_warning ("Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
1488 g_free (class_name);
1492 /* The def_value of fields is compute lazily during vtable creation */
1495 if (class == mono_defaults.string_class)
1498 class->blittable = blittable;
1500 if (class->enumtype && !mono_class_enum_basetype (class)) {
1501 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1504 if (explicit_size && real_size) {
1505 class->instance_size = MAX (real_size, class->instance_size);
1508 if (class->exception_type)
1510 mono_class_layout_fields (class);
1512 /*valuetypes can't be neither bigger than 1Mb or empty. */
1513 if (class->valuetype && (class->instance_size <= 0 || class->instance_size > (0x100000 + sizeof (MonoObject))))
1514 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1518 * mono_class_setup_fields_locking:
1519 * @class: The class to initialize
1521 * Initializes the class->fields array of fields.
1522 * Aquires the loader lock.
1525 mono_class_setup_fields_locking (MonoClass *class)
1527 mono_loader_lock ();
1528 mono_class_setup_fields (class);
1529 mono_loader_unlock ();
1533 * mono_class_has_references:
1535 * Returns whenever @klass->has_references is set, initializing it if needed.
1536 * Aquires the loader lock.
1539 mono_class_has_references (MonoClass *klass)
1541 if (klass->init_pending) {
1542 /* Be conservative */
1545 mono_class_init (klass);
1547 return klass->has_references;
1552 * mono_type_get_basic_type_from_generic:
1555 * Returns a closed type corresponding to the possibly open type
1559 mono_type_get_basic_type_from_generic (MonoType *type)
1561 /* When we do generic sharing we let type variables stand for reference types. */
1562 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1563 return &mono_defaults.object_class->byval_arg;
1568 * mono_class_layout_fields:
1571 * Compute the placement of fields inside an object or struct, according to
1572 * the layout rules and set the following fields in @class:
1573 * - has_references (if the class contains instance references firled or structs that contain references)
1574 * - has_static_refs (same, but for static fields)
1575 * - instance_size (size of the object in memory)
1576 * - class_size (size needed for the static fields)
1577 * - size_inited (flag set when the instance_size is set)
1579 * LOCKING: this is supposed to be called with the loader lock held.
1582 mono_class_layout_fields (MonoClass *class)
1585 const int top = class->field.count;
1586 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1587 guint32 pass, passes, real_size;
1588 gboolean gc_aware_layout = FALSE;
1589 MonoClassField *field;
1592 * When we do generic sharing we need to have layout
1593 * information for open generic classes (either with a generic
1594 * context containing type variables or with a generic
1595 * container), so we don't return in that case anymore.
1599 * Enable GC aware auto layout: in this mode, reference
1600 * fields are grouped together inside objects, increasing collector
1602 * Requires that all classes whose layout is known to native code be annotated
1603 * with [StructLayout (LayoutKind.Sequential)]
1604 * Value types have gc_aware_layout disabled by default, as per
1605 * what the default is for other runtimes.
1607 /* corlib is missing [StructLayout] directives in many places */
1608 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1609 if (class->image != mono_defaults.corlib &&
1610 class->byval_arg.type != MONO_TYPE_VALUETYPE)
1611 gc_aware_layout = TRUE;
1612 /* from System.dll, used in metadata/process.h */
1613 if (strcmp (class->name, "ProcessStartInfo") == 0)
1614 gc_aware_layout = FALSE;
1617 /* Compute klass->has_references */
1619 * Process non-static fields first, since static fields might recursively
1620 * refer to the class itself.
1622 for (i = 0; i < top; i++) {
1625 field = &class->fields [i];
1627 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1628 ftype = mono_type_get_underlying_type (field->type);
1629 ftype = mono_type_get_basic_type_from_generic (ftype);
1630 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1631 class->has_references = TRUE;
1635 for (i = 0; i < top; i++) {
1638 field = &class->fields [i];
1640 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1641 ftype = mono_type_get_underlying_type (field->type);
1642 ftype = mono_type_get_basic_type_from_generic (ftype);
1643 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1644 class->has_static_refs = TRUE;
1648 for (i = 0; i < top; i++) {
1651 field = &class->fields [i];
1653 ftype = mono_type_get_underlying_type (field->type);
1654 ftype = mono_type_get_basic_type_from_generic (ftype);
1655 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1656 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1657 class->has_static_refs = TRUE;
1659 class->has_references = TRUE;
1664 * Compute field layout and total size (not considering static fields)
1668 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1669 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1671 if (gc_aware_layout)
1676 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1679 if (class->parent) {
1680 mono_class_setup_fields (class->parent);
1681 if (class->parent->exception_type) {
1682 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1685 real_size = class->parent->instance_size;
1687 real_size = sizeof (MonoObject);
1690 for (pass = 0; pass < passes; ++pass) {
1691 for (i = 0; i < top; i++){
1696 field = &class->fields [i];
1698 if (mono_field_is_deleted (field))
1700 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1703 ftype = mono_type_get_underlying_type (field->type);
1704 ftype = mono_type_get_basic_type_from_generic (ftype);
1705 if (gc_aware_layout) {
1706 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1715 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1716 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1717 /* This field is a hack inserted by MCS to empty structures */
1721 size = mono_type_size (field->type, &align);
1723 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1724 align = class->packing_size ? MIN (class->packing_size, align): align;
1725 /* if the field has managed references, we need to force-align it
1728 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1729 align = MAX (align, sizeof (gpointer));
1731 class->min_align = MAX (align, class->min_align);
1732 field->offset = real_size;
1734 field->offset += align - 1;
1735 field->offset &= ~(align - 1);
1737 /*TypeBuilders produce all sort of weird things*/
1738 g_assert (class->image->dynamic || field->offset > 0);
1739 real_size = field->offset + size;
1742 class->instance_size = MAX (real_size, class->instance_size);
1744 if (class->instance_size & (class->min_align - 1)) {
1745 class->instance_size += class->min_align - 1;
1746 class->instance_size &= ~(class->min_align - 1);
1750 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1752 for (i = 0; i < top; i++) {
1757 field = &class->fields [i];
1760 * There must be info about all the fields in a type if it
1761 * uses explicit layout.
1764 if (mono_field_is_deleted (field))
1766 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1769 size = mono_type_size (field->type, &align);
1770 class->min_align = MAX (align, class->min_align);
1773 * When we get here, field->offset is already set by the
1774 * loader (for either runtime fields or fields loaded from metadata).
1775 * The offset is from the start of the object: this works for both
1776 * classes and valuetypes.
1778 field->offset += sizeof (MonoObject);
1779 ftype = mono_type_get_underlying_type (field->type);
1780 ftype = mono_type_get_basic_type_from_generic (ftype);
1781 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1782 if (field->offset % sizeof (gpointer)) {
1783 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1790 real_size = MAX (real_size, size + field->offset);
1792 class->instance_size = MAX (real_size, class->instance_size);
1796 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1798 * For small structs, set min_align to at least the struct size to improve
1799 * performance, and since the JIT memset/memcpy code assumes this and generates
1800 * unaligned accesses otherwise. See #78990 for a testcase.
1802 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1803 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1806 class->size_inited = 1;
1809 * Compute static field layout and size
1811 for (i = 0; i < top; i++){
1815 field = &class->fields [i];
1817 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1819 if (mono_field_is_deleted (field))
1822 if (mono_type_has_exceptions (field->type)) {
1823 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1827 size = mono_type_size (field->type, &align);
1828 field->offset = class->sizes.class_size;
1829 /*align is always non-zero here*/
1830 field->offset += align - 1;
1831 field->offset &= ~(align - 1);
1832 class->sizes.class_size = field->offset + size;
1837 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1841 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1842 method->klass = class;
1843 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1844 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1845 method->signature = sig;
1846 method->name = name;
1849 if (name [0] == '.') {
1850 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1852 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1858 * mono_class_setup_methods:
1861 * Initializes the 'methods' array in the klass.
1862 * Calling this method should be avoided if possible since it allocates a lot
1863 * of long-living MonoMethod structures.
1864 * Methods belonging to an interface are assigned a sequential slot starting
1867 * On failure this function sets class->exception_type
1870 mono_class_setup_methods (MonoClass *class)
1873 MonoMethod **methods;
1878 mono_loader_lock ();
1880 if (class->methods) {
1881 mono_loader_unlock ();
1885 if (class->generic_class) {
1887 MonoClass *gklass = class->generic_class->container_class;
1889 mono_class_init (gklass);
1890 if (!gklass->exception_type)
1891 mono_class_setup_methods (gklass);
1892 if (gklass->exception_type) {
1893 /*FIXME make exception_data less opaque so it's possible to dup it here*/
1894 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
1895 mono_loader_unlock ();
1899 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1900 class->method.count = gklass->method.count;
1901 methods = mono_class_alloc0 (class, sizeof (MonoMethod*) * (class->method.count + 1));
1903 for (i = 0; i < class->method.count; i++) {
1904 methods [i] = mono_class_inflate_generic_method_full_checked (
1905 gklass->methods [i], class, mono_class_get_context (class), &error);
1906 if (!mono_error_ok (&error)) {
1907 char *method = mono_method_full_name (gklass->methods [i], TRUE);
1908 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)));
1911 mono_error_cleanup (&error);
1912 mono_loader_unlock ();
1916 } else if (class->rank) {
1918 MonoMethod *amethod;
1919 MonoMethodSignature *sig;
1920 int count_generic = 0, first_generic = 0;
1923 class->method.count = 3 + (class->rank > 1? 2: 1);
1925 mono_class_setup_interfaces (class, &error);
1926 g_assert (mono_error_ok (&error)); /*FIXME can this fail for array types?*/
1928 if (class->interface_count) {
1929 count_generic = generic_array_methods (class);
1930 first_generic = class->method.count;
1931 class->method.count += class->interface_count * count_generic;
1934 methods = mono_class_alloc0 (class, sizeof (MonoMethod*) * class->method.count);
1936 sig = mono_metadata_signature_alloc (class->image, class->rank);
1937 sig->ret = &mono_defaults.void_class->byval_arg;
1938 sig->pinvoke = TRUE;
1939 sig->hasthis = TRUE;
1940 for (i = 0; i < class->rank; ++i)
1941 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1943 amethod = create_array_method (class, ".ctor", sig);
1944 methods [method_num++] = amethod;
1945 if (class->rank > 1) {
1946 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1947 sig->ret = &mono_defaults.void_class->byval_arg;
1948 sig->pinvoke = TRUE;
1949 sig->hasthis = TRUE;
1950 for (i = 0; i < class->rank * 2; ++i)
1951 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1953 amethod = create_array_method (class, ".ctor", sig);
1954 methods [method_num++] = amethod;
1956 /* element Get (idx11, [idx2, ...]) */
1957 sig = mono_metadata_signature_alloc (class->image, class->rank);
1958 sig->ret = &class->element_class->byval_arg;
1959 sig->pinvoke = TRUE;
1960 sig->hasthis = TRUE;
1961 for (i = 0; i < class->rank; ++i)
1962 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1963 amethod = create_array_method (class, "Get", sig);
1964 methods [method_num++] = amethod;
1965 /* element& Address (idx11, [idx2, ...]) */
1966 sig = mono_metadata_signature_alloc (class->image, class->rank);
1967 sig->ret = &class->element_class->this_arg;
1968 sig->pinvoke = TRUE;
1969 sig->hasthis = TRUE;
1970 for (i = 0; i < class->rank; ++i)
1971 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1972 amethod = create_array_method (class, "Address", sig);
1973 methods [method_num++] = amethod;
1974 /* void Set (idx11, [idx2, ...], element) */
1975 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1976 sig->ret = &mono_defaults.void_class->byval_arg;
1977 sig->pinvoke = TRUE;
1978 sig->hasthis = TRUE;
1979 for (i = 0; i < class->rank; ++i)
1980 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1981 sig->params [i] = &class->element_class->byval_arg;
1982 amethod = create_array_method (class, "Set", sig);
1983 methods [method_num++] = amethod;
1985 for (i = 0; i < class->interface_count; i++)
1986 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1988 methods = mono_class_alloc (class, sizeof (MonoMethod*) * class->method.count);
1989 for (i = 0; i < class->method.count; ++i) {
1990 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1991 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1995 if (MONO_CLASS_IS_INTERFACE (class)) {
1997 /*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
1998 for (i = 0; i < class->method.count; ++i) {
1999 if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
2000 methods [i]->slot = slot++;
2004 /* Needed because of the double-checking locking pattern */
2005 mono_memory_barrier ();
2007 class->methods = methods;
2009 if (mono_debugger_class_loaded_methods_func)
2010 mono_debugger_class_loaded_methods_func (class);
2012 mono_loader_unlock ();
2016 * mono_class_get_method_by_index:
2018 * Returns class->methods [index], initializing class->methods if neccesary.
2020 * LOCKING: Acquires the loader lock.
2023 mono_class_get_method_by_index (MonoClass *class, int index)
2025 /* Avoid calling setup_methods () if possible */
2026 if (class->generic_class && !class->methods) {
2027 MonoClass *gklass = class->generic_class->container_class;
2030 m = mono_class_inflate_generic_method_full (
2031 gklass->methods [index], class, mono_class_get_context (class));
2033 * If setup_methods () is called later for this class, no duplicates are created,
2034 * since inflate_generic_method guarantees that only one instance of a method
2035 * is created for each context.
2038 mono_class_setup_methods (class);
2039 g_assert (m == class->methods [index]);
2043 mono_class_setup_methods (class);
2044 if (class->exception_type) /*FIXME do proper error handling*/
2046 g_assert (index >= 0 && index < class->method.count);
2047 return class->methods [index];
2052 * mono_class_get_inflated_method:
2054 * Given an inflated class CLASS and a method METHOD which should be a method of
2055 * CLASS's generic definition, return the inflated method corresponding to METHOD.
2058 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
2060 MonoClass *gklass = class->generic_class->container_class;
2063 g_assert (method->klass == gklass);
2065 mono_class_setup_methods (gklass);
2066 g_assert (!gklass->exception_type); /*FIXME do proper error handling*/
2068 for (i = 0; i < gklass->method.count; ++i) {
2069 if (gklass->methods [i] == method) {
2071 return class->methods [i];
2073 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
2081 * mono_class_get_vtable_entry:
2083 * Returns class->vtable [offset], computing it if neccesary. Returns NULL on failure.
2084 * LOCKING: Acquires the loader lock.
2087 mono_class_get_vtable_entry (MonoClass *class, int offset)
2091 if (class->rank == 1) {
2093 * szarrays do not overwrite any methods of Array, so we can avoid
2094 * initializing their vtables in some cases.
2096 mono_class_setup_vtable (class->parent);
2097 if (offset < class->parent->vtable_size)
2098 return class->parent->vtable [offset];
2101 if (class->generic_class) {
2102 MonoClass *gklass = class->generic_class->container_class;
2103 mono_class_setup_vtable (gklass);
2104 m = gklass->vtable [offset];
2106 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
2108 mono_class_setup_vtable (class);
2109 if (class->exception_type)
2111 m = class->vtable [offset];
2118 * mono_class_get_vtable_size:
2120 * Return the vtable size for KLASS.
2123 mono_class_get_vtable_size (MonoClass *klass)
2125 mono_class_setup_vtable (klass);
2127 return klass->vtable_size;
2130 /*This method can fail the class.*/
2132 mono_class_setup_properties (MonoClass *class)
2134 guint startm, endm, i, j;
2135 guint32 cols [MONO_PROPERTY_SIZE];
2136 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2137 MonoProperty *properties;
2140 if (class->ext && class->ext->properties)
2143 mono_loader_lock ();
2145 if (class->ext && class->ext->properties) {
2146 mono_loader_unlock ();
2150 mono_class_alloc_ext (class);
2152 if (class->generic_class) {
2153 MonoClass *gklass = class->generic_class->container_class;
2155 mono_class_init (gklass);
2156 mono_class_setup_properties (gklass);
2157 if (gklass->exception_type) {
2158 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2159 mono_loader_unlock ();
2163 class->ext->property = gklass->ext->property;
2165 properties = mono_class_new0 (class, MonoProperty, class->ext->property.count + 1);
2167 for (i = 0; i < class->ext->property.count; i++) {
2168 MonoProperty *prop = &properties [i];
2170 *prop = gklass->ext->properties [i];
2173 prop->get = mono_class_inflate_generic_method_full (
2174 prop->get, class, mono_class_get_context (class));
2176 prop->set = mono_class_inflate_generic_method_full (
2177 prop->set, class, mono_class_get_context (class));
2179 prop->parent = class;
2182 int first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2183 int count = last - first;
2186 mono_class_setup_methods (class);
2187 if (class->exception_type) {
2188 mono_loader_unlock ();
2193 class->ext->property.first = first;
2194 class->ext->property.count = count;
2195 properties = mono_class_alloc0 (class, sizeof (MonoProperty) * count);
2196 for (i = first; i < last; ++i) {
2197 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
2198 properties [i - first].parent = class;
2199 properties [i - first].attrs = cols [MONO_PROPERTY_FLAGS];
2200 properties [i - first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
2202 startm = mono_metadata_methods_from_property (class->image, i, &endm);
2203 for (j = startm; j < endm; ++j) {
2206 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2208 if (class->image->uncompressed_metadata)
2209 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2210 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2212 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2214 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2215 case METHOD_SEMANTIC_SETTER:
2216 properties [i - first].set = method;
2218 case METHOD_SEMANTIC_GETTER:
2219 properties [i - first].get = method;
2227 /*Flush any pending writes as we do double checked locking on class->properties */
2228 mono_memory_barrier ();
2230 /* Leave this assignment as the last op in the function */
2231 class->ext->properties = properties;
2233 mono_loader_unlock ();
2237 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
2239 MonoMethod **om, **retval;
2242 for (om = methods, count = 0; *om; ++om, ++count)
2245 retval = g_new0 (MonoMethod*, count + 1);
2247 for (om = methods, count = 0; *om; ++om, ++count)
2248 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
2253 /*This method can fail the class.*/
2255 mono_class_setup_events (MonoClass *class)
2258 guint startm, endm, i, j;
2259 guint32 cols [MONO_EVENT_SIZE];
2260 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2264 if (class->ext && class->ext->events)
2267 mono_loader_lock ();
2269 if (class->ext && class->ext->events) {
2270 mono_loader_unlock ();
2274 mono_class_alloc_ext (class);
2276 if (class->generic_class) {
2277 MonoClass *gklass = class->generic_class->container_class;
2278 MonoGenericContext *context;
2280 mono_class_setup_events (gklass);
2281 if (gklass->exception_type) {
2282 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2283 mono_loader_unlock ();
2287 class->ext->event = gklass->ext->event;
2288 class->ext->events = mono_class_new0 (class, MonoEvent, class->ext->event.count);
2290 if (class->ext->event.count)
2291 context = mono_class_get_context (class);
2293 for (i = 0; i < class->ext->event.count; i++) {
2294 MonoEvent *event = &class->ext->events [i];
2295 MonoEvent *gevent = &gklass->ext->events [i];
2297 event->parent = class;
2298 event->name = gevent->name;
2299 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
2300 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
2301 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
2302 #ifndef MONO_SMALL_CONFIG
2303 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
2305 event->attrs = gevent->attrs;
2308 mono_loader_unlock ();
2312 first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2313 count = last - first;
2316 mono_class_setup_methods (class);
2317 if (class->exception_type) {
2318 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2319 mono_loader_unlock ();
2323 class->ext->event.first = first;
2324 class->ext->event.count = count;
2325 events = mono_class_alloc0 (class, sizeof (MonoEvent) * class->ext->event.count);
2326 for (i = first; i < last; ++i) {
2327 MonoEvent *event = &events [i - first];
2329 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
2330 event->parent = class;
2331 event->attrs = cols [MONO_EVENT_FLAGS];
2332 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
2334 startm = mono_metadata_methods_from_event (class->image, i, &endm);
2335 for (j = startm; j < endm; ++j) {
2338 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2340 if (class->image->uncompressed_metadata)
2341 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2342 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2344 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2346 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2347 case METHOD_SEMANTIC_ADD_ON:
2348 event->add = method;
2350 case METHOD_SEMANTIC_REMOVE_ON:
2351 event->remove = method;
2353 case METHOD_SEMANTIC_FIRE:
2354 event->raise = method;
2356 case METHOD_SEMANTIC_OTHER: {
2357 #ifndef MONO_SMALL_CONFIG
2360 if (event->other == NULL) {
2361 event->other = g_new0 (MonoMethod*, 2);
2363 while (event->other [n])
2365 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
2367 event->other [n] = method;
2368 /* NULL terminated */
2369 event->other [n + 1] = NULL;
2378 /*Flush any pending writes as we do double checked locking on class->properties */
2379 mono_memory_barrier ();
2381 /* Leave this assignment as the last op in the function */
2382 class->ext->events = events;
2384 mono_loader_unlock ();
2388 * Global pool of interface IDs, represented as a bitset.
2389 * LOCKING: this is supposed to be accessed with the loader lock held.
2391 static MonoBitSet *global_interface_bitset = NULL;
2394 * mono_unload_interface_ids:
2395 * @bitset: bit set of interface IDs
2397 * When an image is unloaded, the interface IDs associated with
2398 * the image are put back in the global pool of IDs so the numbers
2402 mono_unload_interface_ids (MonoBitSet *bitset)
2404 mono_loader_lock ();
2405 mono_bitset_sub (global_interface_bitset, bitset);
2406 mono_loader_unlock ();
2410 mono_unload_interface_id (MonoClass *class)
2412 if (class->interface_id) {
2413 mono_loader_lock ();
2414 mono_bitset_clear (global_interface_bitset, class->interface_id);
2415 mono_loader_unlock ();
2420 * mono_get_unique_iid:
2423 * Assign a unique integer ID to the interface represented by @class.
2424 * The ID will positive and as small as possible.
2425 * LOCKING: this is supposed to be called with the loader lock held.
2426 * Returns: the new ID.
2429 mono_get_unique_iid (MonoClass *class)
2433 g_assert (MONO_CLASS_IS_INTERFACE (class));
2435 if (!global_interface_bitset) {
2436 global_interface_bitset = mono_bitset_new (128, 0);
2439 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2441 int old_size = mono_bitset_size (global_interface_bitset);
2442 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2443 mono_bitset_free (global_interface_bitset);
2444 global_interface_bitset = new_set;
2447 mono_bitset_set (global_interface_bitset, iid);
2448 /* set the bit also in the per-image set */
2449 if (!class->generic_class) {
2450 if (class->image->interface_bitset) {
2451 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2452 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2453 mono_bitset_free (class->image->interface_bitset);
2454 class->image->interface_bitset = new_set;
2457 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2459 mono_bitset_set (class->image->interface_bitset, iid);
2462 #ifndef MONO_SMALL_CONFIG
2463 if (mono_print_vtable) {
2465 char *type_name = mono_type_full_name (&class->byval_arg);
2466 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2467 generic_id = class->generic_class->context.class_inst->id;
2468 g_assert (generic_id != 0);
2472 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2477 g_assert (iid <= 65535);
2482 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res, MonoError *error)
2487 mono_class_setup_interfaces (klass, error);
2488 if (!mono_error_ok (error))
2491 for (i = 0; i < klass->interface_count; i++) {
2492 ic = klass->interfaces [i];
2495 *res = g_ptr_array_new ();
2496 g_ptr_array_add (*res, ic);
2497 mono_class_init (ic);
2498 if (ic->exception_type) {
2499 mono_error_set_type_load_class (error, ic, "Error Loading class");
2503 collect_implemented_interfaces_aux (ic, res, error);
2504 if (!mono_error_ok (error))
2510 mono_class_get_implemented_interfaces (MonoClass *klass, MonoError *error)
2512 GPtrArray *res = NULL;
2514 collect_implemented_interfaces_aux (klass, &res, error);
2515 if (!mono_error_ok (error)) {
2517 g_ptr_array_free (res, TRUE);
2524 compare_interface_ids (const void *p_key, const void *p_element) {
2525 const MonoClass *key = p_key;
2526 const MonoClass *element = *(MonoClass**) p_element;
2528 return (key->interface_id - element->interface_id);
2531 /*FIXME verify all callers if they should switch to mono_class_interface_offset_with_variance*/
2533 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2534 MonoClass **result = bsearch (
2536 klass->interfaces_packed,
2537 klass->interface_offsets_count,
2538 sizeof (MonoClass *),
2539 compare_interface_ids);
2541 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2548 * mono_class_interface_offset_with_variance:
2550 * Return the interface offset of @itf in @klass. Sets @non_exact_match to TRUE if the match required variance check
2551 * If @itf is an interface with generic variant arguments, try to find the compatible one.
2553 * Note that this function is responsible for resolving ambiguities. Right now we use whatever ordering interfaces_packed gives us.
2555 * FIXME figure out MS disambiguation rules and fix this function.
2558 mono_class_interface_offset_with_variance (MonoClass *klass, MonoClass *itf, gboolean *non_exact_match) {
2559 int i = mono_class_interface_offset (klass, itf);
2560 *non_exact_match = FALSE;
2564 if (!mono_class_has_variant_generic_params (itf))
2567 for (i = 0; i < klass->interface_offsets_count; i++) {
2568 if (mono_class_is_variant_compatible (itf, klass->interfaces_packed [i], FALSE)) {
2569 *non_exact_match = TRUE;
2570 return klass->interface_offsets_packed [i];
2578 print_implemented_interfaces (MonoClass *klass) {
2581 GPtrArray *ifaces = NULL;
2583 int ancestor_level = 0;
2585 name = mono_type_get_full_name (klass);
2586 printf ("Packed interface table for class %s has size %d\n", name, klass->interface_offsets_count);
2589 for (i = 0; i < klass->interface_offsets_count; i++)
2590 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2591 klass->interfaces_packed [i]->interface_id,
2592 klass->interface_offsets_packed [i],
2593 klass->interfaces_packed [i]->method.count,
2594 klass->interfaces_packed [i]->name_space,
2595 klass->interfaces_packed [i]->name );
2596 printf ("Interface flags: ");
2597 for (i = 0; i <= klass->max_interface_id; i++)
2598 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2599 printf ("(%d,T)", i);
2601 printf ("(%d,F)", i);
2603 printf ("Dump interface flags:");
2604 #ifdef COMPRESSED_INTERFACE_BITMAP
2606 const uint8_t* p = klass->interface_bitmap;
2607 i = klass->max_interface_id;
2609 printf (" %d x 00 %02X", p [0], p [1]);
2615 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2616 printf (" %02X", klass->interface_bitmap [i]);
2619 while (klass != NULL) {
2620 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2621 ifaces = mono_class_get_implemented_interfaces (klass, &error);
2622 if (!mono_error_ok (&error)) {
2623 printf (" Type failed due to %s\n", mono_error_get_message (&error));
2624 mono_error_cleanup (&error);
2625 } else if (ifaces) {
2626 for (i = 0; i < ifaces->len; i++) {
2627 MonoClass *ic = g_ptr_array_index (ifaces, i);
2628 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2629 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2631 mono_class_interface_offset (klass, ic),
2636 g_ptr_array_free (ifaces, TRUE);
2639 klass = klass->parent;
2644 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2647 args [0] = &arg0->byval_arg;
2649 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2653 array_class_get_if_rank (MonoClass *class, guint rank)
2655 return rank ? mono_array_class_get (class, rank) : class;
2659 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2661 valuetype_types [0] = eclass;
2662 if (eclass == mono_defaults.int16_class)
2663 valuetype_types [1] = mono_defaults.uint16_class;
2664 else if (eclass == mono_defaults.uint16_class)
2665 valuetype_types [1] = mono_defaults.int16_class;
2666 else if (eclass == mono_defaults.int32_class)
2667 valuetype_types [1] = mono_defaults.uint32_class;
2668 else if (eclass == mono_defaults.uint32_class)
2669 valuetype_types [1] = mono_defaults.int32_class;
2670 else if (eclass == mono_defaults.int64_class)
2671 valuetype_types [1] = mono_defaults.uint64_class;
2672 else if (eclass == mono_defaults.uint64_class)
2673 valuetype_types [1] = mono_defaults.int64_class;
2674 else if (eclass == mono_defaults.byte_class)
2675 valuetype_types [1] = mono_defaults.sbyte_class;
2676 else if (eclass == mono_defaults.sbyte_class)
2677 valuetype_types [1] = mono_defaults.byte_class;
2678 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2679 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2682 /* this won't be needed once bug #325495 is completely fixed
2683 * though we'll need something similar to know which interfaces to allow
2684 * in arrays when they'll be lazyly created
2686 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2687 * MS returns diferrent types based on which instance is called. For example:
2688 * object obj = new byte[10][];
2689 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2690 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2693 * Fixing this should kill quite some code, save some bits and improve compatibility.
2696 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2698 MonoClass *eclass = class->element_class;
2699 static MonoClass* generic_icollection_class = NULL;
2700 static MonoClass* generic_ienumerable_class = NULL;
2701 static MonoClass* generic_ienumerator_class = NULL;
2702 MonoClass *valuetype_types[2] = { NULL, NULL };
2703 MonoClass **interfaces = NULL;
2704 int i, interface_count, real_count, original_rank;
2706 gboolean internal_enumerator;
2707 gboolean eclass_is_valuetype;
2709 if (!mono_defaults.generic_ilist_class) {
2713 internal_enumerator = FALSE;
2714 eclass_is_valuetype = FALSE;
2715 original_rank = eclass->rank;
2716 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2717 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2719 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2721 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2722 original_rank = eclass->rank;
2723 eclass = eclass->element_class;
2724 internal_enumerator = TRUE;
2725 *is_enumerator = TRUE;
2733 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2734 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2736 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2738 if (!generic_icollection_class) {
2739 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2740 "System.Collections.Generic", "ICollection`1");
2741 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2742 "System.Collections.Generic", "IEnumerable`1");
2743 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2744 "System.Collections.Generic", "IEnumerator`1");
2747 mono_class_init (eclass);
2750 * Arrays in 2.0 need to implement a number of generic interfaces
2751 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2752 * on the element class). We collect the types needed to build the
2753 * instantiations in interfaces at intervals of 3, because 3 are
2754 * the generic interfaces needed to implement.
2756 if (eclass->valuetype) {
2757 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2759 /* IList, ICollection, IEnumerable */
2760 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2761 if (internal_enumerator) {
2763 if (valuetype_types [1])
2767 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2768 interfaces [0] = valuetype_types [0];
2769 if (valuetype_types [1])
2770 interfaces [3] = valuetype_types [1];
2772 eclass_is_valuetype = TRUE;
2775 int idepth = eclass->idepth;
2776 if (!internal_enumerator)
2779 // FIXME: This doesn't seem to work/required for generic params
2780 if (!(eclass->this_arg.type == MONO_TYPE_VAR || eclass->this_arg.type == MONO_TYPE_MVAR || (eclass->image->dynamic && !eclass->wastypebuilder)))
2781 mono_class_setup_interface_offsets (eclass);
2783 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2784 /* we add object for interfaces and the supertypes for the other
2785 * types. The last of the supertypes is the element class itself which we
2786 * already created the explicit interfaces for (so we include it for IEnumerator
2787 * and exclude it for arrays).
2789 if (MONO_CLASS_IS_INTERFACE (eclass))
2792 interface_count += idepth;
2793 if (eclass->rank && eclass->element_class->valuetype) {
2794 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2795 if (valuetype_types [1])
2798 /* IList, ICollection, IEnumerable */
2799 interface_count *= 3;
2800 real_count = interface_count;
2801 if (internal_enumerator) {
2802 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2803 if (valuetype_types [1])
2806 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2807 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2808 interfaces [0] = mono_defaults.object_class;
2812 for (i = 0; i < idepth; i++) {
2813 mono_class_init (eclass->supertypes [i]);
2814 interfaces [j] = eclass->supertypes [i];
2818 if (all_interfaces) {
2819 for (i = 0; i < eclass->interface_offsets_count; i++) {
2820 interfaces [j] = eclass->interfaces_packed [i];
2824 for (i = 0; i < eclass->interface_count; i++) {
2825 interfaces [j] = eclass->interfaces [i];
2829 if (valuetype_types [1]) {
2830 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2835 /* instantiate the generic interfaces */
2836 for (i = 0; i < interface_count; i += 3) {
2837 MonoClass *iface = interfaces [i];
2839 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2840 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2841 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2843 if (internal_enumerator) {
2845 /* instantiate IEnumerator<iface> */
2846 for (i = 0; i < interface_count; i++) {
2847 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2849 j = interface_count;
2850 if (!eclass_is_valuetype) {
2851 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2852 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2855 for (i = 0; i < eclass->idepth; i++) {
2856 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2860 for (i = 0; i < eclass->interface_offsets_count; i++) {
2861 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2865 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2867 if (valuetype_types [1])
2868 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2872 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2873 for (i = 0; i < real_count; ++i) {
2874 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2875 g_print ("%s implements %s\n", type_name, name);
2886 find_array_interface (MonoClass *klass, const char *name)
2889 for (i = 0; i < klass->interface_count; ++i) {
2890 if (strcmp (klass->interfaces [i]->name, name) == 0)
2897 * Return the number of virtual methods.
2898 * Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
2899 * Return -1 on failure.
2900 * FIXME It would be nice if this information could be cached somewhere.
2903 count_virtual_methods (MonoClass *class)
2907 class = mono_class_get_generic_type_definition (class); /*We can find this information by looking at the GTD*/
2909 if (class->methods || !MONO_CLASS_HAS_STATIC_METADATA (class)) {
2910 mono_class_setup_methods (class);
2911 if (class->exception_type)
2914 for (i = 0; i < class->method.count; ++i) {
2915 flags = class->methods [i]->flags;
2916 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2920 for (i = 0; i < class->method.count; ++i) {
2921 flags = mono_metadata_decode_table_row_col (class->image, MONO_TABLE_METHOD, class->method.first + i, MONO_METHOD_FLAGS);
2923 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2931 find_interface (int num_ifaces, MonoClass **interfaces_full, MonoClass *ic)
2939 m = (l + num_ifaces) / 2;
2940 if (interfaces_full [m] == ic)
2942 if (l == num_ifaces)
2944 if (!interfaces_full [m] || interfaces_full [m]->interface_id > ic->interface_id) {
2953 find_interface_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic)
2955 int i = find_interface (num_ifaces, interfaces_full, ic);
2957 return interface_offsets_full [i];
2962 set_interface_and_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic, int offset, mono_bool force_set)
2964 int i = find_interface (num_ifaces, interfaces_full, ic);
2968 interface_offsets_full [i] = offset;
2971 for (i = 0; i < num_ifaces; ++i) {
2972 if (interfaces_full [i]) {
2974 if (interfaces_full [i]->interface_id < ic->interface_id)
2977 while (end < num_ifaces && interfaces_full [end]) end++;
2978 memmove (interfaces_full + i + 1, interfaces_full + i, sizeof (MonoClass*) * (end - i));
2979 memmove (interface_offsets_full + i + 1, interface_offsets_full + i, sizeof (int) * (end - i));
2981 interfaces_full [i] = ic;
2982 interface_offsets_full [i] = offset;
2988 #ifdef COMPRESSED_INTERFACE_BITMAP
2991 * Compressed interface bitmap design.
2993 * Interface bitmaps take a large amount of memory, because their size is
2994 * linear with the maximum interface id assigned in the process (each interface
2995 * is assigned a unique id as it is loaded). The number of interface classes
2996 * is high because of the many implicit interfaces implemented by arrays (we'll
2997 * need to lazy-load them in the future).
2998 * Most classes implement a very small number of interfaces, so the bitmap is
2999 * sparse. This bitmap needs to be checked by interface casts, so access to the
3000 * needed bit must be fast and doable with few jit instructions.
3002 * The current compression format is as follows:
3003 * *) it is a sequence of one or more two-byte elements
3004 * *) the first byte in the element is the count of empty bitmap bytes
3005 * at the current bitmap position
3006 * *) the second byte in the element is an actual bitmap byte at the current
3009 * As an example, the following compressed bitmap bytes:
3010 * 0x07 0x01 0x00 0x7
3011 * correspond to the following bitmap:
3012 * 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x07
3014 * Each two-byte element can represent up to 2048 bitmap bits, but as few as a single
3015 * bitmap byte for non-sparse sequences. In practice the interface bitmaps created
3016 * during a gmcs bootstrap are reduced to less tha 5% of the original size.
3020 * mono_compress_bitmap:
3021 * @dest: destination buffer
3022 * @bitmap: bitmap buffer
3023 * @size: size of @bitmap in bytes
3025 * This is a mono internal function.
3026 * The @bitmap data is compressed into a format that is small but
3027 * still searchable in few instructions by the JIT and runtime.
3028 * The compressed data is stored in the buffer pointed to by the
3029 * @dest array. Passing a #NULL value for @dest allows to just compute
3030 * the size of the buffer.
3031 * This compression algorithm assumes the bits set in the bitmap are
3032 * few and far between, like in interface bitmaps.
3033 * Returns: the size of the compressed bitmap in bytes.
3036 mono_compress_bitmap (uint8_t *dest, const uint8_t *bitmap, int size)
3040 const uint8_t *end = bitmap + size;
3041 while (bitmap < end) {
3042 if (*bitmap || numz == 255) {
3066 * mono_class_interface_match:
3067 * @bitmap: a compressed bitmap buffer
3068 * @id: the index to check in the bitmap
3070 * This is a mono internal function.
3071 * Checks if a bit is set in a compressed interface bitmap. @id must
3072 * be already checked for being smaller than the maximum id encoded in the
3075 * Returns: a non-zero value if bit @id is set in the bitmap @bitmap,
3079 mono_class_interface_match (const uint8_t *bitmap, int id)
3082 id -= bitmap [0] * 8;
3086 return bitmap [1] & (1 << id);
3095 * LOCKING: this is supposed to be called with the loader lock held.
3096 * Return -1 on failure and set exception_type
3099 setup_interface_offsets (MonoClass *class, int cur_slot)
3103 int i, j, max_iid, num_ifaces;
3104 MonoClass **interfaces_full = NULL;
3105 int *interface_offsets_full = NULL;
3107 GPtrArray **ifaces_array = NULL;
3108 int interface_offsets_count;
3109 MonoClass **array_interfaces = NULL;
3110 int num_array_interfaces;
3111 int is_enumerator = FALSE;
3113 mono_class_setup_supertypes (class);
3115 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
3116 * implicit interfaces have the property that they are assigned the same slot in the
3117 * vtables for compatible interfaces
3119 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
3121 /* compute maximum number of slots and maximum interface id */
3123 num_ifaces = num_array_interfaces; /* this can include duplicated ones */
3124 ifaces_array = g_new0 (GPtrArray *, class->idepth);
3125 for (j = 0; j < class->idepth; j++) {
3126 k = class->supertypes [j];
3127 num_ifaces += k->interface_count;
3128 for (i = 0; i < k->interface_count; i++) {
3129 ic = k->interfaces [i];
3132 mono_class_init (ic);
3134 if (max_iid < ic->interface_id)
3135 max_iid = ic->interface_id;
3137 ifaces = mono_class_get_implemented_interfaces (k, &error);
3138 if (!mono_error_ok (&error)) {
3139 char *name = mono_type_get_full_name (k);
3140 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)));
3142 mono_error_cleanup (&error);
3147 num_ifaces += ifaces->len;
3148 for (i = 0; i < ifaces->len; ++i) {
3149 ic = g_ptr_array_index (ifaces, i);
3150 if (max_iid < ic->interface_id)
3151 max_iid = ic->interface_id;
3153 ifaces_array [j] = ifaces;
3157 for (i = 0; i < num_array_interfaces; ++i) {
3158 ic = array_interfaces [i];
3159 mono_class_init (ic);
3160 if (max_iid < ic->interface_id)
3161 max_iid = ic->interface_id;
3164 if (MONO_CLASS_IS_INTERFACE (class)) {
3166 if (max_iid < class->interface_id)
3167 max_iid = class->interface_id;
3169 class->max_interface_id = max_iid;
3170 /* compute vtable offset for interfaces */
3171 interfaces_full = g_malloc0 (sizeof (MonoClass*) * num_ifaces);
3172 interface_offsets_full = g_malloc (sizeof (int) * num_ifaces);
3174 for (i = 0; i < num_ifaces; i++) {
3175 interface_offsets_full [i] = -1;
3178 /* skip the current class */
3179 for (j = 0; j < class->idepth - 1; j++) {
3180 k = class->supertypes [j];
3181 ifaces = ifaces_array [j];
3184 for (i = 0; i < ifaces->len; ++i) {
3186 ic = g_ptr_array_index (ifaces, i);
3188 /*Force the sharing of interface offsets between parent and subtypes.*/
3189 io = mono_class_interface_offset (k, ic);
3191 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, io, TRUE);
3196 g_assert (class == class->supertypes [class->idepth - 1]);
3197 ifaces = ifaces_array [class->idepth - 1];
3199 for (i = 0; i < ifaces->len; ++i) {
3201 ic = g_ptr_array_index (ifaces, i);
3202 if (set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, cur_slot, FALSE))
3204 count = count_virtual_methods (ic);
3206 char *name = mono_type_get_full_name (ic);
3207 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Error calculating interface offset of %s", name));
3216 if (MONO_CLASS_IS_INTERFACE (class))
3217 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, class, cur_slot, TRUE);
3219 if (num_array_interfaces) {
3220 if (is_enumerator) {
3221 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
3222 int ienumerator_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ienumerator_idx]);
3223 g_assert (ienumerator_offset >= 0);
3224 for (i = 0; i < num_array_interfaces; ++i) {
3225 ic = array_interfaces [i];
3226 if (strcmp (ic->name, "IEnumerator`1") == 0)
3227 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, ienumerator_offset, TRUE);
3229 g_assert_not_reached ();
3230 /*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);*/
3233 int ilist_offset, icollection_offset, ienumerable_offset;
3234 int ilist_iface_idx = find_array_interface (class, "IList`1");
3235 MonoClass* ilist_class = class->interfaces [ilist_iface_idx];
3236 int icollection_iface_idx = find_array_interface (ilist_class, "ICollection`1");
3237 int ienumerable_iface_idx = find_array_interface (ilist_class, "IEnumerable`1");
3238 ilist_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ilist_iface_idx]);
3239 icollection_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [icollection_iface_idx]);
3240 ienumerable_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [ienumerable_iface_idx]);
3241 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
3242 for (i = 0; i < num_array_interfaces; ++i) {
3244 ic = array_interfaces [i];
3245 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
3246 offset = ilist_offset;
3247 else if (strcmp (ic->name, "ICollection`1") == 0)
3248 offset = icollection_offset;
3249 else if (strcmp (ic->name, "IEnumerable`1") == 0)
3250 offset = ienumerable_offset;
3252 g_assert_not_reached ();
3253 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, offset, TRUE);
3254 /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, offset, class->interfaces [0]->name);*/
3259 for (interface_offsets_count = 0, i = 0; i < num_ifaces; i++) {
3260 if (interface_offsets_full [i] != -1) {
3261 interface_offsets_count ++;
3266 * We might get called twice: once from mono_class_init () then once from
3267 * mono_class_setup_vtable ().
3269 if (class->interfaces_packed) {
3270 g_assert (class->interface_offsets_count == interface_offsets_count);
3274 class->interface_offsets_count = interface_offsets_count;
3275 class->interfaces_packed = mono_class_alloc (class, sizeof (MonoClass*) * interface_offsets_count);
3276 class->interface_offsets_packed = mono_class_alloc (class, sizeof (guint16) * interface_offsets_count);
3277 bsize = (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0);
3278 #ifdef COMPRESSED_INTERFACE_BITMAP
3279 bitmap = g_malloc0 (bsize);
3281 bitmap = mono_class_alloc0 (class, bsize);
3283 for (i = 0; i < interface_offsets_count; i++) {
3284 int id = interfaces_full [i]->interface_id;
3285 bitmap [id >> 3] |= (1 << (id & 7));
3286 class->interfaces_packed [i] = interfaces_full [i];
3287 class->interface_offsets_packed [i] = interface_offsets_full [i];
3288 /*if (num_array_interfaces)
3289 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]);*/
3291 #ifdef COMPRESSED_INTERFACE_BITMAP
3292 i = mono_compress_bitmap (NULL, bitmap, bsize);
3293 class->interface_bitmap = mono_class_alloc0 (class, i);
3294 mono_compress_bitmap (class->interface_bitmap, bitmap, bsize);
3297 class->interface_bitmap = bitmap;
3302 g_free (interfaces_full);
3303 g_free (interface_offsets_full);
3304 g_free (array_interfaces);
3305 for (i = 0; i < class->idepth; i++) {
3306 ifaces = ifaces_array [i];
3308 g_ptr_array_free (ifaces, TRUE);
3310 g_free (ifaces_array);
3312 //printf ("JUST DONE: ");
3313 //print_implemented_interfaces (class);
3319 * Setup interface offsets for interfaces.
3321 * - class->max_interface_id
3322 * - class->interface_offsets_count
3323 * - class->interfaces_packed
3324 * - class->interface_offsets_packed
3325 * - class->interface_bitmap
3327 * This function can fail @class.
3330 mono_class_setup_interface_offsets (MonoClass *class)
3332 mono_loader_lock ();
3334 setup_interface_offsets (class, 0);
3336 mono_loader_unlock ();
3339 /*Checks if @klass has @parent as one of it's parents type gtd
3343 * Bar<T> : Foo<Bar<Bar<T>>>
3347 mono_class_has_gtd_parent (MonoClass *klass, MonoClass *parent)
3349 klass = mono_class_get_generic_type_definition (klass);
3350 parent = mono_class_get_generic_type_definition (parent);
3351 mono_class_setup_supertypes (klass);
3352 mono_class_setup_supertypes (parent);
3354 return klass->idepth >= parent->idepth &&
3355 mono_class_get_generic_type_definition (klass->supertypes [parent->idepth - 1]) == parent;
3359 mono_class_check_vtable_constraints (MonoClass *class, GList *in_setup)
3361 MonoGenericInst *ginst;
3363 if (!class->generic_class) {
3364 mono_class_setup_vtable_full (class, in_setup);
3365 return class->exception_type == 0;
3368 mono_class_setup_vtable_full (mono_class_get_generic_type_definition (class), in_setup);
3369 if (class->generic_class->container_class->exception_type) {
3370 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Failed to load generic definition vtable"));
3374 ginst = class->generic_class->context.class_inst;
3375 for (i = 0; i < ginst->type_argc; ++i) {
3377 if (ginst->type_argv [i]->type != MONO_TYPE_GENERICINST)
3379 arg = mono_class_from_mono_type (ginst->type_argv [i]);
3380 /*Those 2 will be checked by mono_class_setup_vtable itself*/
3381 if (mono_class_has_gtd_parent (class, arg) || mono_class_has_gtd_parent (arg, class))
3383 if (!mono_class_check_vtable_constraints (arg, in_setup)) {
3384 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Failed to load generic parameter %d", i));
3392 * mono_class_setup_vtable:
3394 * Creates the generic vtable of CLASS.
3395 * Initializes the following fields in MonoClass:
3398 * Plus all the fields initialized by setup_interface_offsets ().
3399 * If there is an error during vtable construction, class->exception_type is set.
3401 * LOCKING: Acquires the loader lock.
3404 mono_class_setup_vtable (MonoClass *class)
3406 mono_class_setup_vtable_full (class, NULL);
3410 mono_class_setup_vtable_full (MonoClass *class, GList *in_setup)
3412 MonoMethod **overrides;
3413 MonoGenericContext *context;
3421 if (mono_debug_using_mono_debugger ())
3422 /* The debugger currently depends on this */
3423 mono_class_setup_methods (class);
3425 if (MONO_CLASS_IS_INTERFACE (class)) {
3426 /* This sets method->slot for all methods if this is an interface */
3427 mono_class_setup_methods (class);
3431 if (class->exception_type)
3434 if (g_list_find (in_setup, class))
3437 mono_loader_lock ();
3439 if (class->vtable) {
3440 mono_loader_unlock ();
3444 mono_stats.generic_vtable_count ++;
3445 in_setup = g_list_prepend (in_setup, class);
3447 if (class->generic_class) {
3448 if (!mono_class_check_vtable_constraints (class, in_setup)) {
3449 mono_loader_unlock ();
3450 g_list_remove (in_setup, class);
3454 context = mono_class_get_context (class);
3455 type_token = class->generic_class->container_class->type_token;
3457 context = (MonoGenericContext *) class->generic_container;
3458 type_token = class->type_token;
3461 if (class->image->dynamic) {
3462 /* Generic instances can have zero method overrides without causing any harm.
3463 * This is true since we don't do layout all over again for them, we simply inflate
3464 * the layout of the parent.
3466 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
3468 /* The following call fails if there are missing methods in the type */
3469 /* FIXME it's probably a good idea to avoid this for generic instances. */
3470 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
3474 mono_class_setup_vtable_general (class, overrides, onum, in_setup);
3476 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load list of method overrides"));
3480 mono_loader_unlock ();
3481 g_list_remove (in_setup, class);
3486 #define DEBUG_INTERFACE_VTABLE_CODE 0
3487 #define TRACE_INTERFACE_VTABLE_CODE 0
3488 #define VERIFY_INTERFACE_VTABLE_CODE 0
3489 #define VTABLE_SELECTOR (1)
3491 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3492 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
3493 if (!(VTABLE_SELECTOR)) break; \
3497 #define DEBUG_INTERFACE_VTABLE(stmt)
3500 #if TRACE_INTERFACE_VTABLE_CODE
3501 #define TRACE_INTERFACE_VTABLE(stmt) do {\
3502 if (!(VTABLE_SELECTOR)) break; \
3506 #define TRACE_INTERFACE_VTABLE(stmt)
3509 #if VERIFY_INTERFACE_VTABLE_CODE
3510 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
3511 if (!(VTABLE_SELECTOR)) break; \
3515 #define VERIFY_INTERFACE_VTABLE(stmt)
3519 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3521 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
3525 GString *res = g_string_new ("");
3527 g_string_append_c (res, '(');
3528 for (i = 0; i < sig->param_count; ++i) {
3530 g_string_append_c (res, ',');
3531 mono_type_get_desc (res, sig->params [i], include_namespace);
3533 g_string_append (res, ")=>");
3534 if (sig->ret != NULL) {
3535 mono_type_get_desc (res, sig->ret, include_namespace);
3537 g_string_append (res, "NULL");
3540 g_string_free (res, FALSE);
3544 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
3545 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
3546 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
3547 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
3555 is_wcf_hack_disabled (void)
3557 static gboolean disabled;
3558 static gboolean inited = FALSE;
3560 disabled = g_getenv ("MONO_DISABLE_WCF_HACK") != NULL;
3567 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) {
3568 MonoMethodSignature *cmsig, *imsig;
3569 if (strcmp (im->name, cm->name) == 0) {
3570 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
3571 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
3574 if (! slot_is_empty) {
3575 if (require_newslot) {
3576 if (! interface_is_explicitly_implemented_by_class) {
3577 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
3580 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3581 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
3585 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
3588 cmsig = mono_method_signature (cm);
3589 imsig = mono_method_signature (im);
3590 if (!cmsig || !imsig) {
3591 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not resolve the signature of a virtual method"));
3595 if (! mono_metadata_signature_equal (cmsig, imsig)) {
3596 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
3597 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3598 TRACE_INTERFACE_VTABLE (printf ("]"));
3601 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
3602 /* CAS - SecurityAction.InheritanceDemand on interface */
3603 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3604 mono_secman_inheritancedemand_method (cm, im);
3607 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3608 mono_security_core_clr_check_override (class, cm, im);
3609 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
3610 if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
3611 char *body_name = mono_method_full_name (cm, TRUE);
3612 char *decl_name = mono_method_full_name (im, TRUE);
3613 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));
3621 MonoClass *ic = im->klass;
3622 const char *ic_name_space = ic->name_space;
3623 const char *ic_name = ic->name;
3626 if (! require_newslot) {
3627 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
3630 if (cm->klass->rank == 0) {
3631 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
3634 cmsig = mono_method_signature (cm);
3635 imsig = mono_method_signature (im);
3636 if (!cmsig || !imsig) {
3637 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not resolve the signature of a virtual method"));
3641 if (! mono_metadata_signature_equal (cmsig, imsig)) {
3642 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
3643 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3644 TRACE_INTERFACE_VTABLE (printf ("]"));
3647 if (mono_class_get_image (ic) != mono_defaults.corlib) {
3648 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
3651 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
3652 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
3655 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
3656 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
3660 subname = strstr (cm->name, ic_name_space);
3661 if (subname != cm->name) {
3662 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
3665 subname += strlen (ic_name_space);
3666 if (subname [0] != '.') {
3667 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
3671 if (strstr (subname, ic_name) != subname) {
3672 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
3675 subname += strlen (ic_name);
3676 if (subname [0] != '.') {
3677 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
3681 if (strcmp (subname, im->name) != 0) {
3682 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
3686 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
3687 /* CAS - SecurityAction.InheritanceDemand on interface */
3688 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3689 mono_secman_inheritancedemand_method (cm, im);
3692 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3693 mono_security_core_clr_check_override (class, cm, im);
3695 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
3696 if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
3697 char *body_name = mono_method_full_name (cm, TRUE);
3698 char *decl_name = mono_method_full_name (im, TRUE);
3699 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));
3709 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3711 foreach_override (gpointer key, gpointer value, gpointer user_data) {
3712 MonoMethod *method = key;
3713 MonoMethod *override = value;
3714 MonoClass *method_class = mono_method_get_class (method);
3715 MonoClass *override_class = mono_method_get_class (override);
3717 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
3718 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
3719 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
3722 print_overrides (GHashTable *override_map, const char *message) {
3724 printf ("Override map \"%s\" START:\n", message);
3725 g_hash_table_foreach (override_map, foreach_override, NULL);
3726 printf ("Override map \"%s\" END.\n", message);
3728 printf ("Override map \"%s\" EMPTY.\n", message);
3732 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
3733 char *full_name = mono_type_full_name (&class->byval_arg);
3737 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
3739 if (print_interfaces) {
3740 print_implemented_interfaces (class);
3741 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
3744 if (class->parent) {
3745 parent_size = class->parent->vtable_size;
3749 for (i = 0; i < size; ++i) {
3750 MonoMethod *cm = vtable [i];
3751 char *cm_name = cm ? mono_method_full_name (cm, TRUE) : g_strdup ("nil");
3752 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
3754 printf (" [%c][%03d][INDEX %03d] %s [%p]\n", newness, i, cm ? cm->slot : - 1, cm_name, cm);
3762 #if VERIFY_INTERFACE_VTABLE_CODE
3764 mono_method_try_get_vtable_index (MonoMethod *method)
3766 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3767 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3768 if (imethod->declaring->is_generic)
3769 return imethod->declaring->slot;
3771 return method->slot;
3775 mono_class_verify_vtable (MonoClass *class)
3778 char *full_name = mono_type_full_name (&class->byval_arg);
3780 printf ("*** Verifying VTable of class '%s' \n", full_name);
3784 if (!class->methods)
3787 for (i = 0; i < class->method.count; ++i) {
3788 MonoMethod *cm = class->methods [i];
3791 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
3795 full_name = mono_method_full_name (cm, TRUE);
3797 slot = mono_method_try_get_vtable_index (cm);
3799 if (slot >= class->vtable_size) {
3800 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
3804 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
3805 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3806 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3807 g_free (other_name);
3810 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3817 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3819 char *method_signature;
3822 for (index = 0; index < onum; ++index) {
3823 mono_trace_warning (MONO_TRACE_TYPE, " at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
3824 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3826 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3827 type_name = mono_type_full_name (&class->byval_arg);
3828 mono_trace_warning (MONO_TRACE_TYPE, "no implementation for interface method %s::%s(%s) in class %s\n",
3829 mono_type_get_name (&ic->byval_arg), im->name, method_signature, type_name);
3830 g_free (method_signature);
3832 mono_class_setup_methods (class);
3833 if (class->exception_type) {
3834 char *name = mono_type_get_full_name (class);
3835 mono_trace_warning (MONO_TRACE_TYPE, "CLASS %s failed to resolve methods\n", name);
3839 for (index = 0; index < class->method.count; ++index) {
3840 MonoMethod *cm = class->methods [index];
3841 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3843 mono_trace_warning (MONO_TRACE_TYPE, "METHOD %s(%s)\n", cm->name, method_signature);
3844 g_free (method_signature);
3849 mono_method_get_method_definition (MonoMethod *method)
3851 while (method->is_inflated)
3852 method = ((MonoMethodInflated*)method)->declaring;
3857 verify_class_overrides (MonoClass *class, MonoMethod **overrides, int onum)
3861 for (i = 0; i < onum; ++i) {
3862 MonoMethod *decl = overrides [i * 2];
3863 MonoMethod *body = overrides [i * 2 + 1];
3865 if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (class)) {
3866 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method belongs to a different class than the declared one"));
3870 if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
3871 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3872 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must not be static to override a base type"));
3874 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must be virtual to override a base type"));
3878 if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
3879 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3880 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a static method in a base type"));
3882 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a non virtual method in a base type"));
3886 if (!mono_class_is_assignable_from_slow (decl->klass, class)) {
3887 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method overrides a class or interface that extended or implemented by this type"));
3891 body = mono_method_get_method_definition (body);
3892 decl = mono_method_get_method_definition (decl);
3894 if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (body, decl, NULL)) {
3895 char *body_name = mono_method_full_name (body, TRUE);
3896 char *decl_name = mono_method_full_name (decl, TRUE);
3897 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));
3907 mono_class_need_stelemref_method (MonoClass *class)
3909 return class->rank == 1 && MONO_TYPE_IS_REFERENCE (&class->element_class->byval_arg);
3913 * LOCKING: this is supposed to be called with the loader lock held.
3916 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum, GList *in_setup)
3920 MonoMethod **vtable;
3921 int i, max_vtsize = 0, max_iid, cur_slot = 0;
3922 GPtrArray *ifaces = NULL;
3923 GHashTable *override_map = NULL;
3924 gboolean security_enabled = mono_is_security_manager_active ();
3926 gpointer class_iter;
3927 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3928 int first_non_interface_slot;
3930 GSList *virt_methods = NULL, *l;
3931 int stelemref_slot = 0;
3936 if (overrides && !verify_class_overrides (class, overrides, onum))
3939 ifaces = mono_class_get_implemented_interfaces (class, &error);
3940 if (!mono_error_ok (&error)) {
3941 char *name = mono_type_get_full_name (class);
3942 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)));
3944 mono_error_cleanup (&error);
3946 } else if (ifaces) {
3947 for (i = 0; i < ifaces->len; i++) {
3948 MonoClass *ic = g_ptr_array_index (ifaces, i);
3949 max_vtsize += ic->method.count;
3951 g_ptr_array_free (ifaces, TRUE);
3955 if (class->parent) {
3956 mono_class_init (class->parent);
3957 mono_class_setup_vtable_full (class->parent, in_setup);
3959 if (class->parent->exception_type) {
3960 char *name = mono_type_get_full_name (class->parent);
3961 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Parent %s failed to load", name));
3966 max_vtsize += class->parent->vtable_size;
3967 cur_slot = class->parent->vtable_size;
3970 max_vtsize += class->method.count;
3972 /*Array have a slot for stelemref*/
3973 if (mono_class_need_stelemref_method (class)) {
3974 stelemref_slot = cur_slot;
3979 vtable = alloca (sizeof (gpointer) * max_vtsize);
3980 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3982 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3984 cur_slot = setup_interface_offsets (class, cur_slot);
3985 if (cur_slot == -1) /*setup_interface_offsets fails the type.*/
3988 max_iid = class->max_interface_id;
3989 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3991 /* Optimized version for generic instances */
3992 if (class->generic_class) {
3994 MonoClass *gklass = class->generic_class->container_class;
3997 mono_class_setup_vtable_full (gklass, in_setup);
3998 if (gklass->exception_type != MONO_EXCEPTION_NONE) {
3999 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4003 tmp = mono_class_alloc0 (class, sizeof (gpointer) * gklass->vtable_size);
4004 class->vtable_size = gklass->vtable_size;
4005 for (i = 0; i < gklass->vtable_size; ++i)
4006 if (gklass->vtable [i]) {
4007 MonoMethod *inflated = mono_class_inflate_generic_method_full_checked (gklass->vtable [i], class, mono_class_get_context (class), &error);
4008 if (!mono_error_ok (&error)) {
4009 char *err_msg = g_strdup_printf ("Could not inflate method due to %s", mono_error_get_message (&error));
4010 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
4012 mono_error_cleanup (&error);
4016 tmp [i]->slot = gklass->vtable [i]->slot;
4018 mono_memory_barrier ();
4019 class->vtable = tmp;
4021 /* Have to set method->slot for abstract virtual methods */
4022 if (class->methods && gklass->methods) {
4023 for (i = 0; i < class->method.count; ++i)
4024 if (class->methods [i]->slot == -1)
4025 class->methods [i]->slot = gklass->methods [i]->slot;
4031 if (class->parent && class->parent->vtable_size) {
4032 MonoClass *parent = class->parent;
4035 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
4037 // Also inherit parent interface vtables, just as a starting point.
4038 // This is needed otherwise bug-77127.exe fails when the property methods
4039 // have different names in the iterface and the class, because for child
4040 // classes the ".override" information is not used anymore.
4041 for (i = 0; i < parent->interface_offsets_count; i++) {
4042 MonoClass *parent_interface = parent->interfaces_packed [i];
4043 int interface_offset = mono_class_interface_offset (class, parent_interface);
4044 /*FIXME this is now dead code as this condition will never hold true.
4045 Since interface offsets are inherited then the offset of an interface implemented
4046 by a parent will never be the out of it's vtable boundary.
4048 if (interface_offset >= parent->vtable_size) {
4049 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
4052 mono_class_setup_methods (parent_interface); /*FIXME Just kill this whole chunk of dead code*/
4053 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
4054 for (j = 0; j < parent_interface->method.count && !class->exception_type; j++) {
4055 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
4056 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
4057 parent_interface_offset + j, parent_interface_offset, j,
4058 interface_offset + j, interface_offset, j));
4065 /*Array have a slot for stelemref*/
4066 if (mono_class_need_stelemref_method (class)) {
4067 MonoMethod *method = mono_marshal_get_virtual_stelemref (class);
4069 method->slot = stelemref_slot;
4071 g_assert (method->slot == stelemref_slot);
4073 vtable [stelemref_slot] = method;
4076 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
4077 /* override interface methods */
4078 for (i = 0; i < onum; i++) {
4079 MonoMethod *decl = overrides [i*2];
4080 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
4082 dslot = mono_method_get_vtable_slot (decl);
4084 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4088 dslot += mono_class_interface_offset (class, decl->klass);
4089 vtable [dslot] = overrides [i*2 + 1];
4090 vtable [dslot]->slot = dslot;
4092 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4094 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
4096 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4097 mono_security_core_clr_check_override (class, vtable [dslot], decl);
4100 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
4101 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
4104 * Create a list of virtual methods to avoid calling
4105 * mono_class_get_virtual_methods () which is slow because of the metadata
4109 gpointer iter = NULL;
4112 virt_methods = NULL;
4113 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
4114 virt_methods = g_slist_prepend (virt_methods, cm);
4116 if (class->exception_type)
4120 // Loop on all implemented interfaces...
4121 for (i = 0; i < class->interface_offsets_count; i++) {
4122 MonoClass *parent = class->parent;
4124 gboolean interface_is_explicitly_implemented_by_class;
4127 ic = class->interfaces_packed [i];
4128 ic_offset = mono_class_interface_offset (class, ic);
4130 mono_class_setup_methods (ic);
4131 if (ic->exception_type)
4134 // Check if this interface is explicitly implemented (instead of just inherited)
4135 if (parent != NULL) {
4136 int implemented_interfaces_index;
4137 interface_is_explicitly_implemented_by_class = FALSE;
4138 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
4139 if (ic == class->interfaces [implemented_interfaces_index]) {
4140 interface_is_explicitly_implemented_by_class = TRUE;
4145 interface_is_explicitly_implemented_by_class = TRUE;
4148 // Loop on all interface methods...
4149 for (im_index = 0; im_index < ic->method.count; im_index++) {
4150 MonoMethod *im = ic->methods [im_index];
4151 int im_slot = ic_offset + im->slot;
4152 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
4154 if (im->flags & METHOD_ATTRIBUTE_STATIC)
4157 TRACE_INTERFACE_VTABLE (printf ("\tchecking iface method %s\n", mono_method_full_name (im,1)));
4159 // If there is an explicit implementation, just use it right away,
4160 // otherwise look for a matching method
4161 if (override_im == NULL) {
4166 // First look for a suitable method among the class methods
4168 for (l = virt_methods; l; l = l->next) {
4170 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)));
4171 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
4172 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
4173 vtable [im_slot] = cm;
4174 /* Why do we need this? */
4179 TRACE_INTERFACE_VTABLE (printf ("\n"));
4180 if (class->exception_type) /*Might be set by check_interface_method_override*/
4184 // If the slot is still empty, look in all the inherited virtual methods...
4185 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
4186 MonoClass *parent = class->parent;
4187 // Reverse order, so that last added methods are preferred
4188 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
4189 MonoMethod *cm = parent->vtable [cm_index];
4191 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));
4192 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
4193 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
4194 vtable [im_slot] = cm;
4195 /* Why do we need this? */
4201 if (class->exception_type) /*Might be set by check_interface_method_override*/
4203 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
4207 g_assert (vtable [im_slot] == override_im);
4212 // If the class is not abstract, check that all its interface slots are full.
4213 // The check is done here and not directly at the end of the loop above because
4214 // it can happen (for injected generic array interfaces) that the same slot is
4215 // processed multiple times (those interfaces have overlapping slots), and it
4216 // will not always be the first pass the one that fills the slot.
4217 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
4218 for (i = 0; i < class->interface_offsets_count; i++) {
4222 ic = class->interfaces_packed [i];
4223 ic_offset = mono_class_interface_offset (class, ic);
4225 for (im_index = 0; im_index < ic->method.count; im_index++) {
4226 MonoMethod *im = ic->methods [im_index];
4227 int im_slot = ic_offset + im->slot;
4229 if (im->flags & METHOD_ATTRIBUTE_STATIC)
4232 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
4233 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
4234 if (vtable [im_slot] == NULL) {
4235 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
4242 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
4244 for (l = virt_methods; l; l = l->next) {
4247 * If the method is REUSE_SLOT, we must check in the
4248 * base class for a method to override.
4250 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
4252 for (k = class->parent; k ; k = k->parent) {
4257 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
4258 MonoMethodSignature *cmsig, *m1sig;
4260 cmsig = mono_method_signature (cm);
4261 m1sig = mono_method_signature (m1);
4263 if (!cmsig || !m1sig) {
4264 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4268 if (!strcmp(cm->name, m1->name) &&
4269 mono_metadata_signature_equal (cmsig, m1sig)) {
4271 /* CAS - SecurityAction.InheritanceDemand */
4272 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
4273 mono_secman_inheritancedemand_method (cm, m1);
4276 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4277 mono_security_core_clr_check_override (class, cm, m1);
4279 slot = mono_method_get_vtable_slot (m1);
4283 if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, m1, NULL)) {
4284 char *body_name = mono_method_full_name (cm, TRUE);
4285 char *decl_name = mono_method_full_name (m1, TRUE);
4286 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));
4292 g_assert (cm->slot < max_vtsize);
4294 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4295 TRACE_INTERFACE_VTABLE (printf ("adding iface override from %s [%p] to %s [%p]\n",
4296 mono_method_full_name (m1, 1), m1,
4297 mono_method_full_name (cm, 1), cm));
4298 g_hash_table_insert (override_map, m1, cm);
4302 if (k->exception_type)
4312 /*Non final newslot methods must be given a non-interface vtable slot*/
4313 if ((cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && !(cm->flags & METHOD_ATTRIBUTE_FINAL) && cm->slot >= 0)
4317 cm->slot = cur_slot++;
4319 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
4320 vtable [cm->slot] = cm;
4323 /* override non interface methods */
4324 for (i = 0; i < onum; i++) {
4325 MonoMethod *decl = overrides [i*2];
4326 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
4327 g_assert (decl->slot != -1);
4328 vtable [decl->slot] = overrides [i*2 + 1];
4329 overrides [i * 2 + 1]->slot = decl->slot;
4331 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4332 TRACE_INTERFACE_VTABLE (printf ("adding explicit override from %s [%p] to %s [%p]\n",
4333 mono_method_full_name (decl, 1), decl,
4334 mono_method_full_name (overrides [i * 2 + 1], 1), overrides [i * 2 + 1]));
4335 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
4337 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4338 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
4343 * If a method occupies more than one place in the vtable, and it is
4344 * overriden, then change the other occurances too.
4349 for (i = 0; i < max_vtsize; ++i)
4351 TRACE_INTERFACE_VTABLE (printf ("checking slot %d method %s[%p] for overrides\n", i, mono_method_full_name (vtable [i], 1), vtable [i]));
4353 cm = g_hash_table_lookup (override_map, vtable [i]);
4358 g_hash_table_destroy (override_map);
4359 override_map = NULL;
4362 g_slist_free (virt_methods);
4363 virt_methods = NULL;
4365 /* Ensure that all vtable slots are filled with concrete instance methods */
4366 if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
4367 for (i = 0; i < cur_slot; ++i) {
4368 if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
4369 char *type_name = mono_type_get_full_name (class);
4370 char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
4371 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));
4373 g_free (method_name);
4379 if (class->generic_class) {
4380 MonoClass *gklass = class->generic_class->container_class;
4382 mono_class_init (gklass);
4384 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
4386 /* Check that the vtable_size value computed in mono_class_init () is correct */
4387 if (class->vtable_size)
4388 g_assert (cur_slot == class->vtable_size);
4389 class->vtable_size = cur_slot;
4392 /* Try to share the vtable with our parent. */
4393 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
4394 mono_memory_barrier ();
4395 class->vtable = class->parent->vtable;
4397 MonoMethod **tmp = mono_class_alloc0 (class, sizeof (gpointer) * class->vtable_size);
4398 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
4399 mono_memory_barrier ();
4400 class->vtable = tmp;
4403 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
4404 if (mono_print_vtable) {
4407 print_implemented_interfaces (class);
4409 for (i = 0; i <= max_iid; i++)
4410 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
4413 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
4414 class->vtable_size, icount);
4416 for (i = 0; i < cur_slot; ++i) {
4421 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
4422 mono_method_full_name (cm, TRUE));
4428 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
4429 class->name, max_iid);
4431 for (i = 0; i < class->interface_count; i++) {
4432 ic = class->interfaces [i];
4433 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
4434 mono_class_interface_offset (class, ic),
4435 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
4438 for (k = class->parent; k ; k = k->parent) {
4439 for (i = 0; i < k->interface_count; i++) {
4440 ic = k->interfaces [i];
4441 printf (" parent slot offset: %03d, method count: %03d, iid: %03d %s\n",
4442 mono_class_interface_offset (class, ic),
4443 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
4449 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
4454 char *name = mono_type_get_full_name (class);
4455 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("VTable setup of type %s failed", name));
4458 g_hash_table_destroy (override_map);
4460 g_slist_free (virt_methods);
4465 * mono_method_get_vtable_slot:
4467 * Returns method->slot, computing it if neccesary. Return -1 on failure.
4468 * LOCKING: Acquires the loader lock.
4470 * FIXME Use proper MonoError machinery here.
4473 mono_method_get_vtable_slot (MonoMethod *method)
4475 if (method->slot == -1) {
4476 mono_class_setup_vtable (method->klass);
4477 if (method->klass->exception_type)
4479 g_assert (method->slot != -1);
4481 return method->slot;
4485 * mono_method_get_vtable_index:
4488 * Returns the index into the runtime vtable to access the method or,
4489 * in the case of a virtual generic method, the virtual generic method
4490 * thunk. Returns -1 on failure.
4492 * FIXME Use proper MonoError machinery here.
4495 mono_method_get_vtable_index (MonoMethod *method)
4497 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4498 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4499 if (imethod->declaring->is_generic)
4500 return mono_method_get_vtable_slot (imethod->declaring);
4502 return mono_method_get_vtable_slot (method);
4505 static MonoMethod *default_ghc = NULL;
4506 static MonoMethod *default_finalize = NULL;
4507 static int finalize_slot = -1;
4508 static int ghc_slot = -1;
4511 initialize_object_slots (MonoClass *class)
4516 if (class == mono_defaults.object_class) {
4517 mono_class_setup_vtable (class);
4518 for (i = 0; i < class->vtable_size; ++i) {
4519 MonoMethod *cm = class->vtable [i];
4521 if (!strcmp (cm->name, "GetHashCode"))
4523 else if (!strcmp (cm->name, "Finalize"))
4527 g_assert (ghc_slot > 0);
4528 default_ghc = class->vtable [ghc_slot];
4530 g_assert (finalize_slot > 0);
4531 default_finalize = class->vtable [finalize_slot];
4536 MonoMethod *array_method;
4538 } GenericArrayMethodInfo;
4540 static int generic_array_method_num = 0;
4541 static GenericArrayMethodInfo *generic_array_method_info = NULL;
4544 generic_array_methods (MonoClass *class)
4546 int i, count_generic = 0;
4547 GList *list = NULL, *tmp;
4548 if (generic_array_method_num)
4549 return generic_array_method_num;
4550 mono_class_setup_methods (class->parent); /*This is setting up System.Array*/
4551 g_assert (!class->parent->exception_type); /*So hitting this assert is a huge problem*/
4552 for (i = 0; i < class->parent->method.count; i++) {
4553 MonoMethod *m = class->parent->methods [i];
4554 if (!strncmp (m->name, "InternalArray__", 15)) {
4556 list = g_list_prepend (list, m);
4559 list = g_list_reverse (list);
4560 generic_array_method_info = mono_image_alloc (mono_defaults.corlib, sizeof (GenericArrayMethodInfo) * count_generic);
4562 for (tmp = list; tmp; tmp = tmp->next) {
4563 const char *mname, *iname;
4565 MonoMethod *m = tmp->data;
4566 generic_array_method_info [i].array_method = m;
4567 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
4568 iname = "System.Collections.Generic.ICollection`1.";
4569 mname = m->name + 27;
4570 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
4571 iname = "System.Collections.Generic.IEnumerable`1.";
4572 mname = m->name + 27;
4573 } else if (!strncmp (m->name, "InternalArray__", 15)) {
4574 iname = "System.Collections.Generic.IList`1.";
4575 mname = m->name + 15;
4577 g_assert_not_reached ();
4580 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
4581 strcpy (name, iname);
4582 strcpy (name + strlen (iname), mname);
4583 generic_array_method_info [i].name = name;
4586 /*g_print ("array generic methods: %d\n", count_generic);*/
4588 generic_array_method_num = count_generic;
4590 return generic_array_method_num;
4594 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
4596 MonoGenericContext tmp_context;
4599 tmp_context.class_inst = NULL;
4600 tmp_context.method_inst = iface->generic_class->context.class_inst;
4601 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
4603 for (i = 0; i < generic_array_method_num; i++) {
4604 MonoMethod *m = generic_array_method_info [i].array_method;
4605 MonoMethod *inflated;
4607 inflated = mono_class_inflate_generic_method (m, &tmp_context);
4608 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
4613 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
4615 int null_length = strlen ("(null)");
4616 int len = (s1 ? strlen (s1) : null_length) + (s2 ? strlen (s2) : null_length) + 2;
4617 char *s = mono_image_alloc (image, len);
4620 result = g_snprintf (s, len, "%s%c%s", s1 ? s1 : "(null)", '\0', s2 ? s2 : "(null)");
4621 g_assert (result == len - 1);
4627 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
4629 gpointer exception_data = NULL;
4631 switch (error->exception_type) {
4632 case MONO_EXCEPTION_TYPE_LOAD:
4633 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
4636 case MONO_EXCEPTION_MISSING_METHOD:
4637 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
4640 case MONO_EXCEPTION_MISSING_FIELD: {
4641 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
4642 const char *class_name;
4645 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
4647 class_name = error->klass->name;
4649 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
4652 g_free ((void*)class_name);
4656 case MONO_EXCEPTION_FILE_NOT_FOUND: {
4659 if (error->ref_only)
4660 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.";
4662 msg = "Could not load file or assembly '%s' or one of its dependencies.";
4664 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
4668 case MONO_EXCEPTION_BAD_IMAGE:
4669 exception_data = error->msg;
4673 g_assert_not_reached ();
4676 mono_class_set_failure (class, error->exception_type, exception_data);
4681 * @class: the class to initialize
4683 * Compute the instance_size, class_size and other infos that cannot be
4684 * computed at mono_class_get() time. Also compute vtable_size if possible.
4685 * Returns TRUE on success or FALSE if there was a problem in loading
4686 * the type (incorrect assemblies, missing assemblies, methods, etc).
4688 * LOCKING: Acquires the loader lock.
4691 mono_class_init (MonoClass *class)
4694 MonoCachedClassInfo cached_info;
4695 gboolean has_cached_info;
4699 /* Double-checking locking pattern */
4700 if (class->inited || class->exception_type)
4701 return class->exception_type == MONO_EXCEPTION_NONE;
4703 /*g_print ("Init class %s\n", mono_type_get_full_name (class));*/
4705 /* We do everything inside the lock to prevent races */
4706 mono_loader_lock ();
4708 if (class->inited || class->exception_type) {
4709 mono_loader_unlock ();
4710 /* Somebody might have gotten in before us */
4711 return class->exception_type == MONO_EXCEPTION_NONE;
4714 if (class->init_pending) {
4715 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Recursive type definition detected"));
4719 class->init_pending = 1;
4721 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
4722 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
4727 if (class->byval_arg.type == MONO_TYPE_ARRAY || class->byval_arg.type == MONO_TYPE_SZARRAY) {
4728 MonoClass *element_class = class->element_class;
4729 if (!element_class->inited)
4730 mono_class_init (element_class);
4731 if (element_class->exception_type != MONO_EXCEPTION_NONE) {
4732 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4737 /* CAS - SecurityAction.InheritanceDemand */
4738 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
4739 mono_secman_inheritancedemand_class (class, class->parent);
4742 mono_stats.initialized_class_count++;
4744 if (class->generic_class && !class->generic_class->is_dynamic) {
4745 MonoClass *gklass = class->generic_class->container_class;
4747 mono_stats.generic_class_count++;
4749 class->method = gklass->method;
4750 class->field = gklass->field;
4752 mono_class_init (gklass);
4753 // FIXME: Why is this needed ?
4754 if (!gklass->exception_type)
4755 mono_class_setup_methods (gklass);
4756 if (gklass->exception_type) {
4757 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Generic Type Defintion failed to init"));
4761 if (MONO_CLASS_IS_INTERFACE (class))
4762 class->interface_id = mono_get_unique_iid (class);
4765 if (class->parent && !class->parent->inited)
4766 mono_class_init (class->parent);
4768 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
4770 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
4771 class->nested_classes_inited = TRUE;
4774 * Computes the size used by the fields, and their locations
4776 if (has_cached_info) {
4777 class->instance_size = cached_info.instance_size;
4778 class->sizes.class_size = cached_info.class_size;
4779 class->packing_size = cached_info.packing_size;
4780 class->min_align = cached_info.min_align;
4781 class->blittable = cached_info.blittable;
4782 class->has_references = cached_info.has_references;
4783 class->has_static_refs = cached_info.has_static_refs;
4784 class->no_special_static_fields = cached_info.no_special_static_fields;
4787 if (!class->size_inited){
4788 mono_class_setup_fields (class);
4789 if (class->exception_type || mono_loader_get_last_error ())
4793 /* Initialize arrays */
4795 class->method.count = 3 + (class->rank > 1? 2: 1);
4797 if (class->interface_count) {
4798 int count_generic = generic_array_methods (class);
4799 class->method.count += class->interface_count * count_generic;
4803 mono_class_setup_supertypes (class);
4806 initialize_object_slots (class);
4809 * Initialize the rest of the data without creating a generic vtable if possible.
4810 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
4811 * also avoid computing a generic vtable.
4813 if (has_cached_info) {
4815 class->vtable_size = cached_info.vtable_size;
4816 class->has_finalize = cached_info.has_finalize;
4817 class->has_finalize_inited = TRUE;
4818 class->ghcimpl = cached_info.ghcimpl;
4819 class->has_cctor = cached_info.has_cctor;
4820 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
4821 /* SZARRAY can have 2 vtable layouts, with and without the stelemref method.
4822 * The first slot if for array with.
4824 static int szarray_vtable_size[2] = { 0 };
4826 int slot = MONO_TYPE_IS_REFERENCE (&class->element_class->byval_arg) ? 0 : 1;
4829 if (!szarray_vtable_size [slot]) {
4830 mono_class_setup_vtable (class);
4831 szarray_vtable_size [slot] = class->vtable_size;
4833 class->vtable_size = szarray_vtable_size[slot];
4835 class->has_finalize_inited = TRUE;
4836 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
4837 MonoClass *gklass = class->generic_class->container_class;
4839 /* Generic instance case */
4840 class->ghcimpl = gklass->ghcimpl;
4841 class->has_finalize = mono_class_has_finalizer (gklass);
4842 class->has_finalize_inited = TRUE;
4843 class->has_cctor = gklass->has_cctor;
4845 mono_class_setup_vtable (gklass);
4846 if (gklass->exception_type) {
4847 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4851 class->vtable_size = gklass->vtable_size;
4855 /* ghcimpl is not currently used
4857 if (class->parent) {
4858 MonoMethod *cmethod = class->vtable [ghc_slot];
4859 if (cmethod->is_inflated)
4860 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4861 if (cmethod == default_ghc) {
4867 /* C# doesn't allow interfaces to have cctors */
4868 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
4869 MonoMethod *cmethod = NULL;
4871 if (class->type_token) {
4872 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
4873 /* The find_method function ignores the 'flags' argument */
4874 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
4875 class->has_cctor = 1;
4877 mono_class_setup_methods (class);
4878 if (class->exception_type)
4881 for (i = 0; i < class->method.count; ++i) {
4882 MonoMethod *method = class->methods [i];
4883 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4884 (strcmp (".cctor", method->name) == 0)) {
4885 class->has_cctor = 1;
4893 if (class->parent) {
4894 int first_iface_slot;
4895 /* This will compute class->parent->vtable_size for some classes */
4896 mono_class_init (class->parent);
4897 if (class->parent->exception_type) {
4898 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4901 if (mono_loader_get_last_error ())
4903 if (!class->parent->vtable_size) {
4904 /* FIXME: Get rid of this somehow */
4905 mono_class_setup_vtable (class->parent);
4906 if (class->parent->exception_type) {
4907 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4910 if (mono_loader_get_last_error ())
4913 first_iface_slot = class->parent->vtable_size;
4914 if (mono_class_need_stelemref_method (class))
4916 setup_interface_offsets (class, first_iface_slot);
4918 setup_interface_offsets (class, 0);
4921 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4922 mono_security_core_clr_check_inheritance (class);
4924 if (mono_loader_get_last_error ()) {
4925 if (class->exception_type == MONO_EXCEPTION_NONE) {
4926 set_failure_from_loader_error (class, mono_loader_get_last_error ());
4928 mono_loader_clear_error ();
4931 if (class->generic_class && !mono_verifier_class_is_valid_generic_instantiation (class))
4932 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Invalid generic instantiation"));
4937 /* Because of the double-checking locking pattern */
4938 mono_memory_barrier ();
4940 class->init_pending = 0;
4942 mono_loader_unlock ();
4944 if (mono_debugger_class_init_func)
4945 mono_debugger_class_init_func (class);
4947 return class->exception_type == MONO_EXCEPTION_NONE;
4951 * mono_class_has_finalizer:
4953 * Return whenever KLASS has a finalizer, initializing klass->has_finalizer in the
4957 mono_class_has_finalizer (MonoClass *klass)
4959 if (!klass->has_finalize_inited) {
4960 MonoClass *class = klass;
4962 mono_loader_lock ();
4964 /* Interfaces and valuetypes are not supposed to have finalizers */
4965 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
4966 MonoMethod *cmethod = NULL;
4968 if (class->parent && class->parent->has_finalize) {
4969 class->has_finalize = 1;
4971 if (class->parent) {
4973 * Can't search in metadata for a method named Finalize, because that
4974 * ignores overrides.
4976 mono_class_setup_vtable (class);
4977 if (class->exception_type || mono_loader_get_last_error ())
4979 cmethod = class->vtable [finalize_slot];
4983 g_assert (class->vtable_size > finalize_slot);
4985 class->has_finalize = 0;
4986 if (class->parent) {
4987 if (cmethod->is_inflated)
4988 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4989 if (cmethod != default_finalize) {
4990 class->has_finalize = 1;
4997 mono_memory_barrier ();
4998 klass->has_finalize_inited = TRUE;
5000 mono_loader_unlock ();
5003 return klass->has_finalize;
5006 mono_loader_unlock ();
5011 mono_is_corlib_image (MonoImage *image)
5013 /* FIXME: allow the dynamic case for our compilers and with full trust */
5015 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
5017 return image == mono_defaults.corlib;
5021 * LOCKING: this assumes the loader lock is held
5024 mono_class_setup_mono_type (MonoClass *class)
5026 const char *name = class->name;
5027 const char *nspace = class->name_space;
5028 gboolean is_corlib = mono_is_corlib_image (class->image);
5030 class->this_arg.byref = 1;
5031 class->this_arg.data.klass = class;
5032 class->this_arg.type = MONO_TYPE_CLASS;
5033 class->byval_arg.data.klass = class;
5034 class->byval_arg.type = MONO_TYPE_CLASS;
5036 if (is_corlib && !strcmp (nspace, "System")) {
5037 if (!strcmp (name, "ValueType")) {
5039 * do not set the valuetype bit for System.ValueType.
5040 * class->valuetype = 1;
5042 class->blittable = TRUE;
5043 } else if (!strcmp (name, "Enum")) {
5045 * do not set the valuetype bit for System.Enum.
5046 * class->valuetype = 1;
5048 class->valuetype = 0;
5049 class->enumtype = 0;
5050 } else if (!strcmp (name, "Object")) {
5051 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
5052 } else if (!strcmp (name, "String")) {
5053 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
5054 } else if (!strcmp (name, "TypedReference")) {
5055 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
5059 if (class->valuetype) {
5060 int t = MONO_TYPE_VALUETYPE;
5062 if (is_corlib && !strcmp (nspace, "System")) {
5065 if (!strcmp (name, "Boolean")) {
5066 t = MONO_TYPE_BOOLEAN;
5067 } else if (!strcmp(name, "Byte")) {
5069 class->blittable = TRUE;
5073 if (!strcmp (name, "Char")) {
5078 if (!strcmp (name, "Double")) {
5080 class->blittable = TRUE;
5084 if (!strcmp (name, "Int32")) {
5086 class->blittable = TRUE;
5087 } else if (!strcmp(name, "Int16")) {
5089 class->blittable = TRUE;
5090 } else if (!strcmp(name, "Int64")) {
5092 class->blittable = TRUE;
5093 } else if (!strcmp(name, "IntPtr")) {
5095 class->blittable = TRUE;
5099 if (!strcmp (name, "Single")) {
5101 class->blittable = TRUE;
5102 } else if (!strcmp(name, "SByte")) {
5104 class->blittable = TRUE;
5108 if (!strcmp (name, "UInt32")) {
5110 class->blittable = TRUE;
5111 } else if (!strcmp(name, "UInt16")) {
5113 class->blittable = TRUE;
5114 } else if (!strcmp(name, "UInt64")) {
5116 class->blittable = TRUE;
5117 } else if (!strcmp(name, "UIntPtr")) {
5119 class->blittable = TRUE;
5123 if (!strcmp (name, "TypedReference")) {
5124 t = MONO_TYPE_TYPEDBYREF;
5125 class->blittable = TRUE;
5129 if (!strcmp (name, "Void")) {
5137 class->this_arg.type = class->byval_arg.type = t;
5140 if (MONO_CLASS_IS_INTERFACE (class))
5141 class->interface_id = mono_get_unique_iid (class);
5146 * COM initialization (using mono_init_com_types) is delayed until needed.
5147 * However when a [ComImport] attribute is present on a type it will trigger
5148 * the initialization. This is not a problem unless the BCL being executed
5149 * lacks the types that COM depends on (e.g. Variant on Silverlight).
5152 init_com_from_comimport (MonoClass *class)
5154 /* we don't always allow COM initialization under the CoreCLR (e.g. Moonlight does not require it) */
5155 if ((mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)) {
5156 /* but some other CoreCLR user could requires it for their platform (i.e. trusted) code */
5157 if (!mono_security_core_clr_determine_platform_image (class->image)) {
5158 /* but it can not be made available for application (i.e. user code) since all COM calls
5159 * are considered native calls. In this case we fail with a TypeLoadException (just like
5160 * Silverlight 2 does */
5161 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5165 /* FIXME : we should add an extra checks to ensure COM can be initialized properly before continuing */
5166 mono_init_com_types ();
5170 * LOCKING: this assumes the loader lock is held
5173 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
5175 gboolean system_namespace;
5176 gboolean is_corlib = mono_is_corlib_image (class->image);
5178 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
5180 /* if root of the hierarchy */
5181 if (system_namespace && !strcmp (class->name, "Object")) {
5182 class->parent = NULL;
5183 class->instance_size = sizeof (MonoObject);
5186 if (!strcmp (class->name, "<Module>")) {
5187 class->parent = NULL;
5188 class->instance_size = 0;
5192 if (!MONO_CLASS_IS_INTERFACE (class)) {
5193 /* Imported COM Objects always derive from __ComObject. */
5194 if (MONO_CLASS_IS_IMPORT (class)) {
5195 init_com_from_comimport (class);
5196 if (parent == mono_defaults.object_class)
5197 parent = mono_defaults.com_object_class;
5200 /* set the parent to something useful and safe, but mark the type as broken */
5201 parent = mono_defaults.object_class;
5202 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5205 class->parent = parent;
5207 if (parent->generic_class && !parent->name) {
5209 * If the parent is a generic instance, we may get
5210 * called before it is fully initialized, especially
5211 * before it has its name.
5216 class->marshalbyref = parent->marshalbyref;
5217 class->contextbound = parent->contextbound;
5218 class->delegate = parent->delegate;
5219 if (MONO_CLASS_IS_IMPORT (class))
5220 class->is_com_object = 1;
5222 class->is_com_object = parent->is_com_object;
5224 if (system_namespace) {
5225 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
5226 class->marshalbyref = 1;
5228 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
5229 class->contextbound = 1;
5231 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
5232 class->delegate = 1;
5235 if (class->parent->enumtype || (mono_is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
5236 (strcmp (class->parent->name_space, "System") == 0)))
5237 class->valuetype = 1;
5238 if (mono_is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
5239 class->valuetype = class->enumtype = 1;
5241 /*class->enumtype = class->parent->enumtype; */
5242 mono_class_setup_supertypes (class);
5244 /* initialize com types if COM interfaces are present */
5245 if (MONO_CLASS_IS_IMPORT (class))
5246 init_com_from_comimport (class);
5247 class->parent = NULL;
5253 * mono_class_setup_supertypes:
5256 * Build the data structure needed to make fast type checks work.
5257 * This currently sets two fields in @class:
5258 * - idepth: distance between @class and System.Object in the type
5260 * - supertypes: array of classes: each element has a class in the hierarchy
5261 * starting from @class up to System.Object
5263 * LOCKING: this assumes the loader lock is held
5266 mono_class_setup_supertypes (MonoClass *class)
5270 if (class->supertypes)
5273 if (class->parent && !class->parent->supertypes)
5274 mono_class_setup_supertypes (class->parent);
5276 class->idepth = class->parent->idepth + 1;
5280 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
5281 class->supertypes = mono_class_alloc0 (class, sizeof (MonoClass *) * ms);
5283 if (class->parent) {
5284 class->supertypes [class->idepth - 1] = class;
5285 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
5287 class->supertypes [0] = class;
5292 * mono_class_create_from_typedef:
5293 * @image: image where the token is valid
5294 * @type_token: typedef token
5296 * Create the MonoClass* representing the specified type token.
5297 * @type_token must be a TypeDef token.
5299 * FIXME: don't return NULL on failure, just the the caller figure it out.
5302 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
5304 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5305 MonoClass *class, *parent = NULL;
5306 guint32 cols [MONO_TYPEDEF_SIZE];
5307 guint32 cols_next [MONO_TYPEDEF_SIZE];
5308 guint tidx = mono_metadata_token_index (type_token);
5309 MonoGenericContext *context = NULL;
5310 const char *name, *nspace;
5312 MonoClass **interfaces;
5313 guint32 field_last, method_last;
5314 guint32 nesting_tokeen;
5316 if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || tidx > tt->rows)
5319 mono_loader_lock ();
5321 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
5322 mono_loader_unlock ();
5326 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5328 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5329 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5331 class = mono_image_alloc0 (image, sizeof (MonoClass));
5334 class->name_space = nspace;
5336 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
5338 class->image = image;
5339 class->type_token = type_token;
5340 class->flags = cols [MONO_TYPEDEF_FLAGS];
5342 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
5344 classes_size += sizeof (MonoClass);
5347 * Check whether we're a generic type definition.
5349 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
5350 if (class->generic_container) {
5351 class->is_generic = 1;
5352 class->generic_container->owner.klass = class;
5353 context = &class->generic_container->context;
5356 if (cols [MONO_TYPEDEF_EXTENDS]) {
5358 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
5360 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
5361 /*WARNING: this must satisfy mono_metadata_type_hash*/
5362 class->this_arg.byref = 1;
5363 class->this_arg.data.klass = class;
5364 class->this_arg.type = MONO_TYPE_CLASS;
5365 class->byval_arg.data.klass = class;
5366 class->byval_arg.type = MONO_TYPE_CLASS;
5368 parent = mono_class_get_full (image, parent_token, context);
5370 if (parent == NULL){
5371 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load parent type"));
5372 mono_loader_clear_error ();
5373 goto parent_failure;
5376 for (tmp = parent; tmp; tmp = tmp->parent) {
5378 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cycle found while resolving parent"));
5379 goto parent_failure;
5381 if (class->generic_container && tmp->generic_class && tmp->generic_class->container_class == class) {
5382 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Parent extends generic instance of this type"));
5383 goto parent_failure;
5388 mono_class_setup_parent (class, parent);
5390 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
5391 mono_class_setup_mono_type (class);
5394 * This might access class->byval_arg for recursion generated by generic constraints,
5395 * so it has to come after setup_mono_type ().
5397 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token))) {
5398 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
5399 if (!class->nested_in) {
5400 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load nestedin type"));
5401 mono_loader_unlock ();
5402 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5407 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
5411 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
5415 class->cast_class = class->element_class = class;
5417 if (!class->enumtype) {
5418 if (!mono_metadata_interfaces_from_typedef_full (
5419 image, type_token, &interfaces, &icount, FALSE, context)){
5420 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load interfaces"));
5421 mono_loader_unlock ();
5422 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5426 class->interfaces = interfaces;
5427 class->interface_count = icount;
5428 class->interfaces_inited = 1;
5431 /*g_print ("Load class %s\n", name);*/
5434 * Compute the field and method lists
5436 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
5437 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
5439 if (tt->rows > tidx){
5440 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
5441 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
5442 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
5444 field_last = image->tables [MONO_TABLE_FIELD].rows;
5445 method_last = image->tables [MONO_TABLE_METHOD].rows;
5448 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
5449 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
5450 class->field.count = field_last - class->field.first;
5452 class->field.count = 0;
5454 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
5455 class->method.count = method_last - class->method.first;
5457 class->method.count = 0;
5459 /* reserve space to store vector pointer in arrays */
5460 if (mono_is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
5461 class->instance_size += 2 * sizeof (gpointer);
5462 g_assert (class->field.count == 0);
5465 if (class->enumtype) {
5466 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
5467 if (!enum_basetype) {
5468 /*set it to a default value as the whole runtime can't handle this to be null*/
5469 class->cast_class = class->element_class = mono_defaults.int32_class;
5470 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5471 mono_loader_unlock ();
5472 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5475 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
5479 * If we're a generic type definition, load the constraints.
5480 * We must do this after the class has been constructed to make certain recursive scenarios
5483 if (class->generic_container && !mono_metadata_load_generic_param_constraints_full (image, type_token, class->generic_container)){
5484 char *class_name = g_strdup_printf("%s.%s", class->name_space, class->name);
5485 char *error = concat_two_strings_with_zero (class->image, class_name, class->image->assembly_name);
5486 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, error);
5487 g_free (class_name);
5488 mono_loader_unlock ();
5489 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5493 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
5494 if (!strncmp (name, "Vector", 6))
5495 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");
5498 mono_loader_unlock ();
5500 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5505 mono_class_setup_mono_type (class);
5506 mono_loader_unlock ();
5507 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5512 /** is klass Nullable<T>? */
5514 mono_class_is_nullable (MonoClass *klass)
5516 return klass->generic_class != NULL &&
5517 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
5521 /** if klass is T? return T */
5523 mono_class_get_nullable_param (MonoClass *klass)
5525 g_assert (mono_class_is_nullable (klass));
5526 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
5530 * Create the `MonoClass' for an instantiation of a generic type.
5531 * We only do this if we actually need it.
5534 mono_generic_class_get_class (MonoGenericClass *gclass)
5536 MonoClass *klass, *gklass;
5538 if (gclass->cached_class)
5539 return gclass->cached_class;
5541 mono_loader_lock ();
5542 if (gclass->cached_class) {
5543 mono_loader_unlock ();
5544 return gclass->cached_class;
5547 klass = mono_image_set_alloc0 (gclass->owner, sizeof (MonoClass));
5549 gklass = gclass->container_class;
5551 if (gklass->nested_in) {
5552 /* The nested_in type should not be inflated since it's possible to produce a nested type with less generic arguments*/
5553 klass->nested_in = gklass->nested_in;
5556 klass->name = gklass->name;
5557 klass->name_space = gklass->name_space;
5559 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
5561 klass->image = gklass->image;
5562 klass->flags = gklass->flags;
5563 klass->type_token = gklass->type_token;
5564 klass->field.count = gklass->field.count;
5566 klass->is_inflated = 1;
5567 klass->generic_class = gclass;
5569 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
5570 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
5571 klass->this_arg.byref = TRUE;
5572 klass->enumtype = gklass->enumtype;
5573 klass->valuetype = gklass->valuetype;
5575 klass->cast_class = klass->element_class = klass;
5577 if (mono_class_is_nullable (klass))
5578 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
5581 * We're not interested in the nested classes of a generic instance.
5582 * We use the generic type definition to look for nested classes.
5585 if (gklass->parent) {
5587 klass->parent = mono_class_inflate_generic_class_checked (gklass->parent, mono_generic_class_get_context (gclass), &error);
5588 if (!mono_error_ok (&error)) {
5589 /*Set parent to something safe as the runtime doesn't handle well this kind of failure.*/
5590 klass->parent = mono_defaults.object_class;
5591 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
5592 mono_error_cleanup (&error);
5597 mono_class_setup_parent (klass, klass->parent);
5599 if (klass->enumtype) {
5600 klass->cast_class = gklass->cast_class;
5601 klass->element_class = gklass->element_class;
5604 if (gclass->is_dynamic) {
5607 mono_class_setup_supertypes (klass);
5609 if (klass->enumtype) {
5611 * For enums, gklass->fields might not been set, but instance_size etc. is
5612 * already set in mono_reflection_create_internal_class (). For non-enums,
5613 * these will be computed normally in mono_class_layout_fields ().
5615 klass->instance_size = gklass->instance_size;
5616 klass->sizes.class_size = gklass->sizes.class_size;
5617 klass->size_inited = 1;
5621 mono_memory_barrier ();
5622 gclass->cached_class = klass;
5624 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
5626 inflated_classes ++;
5627 inflated_classes_size += sizeof (MonoClass);
5629 mono_loader_unlock ();
5635 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
5637 MonoClass *klass, **ptr;
5639 MonoGenericContainer *container = mono_generic_param_owner (param);
5643 image = mono_defaults.corlib;
5645 klass = mono_image_alloc0 (image, sizeof (MonoClass));
5646 classes_size += sizeof (MonoClass);
5649 klass->name = pinfo->name;
5651 int n = mono_generic_param_num (param);
5652 klass->name = mono_image_alloc0 (image, 16);
5653 sprintf ((char*)klass->name, "%d", n);
5658 MonoMethod *omethod = container->owner.method;
5659 klass->name_space = (omethod && omethod->klass) ? omethod->klass->name_space : "";
5661 MonoClass *oklass = container->owner.klass;
5662 klass->name_space = oklass ? oklass->name_space : "";
5665 klass->name_space = "";
5668 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
5672 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
5676 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
5677 klass->parent = pinfo->constraints [0];
5679 } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
5680 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
5682 klass->parent = mono_defaults.object_class;
5685 if (count - pos > 0) {
5686 klass->interface_count = count - pos;
5687 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
5688 klass->interfaces_inited = TRUE;
5689 for (i = pos; i < count; i++)
5690 klass->interfaces [i - pos] = pinfo->constraints [i];
5693 klass->image = image;
5695 klass->inited = TRUE;
5696 klass->cast_class = klass->element_class = klass;
5697 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
5699 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
5700 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
5701 klass->this_arg.byref = TRUE;
5703 /* We don't use type_token for VAR since only classes can use it (not arrays, pointer, VARs, etc) */
5704 klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
5706 /*Init these fields to sane values*/
5707 klass->min_align = 1;
5708 klass->instance_size = sizeof (gpointer);
5709 klass->size_inited = 1;
5711 mono_class_setup_supertypes (klass);
5713 if (count - pos > 0) {
5714 mono_class_setup_vtable (klass->parent);
5715 if (klass->parent->exception_type)
5716 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Failed to setup parent interfaces"));
5718 setup_interface_offsets (klass, klass->parent->vtable_size);
5724 #define FAST_CACHE_SIZE 16
5727 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
5729 int n = mono_generic_param_num (param);
5730 MonoImage *image = param->image;
5735 if (n < FAST_CACHE_SIZE) {
5737 return image->mvar_cache_fast ? image->mvar_cache_fast [n] : NULL;
5739 return image->var_cache_fast ? image->var_cache_fast [n] : NULL;
5741 ht = is_mvar ? image->mvar_cache_slow : image->var_cache_slow;
5742 return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
5747 * LOCKING: Acquires the loader lock.
5750 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
5752 int n = mono_generic_param_num (param);
5753 MonoImage *image = param->image;
5758 if (n < FAST_CACHE_SIZE) {
5760 /* No locking needed */
5761 if (!image->mvar_cache_fast)
5762 image->mvar_cache_fast = mono_image_alloc0 (image, sizeof (MonoClass*) * FAST_CACHE_SIZE);
5763 image->mvar_cache_fast [n] = klass;
5765 if (!image->var_cache_fast)
5766 image->var_cache_fast = mono_image_alloc0 (image, sizeof (MonoClass*) * FAST_CACHE_SIZE);
5767 image->var_cache_fast [n] = klass;
5771 ht = is_mvar ? image->mvar_cache_slow : image->var_cache_slow;
5773 mono_loader_lock ();
5774 ht = is_mvar ? image->mvar_cache_slow : image->var_cache_slow;
5776 ht = g_hash_table_new (NULL, NULL);
5777 mono_memory_barrier ();
5779 image->mvar_cache_slow = ht;
5781 image->var_cache_slow = ht;
5783 mono_loader_unlock ();
5786 g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
5790 * LOCKING: Acquires the loader lock.
5793 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
5795 MonoGenericContainer *container = mono_generic_param_owner (param);
5796 MonoGenericParamInfo *pinfo;
5799 mono_loader_lock ();
5802 pinfo = mono_generic_param_info (param);
5803 if (pinfo->pklass) {
5804 mono_loader_unlock ();
5805 return pinfo->pklass;
5811 klass = get_anon_gparam_class (param, is_mvar);
5813 mono_loader_unlock ();
5818 if (!image && container) {
5820 MonoMethod *method = container->owner.method;
5821 image = (method && method->klass) ? method->klass->image : NULL;
5823 MonoClass *klass = container->owner.klass;
5824 // FIXME: 'klass' should not be null
5825 // But, monodis creates GenericContainers without associating a owner to it
5826 image = klass ? klass->image : NULL;
5830 klass = make_generic_param_class (param, image, is_mvar, pinfo);
5832 mono_memory_barrier ();
5835 pinfo->pklass = klass;
5837 set_anon_gparam_class (param, is_mvar, klass);
5839 mono_loader_unlock ();
5841 /* FIXME: Should this go inside 'make_generic_param_klass'? */
5842 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
5848 mono_ptr_class_get (MonoType *type)
5851 MonoClass *el_class;
5855 el_class = mono_class_from_mono_type (type);
5856 image = el_class->image;
5858 mono_loader_lock ();
5860 if (!image->ptr_cache)
5861 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5863 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
5864 mono_loader_unlock ();
5867 result = mono_image_alloc0 (image, sizeof (MonoClass));
5869 classes_size += sizeof (MonoClass);
5871 result->parent = NULL; /* no parent for PTR types */
5872 result->name_space = el_class->name_space;
5873 name = g_strdup_printf ("%s*", el_class->name);
5874 result->name = mono_image_strdup (image, name);
5877 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5879 result->image = el_class->image;
5880 result->inited = TRUE;
5881 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5882 /* Can pointers get boxed? */
5883 result->instance_size = sizeof (gpointer);
5884 result->cast_class = result->element_class = el_class;
5885 result->blittable = TRUE;
5887 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
5888 result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
5889 result->this_arg.byref = TRUE;
5891 mono_class_setup_supertypes (result);
5893 g_hash_table_insert (image->ptr_cache, el_class, result);
5895 mono_loader_unlock ();
5897 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5903 mono_fnptr_class_get (MonoMethodSignature *sig)
5906 static GHashTable *ptr_hash = NULL;
5908 /* FIXME: These should be allocate from a mempool as well, but which one ? */
5910 mono_loader_lock ();
5913 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5915 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
5916 mono_loader_unlock ();
5919 result = g_new0 (MonoClass, 1);
5921 result->parent = NULL; /* no parent for PTR types */
5922 result->name_space = "System";
5923 result->name = "MonoFNPtrFakeClass";
5925 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5927 result->image = mono_defaults.corlib; /* need to fix... */
5928 result->inited = TRUE;
5929 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
5930 /* Can pointers get boxed? */
5931 result->instance_size = sizeof (gpointer);
5932 result->cast_class = result->element_class = result;
5933 result->blittable = TRUE;
5935 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
5936 result->this_arg.data.method = result->byval_arg.data.method = sig;
5937 result->this_arg.byref = TRUE;
5938 result->blittable = TRUE;
5940 mono_class_setup_supertypes (result);
5942 g_hash_table_insert (ptr_hash, sig, result);
5944 mono_loader_unlock ();
5946 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5952 mono_class_from_mono_type (MonoType *type)
5954 switch (type->type) {
5955 case MONO_TYPE_OBJECT:
5956 return type->data.klass? type->data.klass: mono_defaults.object_class;
5957 case MONO_TYPE_VOID:
5958 return type->data.klass? type->data.klass: mono_defaults.void_class;
5959 case MONO_TYPE_BOOLEAN:
5960 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
5961 case MONO_TYPE_CHAR:
5962 return type->data.klass? type->data.klass: mono_defaults.char_class;
5964 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
5966 return type->data.klass? type->data.klass: mono_defaults.byte_class;
5968 return type->data.klass? type->data.klass: mono_defaults.int16_class;
5970 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
5972 return type->data.klass? type->data.klass: mono_defaults.int32_class;
5974 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
5976 return type->data.klass? type->data.klass: mono_defaults.int_class;
5978 return type->data.klass? type->data.klass: mono_defaults.uint_class;
5980 return type->data.klass? type->data.klass: mono_defaults.int64_class;
5982 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
5984 return type->data.klass? type->data.klass: mono_defaults.single_class;
5986 return type->data.klass? type->data.klass: mono_defaults.double_class;
5987 case MONO_TYPE_STRING:
5988 return type->data.klass? type->data.klass: mono_defaults.string_class;
5989 case MONO_TYPE_TYPEDBYREF:
5990 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
5991 case MONO_TYPE_ARRAY:
5992 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
5994 return mono_ptr_class_get (type->data.type);
5995 case MONO_TYPE_FNPTR:
5996 return mono_fnptr_class_get (type->data.method);
5997 case MONO_TYPE_SZARRAY:
5998 return mono_array_class_get (type->data.klass, 1);
5999 case MONO_TYPE_CLASS:
6000 case MONO_TYPE_VALUETYPE:
6001 return type->data.klass;
6002 case MONO_TYPE_GENERICINST:
6003 return mono_generic_class_get_class (type->data.generic_class);
6005 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
6006 case MONO_TYPE_MVAR:
6007 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
6009 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
6010 g_assert_not_reached ();
6017 * mono_type_retrieve_from_typespec
6018 * @image: context where the image is created
6019 * @type_spec: typespec token
6020 * @context: the generic context used to evaluate generic instantiations in
6023 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate, MonoError *error)
6025 MonoType *t = mono_type_create_from_typespec (image, type_spec);
6027 mono_error_init (error);
6028 *did_inflate = FALSE;
6031 char *name = mono_class_name_from_token (image, type_spec);
6032 char *assembly = mono_assembly_name_from_token (image, type_spec);
6033 mono_error_set_type_load_name (error, name, assembly, "Could not resolve typespec token %08x", type_spec);
6037 if (context && (context->class_inst || context->method_inst)) {
6038 MonoType *inflated = inflate_generic_type (NULL, t, context, error);
6040 if (!mono_error_ok (error))
6045 *did_inflate = TRUE;
6052 * mono_class_create_from_typespec
6053 * @image: context where the image is created
6054 * @type_spec: typespec token
6055 * @context: the generic context used to evaluate generic instantiations in
6058 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, MonoError *error)
6061 gboolean inflated = FALSE;
6062 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated, error);
6063 if (!mono_error_ok (error))
6065 ret = mono_class_from_mono_type (t);
6067 mono_metadata_free_type (t);
6072 * mono_bounded_array_class_get:
6073 * @element_class: element class
6074 * @rank: the dimension of the array class
6075 * @bounded: whenever the array has non-zero bounds
6077 * Returns: a class object describing the array with element type @element_type and
6081 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
6085 MonoClass *parent = NULL;
6086 GSList *list, *rootlist = NULL;
6089 gboolean corlib_type = FALSE;
6091 g_assert (rank <= 255);
6094 /* bounded only matters for one-dimensional arrays */
6097 image = eclass->image;
6099 if (rank == 1 && !bounded) {
6101 * This case is very frequent not just during compilation because of calls
6102 * from mono_class_from_mono_type (), mono_array_new (),
6103 * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
6105 EnterCriticalSection (&image->szarray_cache_lock);
6106 if (!image->szarray_cache)
6107 image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
6108 class = g_hash_table_lookup (image->szarray_cache, eclass);
6109 LeaveCriticalSection (&image->szarray_cache_lock);
6113 mono_loader_lock ();
6115 mono_loader_lock ();
6117 if (!image->array_cache)
6118 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
6120 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
6121 for (; list; list = list->next) {
6123 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
6124 mono_loader_unlock ();
6131 /* for the building corlib use System.Array from it */
6132 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
6133 parent = mono_class_from_name (image, "System", "Array");
6136 parent = mono_defaults.array_class;
6137 if (!parent->inited)
6138 mono_class_init (parent);
6141 class = mono_image_alloc0 (image, sizeof (MonoClass));
6143 class->image = image;
6144 class->name_space = eclass->name_space;
6145 nsize = strlen (eclass->name);
6146 name = g_malloc (nsize + 2 + rank + 1);
6147 memcpy (name, eclass->name, nsize);
6150 memset (name + nsize + 1, ',', rank - 1);
6152 name [nsize + rank] = '*';
6153 name [nsize + rank + bounded] = ']';
6154 name [nsize + rank + bounded + 1] = 0;
6155 class->name = mono_image_strdup (image, name);
6158 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
6160 classes_size += sizeof (MonoClass);
6162 class->type_token = 0;
6163 /* all arrays are marked serializable and sealed, bug #42779 */
6164 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED | TYPE_ATTRIBUTE_PUBLIC;
6165 class->parent = parent;
6166 class->instance_size = mono_class_instance_size (class->parent);
6168 if (eclass->byval_arg.type == MONO_TYPE_TYPEDBYREF || eclass->byval_arg.type == MONO_TYPE_VOID) {
6169 /*Arrays of those two types are invalid.*/
6170 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
6171 } else if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
6172 if (!eclass->ref_info_handle || eclass->wastypebuilder) {
6173 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
6174 g_assert (eclass->ref_info_handle && !eclass->wastypebuilder);
6176 /* element_size -1 is ok as this is not an instantitable type*/
6177 class->sizes.element_size = -1;
6179 class->sizes.element_size = mono_class_array_element_size (eclass);
6181 mono_class_setup_supertypes (class);
6183 if (eclass->generic_class)
6184 mono_class_init (eclass);
6185 if (!eclass->size_inited)
6186 mono_class_setup_fields (eclass);
6187 if (eclass->exception_type) /*FIXME we fail the array type, but we have to let other fields be set.*/
6188 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
6190 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
6194 if (eclass->enumtype)
6195 class->cast_class = eclass->element_class;
6197 class->cast_class = eclass;
6199 switch (class->cast_class->byval_arg.type) {
6201 class->cast_class = mono_defaults.byte_class;
6204 class->cast_class = mono_defaults.int16_class;
6207 #if SIZEOF_VOID_P == 4
6211 class->cast_class = mono_defaults.int32_class;
6214 #if SIZEOF_VOID_P == 8
6218 class->cast_class = mono_defaults.int64_class;
6222 class->element_class = eclass;
6224 if ((rank > 1) || bounded) {
6225 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
6226 class->byval_arg.type = MONO_TYPE_ARRAY;
6227 class->byval_arg.data.array = at;
6228 at->eklass = eclass;
6230 /* FIXME: complete.... */
6232 class->byval_arg.type = MONO_TYPE_SZARRAY;
6233 class->byval_arg.data.klass = eclass;
6235 class->this_arg = class->byval_arg;
6236 class->this_arg.byref = 1;
6241 class->generic_container = eclass->generic_container;
6243 if (rank == 1 && !bounded) {
6244 MonoClass *prev_class;
6246 EnterCriticalSection (&image->szarray_cache_lock);
6247 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
6249 /* Someone got in before us */
6252 g_hash_table_insert (image->szarray_cache, eclass, class);
6253 LeaveCriticalSection (&image->szarray_cache_lock);
6255 list = g_slist_append (rootlist, class);
6256 g_hash_table_insert (image->array_cache, eclass, list);
6259 mono_loader_unlock ();
6261 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
6267 * mono_array_class_get:
6268 * @element_class: element class
6269 * @rank: the dimension of the array class
6271 * Returns: a class object describing the array with element type @element_type and
6275 mono_array_class_get (MonoClass *eclass, guint32 rank)
6277 return mono_bounded_array_class_get (eclass, rank, FALSE);
6281 * mono_class_instance_size:
6284 * Returns: the size of an object instance
6287 mono_class_instance_size (MonoClass *klass)
6289 if (!klass->size_inited)
6290 mono_class_init (klass);
6292 return klass->instance_size;
6296 * mono_class_min_align:
6299 * Returns: minimm alignment requirements
6302 mono_class_min_align (MonoClass *klass)
6304 if (!klass->size_inited)
6305 mono_class_init (klass);
6307 return klass->min_align;
6311 * mono_class_value_size:
6314 * This function is used for value types, and return the
6315 * space and the alignment to store that kind of value object.
6317 * Returns: the size of a value of kind @klass
6320 mono_class_value_size (MonoClass *klass, guint32 *align)
6324 /* fixme: check disable, because we still have external revereces to
6325 * mscorlib and Dummy Objects
6327 /*g_assert (klass->valuetype);*/
6329 size = mono_class_instance_size (klass) - sizeof (MonoObject);
6332 *align = klass->min_align;
6338 * mono_class_data_size:
6341 * Returns: the size of the static class data
6344 mono_class_data_size (MonoClass *klass)
6347 mono_class_init (klass);
6349 /* in arrays, sizes.class_size is unioned with element_size
6350 * and arrays have no static fields
6354 return klass->sizes.class_size;
6358 * Auxiliary routine to mono_class_get_field
6360 * Takes a field index instead of a field token.
6362 static MonoClassField *
6363 mono_class_get_field_idx (MonoClass *class, int idx)
6365 mono_class_setup_fields_locking (class);
6366 if (class->exception_type)
6370 if (class->image->uncompressed_metadata) {
6372 * class->field.first points to the FieldPtr table, while idx points into the
6373 * Field table, so we have to do a search.
6375 /*FIXME this is broken for types with multiple fields with the same name.*/
6376 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
6379 for (i = 0; i < class->field.count; ++i)
6380 if (mono_field_get_name (&class->fields [i]) == name)
6381 return &class->fields [i];
6382 g_assert_not_reached ();
6384 if (class->field.count) {
6385 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
6386 return &class->fields [idx - class->field.first];
6390 class = class->parent;
6396 * mono_class_get_field:
6397 * @class: the class to lookup the field.
6398 * @field_token: the field token
6400 * Returns: A MonoClassField representing the type and offset of
6401 * the field, or a NULL value if the field does not belong to this
6405 mono_class_get_field (MonoClass *class, guint32 field_token)
6407 int idx = mono_metadata_token_index (field_token);
6409 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
6411 return mono_class_get_field_idx (class, idx - 1);
6415 * mono_class_get_field_from_name:
6416 * @klass: the class to lookup the field.
6417 * @name: the field name
6419 * Search the class @klass and it's parents for a field with the name @name.
6421 * Returns: the MonoClassField pointer of the named field or NULL
6424 mono_class_get_field_from_name (MonoClass *klass, const char *name)
6426 return mono_class_get_field_from_name_full (klass, name, NULL);
6430 * mono_class_get_field_from_name_full:
6431 * @klass: the class to lookup the field.
6432 * @name: the field name
6433 * @type: the type of the fields. This optional.
6435 * Search the class @klass and it's parents for a field with the name @name and type @type.
6437 * If @klass is an inflated generic type, the type comparison is done with the equivalent field
6438 * of its generic type definition.
6440 * Returns: the MonoClassField pointer of the named field or NULL
6443 mono_class_get_field_from_name_full (MonoClass *klass, const char *name, MonoType *type)
6447 mono_class_setup_fields_locking (klass);
6448 if (klass->exception_type)
6452 for (i = 0; i < klass->field.count; ++i) {
6453 MonoClassField *field = &klass->fields [i];
6455 if (strcmp (name, mono_field_get_name (field)) != 0)
6459 MonoType *field_type = mono_metadata_get_corresponding_field_from_generic_type_definition (field)->type;
6460 if (!mono_metadata_type_equal_full (type, field_type, TRUE))
6465 klass = klass->parent;
6471 * mono_class_get_field_token:
6472 * @field: the field we need the token of
6474 * Get the token of a field. Note that the tokesn is only valid for the image
6475 * the field was loaded from. Don't use this function for fields in dynamic types.
6477 * Returns: the token representing the field in the image it was loaded from.
6480 mono_class_get_field_token (MonoClassField *field)
6482 MonoClass *klass = field->parent;
6485 mono_class_setup_fields_locking (klass);
6490 for (i = 0; i < klass->field.count; ++i) {
6491 if (&klass->fields [i] == field) {
6492 int idx = klass->field.first + i + 1;
6494 if (klass->image->uncompressed_metadata)
6495 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
6496 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
6499 klass = klass->parent;
6502 g_assert_not_reached ();
6507 mono_field_get_index (MonoClassField *field)
6509 int index = field - field->parent->fields;
6511 g_assert (index >= 0 && index < field->parent->field.count);
6517 * mono_class_get_field_default_value:
6519 * Return the default value of the field as a pointer into the metadata blob.
6522 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
6525 guint32 constant_cols [MONO_CONSTANT_SIZE];
6527 MonoClass *klass = field->parent;
6529 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
6531 if (!klass->ext || !klass->ext->field_def_values) {
6532 mono_loader_lock ();
6533 mono_class_alloc_ext (klass);
6534 if (!klass->ext->field_def_values)
6535 klass->ext->field_def_values = mono_class_alloc0 (klass, sizeof (MonoFieldDefaultValue) * klass->field.count);
6536 mono_loader_unlock ();
6539 field_index = mono_field_get_index (field);
6541 if (!klass->ext->field_def_values [field_index].data) {
6542 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
6546 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
6548 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
6549 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
6550 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
6553 *def_type = klass->ext->field_def_values [field_index].def_type;
6554 return klass->ext->field_def_values [field_index].data;
6558 mono_property_get_index (MonoProperty *prop)
6560 int index = prop - prop->parent->ext->properties;
6562 g_assert (index >= 0 && index < prop->parent->ext->property.count);
6568 * mono_class_get_property_default_value:
6570 * Return the default value of the field as a pointer into the metadata blob.
6573 mono_class_get_property_default_value (MonoProperty *property, MonoTypeEnum *def_type)
6576 guint32 constant_cols [MONO_CONSTANT_SIZE];
6577 MonoClass *klass = property->parent;
6579 g_assert (property->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT);
6581 * We don't cache here because it is not used by C# so it's quite rare, but
6582 * we still do the lookup in klass->ext because that is where the data
6583 * is stored for dynamic assemblies.
6586 if (klass->image->dynamic) {
6587 int prop_index = mono_property_get_index (property);
6588 if (klass->ext->prop_def_values && klass->ext->prop_def_values [prop_index].data) {
6589 *def_type = klass->ext->prop_def_values [prop_index].def_type;
6590 return klass->ext->prop_def_values [prop_index].data;
6594 cindex = mono_metadata_get_constant_index (klass->image, mono_class_get_property_token (property), 0);
6598 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
6599 *def_type = constant_cols [MONO_CONSTANT_TYPE];
6600 return (gpointer)mono_metadata_blob_heap (klass->image, constant_cols [MONO_CONSTANT_VALUE]);
6604 mono_class_get_event_token (MonoEvent *event)
6606 MonoClass *klass = event->parent;
6611 for (i = 0; i < klass->ext->event.count; ++i) {
6612 if (&klass->ext->events [i] == event)
6613 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
6616 klass = klass->parent;
6619 g_assert_not_reached ();
6624 mono_class_get_property_from_name (MonoClass *klass, const char *name)
6628 gpointer iter = NULL;
6629 while ((p = mono_class_get_properties (klass, &iter))) {
6630 if (! strcmp (name, p->name))
6633 klass = klass->parent;
6639 mono_class_get_property_token (MonoProperty *prop)
6641 MonoClass *klass = prop->parent;
6645 gpointer iter = NULL;
6646 while ((p = mono_class_get_properties (klass, &iter))) {
6647 if (&klass->ext->properties [i] == prop)
6648 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
6652 klass = klass->parent;
6655 g_assert_not_reached ();
6660 mono_class_name_from_token (MonoImage *image, guint32 type_token)
6662 const char *name, *nspace;
6664 return g_strdup_printf ("DynamicType 0x%08x", type_token);
6666 switch (type_token & 0xff000000){
6667 case MONO_TOKEN_TYPE_DEF: {
6668 guint32 cols [MONO_TYPEDEF_SIZE];
6669 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
6670 guint tidx = mono_metadata_token_index (type_token);
6672 if (tidx > tt->rows)
6673 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6675 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
6676 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6677 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6678 if (strlen (nspace) == 0)
6679 return g_strdup_printf ("%s", name);
6681 return g_strdup_printf ("%s.%s", nspace, name);
6684 case MONO_TOKEN_TYPE_REF: {
6686 guint32 cols [MONO_TYPEREF_SIZE];
6687 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
6688 guint tidx = mono_metadata_token_index (type_token);
6691 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6693 if (!mono_verifier_verify_typeref_row (image, tidx - 1, &error)) {
6694 char *msg = g_strdup_printf ("Invalid type token 0x%08x due to '%s'", type_token, mono_error_get_message (&error));
6695 mono_error_cleanup (&error);
6699 mono_metadata_decode_row (t, tidx-1, cols, MONO_TYPEREF_SIZE);
6700 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
6701 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
6702 if (strlen (nspace) == 0)
6703 return g_strdup_printf ("%s", name);
6705 return g_strdup_printf ("%s.%s", nspace, name);
6708 case MONO_TOKEN_TYPE_SPEC:
6709 return g_strdup_printf ("Typespec 0x%08x", type_token);
6711 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6716 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
6719 return g_strdup_printf ("DynamicAssembly %s", image->name);
6721 switch (type_token & 0xff000000){
6722 case MONO_TOKEN_TYPE_DEF:
6723 if (image->assembly)
6724 return mono_stringify_assembly_name (&image->assembly->aname);
6725 else if (image->assembly_name)
6726 return g_strdup (image->assembly_name);
6727 return g_strdup_printf ("%s", image->name ? image->name : "[Could not resolve assembly name");
6728 case MONO_TOKEN_TYPE_REF: {
6730 MonoAssemblyName aname;
6731 guint32 cols [MONO_TYPEREF_SIZE];
6732 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
6733 guint32 idx = mono_metadata_token_index (type_token);
6736 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6738 if (!mono_verifier_verify_typeref_row (image, idx - 1, &error)) {
6739 char *msg = g_strdup_printf ("Invalid type token 0x%08x due to '%s'", type_token, mono_error_get_message (&error));
6740 mono_error_cleanup (&error);
6743 mono_metadata_decode_row (t, idx-1, cols, MONO_TYPEREF_SIZE);
6745 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
6746 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
6747 case MONO_RESOLTION_SCOPE_MODULE:
6749 return g_strdup ("");
6750 case MONO_RESOLTION_SCOPE_MODULEREF:
6752 return g_strdup ("");
6753 case MONO_RESOLTION_SCOPE_TYPEREF:
6755 return g_strdup ("");
6756 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
6757 mono_assembly_get_assemblyref (image, idx - 1, &aname);
6758 return mono_stringify_assembly_name (&aname);
6760 g_assert_not_reached ();
6764 case MONO_TOKEN_TYPE_SPEC:
6766 return g_strdup ("");
6768 g_assert_not_reached ();
6775 * mono_class_get_full:
6776 * @image: the image where the class resides
6777 * @type_token: the token for the class
6778 * @context: the generic context used to evaluate generic instantiations in
6780 * Returns: the MonoClass that represents @type_token in @image
6783 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
6786 MonoClass *class = NULL;
6788 if (image->dynamic) {
6789 int table = mono_metadata_token_table (type_token);
6791 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
6792 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
6795 return mono_lookup_dynamic_token (image, type_token, context);
6798 switch (type_token & 0xff000000){
6799 case MONO_TOKEN_TYPE_DEF:
6800 class = mono_class_create_from_typedef (image, type_token);
6802 case MONO_TOKEN_TYPE_REF:
6803 class = mono_class_from_typeref (image, type_token);
6805 case MONO_TOKEN_TYPE_SPEC:
6806 class = mono_class_create_from_typespec (image, type_token, context, &error);
6807 if (!mono_error_ok (&error)) {
6808 /*FIXME don't swallow the error message*/
6809 mono_error_cleanup (&error);
6813 g_warning ("unknown token type %x", type_token & 0xff000000);
6814 g_assert_not_reached ();
6818 char *name = mono_class_name_from_token (image, type_token);
6819 char *assembly = mono_assembly_name_from_token (image, type_token);
6820 mono_loader_set_error_type_load (name, assembly);
6830 * mono_type_get_full:
6831 * @image: the image where the type resides
6832 * @type_token: the token for the type
6833 * @context: the generic context used to evaluate generic instantiations in
6835 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
6837 * Returns: the MonoType that represents @type_token in @image
6840 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
6843 MonoType *type = NULL;
6844 gboolean inflated = FALSE;
6846 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
6848 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
6850 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
6851 MonoClass *class = mono_class_get_full (image, type_token, context);
6852 return class ? mono_class_get_type (class) : NULL;
6855 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated, &error);
6857 if (!mono_error_ok (&error)) {
6858 /*FIXME don't swalloc the error message.*/
6859 char *name = mono_class_name_from_token (image, type_token);
6860 char *assembly = mono_assembly_name_from_token (image, type_token);
6862 g_warning ("Error loading type %s from %s due to %s", name, assembly, mono_error_get_message (&error));
6864 mono_error_cleanup (&error);
6865 mono_loader_set_error_type_load (name, assembly);
6870 MonoType *tmp = type;
6871 type = mono_class_get_type (mono_class_from_mono_type (type));
6872 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
6873 * A MonoClass::byval_arg of a generic type definion has type CLASS.
6874 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
6876 * The long term solution is to chaise this places and make then set MonoType::type correctly.
6878 if (type->type != tmp->type)
6881 mono_metadata_free_type (tmp);
6888 mono_class_get (MonoImage *image, guint32 type_token)
6890 return mono_class_get_full (image, type_token, NULL);
6894 * mono_image_init_name_cache:
6896 * Initializes the class name cache stored in image->name_cache.
6898 * LOCKING: Acquires the corresponding image lock.
6901 mono_image_init_name_cache (MonoImage *image)
6903 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
6904 guint32 cols [MONO_TYPEDEF_SIZE];
6907 guint32 i, visib, nspace_index;
6908 GHashTable *name_cache2, *nspace_table;
6910 mono_image_lock (image);
6912 if (image->name_cache) {
6913 mono_image_unlock (image);
6917 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
6919 if (image->dynamic) {
6920 mono_image_unlock (image);
6924 /* Temporary hash table to avoid lookups in the nspace_table */
6925 name_cache2 = g_hash_table_new (NULL, NULL);
6927 for (i = 1; i <= t->rows; ++i) {
6928 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
6929 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
6931 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
6932 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
6934 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
6936 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6937 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6939 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
6940 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6941 if (!nspace_table) {
6942 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6943 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6944 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6947 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
6950 /* Load type names from EXPORTEDTYPES table */
6952 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6953 guint32 cols [MONO_EXP_TYPE_SIZE];
6956 for (i = 0; i < t->rows; ++i) {
6957 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
6958 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
6959 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
6961 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
6962 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6963 if (!nspace_table) {
6964 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6965 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6966 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6969 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
6973 g_hash_table_destroy (name_cache2);
6974 mono_image_unlock (image);
6977 /*FIXME Only dynamic assemblies should allow this operation.*/
6979 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
6980 const char *name, guint32 index)
6982 GHashTable *nspace_table;
6983 GHashTable *name_cache;
6986 mono_image_lock (image);
6988 if (!image->name_cache)
6989 mono_image_init_name_cache (image);
6991 name_cache = image->name_cache;
6992 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
6993 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6994 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
6997 if ((old_index = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, (char*) name))))
6998 g_error ("overrwritting old token %x on image %s for type %s::%s", old_index, image->name, nspace, name);
7000 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
7002 mono_image_unlock (image);
7011 find_nocase (gpointer key, gpointer value, gpointer user_data)
7013 char *name = (char*)key;
7014 FindUserData *data = (FindUserData*)user_data;
7016 if (!data->value && (mono_utf8_strcasecmp (name, (char*)data->key) == 0))
7017 data->value = value;
7021 * mono_class_from_name_case:
7022 * @image: The MonoImage where the type is looked up in
7023 * @name_space: the type namespace
7024 * @name: the type short name.
7026 * Obtains a MonoClass with a given namespace and a given name which
7027 * is located in the given MonoImage. The namespace and name
7028 * lookups are case insensitive.
7031 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
7033 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
7034 guint32 cols [MONO_TYPEDEF_SIZE];
7039 if (image->dynamic) {
7041 FindUserData user_data;
7043 mono_image_lock (image);
7045 if (!image->name_cache)
7046 mono_image_init_name_cache (image);
7048 user_data.key = name_space;
7049 user_data.value = NULL;
7050 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
7052 if (user_data.value) {
7053 GHashTable *nspace_table = (GHashTable*)user_data.value;
7055 user_data.key = name;
7056 user_data.value = NULL;
7058 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
7060 if (user_data.value)
7061 token = GPOINTER_TO_UINT (user_data.value);
7064 mono_image_unlock (image);
7067 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
7073 /* add a cache if needed */
7074 for (i = 1; i <= t->rows; ++i) {
7075 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
7076 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
7078 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
7079 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
7081 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
7083 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
7084 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
7085 if (mono_utf8_strcasecmp (n, name) == 0 && mono_utf8_strcasecmp (nspace, name_space) == 0)
7086 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
7092 return_nested_in (MonoClass *class, char *nested)
7095 char *s = strchr (nested, '/');
7096 gpointer iter = NULL;
7103 while ((found = mono_class_get_nested_types (class, &iter))) {
7104 if (strcmp (found->name, nested) == 0) {
7106 return return_nested_in (found, s);
7114 search_modules (MonoImage *image, const char *name_space, const char *name)
7116 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
7117 MonoImage *file_image;
7122 * The EXPORTEDTYPES table only contains public types, so have to search the
7124 * Note: image->modules contains the contents of the MODULEREF table, while
7125 * the real module list is in the FILE table.
7127 for (i = 0; i < file_table->rows; i++) {
7128 guint32 cols [MONO_FILE_SIZE];
7129 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
7130 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
7133 file_image = mono_image_load_file_for_image (image, i + 1);
7135 class = mono_class_from_name (file_image, name_space, name);
7145 * mono_class_from_name:
7146 * @image: The MonoImage where the type is looked up in
7147 * @name_space: the type namespace
7148 * @name: the type short name.
7150 * Obtains a MonoClass with a given namespace and a given name which
7151 * is located in the given MonoImage.
7154 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
7156 GHashTable *nspace_table;
7157 MonoImage *loaded_image;
7164 if ((nested = strchr (name, '/'))) {
7165 int pos = nested - name;
7166 int len = strlen (name);
7169 memcpy (buf, name, len + 1);
7171 nested = buf + pos + 1;
7175 /* FIXME: get_class_from_name () can't handle types in the EXPORTEDTYPE table */
7176 if (get_class_from_name && image->tables [MONO_TABLE_EXPORTEDTYPE].rows == 0) {
7177 gboolean res = get_class_from_name (image, name_space, name, &class);
7180 class = search_modules (image, name_space, name);
7182 return class ? return_nested_in (class, nested) : NULL;
7188 mono_image_lock (image);
7190 if (!image->name_cache)
7191 mono_image_init_name_cache (image);
7193 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
7196 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
7198 mono_image_unlock (image);
7200 if (!token && image->dynamic && image->modules) {
7201 /* Search modules as well */
7202 for (i = 0; i < image->module_count; ++i) {
7203 MonoImage *module = image->modules [i];
7205 class = mono_class_from_name (module, name_space, name);
7212 class = search_modules (image, name_space, name);
7220 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
7221 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
7222 guint32 cols [MONO_EXP_TYPE_SIZE];
7225 idx = mono_metadata_token_index (token);
7227 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
7229 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
7230 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
7231 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
7234 class = mono_class_from_name (loaded_image, name_space, name);
7236 return return_nested_in (class, nested);
7238 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
7239 guint32 assembly_idx;
7241 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
7243 mono_assembly_load_reference (image, assembly_idx - 1);
7244 g_assert (image->references [assembly_idx - 1]);
7245 if (image->references [assembly_idx - 1] == (gpointer)-1)
7248 /* FIXME: Cycle detection */
7249 return mono_class_from_name (image->references [assembly_idx - 1]->image, name_space, name);
7251 g_error ("not yet implemented");
7255 token = MONO_TOKEN_TYPE_DEF | token;
7257 class = mono_class_get (image, token);
7259 return return_nested_in (class, nested);
7263 /*FIXME test for interfaces with variant generic arguments*/
7265 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
7266 gboolean check_interfaces)
7268 g_assert (klassc->idepth > 0);
7269 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
7270 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
7272 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
7275 for (i = 0; i < klass->interface_count; i ++) {
7276 MonoClass *ic = klass->interfaces [i];
7281 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
7286 * MS.NET thinks interfaces are a subclass of Object, so we think it as
7289 if (klassc == mono_defaults.object_class)
7296 mono_type_is_generic_argument (MonoType *type)
7298 return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
7302 mono_class_has_variant_generic_params (MonoClass *klass)
7305 MonoGenericContainer *container;
7307 if (!klass->generic_class)
7310 container = klass->generic_class->container_class->generic_container;
7312 for (i = 0; i < container->type_argc; ++i)
7313 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
7320 mono_gparam_is_reference_conversible (MonoClass *target, MonoClass *candidate, gboolean check_for_reference_conv)
7322 if (target == candidate)
7325 if (check_for_reference_conv &&
7326 mono_type_is_generic_argument (&target->byval_arg) &&
7327 mono_type_is_generic_argument (&candidate->byval_arg)) {
7328 MonoGenericParam *gparam = candidate->byval_arg.data.generic_param;
7329 MonoGenericParamInfo *pinfo = mono_generic_param_info (gparam);
7331 if (!pinfo || (pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) == 0)
7334 if (!mono_class_is_assignable_from (target, candidate))
7340 * @container the generic container from the GTD
7341 * @klass: the class to be assigned to
7342 * @oklass: the source class
7344 * Both klass and oklass must be instances of the same generic interface.
7345 * Return true if @klass can be assigned to a @klass variable
7348 mono_class_is_variant_compatible (MonoClass *klass, MonoClass *oklass, gboolean check_for_reference_conv)
7351 MonoType **klass_argv, **oklass_argv;
7352 MonoClass *klass_gtd = mono_class_get_generic_type_definition (klass);
7353 MonoGenericContainer *container = klass_gtd->generic_container;
7355 if (klass == oklass)
7358 /*Viable candidates are instances of the same generic interface*/
7359 if (mono_class_get_generic_type_definition (oklass) != klass_gtd || oklass == klass_gtd)
7362 klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
7363 oklass_argv = &oklass->generic_class->context.class_inst->type_argv [0];
7365 for (j = 0; j < container->type_argc; ++j) {
7366 MonoClass *param1_class = mono_class_from_mono_type (klass_argv [j]);
7367 MonoClass *param2_class = mono_class_from_mono_type (oklass_argv [j]);
7369 if (param1_class->valuetype != param2_class->valuetype || (param1_class->valuetype && param1_class != param2_class))
7373 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
7374 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
7376 if (param1_class != param2_class) {
7377 if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_VARIANT) {
7378 if (!mono_gparam_is_reference_conversible (param1_class, param2_class, check_for_reference_conv))
7380 } else if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_COVARIANT) {
7381 if (!mono_gparam_is_reference_conversible (param2_class, param1_class, check_for_reference_conv))
7391 mono_gparam_is_assignable_from (MonoClass *target, MonoClass *candidate)
7393 MonoGenericParam *gparam, *ogparam;
7394 MonoGenericParamInfo *tinfo, *cinfo;
7395 MonoClass **candidate_class;
7396 gboolean class_constraint_satisfied, valuetype_constraint_satisfied;
7399 if (target == candidate)
7401 if (target->byval_arg.type != candidate->byval_arg.type)
7404 gparam = target->byval_arg.data.generic_param;
7405 ogparam = candidate->byval_arg.data.generic_param;
7406 tinfo = mono_generic_param_info (gparam);
7407 cinfo = mono_generic_param_info (ogparam);
7409 class_constraint_satisfied = FALSE;
7410 valuetype_constraint_satisfied = FALSE;
7412 /*candidate must have a super set of target's special constraints*/
7413 tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
7414 cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
7416 if (cinfo->constraints) {
7417 for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
7418 MonoClass *cc = *candidate_class;
7420 if (mono_type_is_reference (&cc->byval_arg) && !MONO_CLASS_IS_INTERFACE (cc))
7421 class_constraint_satisfied = TRUE;
7422 else if (!mono_type_is_reference (&cc->byval_arg) && !MONO_CLASS_IS_INTERFACE (cc))
7423 valuetype_constraint_satisfied = TRUE;
7426 class_constraint_satisfied |= (cmask & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) != 0;
7427 valuetype_constraint_satisfied |= (cmask & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) != 0;
7429 if ((tmask & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && !class_constraint_satisfied)
7431 if ((tmask & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && !valuetype_constraint_satisfied)
7433 if ((tmask & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !((cmask & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) ||
7434 valuetype_constraint_satisfied)) {
7439 /*candidate type constraints must be a superset of target's*/
7440 if (tinfo->constraints) {
7441 MonoClass **target_class;
7442 for (target_class = tinfo->constraints; *target_class; ++target_class) {
7443 MonoClass *tc = *target_class;
7446 * A constraint from @target might inflate into @candidate itself and in that case we don't need
7447 * check it's constraints since it satisfy the constraint by itself.
7449 if (mono_metadata_type_equal (&tc->byval_arg, &candidate->byval_arg))
7452 if (!cinfo->constraints)
7455 for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
7456 MonoClass *cc = *candidate_class;
7458 if (mono_class_is_assignable_from (tc, cc))
7462 * This happens when we have the following:
7464 * Bar<K> where K : IFace
7465 * Foo<T, U> where T : U where U : IFace
7467 * Bar<T> <- T here satisfy K constraint transitively through to U's constraint
7470 if (mono_type_is_generic_argument (&cc->byval_arg)) {
7471 if (mono_gparam_is_assignable_from (target, cc))
7475 if (!*candidate_class)
7480 /*candidate itself must have a constraint that satisfy target*/
7481 if (cinfo->constraints) {
7482 for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
7483 MonoClass *cc = *candidate_class;
7484 if (mono_class_is_assignable_from (target, cc))
7492 * mono_class_is_assignable_from:
7493 * @klass: the class to be assigned to
7494 * @oklass: the source class
7496 * Return: true if an instance of object oklass can be assigned to an
7497 * instance of object @klass
7500 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
7502 /*FIXME this will cause a lot of irrelevant stuff to be loaded.*/
7504 mono_class_init (klass);
7506 if (!oklass->inited)
7507 mono_class_init (oklass);
7509 if (klass->exception_type || oklass->exception_type)
7512 if (mono_type_is_generic_argument (&klass->byval_arg)) {
7513 if (!mono_type_is_generic_argument (&oklass->byval_arg))
7515 return mono_gparam_is_assignable_from (klass, oklass);
7518 if (MONO_CLASS_IS_INTERFACE (klass)) {
7519 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR)) {
7520 MonoGenericParam *gparam = oklass->byval_arg.data.generic_param;
7521 MonoClass **constraints = mono_generic_container_get_param_info (gparam->owner, gparam->num)->constraints;
7525 for (i = 0; constraints [i]; ++i) {
7526 if (mono_class_is_assignable_from (klass, constraints [i]))
7534 /* interface_offsets might not be set for dynamic classes */
7535 if (oklass->ref_info_handle && !oklass->interface_bitmap)
7537 * oklass might be a generic type parameter but they have
7538 * interface_offsets set.
7540 return mono_reflection_call_is_assignable_to (oklass, klass);
7541 if (!oklass->interface_bitmap)
7542 /* Happens with generic instances of not-yet created dynamic types */
7544 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
7547 if (mono_class_has_variant_generic_params (klass)) {
7550 mono_class_setup_interfaces (oklass, &error);
7551 if (!mono_error_ok (&error)) {
7552 mono_error_cleanup (&error);
7556 /*klass is a generic variant interface, We need to extract from oklass a list of ifaces which are viable candidates.*/
7557 for (i = 0; i < oklass->interface_offsets_count; ++i) {
7558 MonoClass *iface = oklass->interfaces_packed [i];
7560 if (mono_class_is_variant_compatible (klass, iface, FALSE))
7565 } else if (klass->delegate) {
7566 if (mono_class_has_variant_generic_params (klass) && mono_class_is_variant_compatible (klass, oklass, FALSE))
7568 }else if (klass->rank) {
7569 MonoClass *eclass, *eoclass;
7571 if (oklass->rank != klass->rank)
7574 /* vectors vs. one dimensional arrays */
7575 if (oklass->byval_arg.type != klass->byval_arg.type)
7578 eclass = klass->cast_class;
7579 eoclass = oklass->cast_class;
7582 * a is b does not imply a[] is b[] when a is a valuetype, and
7583 * b is a reference type.
7586 if (eoclass->valuetype) {
7587 if ((eclass == mono_defaults.enum_class) ||
7588 (eclass == mono_defaults.enum_class->parent) ||
7589 (eclass == mono_defaults.object_class))
7593 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
7594 } else if (mono_class_is_nullable (klass)) {
7595 if (mono_class_is_nullable (oklass))
7596 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
7598 return mono_class_is_assignable_from (klass->cast_class, oklass);
7599 } else if (klass == mono_defaults.object_class)
7602 return mono_class_has_parent (oklass, klass);
7605 /*Check if @oklass is variant compatible with @klass.*/
7607 mono_class_is_variant_compatible_slow (MonoClass *klass, MonoClass *oklass)
7610 MonoType **klass_argv, **oklass_argv;
7611 MonoClass *klass_gtd = mono_class_get_generic_type_definition (klass);
7612 MonoGenericContainer *container = klass_gtd->generic_container;
7614 /*Viable candidates are instances of the same generic interface*/
7615 if (mono_class_get_generic_type_definition (oklass) != klass_gtd || oklass == klass_gtd)
7618 klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
7619 oklass_argv = &oklass->generic_class->context.class_inst->type_argv [0];
7621 for (j = 0; j < container->type_argc; ++j) {
7622 MonoClass *param1_class = mono_class_from_mono_type (klass_argv [j]);
7623 MonoClass *param2_class = mono_class_from_mono_type (oklass_argv [j]);
7625 if (param1_class->valuetype != param2_class->valuetype)
7629 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
7630 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
7632 if (param1_class != param2_class) {
7633 if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_VARIANT) {
7634 if (!mono_class_is_assignable_from_slow (param1_class, param2_class))
7636 } else if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_COVARIANT) {
7637 if (!mono_class_is_assignable_from_slow (param2_class, param1_class))
7645 /*Check if @candidate implements the interface @target*/
7647 mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
7651 gboolean is_variant = mono_class_has_variant_generic_params (target);
7653 if (is_variant && MONO_CLASS_IS_INTERFACE (candidate)) {
7654 if (mono_class_is_variant_compatible_slow (target, candidate))
7659 if (candidate == target)
7662 /*A TypeBuilder can have more interfaces on tb->interfaces than on candidate->interfaces*/
7663 if (candidate->image->dynamic && !candidate->wastypebuilder) {
7664 MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (candidate);
7666 if (tb && tb->interfaces) {
7667 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
7668 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
7669 MonoClass *iface_class;
7671 /* we can't realize the type here since it can do pretty much anything. */
7674 iface_class = mono_class_from_mono_type (iface->type);
7675 if (iface_class == target)
7677 if (is_variant && mono_class_is_variant_compatible_slow (target, iface_class))
7679 if (mono_class_implement_interface_slow (target, iface_class))
7684 /*setup_interfaces don't mono_class_init anything*/
7685 mono_class_setup_interfaces (candidate, &error);
7686 if (!mono_error_ok (&error)) {
7687 mono_error_cleanup (&error);
7691 for (i = 0; i < candidate->interface_count; ++i) {
7692 if (candidate->interfaces [i] == target)
7695 if (is_variant && mono_class_is_variant_compatible_slow (target, candidate->interfaces [i]))
7698 if (mono_class_implement_interface_slow (target, candidate->interfaces [i]))
7702 candidate = candidate->parent;
7703 } while (candidate);
7709 * Check if @oklass can be assigned to @klass.
7710 * This function does the same as mono_class_is_assignable_from but is safe to be used from mono_class_init context.
7713 mono_class_is_assignable_from_slow (MonoClass *target, MonoClass *candidate)
7715 if (candidate == target)
7717 if (target == mono_defaults.object_class)
7720 /*setup_supertypes don't mono_class_init anything */
7721 mono_class_setup_supertypes (candidate);
7722 mono_class_setup_supertypes (target);
7724 if (mono_class_has_parent (candidate, target))
7727 /*If target is not an interface there is no need to check them.*/
7728 if (MONO_CLASS_IS_INTERFACE (target))
7729 return mono_class_implement_interface_slow (target, candidate);
7731 if (target->delegate && mono_class_has_variant_generic_params (target))
7732 return mono_class_is_variant_compatible (target, candidate, FALSE);
7734 /*FIXME properly handle nullables and arrays */
7735 /*FIXME properly handle (M)VAR */
7740 * mono_class_get_cctor:
7741 * @klass: A MonoClass pointer
7743 * Returns: the static constructor of @klass if it exists, NULL otherwise.
7746 mono_class_get_cctor (MonoClass *klass)
7748 MonoCachedClassInfo cached_info;
7750 if (klass->image->dynamic) {
7752 * has_cctor is not set for these classes because mono_class_init () is
7755 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
7758 if (!klass->has_cctor)
7761 if (mono_class_get_cached_class_info (klass, &cached_info))
7762 return mono_get_method (klass->image, cached_info.cctor_token, klass);
7764 if (klass->generic_class && !klass->methods)
7765 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
7767 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
7771 * mono_class_get_finalizer:
7772 * @klass: The MonoClass pointer
7774 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
7777 mono_class_get_finalizer (MonoClass *klass)
7779 MonoCachedClassInfo cached_info;
7782 mono_class_init (klass);
7783 if (!mono_class_has_finalizer (klass))
7786 if (mono_class_get_cached_class_info (klass, &cached_info))
7787 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
7789 mono_class_setup_vtable (klass);
7790 return klass->vtable [finalize_slot];
7795 * mono_class_needs_cctor_run:
7796 * @klass: the MonoClass pointer
7797 * @caller: a MonoMethod describing the caller
7799 * Determines whenever the class has a static constructor and whenever it
7800 * needs to be called when executing CALLER.
7803 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
7807 method = mono_class_get_cctor (klass);
7809 return (method == caller) ? FALSE : TRUE;
7815 * mono_class_array_element_size:
7818 * Returns: the number of bytes an element of type @klass
7819 * uses when stored into an array.
7822 mono_class_array_element_size (MonoClass *klass)
7824 MonoType *type = &klass->byval_arg;
7827 switch (type->type) {
7830 case MONO_TYPE_BOOLEAN:
7834 case MONO_TYPE_CHAR:
7843 case MONO_TYPE_CLASS:
7844 case MONO_TYPE_STRING:
7845 case MONO_TYPE_OBJECT:
7846 case MONO_TYPE_SZARRAY:
7847 case MONO_TYPE_ARRAY:
7849 case MONO_TYPE_MVAR:
7850 return sizeof (gpointer);
7855 case MONO_TYPE_VALUETYPE:
7856 if (type->data.klass->enumtype) {
7857 type = mono_class_enum_basetype (type->data.klass);
7858 klass = klass->element_class;
7861 return mono_class_instance_size (klass) - sizeof (MonoObject);
7862 case MONO_TYPE_GENERICINST:
7863 type = &type->data.generic_class->container_class->byval_arg;
7866 case MONO_TYPE_VOID:
7870 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
7876 * mono_array_element_size:
7877 * @ac: pointer to a #MonoArrayClass
7879 * Returns: the size of single array element.
7882 mono_array_element_size (MonoClass *ac)
7884 g_assert (ac->rank);
7885 return ac->sizes.element_size;
7889 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
7890 MonoGenericContext *context)
7892 if (image->dynamic) {
7893 MonoClass *tmp_handle_class;
7894 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
7896 g_assert (tmp_handle_class);
7898 *handle_class = tmp_handle_class;
7900 if (tmp_handle_class == mono_defaults.typehandle_class)
7901 return &((MonoClass*)obj)->byval_arg;
7906 switch (token & 0xff000000) {
7907 case MONO_TOKEN_TYPE_DEF:
7908 case MONO_TOKEN_TYPE_REF:
7909 case MONO_TOKEN_TYPE_SPEC: {
7912 *handle_class = mono_defaults.typehandle_class;
7913 type = mono_type_get_full (image, token, context);
7916 mono_class_init (mono_class_from_mono_type (type));
7917 /* We return a MonoType* as handle */
7920 case MONO_TOKEN_FIELD_DEF: {
7922 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
7926 *handle_class = mono_defaults.fieldhandle_class;
7927 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
7930 mono_class_init (class);
7931 return mono_class_get_field (class, token);
7933 case MONO_TOKEN_METHOD_DEF:
7934 case MONO_TOKEN_METHOD_SPEC: {
7936 meth = mono_get_method_full (image, token, NULL, context);
7938 *handle_class = mono_defaults.methodhandle_class;
7941 case MONO_TOKEN_MEMBER_REF: {
7942 guint32 cols [MONO_MEMBERREF_SIZE];
7944 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
7945 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
7946 mono_metadata_decode_blob_size (sig, &sig);
7947 if (*sig == 0x6) { /* it's a field */
7949 MonoClassField *field;
7950 field = mono_field_from_token (image, token, &klass, context);
7952 *handle_class = mono_defaults.fieldhandle_class;
7956 meth = mono_get_method_full (image, token, NULL, context);
7958 *handle_class = mono_defaults.methodhandle_class;
7963 g_warning ("Unknown token 0x%08x in ldtoken", token);
7970 * This function might need to call runtime functions so it can't be part
7971 * of the metadata library.
7973 static MonoLookupDynamicToken lookup_dynamic = NULL;
7976 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
7978 lookup_dynamic = func;
7982 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
7984 MonoClass *handle_class;
7986 return lookup_dynamic (image, token, TRUE, &handle_class, context);
7990 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
7992 return lookup_dynamic (image, token, valid_token, handle_class, context);
7995 static MonoGetCachedClassInfo get_cached_class_info = NULL;
7998 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
8000 get_cached_class_info = func;
8004 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
8006 if (!get_cached_class_info)
8009 return get_cached_class_info (klass, res);
8013 mono_install_get_class_from_name (MonoGetClassFromName func)
8015 get_class_from_name = func;
8019 mono_class_get_image (MonoClass *klass)
8021 return klass->image;
8025 * mono_class_get_element_class:
8026 * @klass: the MonoClass to act on
8028 * Returns: the element class of an array or an enumeration.
8031 mono_class_get_element_class (MonoClass *klass)
8033 return klass->element_class;
8037 * mono_class_is_valuetype:
8038 * @klass: the MonoClass to act on
8040 * Returns: true if the MonoClass represents a ValueType.
8043 mono_class_is_valuetype (MonoClass *klass)
8045 return klass->valuetype;
8049 * mono_class_is_enum:
8050 * @klass: the MonoClass to act on
8052 * Returns: true if the MonoClass represents an enumeration.
8055 mono_class_is_enum (MonoClass *klass)
8057 return klass->enumtype;
8061 * mono_class_enum_basetype:
8062 * @klass: the MonoClass to act on
8064 * Returns: the underlying type representation for an enumeration.
8067 mono_class_enum_basetype (MonoClass *klass)
8069 if (klass->element_class == klass)
8070 /* SRE or broken types */
8073 return &klass->element_class->byval_arg;
8077 * mono_class_get_parent
8078 * @klass: the MonoClass to act on
8080 * Returns: the parent class for this class.
8083 mono_class_get_parent (MonoClass *klass)
8085 return klass->parent;
8089 * mono_class_get_nesting_type;
8090 * @klass: the MonoClass to act on
8092 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
8095 mono_class_get_nesting_type (MonoClass *klass)
8097 return klass->nested_in;
8101 * mono_class_get_rank:
8102 * @klass: the MonoClass to act on
8104 * Returns: the rank for the array (the number of dimensions).
8107 mono_class_get_rank (MonoClass *klass)
8113 * mono_class_get_flags:
8114 * @klass: the MonoClass to act on
8116 * The type flags from the TypeDef table from the metadata.
8117 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
8120 * Returns: the flags from the TypeDef table.
8123 mono_class_get_flags (MonoClass *klass)
8125 return klass->flags;
8129 * mono_class_get_name
8130 * @klass: the MonoClass to act on
8132 * Returns: the name of the class.
8135 mono_class_get_name (MonoClass *klass)
8141 * mono_class_get_namespace:
8142 * @klass: the MonoClass to act on
8144 * Returns: the namespace of the class.
8147 mono_class_get_namespace (MonoClass *klass)
8149 return klass->name_space;
8153 * mono_class_get_type:
8154 * @klass: the MonoClass to act on
8156 * This method returns the internal Type representation for the class.
8158 * Returns: the MonoType from the class.
8161 mono_class_get_type (MonoClass *klass)
8163 return &klass->byval_arg;
8167 * mono_class_get_type_token
8168 * @klass: the MonoClass to act on
8170 * This method returns type token for the class.
8172 * Returns: the type token for the class.
8175 mono_class_get_type_token (MonoClass *klass)
8177 return klass->type_token;
8181 * mono_class_get_byref_type:
8182 * @klass: the MonoClass to act on
8187 mono_class_get_byref_type (MonoClass *klass)
8189 return &klass->this_arg;
8193 * mono_class_num_fields:
8194 * @klass: the MonoClass to act on
8196 * Returns: the number of static and instance fields in the class.
8199 mono_class_num_fields (MonoClass *klass)
8201 return klass->field.count;
8205 * mono_class_num_methods:
8206 * @klass: the MonoClass to act on
8208 * Returns: the number of methods in the class.
8211 mono_class_num_methods (MonoClass *klass)
8213 return klass->method.count;
8217 * mono_class_num_properties
8218 * @klass: the MonoClass to act on
8220 * Returns: the number of properties in the class.
8223 mono_class_num_properties (MonoClass *klass)
8225 mono_class_setup_properties (klass);
8227 return klass->ext->property.count;
8231 * mono_class_num_events:
8232 * @klass: the MonoClass to act on
8234 * Returns: the number of events in the class.
8237 mono_class_num_events (MonoClass *klass)
8239 mono_class_setup_events (klass);
8241 return klass->ext->event.count;
8245 * mono_class_get_fields:
8246 * @klass: the MonoClass to act on
8248 * This routine is an iterator routine for retrieving the fields in a class.
8250 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8251 * iterate over all of the elements. When no more values are
8252 * available, the return value is NULL.
8254 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
8257 mono_class_get_fields (MonoClass* klass, gpointer *iter)
8259 MonoClassField* field;
8263 mono_class_setup_fields_locking (klass);
8264 if (klass->exception_type)
8266 /* start from the first */
8267 if (klass->field.count) {
8268 return *iter = &klass->fields [0];
8276 if (field < &klass->fields [klass->field.count]) {
8277 return *iter = field;
8283 * mono_class_get_methods
8284 * @klass: the MonoClass to act on
8286 * This routine is an iterator routine for retrieving the fields in a class.
8288 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8289 * iterate over all of the elements. When no more values are
8290 * available, the return value is NULL.
8292 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
8295 mono_class_get_methods (MonoClass* klass, gpointer *iter)
8297 MonoMethod** method;
8301 mono_class_setup_methods (klass);
8304 * We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8305 * FIXME we should better report this error to the caller
8307 if (!klass->methods)
8309 /* start from the first */
8310 if (klass->method.count) {
8311 *iter = &klass->methods [0];
8312 return klass->methods [0];
8320 if (method < &klass->methods [klass->method.count]) {
8328 * mono_class_get_virtual_methods:
8330 * Iterate over the virtual methods of KLASS.
8332 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
8335 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
8337 MonoMethod** method;
8340 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
8342 mono_class_setup_methods (klass);
8344 * We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8345 * FIXME we should better report this error to the caller
8347 if (!klass->methods)
8349 /* start from the first */
8350 method = &klass->methods [0];
8355 while (method < &klass->methods [klass->method.count]) {
8356 if (*method && ((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
8360 if (method < &klass->methods [klass->method.count]) {
8367 /* Search directly in metadata to avoid calling setup_methods () */
8368 MonoMethod *res = NULL;
8374 start_index = GPOINTER_TO_UINT (*iter);
8377 for (i = start_index; i < klass->method.count; ++i) {
8380 /* class->method.first points into the methodptr table */
8381 flags = mono_metadata_decode_table_row_col (klass->image, MONO_TABLE_METHOD, klass->method.first + i, MONO_METHOD_FLAGS);
8383 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
8387 if (i < klass->method.count) {
8388 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
8389 /* Add 1 here so the if (*iter) check fails */
8390 *iter = GUINT_TO_POINTER (i + 1);
8399 * mono_class_get_properties:
8400 * @klass: the MonoClass to act on
8402 * This routine is an iterator routine for retrieving the properties in a class.
8404 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8405 * iterate over all of the elements. When no more values are
8406 * available, the return value is NULL.
8408 * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
8411 mono_class_get_properties (MonoClass* klass, gpointer *iter)
8413 MonoProperty* property;
8417 mono_class_setup_properties (klass);
8418 /* start from the first */
8419 if (klass->ext->property.count) {
8420 return *iter = &klass->ext->properties [0];
8428 if (property < &klass->ext->properties [klass->ext->property.count]) {
8429 return *iter = property;
8435 * mono_class_get_events:
8436 * @klass: the MonoClass to act on
8438 * This routine is an iterator routine for retrieving the properties in a class.
8440 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8441 * iterate over all of the elements. When no more values are
8442 * available, the return value is NULL.
8444 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
8447 mono_class_get_events (MonoClass* klass, gpointer *iter)
8453 mono_class_setup_events (klass);
8454 /* start from the first */
8455 if (klass->ext->event.count) {
8456 return *iter = &klass->ext->events [0];
8464 if (event < &klass->ext->events [klass->ext->event.count]) {
8465 return *iter = event;
8471 * mono_class_get_interfaces
8472 * @klass: the MonoClass to act on
8474 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
8476 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8477 * iterate over all of the elements. When no more values are
8478 * available, the return value is NULL.
8480 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
8483 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
8491 mono_class_init (klass);
8492 if (!klass->interfaces_inited) {
8493 mono_class_setup_interfaces (klass, &error);
8494 if (!mono_error_ok (&error)) {
8495 mono_error_cleanup (&error);
8499 /* start from the first */
8500 if (klass->interface_count) {
8501 *iter = &klass->interfaces [0];
8502 return klass->interfaces [0];
8510 if (iface < &klass->interfaces [klass->interface_count]) {
8518 * mono_class_get_nested_types
8519 * @klass: the MonoClass to act on
8521 * This routine is an iterator routine for retrieving the nested types of a class.
8522 * This works only if @klass is non-generic, or a generic type definition.
8524 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8525 * iterate over all of the elements. When no more values are
8526 * available, the return value is NULL.
8528 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
8531 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
8538 if (!klass->nested_classes_inited) {
8539 if (!klass->type_token)
8540 klass->nested_classes_inited = TRUE;
8541 mono_loader_lock ();
8542 if (!klass->nested_classes_inited) {
8543 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
8546 guint32 cols [MONO_NESTED_CLASS_SIZE];
8547 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
8548 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
8550 mono_loader_clear_error ();
8551 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
8554 mono_class_alloc_ext (klass);
8555 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
8557 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
8560 mono_memory_barrier ();
8561 klass->nested_classes_inited = TRUE;
8562 mono_loader_unlock ();
8566 /* start from the first */
8567 if (klass->ext && klass->ext->nested_classes) {
8568 *iter = klass->ext->nested_classes;
8569 return klass->ext->nested_classes->data;
8571 /* no nested types */
8585 * mono_field_get_name:
8586 * @field: the MonoClassField to act on
8588 * Returns: the name of the field.
8591 mono_field_get_name (MonoClassField *field)
8597 * mono_field_get_type:
8598 * @field: the MonoClassField to act on
8600 * Returns: MonoType of the field.
8603 mono_field_get_type (MonoClassField *field)
8606 MonoType *type = mono_field_get_type_checked (field, &error);
8607 if (!mono_error_ok (&error)) {
8608 mono_trace_warning (MONO_TRACE_TYPE, "Could not load field's type due to %s", mono_error_get_message (&error));
8609 mono_error_cleanup (&error);
8616 * mono_field_get_type_checked:
8617 * @field: the MonoClassField to act on
8618 * @error: used to return any erro found while retrieving @field type
8620 * Returns: MonoType of the field.
8623 mono_field_get_type_checked (MonoClassField *field, MonoError *error)
8625 mono_error_init (error);
8627 mono_field_resolve_type (field, error);
8632 * mono_field_get_parent:
8633 * @field: the MonoClassField to act on
8635 * Returns: MonoClass where the field was defined.
8638 mono_field_get_parent (MonoClassField *field)
8640 return field->parent;
8644 * mono_field_get_flags;
8645 * @field: the MonoClassField to act on
8647 * The metadata flags for a field are encoded using the
8648 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
8650 * Returns: the flags for the field.
8653 mono_field_get_flags (MonoClassField *field)
8656 return mono_field_resolve_flags (field);
8657 return field->type->attrs;
8661 * mono_field_get_offset;
8662 * @field: the MonoClassField to act on
8664 * Returns: the field offset.
8667 mono_field_get_offset (MonoClassField *field)
8669 return field->offset;
8673 mono_field_get_rva (MonoClassField *field)
8677 MonoClass *klass = field->parent;
8679 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
8681 if (!klass->ext || !klass->ext->field_def_values) {
8682 mono_loader_lock ();
8683 mono_class_alloc_ext (klass);
8684 if (!klass->ext->field_def_values)
8685 klass->ext->field_def_values = mono_class_alloc0 (klass, sizeof (MonoFieldDefaultValue) * klass->field.count);
8686 mono_loader_unlock ();
8689 field_index = mono_field_get_index (field);
8691 if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
8692 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
8694 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
8695 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
8698 return klass->ext->field_def_values [field_index].data;
8702 * mono_field_get_data;
8703 * @field: the MonoClassField to act on
8705 * Returns: pointer to the metadata constant value or to the field
8706 * data if it has an RVA flag.
8709 mono_field_get_data (MonoClassField *field)
8711 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
8712 MonoTypeEnum def_type;
8714 return mono_class_get_field_default_value (field, &def_type);
8715 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
8716 return mono_field_get_rva (field);
8723 * mono_property_get_name:
8724 * @prop: the MonoProperty to act on
8726 * Returns: the name of the property
8729 mono_property_get_name (MonoProperty *prop)
8735 * mono_property_get_set_method
8736 * @prop: the MonoProperty to act on.
8738 * Returns: the setter method of the property (A MonoMethod)
8741 mono_property_get_set_method (MonoProperty *prop)
8747 * mono_property_get_get_method
8748 * @prop: the MonoProperty to act on.
8750 * Returns: the setter method of the property (A MonoMethod)
8753 mono_property_get_get_method (MonoProperty *prop)
8759 * mono_property_get_parent:
8760 * @prop: the MonoProperty to act on.
8762 * Returns: the MonoClass where the property was defined.
8765 mono_property_get_parent (MonoProperty *prop)
8767 return prop->parent;
8771 * mono_property_get_flags:
8772 * @prop: the MonoProperty to act on.
8774 * The metadata flags for a property are encoded using the
8775 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
8777 * Returns: the flags for the property.
8780 mono_property_get_flags (MonoProperty *prop)
8786 * mono_event_get_name:
8787 * @event: the MonoEvent to act on
8789 * Returns: the name of the event.
8792 mono_event_get_name (MonoEvent *event)
8798 * mono_event_get_add_method:
8799 * @event: The MonoEvent to act on.
8801 * Returns: the @add' method for the event (a MonoMethod).
8804 mono_event_get_add_method (MonoEvent *event)
8810 * mono_event_get_remove_method:
8811 * @event: The MonoEvent to act on.
8813 * Returns: the @remove method for the event (a MonoMethod).
8816 mono_event_get_remove_method (MonoEvent *event)
8818 return event->remove;
8822 * mono_event_get_raise_method:
8823 * @event: The MonoEvent to act on.
8825 * Returns: the @raise method for the event (a MonoMethod).
8828 mono_event_get_raise_method (MonoEvent *event)
8830 return event->raise;
8834 * mono_event_get_parent:
8835 * @event: the MonoEvent to act on.
8837 * Returns: the MonoClass where the event is defined.
8840 mono_event_get_parent (MonoEvent *event)
8842 return event->parent;
8846 * mono_event_get_flags
8847 * @event: the MonoEvent to act on.
8849 * The metadata flags for an event are encoded using the
8850 * EVENT_* constants. See the tabledefs.h file for details.
8852 * Returns: the flags for the event.
8855 mono_event_get_flags (MonoEvent *event)
8857 return event->attrs;
8861 * mono_class_get_method_from_name:
8862 * @klass: where to look for the method
8863 * @name_space: name of the method
8864 * @param_count: number of parameters. -1 for any number.
8866 * Obtains a MonoMethod with a given name and number of parameters.
8867 * It only works if there are no multiple signatures for any given method name.
8870 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
8872 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
8876 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
8878 MonoMethod *res = NULL;
8881 /* Search directly in the metadata to avoid calling setup_methods () */
8882 for (i = 0; i < klass->method.count; ++i) {
8883 guint32 cols [MONO_METHOD_SIZE];
8885 MonoMethodSignature *sig;
8887 /* class->method.first points into the methodptr table */
8888 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
8890 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
8891 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
8892 if (param_count == -1) {
8896 sig = mono_method_signature (method);
8897 if (sig && sig->param_count == param_count) {
8908 * mono_class_get_method_from_name_flags:
8909 * @klass: where to look for the method
8910 * @name_space: name of the method
8911 * @param_count: number of parameters. -1 for any number.
8912 * @flags: flags which must be set in the method
8914 * Obtains a MonoMethod with a given name and number of parameters.
8915 * It only works if there are no multiple signatures for any given method name.
8918 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
8920 MonoMethod *res = NULL;
8923 mono_class_init (klass);
8925 if (klass->generic_class && !klass->methods) {
8926 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
8928 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
8932 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
8933 mono_class_setup_methods (klass);
8935 We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8936 See mono/tests/array_load_exception.il
8937 FIXME we should better report this error to the caller
8939 if (!klass->methods)
8941 for (i = 0; i < klass->method.count; ++i) {
8942 MonoMethod *method = klass->methods [i];
8944 if (method->name[0] == name [0] &&
8945 !strcmp (name, method->name) &&
8946 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
8947 ((method->flags & flags) == flags)) {
8954 res = find_method_in_metadata (klass, name, param_count, flags);
8961 * mono_class_set_failure:
8962 * @klass: class in which the failure was detected
8963 * @ex_type: the kind of exception/error to be thrown (later)
8964 * @ex_data: exception data (specific to each type of exception/error)
8966 * Keep a detected failure informations in the class for later processing.
8967 * Note that only the first failure is kept.
8969 * LOCKING: Acquires the loader lock.
8972 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
8974 if (klass->exception_type)
8977 mono_loader_lock ();
8978 klass->exception_type = ex_type;
8980 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
8981 mono_loader_unlock ();
8987 * mono_class_get_exception_data:
8989 * Return the exception_data property of KLASS.
8991 * LOCKING: Acquires the loader lock.
8994 mono_class_get_exception_data (MonoClass *klass)
8996 return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
9000 * mono_classes_init:
9002 * Initialize the resources used by this module.
9005 mono_classes_init (void)
9007 mono_counters_register ("Inflated methods size",
9008 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
9009 mono_counters_register ("Inflated classes",
9010 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
9011 mono_counters_register ("Inflated classes size",
9012 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
9013 mono_counters_register ("MonoClass size",
9014 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
9015 mono_counters_register ("MonoClassExt size",
9016 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
9020 * mono_classes_cleanup:
9022 * Free the resources used by this module.
9025 mono_classes_cleanup (void)
9027 if (global_interface_bitset)
9028 mono_bitset_free (global_interface_bitset);
9032 * mono_class_get_exception_for_failure:
9033 * @klass: class in which the failure was detected
9035 * Return a constructed MonoException than the caller can then throw
9036 * using mono_raise_exception - or NULL if no failure is present (or
9037 * doesn't result in an exception).
9040 mono_class_get_exception_for_failure (MonoClass *klass)
9042 gpointer exception_data = mono_class_get_exception_data (klass);
9044 switch (klass->exception_type) {
9045 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
9046 MonoDomain *domain = mono_domain_get ();
9047 MonoSecurityManager* secman = mono_security_manager_get_methods ();
9048 MonoMethod *method = exception_data;
9049 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
9050 MonoObject *exc = NULL;
9054 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
9055 args [2] = mono_type_get_object (domain, &klass->byval_arg);
9056 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
9058 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
9059 return (MonoException*) exc;
9061 case MONO_EXCEPTION_TYPE_LOAD: {
9064 char *str = mono_type_get_full_name (klass);
9065 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
9066 name = mono_string_new (mono_domain_get (), str);
9068 ex = mono_get_exception_type_load (name, astr);
9072 case MONO_EXCEPTION_MISSING_METHOD: {
9073 char *class_name = exception_data;
9074 char *assembly_name = class_name + strlen (class_name) + 1;
9076 return mono_get_exception_missing_method (class_name, assembly_name);
9078 case MONO_EXCEPTION_MISSING_FIELD: {
9079 char *class_name = exception_data;
9080 char *member_name = class_name + strlen (class_name) + 1;
9082 return mono_get_exception_missing_field (class_name, member_name);
9084 case MONO_EXCEPTION_FILE_NOT_FOUND: {
9085 char *msg_format = exception_data;
9086 char *assembly_name = msg_format + strlen (msg_format) + 1;
9087 char *msg = g_strdup_printf (msg_format, assembly_name);
9090 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
9096 case MONO_EXCEPTION_BAD_IMAGE: {
9097 return mono_get_exception_bad_image_format (exception_data);
9100 MonoLoaderError *error;
9103 error = mono_loader_get_last_error ();
9105 ex = mono_loader_error_prepare_exception (error);
9109 /* TODO - handle other class related failures */
9116 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
9118 outer_klass = mono_class_get_generic_type_definition (outer_klass);
9119 inner_klass = mono_class_get_generic_type_definition (inner_klass);
9121 if (outer_klass == inner_klass)
9123 inner_klass = inner_klass->nested_in;
9124 } while (inner_klass);
9129 mono_class_get_generic_type_definition (MonoClass *klass)
9131 return klass->generic_class ? klass->generic_class->container_class : klass;
9135 * Check if @klass is a subtype of @parent ignoring generic instantiations.
9137 * Generic instantiations are ignored for all super types of @klass.
9139 * Visibility checks ignoring generic instantiations.
9142 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
9145 klass = mono_class_get_generic_type_definition (klass);
9146 parent = mono_class_get_generic_type_definition (parent);
9148 for (i = 0; i < klass->idepth; ++i) {
9149 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
9155 * Subtype can only access parent members with family protection if the site object
9156 * is subclass of Subtype. For example:
9157 * class A { protected int x; }
9159 * void valid_access () {
9163 * void invalid_access () {
9170 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
9172 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
9175 if (context_klass == NULL)
9177 /*if access_klass is not member_klass context_klass must be type compat*/
9178 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
9184 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
9187 if (accessing == accessed)
9189 if (!accessed || !accessing)
9192 /* extra safety under CoreCLR - the runtime does not verify the strongname signatures
9193 * anywhere so untrusted friends are not safe to access platform's code internals */
9194 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
9195 if (!mono_security_core_clr_can_access_internals (accessing->image, accessed->image))
9199 mono_assembly_load_friends (accessed);
9200 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
9201 MonoAssemblyName *friend = tmp->data;
9202 /* Be conservative with checks */
9205 if (strcmp (accessing->aname.name, friend->name))
9207 if (friend->public_key_token [0]) {
9208 if (!accessing->aname.public_key_token [0])
9210 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
9219 * If klass is a generic type or if it is derived from a generic type, return the
9220 * MonoClass of the generic definition
9221 * Returns NULL if not found
9224 get_generic_definition_class (MonoClass *klass)
9227 if (klass->generic_class && klass->generic_class->container_class)
9228 return klass->generic_class->container_class;
9229 klass = klass->parent;
9235 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
9238 for (i = 0; i < ginst->type_argc; ++i) {
9239 MonoType *type = ginst->type_argv[i];
9240 switch (type->type) {
9241 case MONO_TYPE_SZARRAY:
9242 if (!can_access_type (access_klass, type->data.klass))
9245 case MONO_TYPE_ARRAY:
9246 if (!can_access_type (access_klass, type->data.array->eklass))
9250 if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
9253 case MONO_TYPE_CLASS:
9254 case MONO_TYPE_VALUETYPE:
9255 case MONO_TYPE_GENERICINST:
9256 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
9264 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
9268 if (access_klass->image->assembly && access_klass->image->assembly->corlib_internal)
9271 if (access_klass->element_class && !access_klass->enumtype)
9272 access_klass = access_klass->element_class;
9274 if (member_klass->element_class && !member_klass->enumtype)
9275 member_klass = member_klass->element_class;
9277 access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
9279 if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
9282 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
9285 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
9288 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
9291 /*Non nested type with nested visibility. We just fail it.*/
9292 if (access_level >= TYPE_ATTRIBUTE_NESTED_PRIVATE && access_level <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM && member_klass->nested_in == NULL)
9295 switch (access_level) {
9296 case TYPE_ATTRIBUTE_NOT_PUBLIC:
9297 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9299 case TYPE_ATTRIBUTE_PUBLIC:
9302 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
9305 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
9306 return is_nesting_type (member_klass, access_klass);
9308 case TYPE_ATTRIBUTE_NESTED_FAMILY:
9309 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
9311 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
9312 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9314 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
9315 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
9316 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
9318 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
9319 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
9320 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
9325 /* FIXME: check visibility of type, too */
9327 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
9329 MonoClass *member_generic_def;
9330 if (access_klass->image->assembly && access_klass->image->assembly->corlib_internal)
9333 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
9334 access_klass->generic_container) &&
9335 (member_generic_def = get_generic_definition_class (member_klass))) {
9336 MonoClass *access_container;
9338 if (access_klass->generic_container)
9339 access_container = access_klass;
9341 access_container = access_klass->generic_class->container_class;
9343 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
9347 /* Partition I 8.5.3.2 */
9348 /* the access level values are the same for fields and methods */
9349 switch (access_level) {
9350 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
9351 /* same compilation unit */
9352 return access_klass->image == member_klass->image;
9353 case FIELD_ATTRIBUTE_PRIVATE:
9354 return access_klass == member_klass;
9355 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
9356 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
9357 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
9360 case FIELD_ATTRIBUTE_ASSEMBLY:
9361 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9362 case FIELD_ATTRIBUTE_FAMILY:
9363 if (is_valid_family_access (access_klass, member_klass, context_klass))
9366 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
9367 if (is_valid_family_access (access_klass, member_klass, context_klass))
9369 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9370 case FIELD_ATTRIBUTE_PUBLIC:
9377 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
9379 /* FIXME: check all overlapping fields */
9380 int can = can_access_member (method->klass, field->parent, NULL, mono_field_get_type (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9382 MonoClass *nested = method->klass->nested_in;
9384 can = can_access_member (nested, field->parent, NULL, mono_field_get_type (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9387 nested = nested->nested_in;
9394 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
9396 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9398 MonoClass *nested = method->klass->nested_in;
9400 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9403 nested = nested->nested_in;
9408 * with generics calls to explicit interface implementations can be expressed
9409 * directly: the method is private, but we must allow it. This may be opening
9410 * a hole or the generics code should handle this differently.
9411 * Maybe just ensure the interface type is public.
9413 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
9419 * mono_method_can_access_method_full:
9420 * @method: The caller method
9421 * @called: The called method
9422 * @context_klass: The static type on stack of the owner @called object used
9424 * This function must be used with instance calls, as they have more strict family accessibility.
9425 * It can be used with static methods, but context_klass should be NULL.
9427 * Returns: TRUE if caller have proper visibility and acessibility to @called
9430 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
9432 MonoClass *access_class = method->klass;
9433 MonoClass *member_class = called->klass;
9434 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9436 MonoClass *nested = access_class->nested_in;
9438 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9441 nested = nested->nested_in;
9448 can = can_access_type (access_class, member_class);
9450 MonoClass *nested = access_class->nested_in;
9452 can = can_access_type (nested, member_class);
9455 nested = nested->nested_in;
9462 if (called->is_inflated) {
9463 MonoMethodInflated * infl = (MonoMethodInflated*)called;
9464 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
9473 * mono_method_can_access_field_full:
9474 * @method: The caller method
9475 * @field: The accessed field
9476 * @context_klass: The static type on stack of the owner @field object used
9478 * This function must be used with instance fields, as they have more strict family accessibility.
9479 * It can be used with static fields, but context_klass should be NULL.
9481 * Returns: TRUE if caller have proper visibility and acessibility to @field
9484 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
9486 MonoClass *access_class = method->klass;
9487 MonoClass *member_class = field->parent;
9488 /* FIXME: check all overlapping fields */
9489 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9491 MonoClass *nested = access_class->nested_in;
9493 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9496 nested = nested->nested_in;
9503 can = can_access_type (access_class, member_class);
9505 MonoClass *nested = access_class->nested_in;
9507 can = can_access_type (nested, member_class);
9510 nested = nested->nested_in;
9520 * mono_type_is_valid_enum_basetype:
9521 * @type: The MonoType to check
9523 * Returns: TRUE if the type can be used as the basetype of an enum
9525 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
9526 switch (type->type) {
9529 case MONO_TYPE_BOOLEAN:
9532 case MONO_TYPE_CHAR:
9545 * mono_class_is_valid_enum:
9546 * @klass: An enum class to be validated
9548 * This method verify the required properties an enum should have.
9550 * Returns: TRUE if the informed enum class is valid
9552 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
9553 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
9554 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
9556 gboolean mono_class_is_valid_enum (MonoClass *klass) {
9557 MonoClassField * field;
9558 gpointer iter = NULL;
9559 gboolean found_base_field = FALSE;
9561 g_assert (klass->enumtype);
9562 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
9563 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
9567 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
9570 while ((field = mono_class_get_fields (klass, &iter))) {
9571 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
9572 if (found_base_field)
9574 found_base_field = TRUE;
9575 if (!mono_type_is_valid_enum_basetype (field->type))
9580 if (!found_base_field)
9583 if (klass->method.count > 0)
9590 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
9592 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
9596 * mono_class_setup_interface_id:
9598 * Initializes MonoClass::interface_id if required.
9600 * LOCKING: Acquires the loader lock.
9603 mono_class_setup_interface_id (MonoClass *class)
9605 mono_loader_lock ();
9606 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
9607 class->interface_id = mono_get_unique_iid (class);
9608 mono_loader_unlock ();
9612 * mono_class_alloc_ext:
9614 * Allocate klass->ext if not already done.
9615 * LOCKING: Assumes the loader lock is held.
9618 mono_class_alloc_ext (MonoClass *klass)
9621 klass->ext = mono_class_alloc0 (klass, sizeof (MonoClassExt));
9622 class_ext_size += sizeof (MonoClassExt);
9627 * mono_class_setup_interfaces:
9629 * Initialize class->interfaces/interfaces_count.
9630 * LOCKING: Acquires the loader lock.
9631 * This function can fail the type.
9634 mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
9638 mono_error_init (error);
9640 if (klass->interfaces_inited)
9643 mono_loader_lock ();
9645 if (klass->interfaces_inited) {
9646 mono_loader_unlock ();
9650 if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
9653 /* generic IList, ICollection, IEnumerable */
9654 klass->interface_count = 1;
9655 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
9657 args [0] = &klass->element_class->byval_arg;
9658 klass->interfaces [0] = mono_class_bind_generic_parameters (
9659 mono_defaults.generic_ilist_class, 1, args, FALSE);
9660 } else if (klass->generic_class) {
9661 MonoClass *gklass = klass->generic_class->container_class;
9663 klass->interface_count = gklass->interface_count;
9664 klass->interfaces = mono_class_new0 (klass, MonoClass *, klass->interface_count);
9665 for (i = 0; i < klass->interface_count; i++) {
9666 klass->interfaces [i] = mono_class_inflate_generic_class_checked (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class), error);
9667 if (!mono_error_ok (error)) {
9668 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not setup the interfaces"));
9669 klass->interfaces = NULL;
9675 mono_memory_barrier ();
9677 klass->interfaces_inited = TRUE;
9679 mono_loader_unlock ();
9683 mono_field_resolve_type (MonoClassField *field, MonoError *error)
9685 MonoClass *class = field->parent;
9686 MonoImage *image = class->image;
9687 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
9688 int field_idx = field - class->fields;
9690 mono_error_init (error);
9693 MonoClassField *gfield = >d->fields [field_idx];
9694 MonoType *gtype = mono_field_get_type_checked (gfield, error);
9695 if (!mono_error_ok (error)) {
9696 char *err_msg = g_strdup_printf ("Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
9697 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
9701 field->type = mono_class_inflate_generic_type_no_copy (image, gtype, mono_class_get_context (class), error);
9702 if (!mono_error_ok (error)) {
9703 char *err_msg = g_strdup_printf ("Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
9704 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
9709 guint32 cols [MONO_FIELD_SIZE];
9710 MonoGenericContainer *container = NULL;
9711 int idx = class->field.first + field_idx;
9713 /*FIXME, in theory we do not lazy load SRE fields*/
9714 g_assert (!image->dynamic);
9716 if (class->generic_container) {
9717 container = class->generic_container;
9719 container = gtd->generic_container;
9720 g_assert (container);
9723 /* class->field.first and idx points into the fieldptr table */
9724 mono_metadata_decode_table_row (image, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
9726 if (!mono_verifier_verify_field_signature (image, cols [MONO_FIELD_SIGNATURE], NULL)) {
9727 mono_error_set_type_load_class (error, class, "Could not verify field %s signature", field->name);
9728 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
9732 sig = mono_metadata_blob_heap (image, cols [MONO_FIELD_SIGNATURE]);
9734 mono_metadata_decode_value (sig, &sig);
9735 /* FIELD signature == 0x06 */
9736 g_assert (*sig == 0x06);
9737 field->type = mono_metadata_parse_type_full (image, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
9739 mono_error_set_type_load_class (error, class, "Could not load field %s type", field->name);
9740 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
9741 mono_loader_clear_error ();
9747 mono_field_resolve_flags (MonoClassField *field)
9749 MonoClass *class = field->parent;
9750 MonoImage *image = class->image;
9751 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
9752 int field_idx = field - class->fields;
9756 MonoClassField *gfield = >d->fields [field_idx];
9757 return mono_field_get_flags (gfield);
9759 int idx = class->field.first + field_idx;
9761 /*FIXME, in theory we do not lazy load SRE fields*/
9762 g_assert (!image->dynamic);
9764 return mono_metadata_decode_table_row_col (image, MONO_TABLE_FIELD, idx, MONO_FIELD_FLAGS);
9769 * mono_class_setup_basic_field_info:
9770 * @class: The class to initialize
9772 * Initializes the class->fields array of fields.
9773 * Aquires the loader lock.
9776 mono_class_setup_basic_field_info_locking (MonoClass *class)
9778 mono_loader_lock ();
9779 mono_class_setup_basic_field_info (class);
9780 mono_loader_unlock ();
9784 * mono_class_get_fields_lazy:
9785 * @klass: the MonoClass to act on
9787 * This routine is an iterator routine for retrieving the fields in a class.
9788 * Only minimal information about fields are loaded. Accessors must be used
9789 * for all MonoClassField returned.
9791 * You must pass a gpointer that points to zero and is treated as an opaque handle to
9792 * iterate over all of the elements. When no more values are
9793 * available, the return value is NULL.
9795 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
9798 mono_class_get_fields_lazy (MonoClass* klass, gpointer *iter)
9800 MonoClassField* field;
9804 mono_class_setup_basic_field_info_locking (klass);
9807 /* start from the first */
9808 if (klass->field.count) {
9809 return *iter = &klass->fields [0];
9817 if (field < &klass->fields [klass->field.count]) {
9818 return *iter = field;