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>
47 gboolean mono_print_vtable = FALSE;
50 * Controls whenever mono_class_init () constructs a generic vtable. This is TRUE by
51 * default to avoid breaking embedding apps, but set to FALSE by the runtime executable
54 gboolean mono_setup_vtable_in_class_init = TRUE;
57 guint32 inflated_classes, inflated_classes_size, inflated_methods_size;
58 guint32 classes_size, class_ext_size;
60 /* Function supplied by the runtime to find classes by name using information from the AOT file */
61 static MonoGetClassFromName get_class_from_name = NULL;
63 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
64 static gboolean mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res);
65 static gboolean can_access_type (MonoClass *access_klass, MonoClass *member_klass);
66 static MonoMethod* find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags);
67 static int generic_array_methods (MonoClass *class);
68 static void setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos);
70 static MonoMethod* mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter);
71 static char* mono_assembly_name_from_token (MonoImage *image, guint32 type_token);
74 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
75 void (*mono_debugger_class_loaded_methods_func) (MonoClass *klass) = NULL;
78 * mono_class_from_typeref:
80 * @type_token: a TypeRef token
82 * Creates the MonoClass* structure representing the type defined by
83 * the typeref token valid inside @image.
84 * Returns: the MonoClass* representing the typeref token, NULL ifcould
88 mono_class_from_typeref (MonoImage *image, guint32 type_token)
90 guint32 cols [MONO_TYPEREF_SIZE];
91 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
93 const char *name, *nspace;
97 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
99 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
100 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
102 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
103 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
104 case MONO_RESOLTION_SCOPE_MODULE:
106 g_error ("null ResolutionScope not yet handled");
107 /* a typedef in disguise */
108 return mono_class_from_name (image, nspace, name);
109 case MONO_RESOLTION_SCOPE_MODULEREF:
110 module = mono_image_load_module (image, idx);
112 return mono_class_from_name (module, nspace, name);
114 char *msg = g_strdup_printf ("%s%s%s", nspace, nspace [0] ? "." : "", name);
117 human_name = mono_stringify_assembly_name (&image->assembly->aname);
118 mono_loader_set_error_type_load (msg, human_name);
124 case MONO_RESOLTION_SCOPE_TYPEREF: {
125 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
131 if (enclosing->nested_classes_inited && enclosing->ext) {
132 /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
133 for (tmp = enclosing->ext->nested_classes; tmp; tmp = tmp->next) {
135 if (strcmp (res->name, name) == 0)
139 /* Don't call mono_class_init as we might've been called by it recursively */
140 int i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, 1);
142 guint32 class_nested = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, MONO_NESTED_CLASS_NESTED);
143 guint32 string_offset = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_TYPEDEF], class_nested - 1, MONO_TYPEDEF_NAME);
144 const char *nname = mono_metadata_string_heap (enclosing->image, string_offset);
146 if (strcmp (nname, name) == 0)
147 return mono_class_create_from_typedef (enclosing->image, MONO_TOKEN_TYPE_DEF | class_nested);
149 i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, i + 1);
152 g_warning ("TypeRef ResolutionScope not yet handled (%d) for %s.%s in image %s", idx, nspace, name, image->name);
155 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
159 if (!image->references || !image->references [idx - 1])
160 mono_assembly_load_reference (image, idx - 1);
161 g_assert (image->references [idx - 1]);
163 /* If the assembly did not load, register this as a type load exception */
164 if (image->references [idx - 1] == REFERENCE_MISSING){
165 MonoAssemblyName aname;
168 mono_assembly_get_assemblyref (image, idx - 1, &aname);
169 human_name = mono_stringify_assembly_name (&aname);
170 mono_loader_set_error_assembly_load (human_name, image->assembly->ref_only);
176 return mono_class_from_name (image->references [idx - 1]->image, nspace, name);
181 mono_image_memdup (MonoImage *image, void *data, guint size)
183 void *res = mono_image_alloc (image, size);
184 memcpy (res, data, size);
188 /* Copy everything mono_metadata_free_array free. */
190 mono_dup_array_type (MonoImage *image, MonoArrayType *a)
193 a = mono_image_memdup (image, a, sizeof (MonoArrayType));
195 a->sizes = mono_image_memdup (image, a->sizes, a->numsizes * sizeof (int));
197 a->lobounds = mono_image_memdup (image, a->lobounds, a->numlobounds * sizeof (int));
199 a = g_memdup (a, sizeof (MonoArrayType));
201 a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
203 a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
208 /* Copy everything mono_metadata_free_method_signature free. */
210 mono_metadata_signature_deep_dup (MonoImage *image, MonoMethodSignature *sig)
214 sig = mono_metadata_signature_dup_full (image, sig);
216 sig->ret = mono_metadata_type_dup (image, sig->ret);
217 for (i = 0; i < sig->param_count; ++i)
218 sig->params [i] = mono_metadata_type_dup (image, sig->params [i]);
224 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
226 MonoAssembly *ta = klass->image->assembly;
228 g_string_append_printf (
229 str, ", %s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
231 ta->aname.major, ta->aname.minor, ta->aname.build, ta->aname.revision,
232 ta->aname.culture && *ta->aname.culture? ta->aname.culture: "neutral",
233 ta->aname.public_key_token [0] ? (char *)ta->aname.public_key_token : "null",
234 (ta->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
238 mono_type_name_check_byref (MonoType *type, GString *str)
241 g_string_append_c (str, '&');
245 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
246 MonoTypeNameFormat format)
250 switch (type->type) {
251 case MONO_TYPE_ARRAY: {
252 int i, rank = type->data.array->rank;
253 MonoTypeNameFormat nested_format;
255 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
256 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
258 mono_type_get_name_recurse (
259 &type->data.array->eklass->byval_arg, str, FALSE, nested_format);
260 g_string_append_c (str, '[');
262 g_string_append_c (str, '*');
263 for (i = 1; i < rank; i++)
264 g_string_append_c (str, ',');
265 g_string_append_c (str, ']');
267 mono_type_name_check_byref (type, str);
269 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
270 _mono_type_get_assembly_name (type->data.array->eklass, str);
273 case MONO_TYPE_SZARRAY: {
274 MonoTypeNameFormat nested_format;
276 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
277 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
279 mono_type_get_name_recurse (
280 &type->data.klass->byval_arg, str, FALSE, nested_format);
281 g_string_append (str, "[]");
283 mono_type_name_check_byref (type, str);
285 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
286 _mono_type_get_assembly_name (type->data.klass, str);
289 case MONO_TYPE_PTR: {
290 MonoTypeNameFormat nested_format;
292 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
293 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
295 mono_type_get_name_recurse (
296 type->data.type, str, FALSE, nested_format);
297 g_string_append_c (str, '*');
299 mono_type_name_check_byref (type, str);
301 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
302 _mono_type_get_assembly_name (mono_class_from_mono_type (type->data.type), str);
307 if (!mono_generic_param_info (type->data.generic_param))
308 g_string_append_printf (str, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", type->data.generic_param->num);
310 g_string_append (str, mono_generic_param_info (type->data.generic_param)->name);
312 mono_type_name_check_byref (type, str);
316 klass = mono_class_from_mono_type (type);
317 if (klass->nested_in) {
318 mono_type_get_name_recurse (
319 &klass->nested_in->byval_arg, str, TRUE, format);
320 if (format == MONO_TYPE_NAME_FORMAT_IL)
321 g_string_append_c (str, '.');
323 g_string_append_c (str, '+');
324 } else if (*klass->name_space) {
325 g_string_append (str, klass->name_space);
326 g_string_append_c (str, '.');
328 if (format == MONO_TYPE_NAME_FORMAT_IL) {
329 char *s = strchr (klass->name, '`');
330 int len = s ? s - klass->name : strlen (klass->name);
332 g_string_append_len (str, klass->name, len);
334 g_string_append (str, klass->name);
337 if (klass->generic_class) {
338 MonoGenericClass *gclass = klass->generic_class;
339 MonoGenericInst *inst = gclass->context.class_inst;
340 MonoTypeNameFormat nested_format;
343 nested_format = format == MONO_TYPE_NAME_FORMAT_FULL_NAME ?
344 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED : format;
346 if (format == MONO_TYPE_NAME_FORMAT_IL)
347 g_string_append_c (str, '<');
349 g_string_append_c (str, '[');
350 for (i = 0; i < inst->type_argc; i++) {
351 MonoType *t = inst->type_argv [i];
354 g_string_append_c (str, ',');
355 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
356 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
357 g_string_append_c (str, '[');
358 mono_type_get_name_recurse (inst->type_argv [i], str, FALSE, nested_format);
359 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
360 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
361 g_string_append_c (str, ']');
363 if (format == MONO_TYPE_NAME_FORMAT_IL)
364 g_string_append_c (str, '>');
366 g_string_append_c (str, ']');
367 } else if (klass->generic_container &&
368 (format != MONO_TYPE_NAME_FORMAT_FULL_NAME) &&
369 (format != MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)) {
372 if (format == MONO_TYPE_NAME_FORMAT_IL)
373 g_string_append_c (str, '<');
375 g_string_append_c (str, '[');
376 for (i = 0; i < klass->generic_container->type_argc; i++) {
378 g_string_append_c (str, ',');
379 g_string_append (str, mono_generic_container_get_param_info (klass->generic_container, i)->name);
381 if (format == MONO_TYPE_NAME_FORMAT_IL)
382 g_string_append_c (str, '>');
384 g_string_append_c (str, ']');
387 mono_type_name_check_byref (type, str);
389 if ((format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
390 (type->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
391 _mono_type_get_assembly_name (klass, str);
397 * mono_type_get_name_full:
399 * @format: the format for the return string.
402 * Returns: the string representation in a number of formats:
404 * if format is MONO_TYPE_NAME_FORMAT_REFLECTION, the return string is
405 * returned in the formatrequired by System.Reflection, this is the
406 * inverse of mono_reflection_parse_type ().
408 * if format is MONO_TYPE_NAME_FORMAT_IL, it returns a syntax that can
409 * be used by the IL assembler.
411 * if format is MONO_TYPE_NAME_FORMAT_FULL_NAME
413 * if format is MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED
416 mono_type_get_name_full (MonoType *type, MonoTypeNameFormat format)
420 result = g_string_new ("");
422 mono_type_get_name_recurse (type, result, FALSE, format);
424 return g_string_free (result, FALSE);
428 * mono_type_get_full_name:
431 * Returns: the string representation for type as required by System.Reflection.
432 * The inverse of mono_reflection_parse_type ().
435 mono_type_get_full_name (MonoClass *class)
437 return mono_type_get_name_full (mono_class_get_type (class), MONO_TYPE_NAME_FORMAT_REFLECTION);
441 * mono_type_get_name:
444 * Returns: the string representation for type as it would be represented in IL code.
447 mono_type_get_name (MonoType *type)
449 return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_IL);
453 * mono_type_get_underlying_type:
456 * Returns: the MonoType for the underlying integer type if @type
457 * is an enum and byref is false, otherwise the type itself.
460 mono_type_get_underlying_type (MonoType *type)
462 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype && !type->byref)
463 return mono_class_enum_basetype (type->data.klass);
464 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype && !type->byref)
465 return mono_class_enum_basetype (type->data.generic_class->container_class);
470 * mono_class_is_open_constructed_type:
473 * Returns TRUE if type represents a generics open constructed type
474 * (not all the type parameters required for the instantiation have
478 mono_class_is_open_constructed_type (MonoType *t)
484 case MONO_TYPE_SZARRAY:
485 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
486 case MONO_TYPE_ARRAY:
487 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
489 return mono_class_is_open_constructed_type (t->data.type);
490 case MONO_TYPE_GENERICINST:
491 return t->data.generic_class->context.class_inst->is_open;
498 inflate_generic_type (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
500 mono_error_init (error);
502 switch (type->type) {
503 case MONO_TYPE_MVAR: {
505 int num = mono_type_get_generic_param_num (type);
506 MonoGenericInst *inst = context->method_inst;
507 if (!inst || !inst->type_argv)
509 if (num >= inst->type_argc) {
510 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
511 mono_error_set_bad_image (error, image, "MVAR %d (%s) cannot be expanded in this context with %d instantiations",
512 num, info ? info->name : "", inst->type_argc);
517 * Note that the VAR/MVAR cases are different from the rest. The other cases duplicate @type,
518 * while the VAR/MVAR duplicates a type from the context. So, we need to ensure that the
519 * ->byref and ->attrs from @type are propagated to the returned type.
521 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
522 nt->byref = type->byref;
523 nt->attrs = type->attrs;
526 case MONO_TYPE_VAR: {
528 int num = mono_type_get_generic_param_num (type);
529 MonoGenericInst *inst = context->class_inst;
532 if (num >= inst->type_argc) {
533 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
534 mono_error_set_bad_image (error, image, "VAR %d (%s) cannot be expanded in this context with %d instantiations",
535 num, info ? info->name : "", inst->type_argc);
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_SZARRAY: {
544 MonoClass *eclass = type->data.klass;
545 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
546 if (!inflated || !mono_error_ok (error))
548 nt = mono_metadata_type_dup (image, type);
549 nt->data.klass = mono_class_from_mono_type (inflated);
550 mono_metadata_free_type (inflated);
553 case MONO_TYPE_ARRAY: {
554 MonoClass *eclass = type->data.array->eklass;
555 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
556 if (!inflated || !mono_error_ok (error))
558 nt = mono_metadata_type_dup (image, type);
559 nt->data.array = g_memdup (nt->data.array, sizeof (MonoArrayType));
560 nt->data.array->eklass = mono_class_from_mono_type (inflated);
561 mono_metadata_free_type (inflated);
564 case MONO_TYPE_GENERICINST: {
565 MonoGenericClass *gclass = type->data.generic_class;
566 MonoGenericInst *inst;
568 if (!gclass->context.class_inst->is_open)
571 inst = mono_metadata_inflate_generic_inst (gclass->context.class_inst, context, error);
572 if (!mono_error_ok (error))
574 if (inst != gclass->context.class_inst)
575 gclass = mono_metadata_lookup_generic_class (gclass->container_class, inst, gclass->is_dynamic);
577 if (gclass == type->data.generic_class)
580 nt = mono_metadata_type_dup (image, type);
581 nt->data.generic_class = gclass;
584 case MONO_TYPE_CLASS:
585 case MONO_TYPE_VALUETYPE: {
586 MonoClass *klass = type->data.klass;
587 MonoGenericContainer *container = klass->generic_container;
588 MonoGenericInst *inst;
589 MonoGenericClass *gclass = NULL;
595 /* We can't use context->class_inst directly, since it can have more elements */
596 inst = mono_metadata_inflate_generic_inst (container->context.class_inst, context, error);
597 if (!mono_error_ok (error))
599 if (inst == container->context.class_inst)
602 gclass = mono_metadata_lookup_generic_class (klass, inst, klass->image->dynamic);
604 nt = mono_metadata_type_dup (image, type);
605 nt->type = MONO_TYPE_GENERICINST;
606 nt->data.generic_class = gclass;
616 mono_generic_class_get_context (MonoGenericClass *gclass)
618 return &gclass->context;
622 mono_class_get_context (MonoClass *class)
624 return class->generic_class ? mono_generic_class_get_context (class->generic_class) : NULL;
628 * mono_class_get_generic_container:
630 * Return the generic container of KLASS which should be a generic type definition.
632 MonoGenericContainer*
633 mono_class_get_generic_container (MonoClass *klass)
635 g_assert (klass->is_generic);
637 return klass->generic_container;
641 * mono_class_get_generic_class:
643 * Return the MonoGenericClass of KLASS, which should be a generic instance.
646 mono_class_get_generic_class (MonoClass *klass)
648 g_assert (klass->is_inflated);
650 return klass->generic_class;
654 * mono_class_inflate_generic_type_with_mempool:
655 * @mempool: a mempool
657 * @context: a generics context
658 * @error: error context
660 * The same as mono_class_inflate_generic_type, but allocates the MonoType
661 * from mempool if it is non-NULL. If it is NULL, the MonoType is
662 * allocated on the heap and is owned by the caller.
663 * The returned type can potentially be the same as TYPE, so it should not be
664 * modified by the caller, and it should be freed using mono_metadata_free_type ().
667 mono_class_inflate_generic_type_with_mempool (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
669 MonoType *inflated = NULL;
670 mono_error_init (error);
673 inflated = inflate_generic_type (image, type, context, error);
674 if (!mono_error_ok (error))
678 MonoType *shared = mono_metadata_get_shared_type (type);
683 return mono_metadata_type_dup (image, type);
687 mono_stats.inflated_type_count++;
692 * mono_class_inflate_generic_type:
694 * @context: a generics context
696 * If @type is a generic type and @context is not NULL, instantiate it using the
697 * generics context @context.
699 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
700 * on the heap and is owned by the caller. Returns NULL on error.
702 * @deprecated Please use mono_class_inflate_generic_type_checked instead
705 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
709 result = mono_class_inflate_generic_type_checked (type, context, &error);
711 if (!mono_error_ok (&error)) {
712 mono_error_cleanup (&error);
719 * mono_class_inflate_generic_type:
721 * @context: a generics context
722 * @error: error context to use
724 * If @type is a generic type and @context is not NULL, instantiate it using the
725 * generics context @context.
727 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
728 * on the heap and is owned by the caller.
731 mono_class_inflate_generic_type_checked (MonoType *type, MonoGenericContext *context, MonoError *error)
733 return mono_class_inflate_generic_type_with_mempool (NULL, type, context, error);
737 * mono_class_inflate_generic_type_no_copy:
739 * Same as inflate_generic_type_with_mempool, but return TYPE if no inflation
743 mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context)
746 MonoType *inflated = NULL;
749 inflated = inflate_generic_type (image, type, context, &error);
750 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
756 mono_stats.inflated_type_count++;
761 * mono_class_inflate_generic_class:
763 * Inflate the class GKLASS with CONTEXT.
766 mono_class_inflate_generic_class (MonoClass *gklass, MonoGenericContext *context)
772 inflated = mono_class_inflate_generic_type_checked (&gklass->byval_arg, context, &error);
773 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
775 res = mono_class_from_mono_type (inflated);
776 mono_metadata_free_type (inflated);
781 static MonoGenericContext
782 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with)
785 MonoGenericInst *class_inst = NULL;
786 MonoGenericInst *method_inst = NULL;
787 MonoGenericContext res;
789 if (context->class_inst) {
790 class_inst = mono_metadata_inflate_generic_inst (context->class_inst, inflate_with, &error);
791 g_assert (mono_error_ok (&error)); /*FIXME do proper error handling*/
794 if (context->method_inst) {
795 method_inst = mono_metadata_inflate_generic_inst (context->method_inst, inflate_with, &error);
796 g_assert (mono_error_ok (&error)); /*FIXME do proper error handling*/
799 res.class_inst = class_inst;
800 res.method_inst = method_inst;
806 * mono_class_inflate_generic_method:
807 * @method: a generic method
808 * @context: a generics context
810 * Instantiate the generic method @method using the generics context @context.
812 * Returns: the new instantiated method
815 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
817 return mono_class_inflate_generic_method_full (method, NULL, context);
821 * mono_class_inflate_generic_method_full:
823 * Instantiate method @method with the generic context @context.
824 * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
825 * Use mono_method_signature () and mono_method_get_header () to get the correct values.
828 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
831 MonoMethodInflated *iresult, *cached;
832 MonoMethodSignature *sig;
833 MonoGenericContext tmp_context;
834 gboolean is_mb_open = FALSE;
836 /* The `method' has already been instantiated before => we need to peel out the instantiation and create a new context */
837 while (method->is_inflated) {
838 MonoGenericContext *method_context = mono_method_get_context (method);
839 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
841 tmp_context = inflate_generic_context (method_context, context);
842 context = &tmp_context;
844 if (mono_metadata_generic_context_equal (method_context, context))
847 method = imethod->declaring;
850 if (!method->is_generic && !method->klass->generic_container)
854 * The reason for this hack is to fix the behavior of inflating generic methods that come from a MethodBuilder.
855 * What happens is that instantiating a generic MethodBuilder with its own arguments should create a diferent object.
856 * This is opposite to the way non-SRE MethodInfos behave.
858 * This happens, for example, when we want to emit a recursive generic method. Given the following C# code:
860 * void Example<T> () {
864 * In Example, the method token must be encoded as: "void Example<!!0>()"
866 * The reference to the first generic argument, "!!0", must be explicit otherwise it won't be inflated
867 * properly. To get that we need to inflate the MethodBuilder with its own arguments.
869 * On the other hand, inflating a non-SRE generic method with its own arguments should
870 * return itself. For example:
872 * MethodInfo m = ... //m is a generic method definition
873 * MethodInfo res = m.MakeGenericMethod (m.GetGenericArguments ());
876 * To allow such scenarios we must allow inflation of MethodBuilder to happen in a diferent way than
877 * what happens with regular methods.
879 * There is one last touch to this madness, once a TypeBuilder is finished, IOW CreateType() is called,
880 * everything should behave like a regular type or method.
883 is_mb_open = method->is_generic &&
884 method->klass->image->dynamic && !method->klass->wastypebuilder && /* that is a MethodBuilder from an unfinished TypeBuilder */
885 context->method_inst == mono_method_get_generic_container (method)->context.method_inst; /* and it's been instantiated with its own arguments. */
887 iresult = g_new0 (MonoMethodInflated, 1);
888 iresult->context = *context;
889 iresult->declaring = method;
890 iresult->method.method.is_mb_open = is_mb_open;
892 if (!context->method_inst && method->is_generic)
893 iresult->context.method_inst = mono_method_get_generic_container (method)->context.method_inst;
895 if (!context->class_inst) {
896 g_assert (!iresult->declaring->klass->generic_class);
897 if (iresult->declaring->klass->generic_container)
898 iresult->context.class_inst = iresult->declaring->klass->generic_container->context.class_inst;
899 else if (iresult->declaring->klass->generic_class)
900 iresult->context.class_inst = iresult->declaring->klass->generic_class->context.class_inst;
904 cached = mono_method_inflated_lookup (iresult, FALSE);
906 mono_loader_unlock ();
908 return (MonoMethod*)cached;
911 mono_stats.inflated_method_count++;
913 inflated_methods_size += sizeof (MonoMethodInflated);
915 sig = mono_method_signature (method);
917 memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
919 memcpy (&iresult->method.normal, method, sizeof (MonoMethodNormal));
920 iresult->method.normal.header = NULL;
923 result = (MonoMethod *) iresult;
924 result->is_inflated = TRUE;
925 result->is_generic = FALSE;
926 result->signature = NULL;
927 result->is_mb_open = is_mb_open;
929 if (!context->method_inst) {
930 /* Set the generic_container of the result to the generic_container of method */
931 MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
933 if (generic_container) {
934 result->is_generic = 1;
935 mono_method_set_generic_container (result, generic_container);
939 if (!klass_hint || !klass_hint->generic_class ||
940 klass_hint->generic_class->container_class != method->klass ||
941 klass_hint->generic_class->context.class_inst != context->class_inst)
944 if (method->klass->generic_container)
945 result->klass = klass_hint;
947 if (!result->klass) {
949 MonoType *inflated = inflate_generic_type (NULL, &method->klass->byval_arg, context, &error);
951 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
953 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
955 mono_metadata_free_type (inflated);
958 mono_method_inflated_lookup (iresult, TRUE);
959 mono_loader_unlock ();
964 * mono_get_inflated_method:
966 * Obsolete. We keep it around since it's mentioned in the public API.
969 mono_get_inflated_method (MonoMethod *method)
975 * mono_method_get_context_general:
977 * @uninflated: handle uninflated methods?
979 * Returns the generic context of a method or NULL if it doesn't have
980 * one. For an inflated method that's the context stored in the
981 * method. Otherwise it's in the method's generic container or in the
982 * generic container of the method's class.
985 mono_method_get_context_general (MonoMethod *method, gboolean uninflated)
987 if (method->is_inflated) {
988 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
989 return &imethod->context;
993 if (method->is_generic)
994 return &(mono_method_get_generic_container (method)->context);
995 if (method->klass->generic_container)
996 return &method->klass->generic_container->context;
1001 * mono_method_get_context:
1004 * Returns the generic context for method if it's inflated, otherwise
1008 mono_method_get_context (MonoMethod *method)
1010 return mono_method_get_context_general (method, FALSE);
1014 * mono_method_get_generic_container:
1016 * Returns the generic container of METHOD, which should be a generic method definition.
1017 * Returns NULL if METHOD is not a generic method definition.
1018 * LOCKING: Acquires the loader lock.
1020 MonoGenericContainer*
1021 mono_method_get_generic_container (MonoMethod *method)
1023 MonoGenericContainer *container;
1025 if (!method->is_generic)
1028 container = mono_image_property_lookup (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER);
1029 g_assert (container);
1035 * mono_method_set_generic_container:
1037 * Sets the generic container of METHOD to CONTAINER.
1038 * LOCKING: Acquires the loader lock.
1041 mono_method_set_generic_container (MonoMethod *method, MonoGenericContainer* container)
1043 g_assert (method->is_generic);
1045 mono_image_property_insert (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER, container);
1049 * mono_class_find_enum_basetype:
1050 * @class: The enum class
1052 * Determine the basetype of an enum by iterating through its fields. We do this
1053 * in a separate function since it is cheaper than calling mono_class_setup_fields.
1056 mono_class_find_enum_basetype (MonoClass *class)
1058 MonoGenericContainer *container = NULL;
1059 MonoImage *m = class->image;
1060 const int top = class->field.count;
1063 g_assert (class->enumtype);
1065 if (class->generic_container)
1066 container = class->generic_container;
1067 else if (class->generic_class) {
1068 MonoClass *gklass = class->generic_class->container_class;
1070 container = gklass->generic_container;
1071 g_assert (container);
1075 * Fetch all the field information.
1077 for (i = 0; i < top; i++){
1079 guint32 cols [MONO_FIELD_SIZE];
1080 int idx = class->field.first + i;
1083 /* class->field.first and idx points into the fieldptr table */
1084 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1086 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC) //no need to decode static fields
1089 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL))
1092 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1093 mono_metadata_decode_value (sig, &sig);
1094 /* FIELD signature == 0x06 */
1098 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1101 if (class->generic_class) {
1102 //FIXME do we leak here?
1103 ftype = mono_class_inflate_generic_type (ftype, mono_class_get_context (class));
1104 ftype->attrs = cols [MONO_FIELD_FLAGS];
1114 * Checks for MonoClass::exception_type without resolving all MonoType's into MonoClass'es
1115 * It doesn't resolve generic instances, only check the GTD.
1118 mono_type_has_exceptions (MonoType *type)
1120 switch (type->type) {
1121 case MONO_TYPE_CLASS:
1122 case MONO_TYPE_VALUETYPE:
1123 case MONO_TYPE_SZARRAY:
1124 return type->data.klass->exception_type;
1125 case MONO_TYPE_ARRAY:
1126 return type->data.array->eklass->exception_type;
1127 case MONO_TYPE_GENERICINST:
1128 return type->data.generic_class->container_class->exception_type;
1134 * mono_class_setup_fields:
1135 * @class: The class to initialize
1137 * Initializes the class->fields.
1138 * LOCKING: Assumes the loader lock is held.
1141 mono_class_setup_fields (MonoClass *class)
1143 MonoImage *m = class->image;
1144 int top = class->field.count;
1145 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1146 int i, blittable = TRUE;
1147 guint32 real_size = 0;
1148 guint32 packing_size = 0;
1149 gboolean explicit_size;
1150 MonoClassField *field;
1151 MonoGenericContainer *container = NULL;
1152 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1154 if (class->size_inited)
1157 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1159 * This happens when a generic instance of an unfinished generic typebuilder
1160 * is used as an element type for creating an array type. We can't initialize
1161 * the fields of this class using the fields of gklass, since gklass is not
1162 * finished yet, fields could be added to it later.
1168 mono_class_setup_fields (gtd);
1169 if (gtd->exception_type) {
1170 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1174 top = gtd->field.count;
1175 class->field.first = gtd->field.first;
1176 class->field.count = gtd->field.count;
1179 class->instance_size = 0;
1181 class->sizes.class_size = 0;
1183 if (class->parent) {
1184 /* For generic instances, class->parent might not have been initialized */
1185 mono_class_init (class->parent);
1186 if (!class->parent->size_inited) {
1187 mono_class_setup_fields (class->parent);
1188 if (class->parent->exception_type) {
1189 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1193 class->instance_size += class->parent->instance_size;
1194 class->min_align = class->parent->min_align;
1195 /* we use |= since it may have been set already */
1196 class->has_references |= class->parent->has_references;
1197 blittable = class->parent->blittable;
1199 class->instance_size = sizeof (MonoObject);
1200 class->min_align = 1;
1203 /* We can't really enable 16 bytes alignment until the GC supports it.
1204 The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
1205 boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
1206 Bug #506144 is an example of this issue.
1208 if (class->simd_type)
1209 class->min_align = 16;
1211 /* Get the real size */
1212 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1214 if (explicit_size) {
1215 g_assert ((packing_size & 0xfffffff0) == 0);
1216 class->packing_size = packing_size;
1217 real_size += class->instance_size;
1221 if (explicit_size && real_size) {
1222 class->instance_size = MAX (real_size, class->instance_size);
1224 class->size_inited = 1;
1225 class->blittable = blittable;
1229 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1232 /* Prevent infinite loops if the class references itself */
1233 class->size_inited = 1;
1235 class->fields = mono_image_alloc0 (class->image, sizeof (MonoClassField) * top);
1237 if (class->generic_container) {
1238 container = class->generic_container;
1240 container = gtd->generic_container;
1241 g_assert (container);
1245 * Fetch all the field information.
1247 for (i = 0; i < top; i++){
1248 int idx = class->field.first + i;
1249 field = &class->fields [i];
1251 field->parent = class;
1254 MonoClassField *gfield = >d->fields [i];
1256 field->name = mono_field_get_name (gfield);
1257 /*This memory must come from the image mempool as we don't have a chance to free it.*/
1258 field->type = mono_class_inflate_generic_type_no_copy (class->image, gfield->type, mono_class_get_context (class));
1259 g_assert (field->type->attrs == gfield->type->attrs);
1260 if (mono_field_is_deleted (field))
1262 field->offset = gfield->offset;
1265 guint32 cols [MONO_FIELD_SIZE];
1267 /* class->field.first and idx points into the fieldptr table */
1268 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1269 /* The name is needed for fieldrefs */
1270 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
1271 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL)) {
1272 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1275 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1276 mono_metadata_decode_value (sig, &sig);
1277 /* FIELD signature == 0x06 */
1278 g_assert (*sig == 0x06);
1279 field->type = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1281 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1284 if (mono_field_is_deleted (field))
1286 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1288 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1289 field->offset = offset;
1290 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1291 g_warning ("%s not initialized correctly (missing field layout info for %s)",
1292 class->name, mono_field_get_name (field));
1296 /* Only do these checks if we still think this type is blittable */
1297 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1298 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1301 MonoClass *field_class = mono_class_from_mono_type (field->type);
1303 mono_class_setup_fields (field_class);
1304 if (field_class->exception_type) {
1305 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1309 if (!field_class || !field_class->blittable)
1314 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1315 class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1316 blittable = class->element_class->blittable;
1319 if (mono_type_has_exceptions (field->type)) {
1320 char *class_name = mono_type_get_full_name (class);
1321 char *type_name = mono_type_full_name (field->type);
1323 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1324 g_warning ("Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
1325 g_free (class_name);
1329 /* The def_value of fields is compute lazily during vtable creation */
1332 if (class == mono_defaults.string_class)
1335 class->blittable = blittable;
1337 if (class->enumtype && !mono_class_enum_basetype (class)) {
1338 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1341 if (explicit_size && real_size) {
1342 class->instance_size = MAX (real_size, class->instance_size);
1345 if (class->exception_type)
1347 mono_class_layout_fields (class);
1351 * mono_class_setup_fields_locking:
1352 * @class: The class to initialize
1354 * Initializes the class->fields array of fields.
1355 * Aquires the loader lock.
1358 mono_class_setup_fields_locking (MonoClass *class)
1360 mono_loader_lock ();
1361 mono_class_setup_fields (class);
1362 mono_loader_unlock ();
1366 * mono_class_has_references:
1368 * Returns whenever @klass->has_references is set, initializing it if needed.
1369 * Aquires the loader lock.
1372 mono_class_has_references (MonoClass *klass)
1374 if (klass->init_pending) {
1375 /* Be conservative */
1378 mono_class_init (klass);
1380 return klass->has_references;
1384 /* useful until we keep track of gc-references in corlib etc. */
1386 #define IS_GC_REFERENCE(t) FALSE
1388 #define IS_GC_REFERENCE(t) ((t)->type == MONO_TYPE_U && class->image == mono_defaults.corlib)
1392 * mono_type_get_basic_type_from_generic:
1395 * Returns a closed type corresponding to the possibly open type
1399 mono_type_get_basic_type_from_generic (MonoType *type)
1401 /* When we do generic sharing we let type variables stand for reference types. */
1402 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1403 return &mono_defaults.object_class->byval_arg;
1408 * mono_class_layout_fields:
1411 * Compute the placement of fields inside an object or struct, according to
1412 * the layout rules and set the following fields in @class:
1413 * - has_references (if the class contains instance references firled or structs that contain references)
1414 * - has_static_refs (same, but for static fields)
1415 * - instance_size (size of the object in memory)
1416 * - class_size (size needed for the static fields)
1417 * - size_inited (flag set when the instance_size is set)
1419 * LOCKING: this is supposed to be called with the loader lock held.
1422 mono_class_layout_fields (MonoClass *class)
1425 const int top = class->field.count;
1426 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1427 guint32 pass, passes, real_size;
1428 gboolean gc_aware_layout = FALSE;
1429 MonoClassField *field;
1432 * When we do generic sharing we need to have layout
1433 * information for open generic classes (either with a generic
1434 * context containing type variables or with a generic
1435 * container), so we don't return in that case anymore.
1439 * Enable GC aware auto layout: in this mode, reference
1440 * fields are grouped together inside objects, increasing collector
1442 * Requires that all classes whose layout is known to native code be annotated
1443 * with [StructLayout (LayoutKind.Sequential)]
1444 * Value types have gc_aware_layout disabled by default, as per
1445 * what the default is for other runtimes.
1447 /* corlib is missing [StructLayout] directives in many places */
1448 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1449 if (class->image != mono_defaults.corlib &&
1450 class->byval_arg.type != MONO_TYPE_VALUETYPE)
1451 gc_aware_layout = TRUE;
1452 /* from System.dll, used in metadata/process.h */
1453 if (strcmp (class->name, "ProcessStartInfo") == 0)
1454 gc_aware_layout = FALSE;
1457 /* Compute klass->has_references */
1459 * Process non-static fields first, since static fields might recursively
1460 * refer to the class itself.
1462 for (i = 0; i < top; i++) {
1465 field = &class->fields [i];
1467 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1468 ftype = mono_type_get_underlying_type (field->type);
1469 ftype = mono_type_get_basic_type_from_generic (ftype);
1470 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1471 class->has_references = TRUE;
1475 for (i = 0; i < top; i++) {
1478 field = &class->fields [i];
1480 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1481 ftype = mono_type_get_underlying_type (field->type);
1482 ftype = mono_type_get_basic_type_from_generic (ftype);
1483 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1484 class->has_static_refs = TRUE;
1488 for (i = 0; i < top; i++) {
1491 field = &class->fields [i];
1493 ftype = mono_type_get_underlying_type (field->type);
1494 ftype = mono_type_get_basic_type_from_generic (ftype);
1495 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1496 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1497 class->has_static_refs = TRUE;
1499 class->has_references = TRUE;
1504 * Compute field layout and total size (not considering static fields)
1508 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1509 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1511 if (gc_aware_layout)
1516 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1520 real_size = class->parent->instance_size;
1522 real_size = sizeof (MonoObject);
1524 for (pass = 0; pass < passes; ++pass) {
1525 for (i = 0; i < top; i++){
1530 field = &class->fields [i];
1532 if (mono_field_is_deleted (field))
1534 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1537 ftype = mono_type_get_underlying_type (field->type);
1538 ftype = mono_type_get_basic_type_from_generic (ftype);
1539 if (gc_aware_layout) {
1540 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1549 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1550 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1551 /* This field is a hack inserted by MCS to empty structures */
1555 size = mono_type_size (field->type, &align);
1557 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1558 align = class->packing_size ? MIN (class->packing_size, align): align;
1559 /* if the field has managed references, we need to force-align it
1562 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1563 align = MAX (align, sizeof (gpointer));
1565 class->min_align = MAX (align, class->min_align);
1566 field->offset = real_size;
1567 field->offset += align - 1;
1568 field->offset &= ~(align - 1);
1569 real_size = field->offset + size;
1572 class->instance_size = MAX (real_size, class->instance_size);
1574 if (class->instance_size & (class->min_align - 1)) {
1575 class->instance_size += class->min_align - 1;
1576 class->instance_size &= ~(class->min_align - 1);
1580 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1582 for (i = 0; i < top; i++) {
1587 field = &class->fields [i];
1590 * There must be info about all the fields in a type if it
1591 * uses explicit layout.
1594 if (mono_field_is_deleted (field))
1596 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1599 size = mono_type_size (field->type, &align);
1600 class->min_align = MAX (align, class->min_align);
1603 * When we get here, field->offset is already set by the
1604 * loader (for either runtime fields or fields loaded from metadata).
1605 * The offset is from the start of the object: this works for both
1606 * classes and valuetypes.
1608 field->offset += sizeof (MonoObject);
1609 ftype = mono_type_get_underlying_type (field->type);
1610 ftype = mono_type_get_basic_type_from_generic (ftype);
1611 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1612 if (field->offset % sizeof (gpointer)) {
1613 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1620 real_size = MAX (real_size, size + field->offset);
1622 class->instance_size = MAX (real_size, class->instance_size);
1626 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1628 * For small structs, set min_align to at least the struct size to improve
1629 * performance, and since the JIT memset/memcpy code assumes this and generates
1630 * unaligned accesses otherwise. See #78990 for a testcase.
1632 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1633 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1636 class->size_inited = 1;
1639 * Compute static field layout and size
1641 for (i = 0; i < top; i++){
1645 field = &class->fields [i];
1647 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1649 if (mono_field_is_deleted (field))
1652 size = mono_type_size (field->type, &align);
1653 field->offset = class->sizes.class_size;
1654 field->offset += align - 1;
1655 field->offset &= ~(align - 1);
1656 class->sizes.class_size = field->offset + size;
1661 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1665 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1666 method->klass = class;
1667 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1668 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1669 method->signature = sig;
1670 method->name = name;
1673 if (name [0] == '.') {
1674 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1676 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1682 * mono_class_setup_methods:
1685 * Initializes the 'methods' array in the klass.
1686 * Calling this method should be avoided if possible since it allocates a lot
1687 * of long-living MonoMethod structures.
1688 * Methods belonging to an interface are assigned a sequential slot starting
1692 mono_class_setup_methods (MonoClass *class)
1695 MonoMethod **methods;
1700 mono_loader_lock ();
1702 if (class->methods) {
1703 mono_loader_unlock ();
1707 if (class->generic_class) {
1708 MonoClass *gklass = class->generic_class->container_class;
1710 mono_class_init (gklass);
1711 mono_class_setup_methods (gklass);
1713 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1714 class->method.count = gklass->method.count;
1715 methods = g_new0 (MonoMethod *, class->method.count + 1);
1717 for (i = 0; i < class->method.count; i++) {
1718 methods [i] = mono_class_inflate_generic_method_full (
1719 gklass->methods [i], class, mono_class_get_context (class));
1721 } else if (class->rank) {
1722 MonoMethod *amethod;
1723 MonoMethodSignature *sig;
1724 int count_generic = 0, first_generic = 0;
1727 class->method.count = 3 + (class->rank > 1? 2: 1);
1729 mono_class_setup_interfaces (class);
1731 if (class->interface_count) {
1732 count_generic = generic_array_methods (class);
1733 first_generic = class->method.count;
1734 class->method.count += class->interface_count * count_generic;
1737 methods = mono_image_alloc0 (class->image, sizeof (MonoMethod*) * class->method.count);
1739 sig = mono_metadata_signature_alloc (class->image, class->rank);
1740 sig->ret = &mono_defaults.void_class->byval_arg;
1741 sig->pinvoke = TRUE;
1742 sig->hasthis = TRUE;
1743 for (i = 0; i < class->rank; ++i)
1744 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1746 amethod = create_array_method (class, ".ctor", sig);
1747 methods [method_num++] = amethod;
1748 if (class->rank > 1) {
1749 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1750 sig->ret = &mono_defaults.void_class->byval_arg;
1751 sig->pinvoke = TRUE;
1752 sig->hasthis = TRUE;
1753 for (i = 0; i < class->rank * 2; ++i)
1754 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1756 amethod = create_array_method (class, ".ctor", sig);
1757 methods [method_num++] = amethod;
1759 /* element Get (idx11, [idx2, ...]) */
1760 sig = mono_metadata_signature_alloc (class->image, class->rank);
1761 sig->ret = &class->element_class->byval_arg;
1762 sig->pinvoke = TRUE;
1763 sig->hasthis = TRUE;
1764 for (i = 0; i < class->rank; ++i)
1765 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1766 amethod = create_array_method (class, "Get", sig);
1767 methods [method_num++] = amethod;
1768 /* element& Address (idx11, [idx2, ...]) */
1769 sig = mono_metadata_signature_alloc (class->image, class->rank);
1770 sig->ret = &class->element_class->this_arg;
1771 sig->pinvoke = TRUE;
1772 sig->hasthis = TRUE;
1773 for (i = 0; i < class->rank; ++i)
1774 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1775 amethod = create_array_method (class, "Address", sig);
1776 methods [method_num++] = amethod;
1777 /* void Set (idx11, [idx2, ...], element) */
1778 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1779 sig->ret = &mono_defaults.void_class->byval_arg;
1780 sig->pinvoke = TRUE;
1781 sig->hasthis = TRUE;
1782 for (i = 0; i < class->rank; ++i)
1783 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1784 sig->params [i] = &class->element_class->byval_arg;
1785 amethod = create_array_method (class, "Set", sig);
1786 methods [method_num++] = amethod;
1788 for (i = 0; i < class->interface_count; i++)
1789 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1791 methods = mono_image_alloc (class->image, sizeof (MonoMethod*) * class->method.count);
1792 for (i = 0; i < class->method.count; ++i) {
1793 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1794 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1798 if (MONO_CLASS_IS_INTERFACE (class)) {
1800 /*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
1801 for (i = 0; i < class->method.count; ++i) {
1802 if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
1803 methods [i]->slot = slot++;
1807 /* Needed because of the double-checking locking pattern */
1808 mono_memory_barrier ();
1810 class->methods = methods;
1812 if (mono_debugger_class_loaded_methods_func)
1813 mono_debugger_class_loaded_methods_func (class);
1815 mono_loader_unlock ();
1819 * mono_class_get_method_by_index:
1821 * Returns class->methods [index], initializing class->methods if neccesary.
1823 * LOCKING: Acquires the loader lock.
1826 mono_class_get_method_by_index (MonoClass *class, int index)
1828 /* Avoid calling setup_methods () if possible */
1829 if (class->generic_class && !class->methods) {
1830 MonoClass *gklass = class->generic_class->container_class;
1833 m = mono_class_inflate_generic_method_full (
1834 gklass->methods [index], class, mono_class_get_context (class));
1836 * If setup_methods () is called later for this class, no duplicates are created,
1837 * since inflate_generic_method guarantees that only one instance of a method
1838 * is created for each context.
1841 mono_class_setup_methods (class);
1842 g_assert (m == class->methods [index]);
1846 mono_class_setup_methods (class);
1847 g_assert (index >= 0 && index < class->method.count);
1848 return class->methods [index];
1853 * mono_class_get_inflated_method:
1855 * Given an inflated class CLASS and a method METHOD which should be a method of
1856 * CLASS's generic definition, return the inflated method corresponding to METHOD.
1859 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
1861 MonoClass *gklass = class->generic_class->container_class;
1864 mono_class_setup_methods (gklass);
1865 for (i = 0; i < gklass->method.count; ++i) {
1866 if (gklass->methods [i] == method) {
1868 return class->methods [i];
1870 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
1878 * mono_class_get_vtable_entry:
1880 * Returns class->vtable [offset], computing it if neccesary.
1881 * LOCKING: Acquires the loader lock.
1884 mono_class_get_vtable_entry (MonoClass *class, int offset)
1888 if (class->rank == 1) {
1890 * szarrays do not overwrite any methods of Array, so we can avoid
1891 * initializing their vtables in some cases.
1893 mono_class_setup_vtable (class->parent);
1894 if (offset < class->parent->vtable_size)
1895 return class->parent->vtable [offset];
1898 if (class->generic_class) {
1899 MonoClass *gklass = class->generic_class->container_class;
1900 mono_class_setup_vtable (gklass);
1901 m = gklass->vtable [offset];
1903 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
1905 mono_class_setup_vtable (class);
1906 m = class->vtable [offset];
1913 * mono_class_get_vtable_size:
1915 * Return the vtable size for KLASS.
1918 mono_class_get_vtable_size (MonoClass *klass)
1920 mono_class_setup_vtable (klass);
1922 return klass->vtable_size;
1926 mono_class_setup_properties (MonoClass *class)
1928 guint startm, endm, i, j;
1929 guint32 cols [MONO_PROPERTY_SIZE];
1930 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1931 MonoProperty *properties;
1934 if (class->ext && class->ext->properties)
1937 mono_loader_lock ();
1939 if (class->ext && class->ext->properties) {
1940 mono_loader_unlock ();
1944 mono_class_alloc_ext (class);
1946 if (class->generic_class) {
1947 MonoClass *gklass = class->generic_class->container_class;
1949 mono_class_init (gklass);
1950 mono_class_setup_properties (gklass);
1952 class->ext->property = gklass->ext->property;
1954 properties = g_new0 (MonoProperty, class->ext->property.count + 1);
1956 for (i = 0; i < class->ext->property.count; i++) {
1957 MonoProperty *prop = &properties [i];
1959 *prop = gklass->ext->properties [i];
1962 prop->get = mono_class_inflate_generic_method_full (
1963 prop->get, class, mono_class_get_context (class));
1965 prop->set = mono_class_inflate_generic_method_full (
1966 prop->set, class, mono_class_get_context (class));
1968 prop->parent = class;
1971 class->ext->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1972 class->ext->property.count = last - class->ext->property.first;
1974 if (class->ext->property.count)
1975 mono_class_setup_methods (class);
1977 properties = mono_image_alloc0 (class->image, sizeof (MonoProperty) * class->ext->property.count);
1978 for (i = class->ext->property.first; i < last; ++i) {
1979 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
1980 properties [i - class->ext->property.first].parent = class;
1981 properties [i - class->ext->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
1982 properties [i - class->ext->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
1984 startm = mono_metadata_methods_from_property (class->image, i, &endm);
1985 for (j = startm; j < endm; ++j) {
1988 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1990 if (class->image->uncompressed_metadata)
1991 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1992 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1994 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1996 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1997 case METHOD_SEMANTIC_SETTER:
1998 properties [i - class->ext->property.first].set = method;
2000 case METHOD_SEMANTIC_GETTER:
2001 properties [i - class->ext->property.first].get = method;
2009 /*Flush any pending writes as we do double checked locking on class->properties */
2010 mono_memory_barrier ();
2012 /* Leave this assignment as the last op in the function */
2013 class->ext->properties = properties;
2015 mono_loader_unlock ();
2019 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
2021 MonoMethod **om, **retval;
2024 for (om = methods, count = 0; *om; ++om, ++count)
2027 retval = g_new0 (MonoMethod*, count + 1);
2029 for (om = methods, count = 0; *om; ++om, ++count)
2030 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
2036 mono_class_setup_events (MonoClass *class)
2038 guint startm, endm, i, j;
2039 guint32 cols [MONO_EVENT_SIZE];
2040 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2044 if (class->ext && class->ext->events)
2047 mono_loader_lock ();
2049 if (class->ext && class->ext->events) {
2050 mono_loader_unlock ();
2054 mono_class_alloc_ext (class);
2056 if (class->generic_class) {
2057 MonoClass *gklass = class->generic_class->container_class;
2058 MonoGenericContext *context;
2060 mono_class_setup_events (gklass);
2061 class->ext->event = gklass->ext->event;
2063 class->ext->events = g_new0 (MonoEvent, class->ext->event.count);
2065 if (class->ext->event.count)
2066 context = mono_class_get_context (class);
2068 for (i = 0; i < class->ext->event.count; i++) {
2069 MonoEvent *event = &class->ext->events [i];
2070 MonoEvent *gevent = &gklass->ext->events [i];
2072 event->parent = class;
2073 event->name = gevent->name;
2074 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
2075 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
2076 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
2077 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
2078 event->attrs = gevent->attrs;
2081 mono_loader_unlock ();
2085 class->ext->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2086 class->ext->event.count = last - class->ext->event.first;
2088 if (class->ext->event.count)
2089 mono_class_setup_methods (class);
2091 events = mono_image_alloc0 (class->image, sizeof (MonoEvent) * class->ext->event.count);
2092 for (i = class->ext->event.first; i < last; ++i) {
2093 MonoEvent *event = &events [i - class->ext->event.first];
2095 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
2096 event->parent = class;
2097 event->attrs = cols [MONO_EVENT_FLAGS];
2098 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
2100 startm = mono_metadata_methods_from_event (class->image, i, &endm);
2101 for (j = startm; j < endm; ++j) {
2104 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2106 if (class->image->uncompressed_metadata)
2107 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2108 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2110 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2112 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2113 case METHOD_SEMANTIC_ADD_ON:
2114 event->add = method;
2116 case METHOD_SEMANTIC_REMOVE_ON:
2117 event->remove = method;
2119 case METHOD_SEMANTIC_FIRE:
2120 event->raise = method;
2122 case METHOD_SEMANTIC_OTHER: {
2125 if (event->other == NULL) {
2126 event->other = g_new0 (MonoMethod*, 2);
2128 while (event->other [n])
2130 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
2132 event->other [n] = method;
2133 /* NULL terminated */
2134 event->other [n + 1] = NULL;
2142 /*Flush any pending writes as we do double checked locking on class->properties */
2143 mono_memory_barrier ();
2145 /* Leave this assignment as the last op in the function */
2146 class->ext->events = events;
2148 mono_loader_unlock ();
2152 * Global pool of interface IDs, represented as a bitset.
2153 * LOCKING: this is supposed to be accessed with the loader lock held.
2155 static MonoBitSet *global_interface_bitset = NULL;
2158 * mono_unload_interface_ids:
2159 * @bitset: bit set of interface IDs
2161 * When an image is unloaded, the interface IDs associated with
2162 * the image are put back in the global pool of IDs so the numbers
2166 mono_unload_interface_ids (MonoBitSet *bitset)
2168 mono_loader_lock ();
2169 mono_bitset_sub (global_interface_bitset, bitset);
2170 mono_loader_unlock ();
2174 * mono_get_unique_iid:
2177 * Assign a unique integer ID to the interface represented by @class.
2178 * The ID will positive and as small as possible.
2179 * LOCKING: this is supposed to be called with the loader lock held.
2180 * Returns: the new ID.
2183 mono_get_unique_iid (MonoClass *class)
2187 g_assert (MONO_CLASS_IS_INTERFACE (class));
2189 if (!global_interface_bitset) {
2190 global_interface_bitset = mono_bitset_new (128, 0);
2193 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2195 int old_size = mono_bitset_size (global_interface_bitset);
2196 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2197 mono_bitset_free (global_interface_bitset);
2198 global_interface_bitset = new_set;
2201 mono_bitset_set (global_interface_bitset, iid);
2202 /* set the bit also in the per-image set */
2203 if (class->image->interface_bitset) {
2204 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2205 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2206 mono_bitset_free (class->image->interface_bitset);
2207 class->image->interface_bitset = new_set;
2210 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2212 mono_bitset_set (class->image->interface_bitset, iid);
2214 if (mono_print_vtable) {
2216 char *type_name = mono_type_full_name (&class->byval_arg);
2217 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2218 generic_id = class->generic_class->context.class_inst->id;
2219 g_assert (generic_id != 0);
2223 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2227 g_assert (iid <= 65535);
2232 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
2237 mono_class_setup_interfaces (klass);
2239 for (i = 0; i < klass->interface_count; i++) {
2240 ic = klass->interfaces [i];
2243 *res = g_ptr_array_new ();
2244 g_ptr_array_add (*res, ic);
2245 mono_class_init (ic);
2247 collect_implemented_interfaces_aux (ic, res);
2252 mono_class_get_implemented_interfaces (MonoClass *klass)
2254 GPtrArray *res = NULL;
2256 collect_implemented_interfaces_aux (klass, &res);
2261 compare_interface_ids (const void *p_key, const void *p_element) {
2262 const MonoClass *key = p_key;
2263 const MonoClass *element = *(MonoClass**) p_element;
2265 return (key->interface_id - element->interface_id);
2269 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2270 MonoClass **result = bsearch (
2272 klass->interfaces_packed,
2273 klass->interface_offsets_count,
2274 sizeof (MonoClass *),
2275 compare_interface_ids);
2277 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2284 print_implemented_interfaces (MonoClass *klass) {
2285 GPtrArray *ifaces = NULL;
2287 int ancestor_level = 0;
2289 printf ("Packed interface table for class %s has size %d\n", klass->name, klass->interface_offsets_count);
2290 for (i = 0; i < klass->interface_offsets_count; i++)
2291 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2292 klass->interfaces_packed [i]->interface_id,
2293 klass->interface_offsets_packed [i],
2294 klass->interfaces_packed [i]->method.count,
2295 klass->interfaces_packed [i]->name_space,
2296 klass->interfaces_packed [i]->name );
2297 printf ("Interface flags: ");
2298 for (i = 0; i <= klass->max_interface_id; i++)
2299 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2300 printf ("(%d,T)", i);
2302 printf ("(%d,F)", i);
2304 printf ("Dump interface flags:");
2305 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2306 printf (" %02X", klass->interface_bitmap [i]);
2308 while (klass != NULL) {
2309 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2310 ifaces = mono_class_get_implemented_interfaces (klass);
2312 for (i = 0; i < ifaces->len; i++) {
2313 MonoClass *ic = g_ptr_array_index (ifaces, i);
2314 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2315 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2317 mono_class_interface_offset (klass, ic),
2322 g_ptr_array_free (ifaces, TRUE);
2325 klass = klass->parent;
2330 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2333 args [0] = &arg0->byval_arg;
2335 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2339 array_class_get_if_rank (MonoClass *class, guint rank)
2341 return rank ? mono_array_class_get (class, rank) : class;
2345 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2347 valuetype_types [0] = eclass;
2348 if (eclass == mono_defaults.int16_class)
2349 valuetype_types [1] = mono_defaults.uint16_class;
2350 else if (eclass == mono_defaults.uint16_class)
2351 valuetype_types [1] = mono_defaults.int16_class;
2352 else if (eclass == mono_defaults.int32_class)
2353 valuetype_types [1] = mono_defaults.uint32_class;
2354 else if (eclass == mono_defaults.uint32_class)
2355 valuetype_types [1] = mono_defaults.int32_class;
2356 else if (eclass == mono_defaults.int64_class)
2357 valuetype_types [1] = mono_defaults.uint64_class;
2358 else if (eclass == mono_defaults.uint64_class)
2359 valuetype_types [1] = mono_defaults.int64_class;
2360 else if (eclass == mono_defaults.byte_class)
2361 valuetype_types [1] = mono_defaults.sbyte_class;
2362 else if (eclass == mono_defaults.sbyte_class)
2363 valuetype_types [1] = mono_defaults.byte_class;
2364 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2365 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2368 /* this won't be needed once bug #325495 is completely fixed
2369 * though we'll need something similar to know which interfaces to allow
2370 * in arrays when they'll be lazyly created
2372 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2373 * MS returns diferrent types based on which instance is called. For example:
2374 * object obj = new byte[10][];
2375 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2376 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2379 * Fixing this should kill quite some code, save some bits and improve compatibility.
2382 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2384 MonoClass *eclass = class->element_class;
2385 static MonoClass* generic_icollection_class = NULL;
2386 static MonoClass* generic_ienumerable_class = NULL;
2387 static MonoClass* generic_ienumerator_class = NULL;
2388 MonoClass *valuetype_types[2] = { NULL, NULL };
2389 MonoClass **interfaces = NULL;
2390 int i, interface_count, real_count, original_rank;
2392 gboolean internal_enumerator;
2393 gboolean eclass_is_valuetype;
2395 if (!mono_defaults.generic_ilist_class) {
2399 internal_enumerator = FALSE;
2400 eclass_is_valuetype = FALSE;
2401 original_rank = eclass->rank;
2402 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2403 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2405 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2407 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2408 original_rank = eclass->rank;
2409 eclass = eclass->element_class;
2410 internal_enumerator = TRUE;
2411 *is_enumerator = TRUE;
2419 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2420 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2422 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2424 if (!generic_icollection_class) {
2425 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2426 "System.Collections.Generic", "ICollection`1");
2427 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2428 "System.Collections.Generic", "IEnumerable`1");
2429 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2430 "System.Collections.Generic", "IEnumerator`1");
2433 mono_class_init (eclass);
2436 * Arrays in 2.0 need to implement a number of generic interfaces
2437 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2438 * on the element class). We collect the types needed to build the
2439 * instantiations in interfaces at intervals of 3, because 3 are
2440 * the generic interfaces needed to implement.
2442 if (eclass->valuetype) {
2443 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2445 /* IList, ICollection, IEnumerable */
2446 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2447 if (internal_enumerator) {
2449 if (valuetype_types [1])
2453 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2454 interfaces [0] = valuetype_types [0];
2455 if (valuetype_types [1])
2456 interfaces [3] = valuetype_types [1];
2458 eclass_is_valuetype = TRUE;
2461 int idepth = eclass->idepth;
2462 if (!internal_enumerator)
2464 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2465 /* we add object for interfaces and the supertypes for the other
2466 * types. The last of the supertypes is the element class itself which we
2467 * already created the explicit interfaces for (so we include it for IEnumerator
2468 * and exclude it for arrays).
2470 if (MONO_CLASS_IS_INTERFACE (eclass))
2473 interface_count += idepth;
2474 if (eclass->rank && eclass->element_class->valuetype) {
2475 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2476 if (valuetype_types [1])
2479 /* IList, ICollection, IEnumerable */
2480 interface_count *= 3;
2481 real_count = interface_count;
2482 if (internal_enumerator) {
2483 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2484 if (valuetype_types [1])
2487 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2488 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2489 interfaces [0] = mono_defaults.object_class;
2493 for (i = 0; i < idepth; i++) {
2494 mono_class_init (eclass->supertypes [i]);
2495 interfaces [j] = eclass->supertypes [i];
2499 if (all_interfaces) {
2500 for (i = 0; i < eclass->interface_offsets_count; i++) {
2501 interfaces [j] = eclass->interfaces_packed [i];
2505 for (i = 0; i < eclass->interface_count; i++) {
2506 interfaces [j] = eclass->interfaces [i];
2510 if (valuetype_types [1]) {
2511 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2516 /* instantiate the generic interfaces */
2517 for (i = 0; i < interface_count; i += 3) {
2518 MonoClass *iface = interfaces [i];
2520 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2521 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2522 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2524 if (internal_enumerator) {
2526 /* instantiate IEnumerator<iface> */
2527 for (i = 0; i < interface_count; i++) {
2528 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2530 j = interface_count;
2531 if (!eclass_is_valuetype) {
2532 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2533 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2536 for (i = 0; i < eclass->idepth; i++) {
2537 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2541 for (i = 0; i < eclass->interface_offsets_count; i++) {
2542 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2546 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2548 if (valuetype_types [1])
2549 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2553 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2554 for (i = 0; i < real_count; ++i) {
2555 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2556 g_print ("%s implements %s\n", type_name, name);
2567 find_array_interface (MonoClass *klass, const char *name)
2570 for (i = 0; i < klass->interface_count; ++i) {
2571 if (strcmp (klass->interfaces [i]->name, name) == 0)
2578 * Return the number of virtual methods.
2579 * Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
2580 * FIXME It would be nice if this information could be cached somewhere.
2583 count_virtual_methods (MonoClass *class)
2587 class = mono_class_get_generic_type_definition (class); /*We can find this information by looking at the GTD*/
2589 if (class->methods || !MONO_CLASS_HAS_STATIC_METADATA (class)) {
2590 mono_class_setup_methods (class);
2592 for (i = 0; i < class->method.count; ++i) {
2593 flags = class->methods [i]->flags;
2594 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2598 for (i = 0; i < class->method.count; ++i) {
2599 flags = mono_metadata_decode_table_row_col (class->image, MONO_TABLE_METHOD, class->method.first + i, MONO_METHOD_FLAGS);
2601 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2609 * LOCKING: this is supposed to be called with the loader lock held.
2612 setup_interface_offsets (MonoClass *class, int cur_slot)
2616 MonoClass **interfaces_full;
2617 int *interface_offsets_full;
2619 int interface_offsets_count;
2620 MonoClass **array_interfaces;
2621 int num_array_interfaces;
2622 int is_enumerator = FALSE;
2625 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
2626 * implicit interfaces have the property that they are assigned the same slot in the
2627 * vtables for compatible interfaces
2629 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
2631 /* compute maximum number of slots and maximum interface id */
2633 for (k = class; k ; k = k->parent) {
2634 for (i = 0; i < k->interface_count; i++) {
2635 ic = k->interfaces [i];
2638 mono_class_init (ic);
2640 if (max_iid < ic->interface_id)
2641 max_iid = ic->interface_id;
2643 ifaces = mono_class_get_implemented_interfaces (k);
2645 for (i = 0; i < ifaces->len; ++i) {
2646 ic = g_ptr_array_index (ifaces, i);
2647 if (max_iid < ic->interface_id)
2648 max_iid = ic->interface_id;
2650 g_ptr_array_free (ifaces, TRUE);
2653 for (i = 0; i < num_array_interfaces; ++i) {
2654 ic = array_interfaces [i];
2655 mono_class_init (ic);
2656 if (max_iid < ic->interface_id)
2657 max_iid = ic->interface_id;
2660 if (MONO_CLASS_IS_INTERFACE (class)) {
2661 if (max_iid < class->interface_id)
2662 max_iid = class->interface_id;
2664 class->max_interface_id = max_iid;
2665 /* compute vtable offset for interfaces */
2666 interfaces_full = g_malloc (sizeof (MonoClass*) * (max_iid + 1));
2667 interface_offsets_full = g_malloc (sizeof (int) * (max_iid + 1));
2669 for (i = 0; i <= max_iid; i++) {
2670 interfaces_full [i] = NULL;
2671 interface_offsets_full [i] = -1;
2674 for (k = class->parent; k ; k = k->parent) {
2675 ifaces = mono_class_get_implemented_interfaces (k);
2677 for (i = 0; i < ifaces->len; ++i) {
2679 ic = g_ptr_array_index (ifaces, i);
2681 /*Force the sharing of interface offsets between parent and subtypes.*/
2682 io = mono_class_interface_offset (k, ic);
2684 interfaces_full [ic->interface_id] = ic;
2685 interface_offsets_full [ic->interface_id] = io;
2687 g_ptr_array_free (ifaces, TRUE);
2692 ifaces = mono_class_get_implemented_interfaces (class);
2694 for (i = 0; i < ifaces->len; ++i) {
2695 ic = g_ptr_array_index (ifaces, i);
2696 if (interfaces_full [ic->interface_id] != NULL)
2698 interfaces_full [ic->interface_id] = ic;
2699 interface_offsets_full [ic->interface_id] = cur_slot;
2700 cur_slot += count_virtual_methods (ic);
2702 g_ptr_array_free (ifaces, TRUE);
2705 if (MONO_CLASS_IS_INTERFACE (class)) {
2706 interfaces_full [class->interface_id] = class;
2707 interface_offsets_full [class->interface_id] = cur_slot;
2710 if (num_array_interfaces) {
2711 if (is_enumerator) {
2712 int ienumerator_offset;
2713 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
2714 ienumerator_offset = interface_offsets_full [class->interfaces [ienumerator_idx]->interface_id];
2715 for (i = 0; i < num_array_interfaces; ++i) {
2716 ic = array_interfaces [i];
2717 interfaces_full [ic->interface_id] = ic;
2718 if (strcmp (ic->name, "IEnumerator`1") == 0)
2719 interface_offsets_full [ic->interface_id] = ienumerator_offset;
2721 g_assert_not_reached ();
2722 /*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);*/
2725 int ilist_offset, icollection_offset, ienumerable_offset;
2726 int ilist_iface_idx = find_array_interface (class, "IList`1");
2727 int icollection_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "ICollection`1");
2728 int ienumerable_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "IEnumerable`1");
2729 ilist_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interface_id];
2730 icollection_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [icollection_iface_idx]->interface_id];
2731 ienumerable_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [ienumerable_iface_idx]->interface_id];
2732 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
2733 for (i = 0; i < num_array_interfaces; ++i) {
2734 ic = array_interfaces [i];
2735 interfaces_full [ic->interface_id] = ic;
2736 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
2737 interface_offsets_full [ic->interface_id] = ilist_offset;
2738 else if (strcmp (ic->name, "ICollection`1") == 0)
2739 interface_offsets_full [ic->interface_id] = icollection_offset;
2740 else if (strcmp (ic->name, "IEnumerable`1") == 0)
2741 interface_offsets_full [ic->interface_id] = ienumerable_offset;
2743 g_assert_not_reached ();
2744 /*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);*/
2749 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2750 if (interface_offsets_full [i] != -1) {
2751 interface_offsets_count ++;
2756 * We might get called twice: once from mono_class_init () then once from
2757 * mono_class_setup_vtable ().
2759 if (class->interfaces_packed) {
2760 g_assert (class->interface_offsets_count == interface_offsets_count);
2762 class->interface_offsets_count = interface_offsets_count;
2763 class->interfaces_packed = mono_image_alloc (class->image, sizeof (MonoClass*) * interface_offsets_count);
2764 class->interface_offsets_packed = mono_image_alloc (class->image, sizeof (guint16) * interface_offsets_count);
2765 class->interface_bitmap = mono_image_alloc0 (class->image, (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0));
2766 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2767 if (interface_offsets_full [i] != -1) {
2768 class->interface_bitmap [i >> 3] |= (1 << (i & 7));
2769 class->interfaces_packed [interface_offsets_count] = interfaces_full [i];
2770 class->interface_offsets_packed [interface_offsets_count] = interface_offsets_full [i];
2771 /*if (num_array_interfaces)
2772 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]);*/
2773 interface_offsets_count ++;
2778 g_free (interfaces_full);
2779 g_free (interface_offsets_full);
2780 g_free (array_interfaces);
2782 //printf ("JUST DONE: ");
2783 //print_implemented_interfaces (class);
2789 * Setup interface offsets for interfaces.
2791 * - class->max_interface_id
2792 * - class->interface_offsets_count
2793 * - class->interfaces_packed
2794 * - class->interface_offsets_packed
2795 * - class->interface_bitmap
2798 mono_class_setup_interface_offsets (MonoClass *class)
2800 mono_loader_lock ();
2802 setup_interface_offsets (class, 0);
2804 mono_loader_unlock ();
2808 * mono_class_setup_vtable:
2810 * Creates the generic vtable of CLASS.
2811 * Initializes the following fields in MonoClass:
2814 * Plus all the fields initialized by setup_interface_offsets ().
2815 * If there is an error during vtable construction, class->exception_type is set.
2817 * LOCKING: Acquires the loader lock.
2820 mono_class_setup_vtable (MonoClass *class)
2822 MonoMethod **overrides;
2823 MonoGenericContext *context;
2832 if (mono_debug_using_mono_debugger ())
2833 /* The debugger currently depends on this */
2834 mono_class_setup_methods (class);
2836 if (MONO_CLASS_IS_INTERFACE (class)) {
2837 /* This sets method->slot for all methods if this is an interface */
2838 mono_class_setup_methods (class);
2842 mono_loader_lock ();
2844 if (class->vtable) {
2845 mono_loader_unlock ();
2849 mono_stats.generic_vtable_count ++;
2851 if (class->generic_class) {
2852 context = mono_class_get_context (class);
2853 type_token = class->generic_class->container_class->type_token;
2855 context = (MonoGenericContext *) class->generic_container;
2856 type_token = class->type_token;
2859 if (class->image->dynamic) {
2860 if (class->generic_class) {
2861 MonoClass *gklass = class->generic_class->container_class;
2863 mono_reflection_get_dynamic_overrides (gklass, &overrides, &onum);
2864 for (i = 0; i < onum; ++i) {
2865 MonoMethod *override = overrides [(i * 2) + 1];
2866 MonoMethod *inflated = NULL;
2869 for (j = 0; j < class->method.count; ++j) {
2870 if (gklass->methods [j] == override) {
2871 inflated = class->methods [j];
2875 g_assert (inflated);
2877 overrides [(i * 2) + 1] = inflated;
2880 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
2883 /* The following call fails if there are missing methods in the type */
2884 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
2888 mono_class_setup_vtable_general (class, overrides, onum);
2892 mono_loader_unlock ();
2897 #define DEBUG_INTERFACE_VTABLE_CODE 0
2898 #define TRACE_INTERFACE_VTABLE_CODE 0
2899 #define VERIFY_INTERFACE_VTABLE_CODE 0
2900 #define VTABLE_SELECTOR (1)
2902 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2903 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
2904 if (!(VTABLE_SELECTOR)) break; \
2908 #define DEBUG_INTERFACE_VTABLE(stmt)
2911 #if TRACE_INTERFACE_VTABLE_CODE
2912 #define TRACE_INTERFACE_VTABLE(stmt) do {\
2913 if (!(VTABLE_SELECTOR)) break; \
2917 #define TRACE_INTERFACE_VTABLE(stmt)
2920 #if VERIFY_INTERFACE_VTABLE_CODE
2921 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
2922 if (!(VTABLE_SELECTOR)) break; \
2926 #define VERIFY_INTERFACE_VTABLE(stmt)
2930 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2932 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
2936 GString *res = g_string_new ("");
2938 g_string_append_c (res, '(');
2939 for (i = 0; i < sig->param_count; ++i) {
2941 g_string_append_c (res, ',');
2942 mono_type_get_desc (res, sig->params [i], include_namespace);
2944 g_string_append (res, ")=>");
2945 if (sig->ret != NULL) {
2946 mono_type_get_desc (res, sig->ret, include_namespace);
2948 g_string_append (res, "NULL");
2951 g_string_free (res, FALSE);
2955 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
2956 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
2957 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
2958 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
2966 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) {
2967 MonoMethodSignature *cmsig, *imsig;
2968 if (strcmp (im->name, cm->name) == 0) {
2969 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
2970 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
2973 if (! slot_is_empty) {
2974 if (require_newslot) {
2975 if (! interface_is_explicitly_implemented_by_class) {
2976 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
2979 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
2980 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
2984 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
2987 cmsig = mono_method_signature (cm);
2988 imsig = mono_method_signature (im);
2989 if (!cmsig || !imsig) {
2990 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not resolve the signature of a virtual method"));
2994 if (! mono_metadata_signature_equal (cmsig, imsig)) {
2995 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
2996 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2997 TRACE_INTERFACE_VTABLE (printf ("]"));
3000 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
3001 /* CAS - SecurityAction.InheritanceDemand on interface */
3002 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3003 mono_secman_inheritancedemand_method (cm, im);
3006 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3007 mono_security_core_clr_check_override (class, cm, im);
3008 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
3011 MonoClass *ic = im->klass;
3012 const char *ic_name_space = ic->name_space;
3013 const char *ic_name = ic->name;
3016 if (! require_newslot) {
3017 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
3020 if (cm->klass->rank == 0) {
3021 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
3024 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
3025 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
3026 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3027 TRACE_INTERFACE_VTABLE (printf ("]"));
3030 if (mono_class_get_image (ic) != mono_defaults.corlib) {
3031 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
3034 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
3035 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
3038 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
3039 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
3043 subname = strstr (cm->name, ic_name_space);
3044 if (subname != cm->name) {
3045 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
3048 subname += strlen (ic_name_space);
3049 if (subname [0] != '.') {
3050 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
3054 if (strstr (subname, ic_name) != subname) {
3055 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
3058 subname += strlen (ic_name);
3059 if (subname [0] != '.') {
3060 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
3064 if (strcmp (subname, im->name) != 0) {
3065 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
3069 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
3070 /* CAS - SecurityAction.InheritanceDemand on interface */
3071 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3072 mono_secman_inheritancedemand_method (cm, im);
3075 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3076 mono_security_core_clr_check_override (class, cm, im);
3078 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
3083 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3085 foreach_override (gpointer key, gpointer value, gpointer user_data) {
3086 MonoMethod *method = key;
3087 MonoMethod *override = value;
3088 MonoClass *method_class = mono_method_get_class (method);
3089 MonoClass *override_class = mono_method_get_class (override);
3091 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
3092 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
3093 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
3096 print_overrides (GHashTable *override_map, const char *message) {
3098 printf ("Override map \"%s\" START:\n", message);
3099 g_hash_table_foreach (override_map, foreach_override, NULL);
3100 printf ("Override map \"%s\" END.\n", message);
3102 printf ("Override map \"%s\" EMPTY.\n", message);
3106 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
3107 char *full_name = mono_type_full_name (&class->byval_arg);
3111 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
3113 if (print_interfaces) {
3114 print_implemented_interfaces (class);
3115 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
3118 if (class->parent) {
3119 parent_size = class->parent->vtable_size;
3123 for (i = 0; i < size; ++i) {
3124 MonoMethod *cm = vtable [i];
3126 char *cm_name = mono_method_full_name (cm, TRUE);
3127 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
3128 printf (" [%c][%03d][INDEX %03d] %s\n", newness, i, cm->slot, cm_name);
3137 #if VERIFY_INTERFACE_VTABLE_CODE
3139 mono_method_try_get_vtable_index (MonoMethod *method)
3141 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3142 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3143 if (imethod->declaring->is_generic)
3144 return imethod->declaring->slot;
3146 return method->slot;
3150 mono_class_verify_vtable (MonoClass *class)
3153 char *full_name = mono_type_full_name (&class->byval_arg);
3155 printf ("*** Verifying VTable of class '%s' \n", full_name);
3159 if (!class->methods)
3162 for (i = 0; i < class->method.count; ++i) {
3163 MonoMethod *cm = class->methods [i];
3166 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
3170 full_name = mono_method_full_name (cm, TRUE);
3172 slot = mono_method_try_get_vtable_index (cm);
3174 if (slot >= class->vtable_size) {
3175 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
3179 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
3180 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3181 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3182 g_free (other_name);
3185 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3192 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3194 char *method_signature;
3197 for (index = 0; index < onum; ++index) {
3198 g_print (" at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
3199 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3201 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3202 type_name = mono_type_full_name (&class->byval_arg);
3203 printf ("no implementation for interface method %s::%s(%s) in class %s\n",
3204 mono_type_get_name (&ic->byval_arg), im->name, method_signature, type_name);
3205 g_free (method_signature);
3207 mono_class_setup_methods (class);
3208 for (index = 0; index < class->method.count; ++index) {
3209 MonoMethod *cm = class->methods [index];
3210 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3212 printf ("METHOD %s(%s)\n", cm->name, method_signature);
3213 g_free (method_signature);
3218 verify_class_overrides (MonoClass *class, MonoMethod **overrides, int onum)
3222 for (i = 0; i < onum; ++i) {
3223 MonoMethod *decl = overrides [i * 2];
3224 MonoMethod *body = overrides [i * 2 + 1];
3226 if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (class)) {
3227 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method belongs to a different class than the declared one"));
3231 if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
3232 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3233 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must not be static to override a base type"));
3235 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must be virtual to override a base type"));
3239 if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
3240 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3241 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a static method in a base type"));
3243 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a non virtual method in a base type"));
3247 if (!mono_class_is_assignable_from_slow (decl->klass, class)) {
3248 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method overrides a class or interface that extended or implemented by this type"));
3255 * LOCKING: this is supposed to be called with the loader lock held.
3258 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
3261 MonoMethod **vtable;
3262 int i, max_vtsize = 0, max_iid, cur_slot = 0;
3263 GPtrArray *ifaces = NULL;
3264 GHashTable *override_map = NULL;
3265 gboolean security_enabled = mono_is_security_manager_active ();
3267 gpointer class_iter;
3268 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3269 int first_non_interface_slot;
3271 GSList *virt_methods, *l;
3276 if (overrides && !verify_class_overrides (class, overrides, onum))
3279 ifaces = mono_class_get_implemented_interfaces (class);
3282 for (i = 0; i < ifaces->len; i++) {
3283 MonoClass *ic = g_ptr_array_index (ifaces, i);
3284 max_vtsize += ic->method.count;
3286 g_ptr_array_free (ifaces, TRUE);
3290 if (class->parent) {
3291 mono_class_init (class->parent);
3292 mono_class_setup_vtable (class->parent);
3293 max_vtsize += class->parent->vtable_size;
3294 cur_slot = class->parent->vtable_size;
3297 max_vtsize += class->method.count;
3299 vtable = alloca (sizeof (gpointer) * max_vtsize);
3300 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3302 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3304 cur_slot = setup_interface_offsets (class, cur_slot);
3305 max_iid = class->max_interface_id;
3306 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3308 /* Optimized version for generic instances */
3309 if (class->generic_class) {
3310 MonoClass *gklass = class->generic_class->container_class;
3313 mono_class_setup_vtable (gklass);
3314 if (gklass->exception_type != MONO_EXCEPTION_NONE) {
3315 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3319 tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * gklass->vtable_size);
3320 class->vtable_size = gklass->vtable_size;
3321 for (i = 0; i < gklass->vtable_size; ++i)
3322 if (gklass->vtable [i]) {
3323 tmp [i] = mono_class_inflate_generic_method_full (gklass->vtable [i], class, mono_class_get_context (class));
3324 tmp [i]->slot = gklass->vtable [i]->slot;
3326 mono_memory_barrier ();
3327 class->vtable = tmp;
3329 /* Have to set method->slot for abstract virtual methods */
3330 if (class->methods && gklass->methods) {
3331 for (i = 0; i < class->method.count; ++i)
3332 if (class->methods [i]->slot == -1)
3333 class->methods [i]->slot = gklass->methods [i]->slot;
3339 if (class->parent && class->parent->vtable_size) {
3340 MonoClass *parent = class->parent;
3343 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
3345 // Also inherit parent interface vtables, just as a starting point.
3346 // This is needed otherwise bug-77127.exe fails when the property methods
3347 // have different names in the iterface and the class, because for child
3348 // classes the ".override" information is not used anymore.
3349 for (i = 0; i < parent->interface_offsets_count; i++) {
3350 MonoClass *parent_interface = parent->interfaces_packed [i];
3351 int interface_offset = mono_class_interface_offset (class, parent_interface);
3352 /*FIXME this is now dead code as this condition will never hold true.
3353 Since interface offsets are inherited then the offset of an interface implemented
3354 by a parent will never be the out of it's vtable boundary.
3356 if (interface_offset >= parent->vtable_size) {
3357 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
3360 mono_class_setup_methods (parent_interface);
3361 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
3362 for (j = 0; j < parent_interface->method.count; j++) {
3363 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
3364 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
3365 parent_interface_offset + j, parent_interface_offset, j,
3366 interface_offset + j, interface_offset, j));
3373 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
3374 /* override interface methods */
3375 for (i = 0; i < onum; i++) {
3376 MonoMethod *decl = overrides [i*2];
3377 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
3379 dslot = mono_method_get_vtable_slot (decl);
3381 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3385 dslot += mono_class_interface_offset (class, decl->klass);
3386 vtable [dslot] = overrides [i*2 + 1];
3387 vtable [dslot]->slot = dslot;
3389 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3391 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
3393 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3394 mono_security_core_clr_check_override (class, vtable [dslot], decl);
3397 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
3398 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
3401 * Create a list of virtual methods to avoid calling
3402 * mono_class_get_virtual_methods () which is slow because of the metadata
3406 gpointer iter = NULL;
3409 virt_methods = NULL;
3410 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
3411 virt_methods = g_slist_prepend (virt_methods, cm);
3415 // Loop on all implemented interfaces...
3416 for (i = 0; i < class->interface_offsets_count; i++) {
3417 MonoClass *parent = class->parent;
3419 gboolean interface_is_explicitly_implemented_by_class;
3422 ic = class->interfaces_packed [i];
3423 ic_offset = mono_class_interface_offset (class, ic);
3425 mono_class_setup_methods (ic);
3427 // Check if this interface is explicitly implemented (instead of just inherited)
3428 if (parent != NULL) {
3429 int implemented_interfaces_index;
3430 interface_is_explicitly_implemented_by_class = FALSE;
3431 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
3432 if (ic == class->interfaces [implemented_interfaces_index]) {
3433 interface_is_explicitly_implemented_by_class = TRUE;
3438 interface_is_explicitly_implemented_by_class = TRUE;
3441 // Loop on all interface methods...
3442 for (im_index = 0; im_index < ic->method.count; im_index++) {
3443 MonoMethod *im = ic->methods [im_index];
3444 int im_slot = ic_offset + im->slot;
3445 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
3447 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3450 // If there is an explicit implementation, just use it right away,
3451 // otherwise look for a matching method
3452 if (override_im == NULL) {
3457 // First look for a suitable method among the class methods
3459 for (l = virt_methods; l; l = l->next) {
3461 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)));
3462 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
3463 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
3464 vtable [im_slot] = cm;
3465 /* Why do we need this? */
3470 TRACE_INTERFACE_VTABLE (printf ("\n"));
3471 if (class->exception_type) /*Might be set by check_interface_method_override*/
3475 // If the slot is still empty, look in all the inherited virtual methods...
3476 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
3477 MonoClass *parent = class->parent;
3478 // Reverse order, so that last added methods are preferred
3479 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
3480 MonoMethod *cm = parent->vtable [cm_index];
3482 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));
3483 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
3484 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
3485 vtable [im_slot] = cm;
3486 /* Why do we need this? */
3492 if (class->exception_type) /*Might be set by check_interface_method_override*/
3494 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
3498 g_assert (vtable [im_slot] == override_im);
3503 // If the class is not abstract, check that all its interface slots are full.
3504 // The check is done here and not directly at the end of the loop above because
3505 // it can happen (for injected generic array interfaces) that the same slot is
3506 // processed multiple times (those interfaces have overlapping slots), and it
3507 // will not always be the first pass the one that fills the slot.
3508 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3509 for (i = 0; i < class->interface_offsets_count; i++) {
3513 ic = class->interfaces_packed [i];
3514 ic_offset = mono_class_interface_offset (class, ic);
3516 for (im_index = 0; im_index < ic->method.count; im_index++) {
3517 MonoMethod *im = ic->methods [im_index];
3518 int im_slot = ic_offset + im->slot;
3520 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3523 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
3524 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
3525 if (vtable [im_slot] == NULL) {
3526 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
3527 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3529 g_hash_table_destroy (override_map);
3536 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
3538 for (l = virt_methods; l; l = l->next) {
3541 * If the method is REUSE_SLOT, we must check in the
3542 * base class for a method to override.
3544 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3546 for (k = class->parent; k ; k = k->parent) {
3551 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
3552 MonoMethodSignature *cmsig, *m1sig;
3554 cmsig = mono_method_signature (cm);
3555 m1sig = mono_method_signature (m1);
3557 if (!cmsig || !m1sig) {
3558 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3562 if (!strcmp(cm->name, m1->name) &&
3563 mono_metadata_signature_equal (cmsig, m1sig)) {
3565 /* CAS - SecurityAction.InheritanceDemand */
3566 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3567 mono_secman_inheritancedemand_method (cm, m1);
3570 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3571 mono_security_core_clr_check_override (class, cm, m1);
3573 slot = mono_method_get_vtable_slot (m1);
3575 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3579 g_assert (cm->slot < max_vtsize);
3581 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3582 g_hash_table_insert (override_map, m1, cm);
3593 /*Non final newslot methods must be given a non-interface vtable slot*/
3594 if ((cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && !(cm->flags & METHOD_ATTRIBUTE_FINAL) && cm->slot >= 0)
3598 cm->slot = cur_slot++;
3600 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
3601 vtable [cm->slot] = cm;
3604 /* override non interface methods */
3605 for (i = 0; i < onum; i++) {
3606 MonoMethod *decl = overrides [i*2];
3607 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
3608 g_assert (decl->slot != -1);
3609 vtable [decl->slot] = overrides [i*2 + 1];
3610 overrides [i * 2 + 1]->slot = decl->slot;
3612 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3613 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
3615 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3616 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
3621 * If a method occupies more than one place in the vtable, and it is
3622 * overriden, then change the other occurances too.
3625 for (i = 0; i < max_vtsize; ++i)
3627 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
3632 g_hash_table_destroy (override_map);
3635 g_slist_free (virt_methods);
3637 /* Ensure that all vtable slots are filled with concrete instance methods */
3638 if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3639 for (i = 0; i < cur_slot; ++i) {
3640 if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
3641 char *type_name = mono_type_get_full_name (class);
3642 char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
3643 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));
3645 g_free (method_name);
3651 if (class->generic_class) {
3652 MonoClass *gklass = class->generic_class->container_class;
3654 mono_class_init (gklass);
3656 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
3658 /* Check that the vtable_size value computed in mono_class_init () is correct */
3659 if (class->vtable_size)
3660 g_assert (cur_slot == class->vtable_size);
3661 class->vtable_size = cur_slot;
3664 /* Try to share the vtable with our parent. */
3665 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
3666 mono_memory_barrier ();
3667 class->vtable = class->parent->vtable;
3669 MonoMethod **tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * class->vtable_size);
3670 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
3671 mono_memory_barrier ();
3672 class->vtable = tmp;
3675 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
3676 if (mono_print_vtable) {
3679 print_implemented_interfaces (class);
3681 for (i = 0; i <= max_iid; i++)
3682 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
3685 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
3686 class->vtable_size, icount);
3688 for (i = 0; i < cur_slot; ++i) {
3693 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
3694 mono_method_full_name (cm, TRUE));
3700 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
3701 class->name, max_iid);
3703 for (i = 0; i < class->interface_count; i++) {
3704 ic = class->interfaces [i];
3705 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
3706 mono_class_interface_offset (class, ic),
3707 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
3710 for (k = class->parent; k ; k = k->parent) {
3711 for (i = 0; i < k->interface_count; i++) {
3712 ic = k->interfaces [i];
3713 printf (" parent slot offset: %03d, method count: %03d, iid: %03d %s\n",
3714 mono_class_interface_offset (class, ic),
3715 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
3721 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
3725 * mono_method_get_vtable_slot:
3727 * Returns method->slot, computing it if neccesary. Return -1 on failure.
3728 * LOCKING: Acquires the loader lock.
3730 * FIXME Use proper MonoError machinery here.
3733 mono_method_get_vtable_slot (MonoMethod *method)
3735 if (method->slot == -1) {
3736 mono_class_setup_vtable (method->klass);
3737 if (method->klass->exception_type)
3739 g_assert (method->slot != -1);
3741 return method->slot;
3745 * mono_method_get_vtable_index:
3748 * Returns the index into the runtime vtable to access the method or,
3749 * in the case of a virtual generic method, the virtual generic method
3750 * thunk. Returns -1 on failure.
3752 * FIXME Use proper MonoError machinery here.
3755 mono_method_get_vtable_index (MonoMethod *method)
3757 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3758 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3759 if (imethod->declaring->is_generic)
3760 return mono_method_get_vtable_slot (imethod->declaring);
3762 return mono_method_get_vtable_slot (method);
3765 static MonoMethod *default_ghc = NULL;
3766 static MonoMethod *default_finalize = NULL;
3767 static int finalize_slot = -1;
3768 static int ghc_slot = -1;
3771 initialize_object_slots (MonoClass *class)
3776 if (class == mono_defaults.object_class) {
3777 mono_class_setup_vtable (class);
3778 for (i = 0; i < class->vtable_size; ++i) {
3779 MonoMethod *cm = class->vtable [i];
3781 if (!strcmp (cm->name, "GetHashCode"))
3783 else if (!strcmp (cm->name, "Finalize"))
3787 g_assert (ghc_slot > 0);
3788 default_ghc = class->vtable [ghc_slot];
3790 g_assert (finalize_slot > 0);
3791 default_finalize = class->vtable [finalize_slot];
3796 MonoMethod *array_method;
3798 } GenericArrayMethodInfo;
3800 static int generic_array_method_num = 0;
3801 static GenericArrayMethodInfo *generic_array_method_info = NULL;
3804 generic_array_methods (MonoClass *class)
3806 int i, count_generic = 0;
3807 GList *list = NULL, *tmp;
3808 if (generic_array_method_num)
3809 return generic_array_method_num;
3810 mono_class_setup_methods (class->parent);
3811 for (i = 0; i < class->parent->method.count; i++) {
3812 MonoMethod *m = class->parent->methods [i];
3813 if (!strncmp (m->name, "InternalArray__", 15)) {
3815 list = g_list_prepend (list, m);
3818 list = g_list_reverse (list);
3819 generic_array_method_info = g_malloc (sizeof (GenericArrayMethodInfo) * count_generic);
3821 for (tmp = list; tmp; tmp = tmp->next) {
3822 const char *mname, *iname;
3824 MonoMethod *m = tmp->data;
3825 generic_array_method_info [i].array_method = m;
3826 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
3827 iname = "System.Collections.Generic.ICollection`1.";
3828 mname = m->name + 27;
3829 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
3830 iname = "System.Collections.Generic.IEnumerable`1.";
3831 mname = m->name + 27;
3832 } else if (!strncmp (m->name, "InternalArray__", 15)) {
3833 iname = "System.Collections.Generic.IList`1.";
3834 mname = m->name + 15;
3836 g_assert_not_reached ();
3839 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
3840 strcpy (name, iname);
3841 strcpy (name + strlen (iname), mname);
3842 generic_array_method_info [i].name = name;
3845 /*g_print ("array generic methods: %d\n", count_generic);*/
3847 generic_array_method_num = count_generic;
3849 return generic_array_method_num;
3853 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
3855 MonoGenericContext tmp_context;
3858 tmp_context.class_inst = NULL;
3859 tmp_context.method_inst = iface->generic_class->context.class_inst;
3860 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
3862 for (i = 0; i < generic_array_method_num; i++) {
3863 MonoMethod *m = generic_array_method_info [i].array_method;
3864 MonoMethod *inflated;
3866 inflated = mono_class_inflate_generic_method (m, &tmp_context);
3867 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
3872 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
3874 int len = strlen (s1) + strlen (s2) + 2;
3875 char *s = mono_image_alloc (image, len);
3878 result = g_snprintf (s, len, "%s%c%s", s1, '\0', s2);
3879 g_assert (result == len - 1);
3885 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
3887 gpointer exception_data = NULL;
3889 switch (error->exception_type) {
3890 case MONO_EXCEPTION_TYPE_LOAD:
3891 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
3894 case MONO_EXCEPTION_MISSING_METHOD:
3895 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
3898 case MONO_EXCEPTION_MISSING_FIELD: {
3899 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
3900 const char *class_name;
3903 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
3905 class_name = error->klass->name;
3907 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
3910 g_free ((void*)class_name);
3914 case MONO_EXCEPTION_FILE_NOT_FOUND: {
3917 if (error->ref_only)
3918 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.";
3920 msg = "Could not load file or assembly '%s' or one of its dependencies.";
3922 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
3926 case MONO_EXCEPTION_BAD_IMAGE:
3927 exception_data = error->msg;
3931 g_assert_not_reached ();
3934 mono_class_set_failure (class, error->exception_type, exception_data);
3939 * @class: the class to initialize
3941 * Compute the instance_size, class_size and other infos that cannot be
3942 * computed at mono_class_get() time. Also compute vtable_size if possible.
3943 * Returns TRUE on success or FALSE if there was a problem in loading
3944 * the type (incorrect assemblies, missing assemblies, methods, etc).
3946 * LOCKING: Acquires the loader lock.
3949 mono_class_init (MonoClass *class)
3952 MonoCachedClassInfo cached_info;
3953 gboolean has_cached_info;
3954 int class_init_ok = TRUE;
3958 /* Double-checking locking pattern */
3960 return class->exception_type == MONO_EXCEPTION_NONE;
3962 /*g_print ("Init class %s\n", class->name);*/
3964 /* We do everything inside the lock to prevent races */
3965 mono_loader_lock ();
3967 if (class->inited) {
3968 mono_loader_unlock ();
3969 /* Somebody might have gotten in before us */
3970 return class->exception_type == MONO_EXCEPTION_NONE;
3973 if (class->init_pending) {
3974 mono_loader_unlock ();
3975 /* this indicates a cyclic dependency */
3976 g_error ("pending init %s.%s\n", class->name_space, class->name);
3979 class->init_pending = 1;
3981 if (class->byval_arg.type == MONO_TYPE_ARRAY || class->byval_arg.type == MONO_TYPE_SZARRAY) {
3982 MonoClass *element_class = class->element_class;
3983 if (!element_class->inited)
3984 mono_class_init (element_class);
3985 if (element_class->exception_type != MONO_EXCEPTION_NONE) {
3986 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3991 /* CAS - SecurityAction.InheritanceDemand */
3992 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
3993 mono_secman_inheritancedemand_class (class, class->parent);
3996 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3997 mono_security_core_clr_check_inheritance (class);
3999 mono_stats.initialized_class_count++;
4001 if (class->generic_class && !class->generic_class->is_dynamic) {
4002 MonoClass *gklass = class->generic_class->container_class;
4004 mono_stats.generic_class_count++;
4006 class->method = gklass->method;
4007 class->field = gklass->field;
4009 mono_class_init (gklass);
4010 // FIXME: Why is this needed ?
4011 mono_class_setup_methods (gklass);
4013 if (MONO_CLASS_IS_INTERFACE (class))
4014 class->interface_id = mono_get_unique_iid (class);
4017 if (class->parent && !class->parent->inited)
4018 mono_class_init (class->parent);
4020 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
4022 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
4023 class->nested_classes_inited = TRUE;
4026 * Computes the size used by the fields, and their locations
4028 if (has_cached_info) {
4029 class->instance_size = cached_info.instance_size;
4030 class->sizes.class_size = cached_info.class_size;
4031 class->packing_size = cached_info.packing_size;
4032 class->min_align = cached_info.min_align;
4033 class->blittable = cached_info.blittable;
4034 class->has_references = cached_info.has_references;
4035 class->has_static_refs = cached_info.has_static_refs;
4036 class->no_special_static_fields = cached_info.no_special_static_fields;
4039 if (!class->size_inited){
4040 mono_class_setup_fields (class);
4041 if (class->exception_type || mono_loader_get_last_error ()){
4042 class_init_ok = FALSE;
4047 /* Initialize arrays */
4049 class->method.count = 3 + (class->rank > 1? 2: 1);
4051 if (class->interface_count) {
4052 int count_generic = generic_array_methods (class);
4053 class->method.count += class->interface_count * count_generic;
4057 mono_class_setup_supertypes (class);
4060 initialize_object_slots (class);
4063 * Initialize the rest of the data without creating a generic vtable if possible.
4064 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
4065 * also avoid computing a generic vtable.
4067 if (has_cached_info) {
4069 class->vtable_size = cached_info.vtable_size;
4070 class->has_finalize = cached_info.has_finalize;
4071 class->ghcimpl = cached_info.ghcimpl;
4072 class->has_cctor = cached_info.has_cctor;
4073 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
4074 static int szarray_vtable_size = 0;
4077 if (!szarray_vtable_size) {
4078 mono_class_setup_vtable (class);
4079 szarray_vtable_size = class->vtable_size;
4081 class->vtable_size = szarray_vtable_size;
4083 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
4084 MonoClass *gklass = class->generic_class->container_class;
4086 /* Generic instance case */
4087 class->ghcimpl = gklass->ghcimpl;
4088 class->has_finalize = gklass->has_finalize;
4089 class->has_cctor = gklass->has_cctor;
4091 mono_class_setup_vtable (gklass);
4092 if (gklass->exception_type) {
4093 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4097 class->vtable_size = gklass->vtable_size;
4101 /* ghcimpl is not currently used
4103 if (class->parent) {
4104 MonoMethod *cmethod = class->vtable [ghc_slot];
4105 if (cmethod->is_inflated)
4106 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4107 if (cmethod == default_ghc) {
4113 /* Interfaces and valuetypes are not supposed to have finalizers */
4114 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
4115 MonoMethod *cmethod = NULL;
4117 if (class->parent && class->parent->has_finalize) {
4118 class->has_finalize = 1;
4120 if (class->type_token) {
4121 cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
4122 } else if (class->parent) {
4123 /* FIXME: Optimize this */
4124 mono_class_setup_vtable (class);
4125 if (class->exception_type || mono_loader_get_last_error ())
4127 cmethod = class->vtable [finalize_slot];
4131 /* Check that this is really the finalizer method */
4132 mono_class_setup_vtable (class);
4133 if (class->exception_type || mono_loader_get_last_error ())
4136 class->has_finalize = 0;
4137 if (class->parent) {
4138 cmethod = class->vtable [finalize_slot];
4139 if (cmethod->is_inflated)
4140 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4141 if (cmethod != default_finalize) {
4142 class->has_finalize = 1;
4149 /* C# doesn't allow interfaces to have cctors */
4150 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
4151 MonoMethod *cmethod = NULL;
4153 if (class->type_token) {
4154 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
4155 /* The find_method function ignores the 'flags' argument */
4156 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
4157 class->has_cctor = 1;
4159 mono_class_setup_methods (class);
4161 for (i = 0; i < class->method.count; ++i) {
4162 MonoMethod *method = class->methods [i];
4163 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4164 (strcmp (".cctor", method->name) == 0)) {
4165 class->has_cctor = 1;
4173 if (!mono_setup_vtable_in_class_init) {
4175 * This is an embedding API break, since the caller might assume that
4176 * mono_class_init () constructs a generic vtable, so vtable construction errors
4177 * are visible right after the mono_class_init (), and not after
4178 * mono_class_vtable ().
4180 if (class->parent) {
4181 /* This will compute class->parent->vtable_size for some classes */
4182 mono_class_init (class->parent);
4183 if (class->parent->exception_type) {
4184 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4187 if (mono_loader_get_last_error ())
4189 if (!class->parent->vtable_size) {
4190 /* FIXME: Get rid of this somehow */
4191 mono_class_setup_vtable (class->parent);
4192 if (class->parent->exception_type) {
4193 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4196 if (mono_loader_get_last_error ())
4199 setup_interface_offsets (class, class->parent->vtable_size);
4201 setup_interface_offsets (class, 0);
4204 mono_class_setup_vtable (class);
4206 if (MONO_CLASS_IS_INTERFACE (class))
4207 setup_interface_offsets (class, 0);
4210 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
4211 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
4212 class_init_ok = FALSE;
4218 class_init_ok = FALSE;
4221 /* Because of the double-checking locking pattern */
4222 mono_memory_barrier ();
4224 class->init_pending = 0;
4226 if (mono_loader_get_last_error ()) {
4227 if (class->exception_type == MONO_EXCEPTION_NONE)
4228 set_failure_from_loader_error (class, mono_loader_get_last_error ());
4230 mono_loader_clear_error ();
4233 mono_loader_unlock ();
4235 if (mono_debugger_class_init_func)
4236 mono_debugger_class_init_func (class);
4238 return class_init_ok;
4242 is_corlib_image (MonoImage *image)
4244 /* FIXME: allow the dynamic case for our compilers and with full trust */
4246 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
4248 return image == mono_defaults.corlib;
4252 * LOCKING: this assumes the loader lock is held
4255 mono_class_setup_mono_type (MonoClass *class)
4257 const char *name = class->name;
4258 const char *nspace = class->name_space;
4259 gboolean is_corlib = is_corlib_image (class->image);
4261 class->this_arg.byref = 1;
4262 class->this_arg.data.klass = class;
4263 class->this_arg.type = MONO_TYPE_CLASS;
4264 class->byval_arg.data.klass = class;
4265 class->byval_arg.type = MONO_TYPE_CLASS;
4267 if (is_corlib && !strcmp (nspace, "System")) {
4268 if (!strcmp (name, "ValueType")) {
4270 * do not set the valuetype bit for System.ValueType.
4271 * class->valuetype = 1;
4273 class->blittable = TRUE;
4274 } else if (!strcmp (name, "Enum")) {
4276 * do not set the valuetype bit for System.Enum.
4277 * class->valuetype = 1;
4279 class->valuetype = 0;
4280 class->enumtype = 0;
4281 } else if (!strcmp (name, "Object")) {
4282 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
4283 } else if (!strcmp (name, "String")) {
4284 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
4285 } else if (!strcmp (name, "TypedReference")) {
4286 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
4290 if (class->valuetype) {
4291 int t = MONO_TYPE_VALUETYPE;
4293 if (is_corlib && !strcmp (nspace, "System")) {
4296 if (!strcmp (name, "Boolean")) {
4297 t = MONO_TYPE_BOOLEAN;
4298 } else if (!strcmp(name, "Byte")) {
4300 class->blittable = TRUE;
4304 if (!strcmp (name, "Char")) {
4309 if (!strcmp (name, "Double")) {
4311 class->blittable = TRUE;
4315 if (!strcmp (name, "Int32")) {
4317 class->blittable = TRUE;
4318 } else if (!strcmp(name, "Int16")) {
4320 class->blittable = TRUE;
4321 } else if (!strcmp(name, "Int64")) {
4323 class->blittable = TRUE;
4324 } else if (!strcmp(name, "IntPtr")) {
4326 class->blittable = TRUE;
4330 if (!strcmp (name, "Single")) {
4332 class->blittable = TRUE;
4333 } else if (!strcmp(name, "SByte")) {
4335 class->blittable = TRUE;
4339 if (!strcmp (name, "UInt32")) {
4341 class->blittable = TRUE;
4342 } else if (!strcmp(name, "UInt16")) {
4344 class->blittable = TRUE;
4345 } else if (!strcmp(name, "UInt64")) {
4347 class->blittable = TRUE;
4348 } else if (!strcmp(name, "UIntPtr")) {
4350 class->blittable = TRUE;
4354 if (!strcmp (name, "TypedReference")) {
4355 t = MONO_TYPE_TYPEDBYREF;
4356 class->blittable = TRUE;
4360 if (!strcmp (name, "Void")) {
4368 class->this_arg.type = class->byval_arg.type = t;
4371 if (MONO_CLASS_IS_INTERFACE (class))
4372 class->interface_id = mono_get_unique_iid (class);
4377 * COM initialization (using mono_init_com_types) is delayed until needed.
4378 * However when a [ComImport] attribute is present on a type it will trigger
4379 * the initialization. This is not a problem unless the BCL being executed
4380 * lacks the types that COM depends on (e.g. Variant on Silverlight).
4383 init_com_from_comimport (MonoClass *class)
4385 /* we don't always allow COM initialization under the CoreCLR (e.g. Moonlight does not require it) */
4386 if ((mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)) {
4387 /* but some other CoreCLR user could requires it for their platform (i.e. trusted) code */
4388 if (!mono_security_core_clr_determine_platform_image (class->image)) {
4389 /* but it can not be made available for application (i.e. user code) since all COM calls
4390 * are considered native calls. In this case we fail with a TypeLoadException (just like
4391 * Silverlight 2 does */
4392 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4396 /* FIXME : we should add an extra checks to ensure COM can be initialized properly before continuing */
4397 mono_init_com_types ();
4401 * LOCKING: this assumes the loader lock is held
4404 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
4406 gboolean system_namespace;
4407 gboolean is_corlib = is_corlib_image (class->image);
4409 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
4411 /* if root of the hierarchy */
4412 if (system_namespace && !strcmp (class->name, "Object")) {
4413 class->parent = NULL;
4414 class->instance_size = sizeof (MonoObject);
4417 if (!strcmp (class->name, "<Module>")) {
4418 class->parent = NULL;
4419 class->instance_size = 0;
4423 if (!MONO_CLASS_IS_INTERFACE (class)) {
4424 /* Imported COM Objects always derive from __ComObject. */
4425 if (MONO_CLASS_IS_IMPORT (class)) {
4426 init_com_from_comimport (class);
4427 if (parent == mono_defaults.object_class)
4428 parent = mono_defaults.com_object_class;
4431 /* set the parent to something useful and safe, but mark the type as broken */
4432 parent = mono_defaults.object_class;
4433 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4436 class->parent = parent;
4438 if (parent->generic_class && !parent->name) {
4440 * If the parent is a generic instance, we may get
4441 * called before it is fully initialized, especially
4442 * before it has its name.
4447 class->marshalbyref = parent->marshalbyref;
4448 class->contextbound = parent->contextbound;
4449 class->delegate = parent->delegate;
4450 if (MONO_CLASS_IS_IMPORT (class))
4451 class->is_com_object = 1;
4453 class->is_com_object = parent->is_com_object;
4455 if (system_namespace) {
4456 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
4457 class->marshalbyref = 1;
4459 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
4460 class->contextbound = 1;
4462 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
4463 class->delegate = 1;
4466 if (class->parent->enumtype || (is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
4467 (strcmp (class->parent->name_space, "System") == 0)))
4468 class->valuetype = 1;
4469 if (is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
4470 class->valuetype = class->enumtype = 1;
4472 /*class->enumtype = class->parent->enumtype; */
4473 mono_class_setup_supertypes (class);
4475 /* initialize com types if COM interfaces are present */
4476 if (MONO_CLASS_IS_IMPORT (class))
4477 init_com_from_comimport (class);
4478 class->parent = NULL;
4484 * mono_class_setup_supertypes:
4487 * Build the data structure needed to make fast type checks work.
4488 * This currently sets two fields in @class:
4489 * - idepth: distance between @class and System.Object in the type
4491 * - supertypes: array of classes: each element has a class in the hierarchy
4492 * starting from @class up to System.Object
4494 * LOCKING: this assumes the loader lock is held
4497 mono_class_setup_supertypes (MonoClass *class)
4501 if (class->supertypes)
4504 if (class->parent && !class->parent->supertypes)
4505 mono_class_setup_supertypes (class->parent);
4507 class->idepth = class->parent->idepth + 1;
4511 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
4512 class->supertypes = mono_image_alloc0 (class->image, sizeof (MonoClass *) * ms);
4514 if (class->parent) {
4515 class->supertypes [class->idepth - 1] = class;
4516 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
4518 class->supertypes [0] = class;
4523 * mono_class_create_from_typedef:
4524 * @image: image where the token is valid
4525 * @type_token: typedef token
4527 * Create the MonoClass* representing the specified type token.
4528 * @type_token must be a TypeDef token.
4531 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
4533 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
4534 MonoClass *class, *parent = NULL;
4535 guint32 cols [MONO_TYPEDEF_SIZE];
4536 guint32 cols_next [MONO_TYPEDEF_SIZE];
4537 guint tidx = mono_metadata_token_index (type_token);
4538 MonoGenericContext *context = NULL;
4539 const char *name, *nspace;
4541 MonoClass **interfaces;
4542 guint32 field_last, method_last;
4543 guint32 nesting_tokeen;
4545 if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || tidx > tt->rows)
4548 mono_loader_lock ();
4550 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
4551 mono_loader_unlock ();
4555 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
4557 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
4558 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
4560 class = mono_image_alloc0 (image, sizeof (MonoClass));
4563 class->name_space = nspace;
4565 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4567 class->image = image;
4568 class->type_token = type_token;
4569 class->flags = cols [MONO_TYPEDEF_FLAGS];
4571 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
4573 classes_size += sizeof (MonoClass);
4576 * Check whether we're a generic type definition.
4578 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
4579 if (class->generic_container) {
4580 class->is_generic = 1;
4581 class->generic_container->owner.klass = class;
4582 context = &class->generic_container->context;
4585 if (cols [MONO_TYPEDEF_EXTENDS]) {
4586 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
4588 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
4589 /*WARNING: this must satisfy mono_metadata_type_hash*/
4590 class->this_arg.byref = 1;
4591 class->this_arg.data.klass = class;
4592 class->this_arg.type = MONO_TYPE_CLASS;
4593 class->byval_arg.data.klass = class;
4594 class->byval_arg.type = MONO_TYPE_CLASS;
4596 parent = mono_class_get_full (image, parent_token, context);
4598 if (parent == NULL){
4599 mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
4600 mono_loader_unlock ();
4601 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4606 /* do this early so it's available for interfaces in setup_mono_type () */
4607 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token))) {
4608 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
4609 if (!class->nested_in) {
4610 mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
4611 mono_loader_unlock ();
4612 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4617 mono_class_setup_parent (class, parent);
4619 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
4620 mono_class_setup_mono_type (class);
4622 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
4626 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
4630 class->cast_class = class->element_class = class;
4632 if (!class->enumtype) {
4633 if (!mono_metadata_interfaces_from_typedef_full (
4634 image, type_token, &interfaces, &icount, FALSE, context)){
4635 mono_loader_unlock ();
4636 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4640 class->interfaces = interfaces;
4641 class->interface_count = icount;
4642 class->interfaces_inited = 1;
4645 /*g_print ("Load class %s\n", name);*/
4648 * Compute the field and method lists
4650 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
4651 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
4653 if (tt->rows > tidx){
4654 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
4655 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
4656 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
4658 field_last = image->tables [MONO_TABLE_FIELD].rows;
4659 method_last = image->tables [MONO_TABLE_METHOD].rows;
4662 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
4663 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
4664 class->field.count = field_last - class->field.first;
4666 class->field.count = 0;
4668 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
4669 class->method.count = method_last - class->method.first;
4671 class->method.count = 0;
4673 /* reserve space to store vector pointer in arrays */
4674 if (is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
4675 class->instance_size += 2 * sizeof (gpointer);
4676 g_assert (class->field.count == 0);
4679 if (class->enumtype) {
4680 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
4681 if (!enum_basetype) {
4682 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4683 mono_loader_unlock ();
4684 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4687 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
4691 * If we're a generic type definition, load the constraints.
4692 * We must do this after the class has been constructed to make certain recursive scenarios
4695 if (class->generic_container && !mono_metadata_load_generic_param_constraints_full (image, type_token, class->generic_container)){
4696 char *class_name = g_strdup_printf("%s.%s", class->name_space, class->name);
4697 char *error = concat_two_strings_with_zero (class->image, class_name, class->image->assembly_name);
4698 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, error);
4699 g_free (class_name);
4700 mono_loader_unlock ();
4701 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4705 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
4706 if (!strncmp (name, "Vector", 6))
4707 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");
4710 mono_loader_unlock ();
4712 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4717 /** is klass Nullable<T>? */
4719 mono_class_is_nullable (MonoClass *klass)
4721 return klass->generic_class != NULL &&
4722 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
4726 /** if klass is T? return T */
4728 mono_class_get_nullable_param (MonoClass *klass)
4730 g_assert (mono_class_is_nullable (klass));
4731 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4735 * Create the `MonoClass' for an instantiation of a generic type.
4736 * We only do this if we actually need it.
4739 mono_generic_class_get_class (MonoGenericClass *gclass)
4741 MonoClass *klass, *gklass;
4743 mono_loader_lock ();
4744 if (gclass->cached_class) {
4745 mono_loader_unlock ();
4746 return gclass->cached_class;
4749 gclass->cached_class = g_malloc0 (sizeof (MonoClass));
4750 klass = gclass->cached_class;
4752 gklass = gclass->container_class;
4754 if (gklass->nested_in) {
4756 * FIXME: the nested type context should include everything the
4757 * nesting context should have, but it may also have additional
4758 * generic parameters...
4760 klass->nested_in = mono_class_inflate_generic_class (gklass->nested_in,
4761 mono_generic_class_get_context (gclass));
4764 klass->name = gklass->name;
4765 klass->name_space = gklass->name_space;
4767 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4769 klass->image = gklass->image;
4770 klass->flags = gklass->flags;
4771 klass->type_token = gklass->type_token;
4772 klass->field.count = gklass->field.count;
4774 klass->is_inflated = 1;
4775 klass->generic_class = gclass;
4777 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
4778 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
4779 klass->this_arg.byref = TRUE;
4780 klass->enumtype = gklass->enumtype;
4781 klass->valuetype = gklass->valuetype;
4783 klass->cast_class = klass->element_class = klass;
4785 if (mono_class_is_nullable (klass))
4786 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
4789 * We're not interested in the nested classes of a generic instance.
4790 * We use the generic type definition to look for nested classes.
4793 if (gklass->parent) {
4794 klass->parent = mono_class_inflate_generic_class (gklass->parent, mono_generic_class_get_context (gclass));
4798 mono_class_setup_parent (klass, klass->parent);
4800 if (klass->enumtype) {
4801 klass->cast_class = gklass->cast_class;
4802 klass->element_class = gklass->element_class;
4805 if (gclass->is_dynamic) {
4808 mono_class_setup_supertypes (klass);
4810 if (klass->enumtype) {
4812 * For enums, gklass->fields might not been set, but instance_size etc. is
4813 * already set in mono_reflection_create_internal_class (). For non-enums,
4814 * these will be computed normally in mono_class_layout_fields ().
4816 klass->instance_size = gklass->instance_size;
4817 klass->sizes.class_size = gklass->sizes.class_size;
4818 klass->size_inited = 1;
4822 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4824 inflated_classes ++;
4825 inflated_classes_size += sizeof (MonoClass);
4827 mono_loader_unlock ();
4833 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
4835 MonoClass *klass, **ptr;
4837 MonoGenericContainer *container = mono_generic_param_owner (param);
4841 image = mono_defaults.corlib;
4843 klass = mono_image_alloc0 (image, sizeof (MonoClass));
4844 classes_size += sizeof (MonoClass);
4847 klass->name = pinfo->name;
4849 int n = mono_generic_param_num (param);
4850 klass->name = mono_image_alloc0 (image, 16);
4851 sprintf ((char*)klass->name, "%d", n);
4856 MonoMethod *omethod = container->owner.method;
4857 klass->name_space = (omethod && omethod->klass) ? omethod->klass->name_space : "";
4859 MonoClass *oklass = container->owner.klass;
4860 klass->name_space = oklass ? oklass->name_space : "";
4863 klass->name_space = "";
4866 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4870 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
4874 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
4875 klass->parent = pinfo->constraints [0];
4877 } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
4878 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
4880 klass->parent = mono_defaults.object_class;
4883 if (count - pos > 0) {
4884 klass->interface_count = count - pos;
4885 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
4886 for (i = pos; i < count; i++)
4887 klass->interfaces [i - pos] = pinfo->constraints [i];
4890 klass->image = image;
4892 klass->inited = TRUE;
4893 klass->cast_class = klass->element_class = klass;
4894 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
4896 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
4897 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
4898 klass->this_arg.byref = TRUE;
4900 /* FIXME: shouldn't this be ->type_token? */
4901 klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
4903 mono_class_setup_supertypes (klass);
4908 #define FAST_CACHE_SIZE 1024
4909 static MonoClass *var_cache_fast [FAST_CACHE_SIZE];
4910 static MonoClass *mvar_cache_fast [FAST_CACHE_SIZE];
4911 static GHashTable *var_cache_slow;
4912 static GHashTable *mvar_cache_slow;
4915 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
4917 int n = mono_generic_param_num (param);
4920 if (n < FAST_CACHE_SIZE)
4921 return (is_mvar ? mvar_cache_fast : var_cache_fast) [n];
4922 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4923 return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
4927 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
4929 int n = mono_generic_param_num (param);
4932 if (n < FAST_CACHE_SIZE) {
4933 (is_mvar ? mvar_cache_fast : var_cache_fast) [n] = klass;
4936 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4938 ht = g_hash_table_new (NULL, NULL);
4940 mvar_cache_slow = ht;
4942 var_cache_slow = ht;
4945 g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
4949 * LOCKING: Acquires the loader lock.
4952 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
4954 MonoGenericContainer *container = mono_generic_param_owner (param);
4955 MonoGenericParamInfo *pinfo;
4958 mono_loader_lock ();
4961 pinfo = mono_generic_param_info (param);
4962 if (pinfo->pklass) {
4963 mono_loader_unlock ();
4964 return pinfo->pklass;
4970 klass = get_anon_gparam_class (param, is_mvar);
4972 mono_loader_unlock ();
4977 if (!image && container) {
4979 MonoMethod *method = container->owner.method;
4980 image = (method && method->klass) ? method->klass->image : NULL;
4982 MonoClass *klass = container->owner.klass;
4983 // FIXME: 'klass' should not be null
4984 // But, monodis creates GenericContainers without associating a owner to it
4985 image = klass ? klass->image : NULL;
4989 klass = make_generic_param_class (param, image, is_mvar, pinfo);
4991 mono_memory_barrier ();
4994 pinfo->pklass = klass;
4996 set_anon_gparam_class (param, is_mvar, klass);
4998 mono_loader_unlock ();
5000 /* FIXME: Should this go inside 'make_generic_param_klass'? */
5001 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
5007 mono_ptr_class_get (MonoType *type)
5010 MonoClass *el_class;
5014 el_class = mono_class_from_mono_type (type);
5015 image = el_class->image;
5017 mono_loader_lock ();
5019 if (!image->ptr_cache)
5020 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5022 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
5023 mono_loader_unlock ();
5026 result = mono_image_alloc0 (image, sizeof (MonoClass));
5028 classes_size += sizeof (MonoClass);
5030 result->parent = NULL; /* no parent for PTR types */
5031 result->name_space = el_class->name_space;
5032 name = g_strdup_printf ("%s*", el_class->name);
5033 result->name = mono_image_strdup (image, name);
5036 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5038 result->image = el_class->image;
5039 result->inited = TRUE;
5040 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5041 /* Can pointers get boxed? */
5042 result->instance_size = sizeof (gpointer);
5043 result->cast_class = result->element_class = el_class;
5044 result->blittable = TRUE;
5046 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
5047 result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
5048 result->this_arg.byref = TRUE;
5050 mono_class_setup_supertypes (result);
5052 g_hash_table_insert (image->ptr_cache, el_class, result);
5054 mono_loader_unlock ();
5056 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5062 mono_fnptr_class_get (MonoMethodSignature *sig)
5065 static GHashTable *ptr_hash = NULL;
5067 /* FIXME: These should be allocate from a mempool as well, but which one ? */
5069 mono_loader_lock ();
5072 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5074 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
5075 mono_loader_unlock ();
5078 result = g_new0 (MonoClass, 1);
5080 result->parent = NULL; /* no parent for PTR types */
5081 result->name_space = "System";
5082 result->name = "MonoFNPtrFakeClass";
5084 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5086 result->image = mono_defaults.corlib; /* need to fix... */
5087 result->inited = TRUE;
5088 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
5089 /* Can pointers get boxed? */
5090 result->instance_size = sizeof (gpointer);
5091 result->cast_class = result->element_class = result;
5092 result->blittable = TRUE;
5094 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
5095 result->this_arg.data.method = result->byval_arg.data.method = sig;
5096 result->this_arg.byref = TRUE;
5097 result->blittable = TRUE;
5099 mono_class_setup_supertypes (result);
5101 g_hash_table_insert (ptr_hash, sig, result);
5103 mono_loader_unlock ();
5105 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5111 mono_class_from_mono_type (MonoType *type)
5113 switch (type->type) {
5114 case MONO_TYPE_OBJECT:
5115 return type->data.klass? type->data.klass: mono_defaults.object_class;
5116 case MONO_TYPE_VOID:
5117 return type->data.klass? type->data.klass: mono_defaults.void_class;
5118 case MONO_TYPE_BOOLEAN:
5119 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
5120 case MONO_TYPE_CHAR:
5121 return type->data.klass? type->data.klass: mono_defaults.char_class;
5123 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
5125 return type->data.klass? type->data.klass: mono_defaults.byte_class;
5127 return type->data.klass? type->data.klass: mono_defaults.int16_class;
5129 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
5131 return type->data.klass? type->data.klass: mono_defaults.int32_class;
5133 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
5135 return type->data.klass? type->data.klass: mono_defaults.int_class;
5137 return type->data.klass? type->data.klass: mono_defaults.uint_class;
5139 return type->data.klass? type->data.klass: mono_defaults.int64_class;
5141 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
5143 return type->data.klass? type->data.klass: mono_defaults.single_class;
5145 return type->data.klass? type->data.klass: mono_defaults.double_class;
5146 case MONO_TYPE_STRING:
5147 return type->data.klass? type->data.klass: mono_defaults.string_class;
5148 case MONO_TYPE_TYPEDBYREF:
5149 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
5150 case MONO_TYPE_ARRAY:
5151 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
5153 return mono_ptr_class_get (type->data.type);
5154 case MONO_TYPE_FNPTR:
5155 return mono_fnptr_class_get (type->data.method);
5156 case MONO_TYPE_SZARRAY:
5157 return mono_array_class_get (type->data.klass, 1);
5158 case MONO_TYPE_CLASS:
5159 case MONO_TYPE_VALUETYPE:
5160 return type->data.klass;
5161 case MONO_TYPE_GENERICINST:
5162 return mono_generic_class_get_class (type->data.generic_class);
5164 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
5165 case MONO_TYPE_MVAR:
5166 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
5168 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
5169 g_assert_not_reached ();
5176 * mono_type_retrieve_from_typespec
5177 * @image: context where the image is created
5178 * @type_spec: typespec token
5179 * @context: the generic context used to evaluate generic instantiations in
5182 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate, MonoError *error)
5184 MonoType *t = mono_type_create_from_typespec (image, type_spec);
5186 mono_error_init (error);
5187 *did_inflate = FALSE;
5190 char *name = mono_class_name_from_token (image, type_spec);
5191 char *assembly = mono_assembly_name_from_token (image, type_spec);
5192 mono_error_set_type_load_name (error, name, assembly, "Could not resolve typespec token %08x", type_spec);
5196 if (context && (context->class_inst || context->method_inst)) {
5197 MonoType *inflated = inflate_generic_type (NULL, t, context, error);
5199 if (!mono_error_ok (error))
5204 *did_inflate = TRUE;
5211 * mono_class_create_from_typespec
5212 * @image: context where the image is created
5213 * @type_spec: typespec token
5214 * @context: the generic context used to evaluate generic instantiations in
5217 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, MonoError *error)
5220 gboolean inflated = FALSE;
5221 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated, error);
5222 if (!mono_error_ok (error))
5224 ret = mono_class_from_mono_type (t);
5226 mono_metadata_free_type (t);
5231 * mono_bounded_array_class_get:
5232 * @element_class: element class
5233 * @rank: the dimension of the array class
5234 * @bounded: whenever the array has non-zero bounds
5236 * Returns: a class object describing the array with element type @element_type and
5240 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
5244 MonoClass *parent = NULL;
5245 GSList *list, *rootlist = NULL;
5248 gboolean corlib_type = FALSE;
5250 g_assert (rank <= 255);
5253 /* bounded only matters for one-dimensional arrays */
5256 image = eclass->image;
5258 if (rank == 1 && !bounded) {
5260 * This case is very frequent not just during compilation because of calls
5261 * from mono_class_from_mono_type (), mono_array_new (),
5262 * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
5264 EnterCriticalSection (&image->szarray_cache_lock);
5265 if (!image->szarray_cache)
5266 image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5267 class = g_hash_table_lookup (image->szarray_cache, eclass);
5268 LeaveCriticalSection (&image->szarray_cache_lock);
5272 mono_loader_lock ();
5274 mono_loader_lock ();
5276 if (!image->array_cache)
5277 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5279 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
5280 for (; list; list = list->next) {
5282 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
5283 mono_loader_unlock ();
5290 /* for the building corlib use System.Array from it */
5291 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
5292 parent = mono_class_from_name (image, "System", "Array");
5295 parent = mono_defaults.array_class;
5296 if (!parent->inited)
5297 mono_class_init (parent);
5300 class = mono_image_alloc0 (image, sizeof (MonoClass));
5302 class->image = image;
5303 class->name_space = eclass->name_space;
5304 nsize = strlen (eclass->name);
5305 name = g_malloc (nsize + 2 + rank + 1);
5306 memcpy (name, eclass->name, nsize);
5309 memset (name + nsize + 1, ',', rank - 1);
5311 name [nsize + rank] = '*';
5312 name [nsize + rank + bounded] = ']';
5313 name [nsize + rank + bounded + 1] = 0;
5314 class->name = mono_image_strdup (image, name);
5317 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
5319 classes_size += sizeof (MonoClass);
5321 class->type_token = 0;
5322 /* all arrays are marked serializable and sealed, bug #42779 */
5323 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
5324 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5325 class->parent = parent;
5326 class->instance_size = mono_class_instance_size (class->parent);
5328 if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
5329 if (!eclass->reflection_info || eclass->wastypebuilder) {
5330 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
5331 g_assert (eclass->reflection_info && !eclass->wastypebuilder);
5333 /* element_size -1 is ok as this is not an instantitable type*/
5334 class->sizes.element_size = -1;
5336 class->sizes.element_size = mono_class_array_element_size (eclass);
5338 mono_class_setup_supertypes (class);
5340 if (eclass->generic_class)
5341 mono_class_init (eclass);
5342 if (!eclass->size_inited)
5343 mono_class_setup_fields (eclass);
5344 if (eclass->exception_type) /*FIXME we fail the array type, but we have to let other fields be set.*/
5345 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5347 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
5351 if (eclass->enumtype)
5352 class->cast_class = eclass->element_class;
5354 class->cast_class = eclass;
5356 class->element_class = eclass;
5358 if ((rank > 1) || bounded) {
5359 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
5360 class->byval_arg.type = MONO_TYPE_ARRAY;
5361 class->byval_arg.data.array = at;
5362 at->eklass = eclass;
5364 /* FIXME: complete.... */
5366 class->byval_arg.type = MONO_TYPE_SZARRAY;
5367 class->byval_arg.data.klass = eclass;
5369 class->this_arg = class->byval_arg;
5370 class->this_arg.byref = 1;
5375 class->generic_container = eclass->generic_container;
5377 if (rank == 1 && !bounded) {
5378 MonoClass *prev_class;
5380 EnterCriticalSection (&image->szarray_cache_lock);
5381 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
5383 /* Someone got in before us */
5386 g_hash_table_insert (image->szarray_cache, eclass, class);
5387 LeaveCriticalSection (&image->szarray_cache_lock);
5389 list = g_slist_append (rootlist, class);
5390 g_hash_table_insert (image->array_cache, eclass, list);
5393 mono_loader_unlock ();
5395 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5401 * mono_array_class_get:
5402 * @element_class: element class
5403 * @rank: the dimension of the array class
5405 * Returns: a class object describing the array with element type @element_type and
5409 mono_array_class_get (MonoClass *eclass, guint32 rank)
5411 return mono_bounded_array_class_get (eclass, rank, FALSE);
5415 * mono_class_instance_size:
5418 * Returns: the size of an object instance
5421 mono_class_instance_size (MonoClass *klass)
5423 if (!klass->size_inited)
5424 mono_class_init (klass);
5426 return klass->instance_size;
5430 * mono_class_min_align:
5433 * Returns: minimm alignment requirements
5436 mono_class_min_align (MonoClass *klass)
5438 if (!klass->size_inited)
5439 mono_class_init (klass);
5441 return klass->min_align;
5445 * mono_class_value_size:
5448 * This function is used for value types, and return the
5449 * space and the alignment to store that kind of value object.
5451 * Returns: the size of a value of kind @klass
5454 mono_class_value_size (MonoClass *klass, guint32 *align)
5458 /* fixme: check disable, because we still have external revereces to
5459 * mscorlib and Dummy Objects
5461 /*g_assert (klass->valuetype);*/
5463 size = mono_class_instance_size (klass) - sizeof (MonoObject);
5466 *align = klass->min_align;
5472 * mono_class_data_size:
5475 * Returns: the size of the static class data
5478 mono_class_data_size (MonoClass *klass)
5481 mono_class_init (klass);
5483 /* in arrays, sizes.class_size is unioned with element_size
5484 * and arrays have no static fields
5488 return klass->sizes.class_size;
5492 * Auxiliary routine to mono_class_get_field
5494 * Takes a field index instead of a field token.
5496 static MonoClassField *
5497 mono_class_get_field_idx (MonoClass *class, int idx)
5499 mono_class_setup_fields_locking (class);
5500 if (class->exception_type)
5504 if (class->image->uncompressed_metadata) {
5506 * class->field.first points to the FieldPtr table, while idx points into the
5507 * Field table, so we have to do a search.
5509 /*FIXME this is broken for types with multiple fields with the same name.*/
5510 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
5513 for (i = 0; i < class->field.count; ++i)
5514 if (mono_field_get_name (&class->fields [i]) == name)
5515 return &class->fields [i];
5516 g_assert_not_reached ();
5518 if (class->field.count) {
5519 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
5520 return &class->fields [idx - class->field.first];
5524 class = class->parent;
5530 * mono_class_get_field:
5531 * @class: the class to lookup the field.
5532 * @field_token: the field token
5534 * Returns: A MonoClassField representing the type and offset of
5535 * the field, or a NULL value if the field does not belong to this
5539 mono_class_get_field (MonoClass *class, guint32 field_token)
5541 int idx = mono_metadata_token_index (field_token);
5543 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
5545 return mono_class_get_field_idx (class, idx - 1);
5549 * mono_class_get_field_from_name:
5550 * @klass: the class to lookup the field.
5551 * @name: the field name
5553 * Search the class @klass and it's parents for a field with the name @name.
5555 * Returns: the MonoClassField pointer of the named field or NULL
5558 mono_class_get_field_from_name (MonoClass *klass, const char *name)
5560 return mono_class_get_field_from_name_full (klass, name, NULL);
5564 * mono_class_get_field_from_name_full:
5565 * @klass: the class to lookup the field.
5566 * @name: the field name
5567 * @type: the type of the fields. This optional.
5569 * Search the class @klass and it's parents for a field with the name @name and type @type.
5571 * If @klass is an inflated generic type, the type comparison is done with the equivalent field
5572 * of its generic type definition.
5574 * Returns: the MonoClassField pointer of the named field or NULL
5577 mono_class_get_field_from_name_full (MonoClass *klass, const char *name, MonoType *type)
5581 mono_class_setup_fields_locking (klass);
5582 if (klass->exception_type)
5586 for (i = 0; i < klass->field.count; ++i) {
5587 MonoClassField *field = &klass->fields [i];
5589 if (strcmp (name, mono_field_get_name (field)) != 0)
5593 MonoType *field_type = mono_metadata_get_corresponding_field_from_generic_type_definition (field)->type;
5594 if (!mono_metadata_type_equal_full (type, field_type, TRUE))
5599 klass = klass->parent;
5605 * mono_class_get_field_token:
5606 * @field: the field we need the token of
5608 * Get the token of a field. Note that the tokesn is only valid for the image
5609 * the field was loaded from. Don't use this function for fields in dynamic types.
5611 * Returns: the token representing the field in the image it was loaded from.
5614 mono_class_get_field_token (MonoClassField *field)
5616 MonoClass *klass = field->parent;
5619 mono_class_setup_fields_locking (klass);
5620 if (klass->exception_type)
5624 for (i = 0; i < klass->field.count; ++i) {
5625 if (&klass->fields [i] == field) {
5626 int idx = klass->field.first + i + 1;
5628 if (klass->image->uncompressed_metadata)
5629 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
5630 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
5633 klass = klass->parent;
5636 g_assert_not_reached ();
5641 mono_field_get_index (MonoClassField *field)
5643 int index = field - field->parent->fields;
5645 g_assert (index >= 0 && index < field->parent->field.count);
5651 * mono_class_get_field_default_value:
5653 * Return the default value of the field as a pointer into the metadata blob.
5656 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
5659 guint32 constant_cols [MONO_CONSTANT_SIZE];
5661 MonoClass *klass = field->parent;
5663 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
5665 if (!klass->ext || !klass->ext->field_def_values) {
5666 mono_loader_lock ();
5667 mono_class_alloc_ext (klass);
5668 if (!klass->ext->field_def_values)
5669 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
5670 mono_loader_unlock ();
5673 field_index = mono_field_get_index (field);
5675 if (!klass->ext->field_def_values [field_index].data) {
5676 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
5678 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
5680 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
5681 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
5682 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
5685 *def_type = klass->ext->field_def_values [field_index].def_type;
5686 return klass->ext->field_def_values [field_index].data;
5690 mono_class_get_event_token (MonoEvent *event)
5692 MonoClass *klass = event->parent;
5697 for (i = 0; i < klass->ext->event.count; ++i) {
5698 if (&klass->ext->events [i] == event)
5699 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
5702 klass = klass->parent;
5705 g_assert_not_reached ();
5710 mono_class_get_property_from_name (MonoClass *klass, const char *name)
5714 gpointer iter = NULL;
5715 while ((p = mono_class_get_properties (klass, &iter))) {
5716 if (! strcmp (name, p->name))
5719 klass = klass->parent;
5725 mono_class_get_property_token (MonoProperty *prop)
5727 MonoClass *klass = prop->parent;
5731 gpointer iter = NULL;
5732 while ((p = mono_class_get_properties (klass, &iter))) {
5733 if (&klass->ext->properties [i] == prop)
5734 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
5738 klass = klass->parent;
5741 g_assert_not_reached ();
5746 mono_class_name_from_token (MonoImage *image, guint32 type_token)
5748 const char *name, *nspace;
5750 return g_strdup_printf ("DynamicType 0x%08x", type_token);
5752 switch (type_token & 0xff000000){
5753 case MONO_TOKEN_TYPE_DEF: {
5754 guint32 cols [MONO_TYPEDEF_SIZE];
5755 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5756 guint tidx = mono_metadata_token_index (type_token);
5758 if (tidx > tt->rows)
5759 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
5761 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5762 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5763 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5764 if (strlen (nspace) == 0)
5765 return g_strdup_printf ("%s", name);
5767 return g_strdup_printf ("%s.%s", nspace, name);
5770 case MONO_TOKEN_TYPE_REF: {
5771 guint32 cols [MONO_TYPEREF_SIZE];
5772 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5773 guint tidx = mono_metadata_token_index (type_token);
5776 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
5777 mono_metadata_decode_row (t, tidx-1, cols, MONO_TYPEREF_SIZE);
5778 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
5779 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
5780 if (strlen (nspace) == 0)
5781 return g_strdup_printf ("%s", name);
5783 return g_strdup_printf ("%s.%s", nspace, name);
5786 case MONO_TOKEN_TYPE_SPEC:
5787 return g_strdup_printf ("Typespec 0x%08x", type_token);
5789 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
5794 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
5797 return g_strdup_printf ("DynamicAssembly %s", image->name);
5799 switch (type_token & 0xff000000){
5800 case MONO_TOKEN_TYPE_DEF:
5801 return mono_stringify_assembly_name (&image->assembly->aname);
5803 case MONO_TOKEN_TYPE_REF: {
5804 MonoAssemblyName aname;
5805 guint32 cols [MONO_TYPEREF_SIZE];
5806 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5807 guint32 idx = mono_metadata_token_index (type_token);
5810 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
5812 mono_metadata_decode_row (t, idx-1, cols, MONO_TYPEREF_SIZE);
5814 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
5815 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
5816 case MONO_RESOLTION_SCOPE_MODULE:
5818 return g_strdup ("");
5819 case MONO_RESOLTION_SCOPE_MODULEREF:
5821 return g_strdup ("");
5822 case MONO_RESOLTION_SCOPE_TYPEREF:
5824 return g_strdup ("");
5825 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
5826 mono_assembly_get_assemblyref (image, idx - 1, &aname);
5827 return mono_stringify_assembly_name (&aname);
5829 g_assert_not_reached ();
5833 case MONO_TOKEN_TYPE_SPEC:
5835 return g_strdup ("");
5837 g_assert_not_reached ();
5844 * mono_class_get_full:
5845 * @image: the image where the class resides
5846 * @type_token: the token for the class
5847 * @context: the generic context used to evaluate generic instantiations in
5849 * Returns: the MonoClass that represents @type_token in @image
5852 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5855 MonoClass *class = NULL;
5857 if (image->dynamic) {
5858 int table = mono_metadata_token_table (type_token);
5860 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
5861 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
5864 return mono_lookup_dynamic_token (image, type_token, context);
5867 switch (type_token & 0xff000000){
5868 case MONO_TOKEN_TYPE_DEF:
5869 class = mono_class_create_from_typedef (image, type_token);
5871 case MONO_TOKEN_TYPE_REF:
5872 class = mono_class_from_typeref (image, type_token);
5874 case MONO_TOKEN_TYPE_SPEC:
5875 class = mono_class_create_from_typespec (image, type_token, context, &error);
5876 if (!mono_error_ok (&error)) {
5877 /*FIXME don't swallow the error message*/
5878 mono_error_cleanup (&error);
5882 g_warning ("unknown token type %x", type_token & 0xff000000);
5883 g_assert_not_reached ();
5887 char *name = mono_class_name_from_token (image, type_token);
5888 char *assembly = mono_assembly_name_from_token (image, type_token);
5889 mono_loader_set_error_type_load (name, assembly);
5897 * mono_type_get_full:
5898 * @image: the image where the type resides
5899 * @type_token: the token for the type
5900 * @context: the generic context used to evaluate generic instantiations in
5902 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
5904 * Returns: the MonoType that represents @type_token in @image
5907 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5910 MonoType *type = NULL;
5911 gboolean inflated = FALSE;
5913 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
5915 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
5917 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
5918 MonoClass *class = mono_class_get_full (image, type_token, context);
5919 return class ? mono_class_get_type (class) : NULL;
5922 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated, &error);
5924 if (!mono_error_ok (&error)) {
5925 /*FIXME don't swalloc the error message.*/
5926 char *name = mono_class_name_from_token (image, type_token);
5927 char *assembly = mono_assembly_name_from_token (image, type_token);
5929 mono_error_cleanup (&error);
5930 mono_loader_set_error_type_load (name, assembly);
5935 MonoType *tmp = type;
5936 type = mono_class_get_type (mono_class_from_mono_type (type));
5937 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
5938 * A MonoClass::byval_arg of a generic type definion has type CLASS.
5939 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
5941 * The long term solution is to chaise this places and make then set MonoType::type correctly.
5943 if (type->type != tmp->type)
5946 mono_metadata_free_type (tmp);
5953 mono_class_get (MonoImage *image, guint32 type_token)
5955 return mono_class_get_full (image, type_token, NULL);
5959 * mono_image_init_name_cache:
5961 * Initializes the class name cache stored in image->name_cache.
5963 * LOCKING: Acquires the corresponding image lock.
5966 mono_image_init_name_cache (MonoImage *image)
5968 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5969 guint32 cols [MONO_TYPEDEF_SIZE];
5972 guint32 i, visib, nspace_index;
5973 GHashTable *name_cache2, *nspace_table;
5975 mono_image_lock (image);
5977 if (image->name_cache) {
5978 mono_image_unlock (image);
5982 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
5984 if (image->dynamic) {
5985 mono_image_unlock (image);
5989 /* Temporary hash table to avoid lookups in the nspace_table */
5990 name_cache2 = g_hash_table_new (NULL, NULL);
5992 for (i = 1; i <= t->rows; ++i) {
5993 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5994 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5996 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5997 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5999 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
6001 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6002 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6004 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
6005 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6006 if (!nspace_table) {
6007 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6008 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6009 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6012 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
6015 /* Load type names from EXPORTEDTYPES table */
6017 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6018 guint32 cols [MONO_EXP_TYPE_SIZE];
6021 for (i = 0; i < t->rows; ++i) {
6022 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
6023 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
6024 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
6026 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
6027 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6028 if (!nspace_table) {
6029 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6030 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6031 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6034 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
6038 g_hash_table_destroy (name_cache2);
6039 mono_image_unlock (image);
6042 /*FIXME Only dynamic assemblies should allow this operation.*/
6044 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
6045 const char *name, guint32 index)
6047 GHashTable *nspace_table;
6048 GHashTable *name_cache;
6051 mono_image_lock (image);
6053 if (!image->name_cache)
6054 mono_image_init_name_cache (image);
6056 name_cache = image->name_cache;
6057 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
6058 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6059 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
6062 if ((old_index = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, (char*) name))))
6063 g_error ("overrwritting old token %x on image %s for type %s::%s", old_index, image->name, nspace, name);
6065 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
6067 mono_image_unlock (image);
6076 find_nocase (gpointer key, gpointer value, gpointer user_data)
6078 char *name = (char*)key;
6079 FindUserData *data = (FindUserData*)user_data;
6081 if (!data->value && (mono_utf8_strcasecmp (name, (char*)data->key) == 0))
6082 data->value = value;
6086 * mono_class_from_name_case:
6087 * @image: The MonoImage where the type is looked up in
6088 * @name_space: the type namespace
6089 * @name: the type short name.
6091 * Obtains a MonoClass with a given namespace and a given name which
6092 * is located in the given MonoImage. The namespace and name
6093 * lookups are case insensitive.
6096 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
6098 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
6099 guint32 cols [MONO_TYPEDEF_SIZE];
6104 if (image->dynamic) {
6106 FindUserData user_data;
6108 mono_image_lock (image);
6110 if (!image->name_cache)
6111 mono_image_init_name_cache (image);
6113 user_data.key = name_space;
6114 user_data.value = NULL;
6115 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
6117 if (user_data.value) {
6118 GHashTable *nspace_table = (GHashTable*)user_data.value;
6120 user_data.key = name;
6121 user_data.value = NULL;
6123 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
6125 if (user_data.value)
6126 token = GPOINTER_TO_UINT (user_data.value);
6129 mono_image_unlock (image);
6132 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
6138 /* add a cache if needed */
6139 for (i = 1; i <= t->rows; ++i) {
6140 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
6141 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
6143 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
6144 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
6146 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
6148 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6149 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6150 if (mono_utf8_strcasecmp (n, name) == 0 && mono_utf8_strcasecmp (nspace, name_space) == 0)
6151 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
6157 return_nested_in (MonoClass *class, char *nested)
6160 char *s = strchr (nested, '/');
6161 gpointer iter = NULL;
6168 while ((found = mono_class_get_nested_types (class, &iter))) {
6169 if (strcmp (found->name, nested) == 0) {
6171 return return_nested_in (found, s);
6179 search_modules (MonoImage *image, const char *name_space, const char *name)
6181 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
6182 MonoImage *file_image;
6187 * The EXPORTEDTYPES table only contains public types, so have to search the
6189 * Note: image->modules contains the contents of the MODULEREF table, while
6190 * the real module list is in the FILE table.
6192 for (i = 0; i < file_table->rows; i++) {
6193 guint32 cols [MONO_FILE_SIZE];
6194 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
6195 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
6198 file_image = mono_image_load_file_for_image (image, i + 1);
6200 class = mono_class_from_name (file_image, name_space, name);
6210 * mono_class_from_name:
6211 * @image: The MonoImage where the type is looked up in
6212 * @name_space: the type namespace
6213 * @name: the type short name.
6215 * Obtains a MonoClass with a given namespace and a given name which
6216 * is located in the given MonoImage.
6219 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
6221 GHashTable *nspace_table;
6222 MonoImage *loaded_image;
6229 if ((nested = strchr (name, '/'))) {
6230 int pos = nested - name;
6231 int len = strlen (name);
6234 memcpy (buf, name, len + 1);
6236 nested = buf + pos + 1;
6240 if (get_class_from_name) {
6241 gboolean res = get_class_from_name (image, name_space, name, &class);
6244 class = search_modules (image, name_space, name);
6246 return class ? return_nested_in (class, nested) : NULL;
6252 mono_image_lock (image);
6254 if (!image->name_cache)
6255 mono_image_init_name_cache (image);
6257 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
6260 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
6262 mono_image_unlock (image);
6264 if (!token && image->dynamic && image->modules) {
6265 /* Search modules as well */
6266 for (i = 0; i < image->module_count; ++i) {
6267 MonoImage *module = image->modules [i];
6269 class = mono_class_from_name (module, name_space, name);
6276 class = search_modules (image, name_space, name);
6284 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
6285 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6286 guint32 cols [MONO_EXP_TYPE_SIZE];
6289 idx = mono_metadata_token_index (token);
6291 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
6293 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
6294 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
6295 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
6298 class = mono_class_from_name (loaded_image, name_space, name);
6300 return return_nested_in (class, nested);
6302 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
6303 guint32 assembly_idx;
6305 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
6307 mono_assembly_load_reference (image, assembly_idx - 1);
6308 g_assert (image->references [assembly_idx - 1]);
6309 if (image->references [assembly_idx - 1] == (gpointer)-1)
6312 /* FIXME: Cycle detection */
6313 return mono_class_from_name (image->references [assembly_idx - 1]->image, name_space, name);
6315 g_error ("not yet implemented");
6319 token = MONO_TOKEN_TYPE_DEF | token;
6321 class = mono_class_get (image, token);
6323 return return_nested_in (class, nested);
6328 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
6329 gboolean check_interfaces)
6331 g_assert (klassc->idepth > 0);
6332 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
6333 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
6335 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
6338 for (i = 0; i < klass->interface_count; i ++) {
6339 MonoClass *ic = klass->interfaces [i];
6344 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
6349 * MS.NET thinks interfaces are a subclass of Object, so we think it as
6352 if (klassc == mono_defaults.object_class)
6359 mono_class_has_variant_generic_params (MonoClass *klass)
6362 MonoGenericContainer *container;
6364 if (!klass->generic_class)
6367 container = klass->generic_class->container_class->generic_container;
6369 for (i = 0; i < container->type_argc; ++i)
6370 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
6377 * mono_class_is_assignable_from:
6378 * @klass: the class to be assigned to
6379 * @oklass: the source class
6381 * Return: true if an instance of object oklass can be assigned to an
6382 * instance of object @klass
6385 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
6388 mono_class_init (klass);
6390 if (!oklass->inited)
6391 mono_class_init (oklass);
6393 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
6394 return klass == oklass;
6396 if (MONO_CLASS_IS_INTERFACE (klass)) {
6397 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
6400 /* interface_offsets might not be set for dynamic classes */
6401 if (oklass->reflection_info && !oklass->interface_bitmap)
6403 * oklass might be a generic type parameter but they have
6404 * interface_offsets set.
6406 return mono_reflection_call_is_assignable_to (oklass, klass);
6407 if (!oklass->interface_bitmap)
6408 /* Happens with generic instances of not-yet created dynamic types */
6410 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
6413 if (mono_class_has_variant_generic_params (klass)) {
6414 if (oklass->generic_class) {
6416 gboolean match = FALSE;
6417 MonoClass *container_class1 = klass->generic_class->container_class;
6418 MonoClass *container_class2 = oklass->generic_class->container_class;
6421 * Check whenever the generic definition of oklass implements the
6422 * generic definition of klass. The IMPLEMENTS_INTERFACE stuff is not usable
6423 * here since the relevant tables are not set up.
6425 for (i = 0; i < container_class2->interface_offsets_count; ++i)
6426 if ((container_class2->interfaces_packed [i] == container_class1) || (container_class2->interfaces_packed [i]->generic_class && (container_class2->interfaces_packed [i]->generic_class->container_class == container_class1)))
6430 MonoGenericContainer *container;
6432 container = klass->generic_class->container_class->generic_container;
6435 for (i = 0; i < container->type_argc; ++i) {
6436 MonoClass *param1_class = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [i]);
6437 MonoClass *param2_class = mono_class_from_mono_type (oklass->generic_class->context.class_inst->type_argv [i]);
6439 if (param1_class->valuetype != param2_class->valuetype) {
6444 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
6445 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
6447 if (param1_class != param2_class) {
6448 if ((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_VARIANT) && mono_class_is_assignable_from (param1_class, param2_class))
6450 else if (((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_COVARIANT) && mono_class_is_assignable_from (param2_class, param1_class)))
6464 } else if (klass->rank) {
6465 MonoClass *eclass, *eoclass;
6467 if (oklass->rank != klass->rank)
6470 /* vectors vs. one dimensional arrays */
6471 if (oklass->byval_arg.type != klass->byval_arg.type)
6474 eclass = klass->cast_class;
6475 eoclass = oklass->cast_class;
6478 * a is b does not imply a[] is b[] when a is a valuetype, and
6479 * b is a reference type.
6482 if (eoclass->valuetype) {
6483 if ((eclass == mono_defaults.enum_class) ||
6484 (eclass == mono_defaults.enum_class->parent) ||
6485 (eclass == mono_defaults.object_class))
6489 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6490 } else if (mono_class_is_nullable (klass)) {
6491 if (mono_class_is_nullable (oklass))
6492 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6494 return mono_class_is_assignable_from (klass->cast_class, oklass);
6495 } else if (klass == mono_defaults.object_class)
6498 return mono_class_has_parent (oklass, klass);
6501 /*Check if @candidate implements the interface @target*/
6503 mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
6508 if (candidate == target)
6511 /*A TypeBuilder can have more interfaces on tb->interfaces than on candidate->interfaces*/
6512 if (candidate->image->dynamic && !candidate->wastypebuilder) {
6513 MonoReflectionTypeBuilder *tb = candidate->reflection_info;
6515 if (tb->interfaces) {
6516 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
6517 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
6518 MonoClass *iface_class = mono_class_from_mono_type (iface->type);
6519 if (iface_class == target || mono_class_implement_interface_slow (target, iface_class))
6524 /*setup_interfaces don't mono_class_init anything*/
6525 mono_class_setup_interfaces (candidate);
6526 for (i = 0; i < candidate->interface_count; ++i) {
6527 if (candidate->interfaces [i] == target || mono_class_implement_interface_slow (target, candidate->interfaces [i]))
6531 candidate = candidate->parent;
6532 } while (candidate);
6538 * Check if @oklass can be assigned to @klass.
6539 * This function does the same as mono_class_is_assignable_from but is safe to be used from mono_class_init context.
6542 mono_class_is_assignable_from_slow (MonoClass *target, MonoClass *candidate)
6544 if (candidate == target)
6546 if (target == mono_defaults.object_class)
6549 /*setup_supertypes don't mono_class_init anything */
6550 mono_class_setup_supertypes (candidate);
6551 mono_class_setup_supertypes (target);
6553 if (mono_class_has_parent (candidate, target))
6556 /*If target is not an interface there is no need to check them.*/
6557 if (!MONO_CLASS_IS_INTERFACE (target))
6559 return mono_class_implement_interface_slow (target, candidate);
6563 * mono_class_get_cctor:
6564 * @klass: A MonoClass pointer
6566 * Returns: the static constructor of @klass if it exists, NULL otherwise.
6569 mono_class_get_cctor (MonoClass *klass)
6571 MonoCachedClassInfo cached_info;
6573 if (!klass->has_cctor)
6576 if (mono_class_get_cached_class_info (klass, &cached_info))
6577 return mono_get_method (klass->image, cached_info.cctor_token, klass);
6579 if (klass->generic_class && !klass->methods)
6580 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
6582 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
6586 * mono_class_get_finalizer:
6587 * @klass: The MonoClass pointer
6589 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
6592 mono_class_get_finalizer (MonoClass *klass)
6594 MonoCachedClassInfo cached_info;
6597 mono_class_init (klass);
6598 if (!klass->has_finalize)
6601 if (mono_class_get_cached_class_info (klass, &cached_info))
6602 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
6604 mono_class_setup_vtable (klass);
6605 return klass->vtable [finalize_slot];
6610 * mono_class_needs_cctor_run:
6611 * @klass: the MonoClass pointer
6612 * @caller: a MonoMethod describing the caller
6614 * Determines whenever the class has a static constructor and whenever it
6615 * needs to be called when executing CALLER.
6618 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
6622 method = mono_class_get_cctor (klass);
6624 return (method == caller) ? FALSE : TRUE;
6630 * mono_class_array_element_size:
6633 * Returns: the number of bytes an element of type @klass
6634 * uses when stored into an array.
6637 mono_class_array_element_size (MonoClass *klass)
6639 MonoType *type = &klass->byval_arg;
6642 switch (type->type) {
6645 case MONO_TYPE_BOOLEAN:
6649 case MONO_TYPE_CHAR:
6658 case MONO_TYPE_CLASS:
6659 case MONO_TYPE_STRING:
6660 case MONO_TYPE_OBJECT:
6661 case MONO_TYPE_SZARRAY:
6662 case MONO_TYPE_ARRAY:
6664 case MONO_TYPE_MVAR:
6665 return sizeof (gpointer);
6670 case MONO_TYPE_VALUETYPE:
6671 if (type->data.klass->enumtype) {
6672 type = mono_class_enum_basetype (type->data.klass);
6673 klass = klass->element_class;
6676 return mono_class_instance_size (klass) - sizeof (MonoObject);
6677 case MONO_TYPE_GENERICINST:
6678 type = &type->data.generic_class->container_class->byval_arg;
6681 case MONO_TYPE_VOID:
6685 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
6691 * mono_array_element_size:
6692 * @ac: pointer to a #MonoArrayClass
6694 * Returns: the size of single array element.
6697 mono_array_element_size (MonoClass *ac)
6699 g_assert (ac->rank);
6700 return ac->sizes.element_size;
6704 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
6705 MonoGenericContext *context)
6707 if (image->dynamic) {
6708 MonoClass *tmp_handle_class;
6709 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
6711 g_assert (tmp_handle_class);
6713 *handle_class = tmp_handle_class;
6715 if (tmp_handle_class == mono_defaults.typehandle_class)
6716 return &((MonoClass*)obj)->byval_arg;
6721 switch (token & 0xff000000) {
6722 case MONO_TOKEN_TYPE_DEF:
6723 case MONO_TOKEN_TYPE_REF:
6724 case MONO_TOKEN_TYPE_SPEC: {
6727 *handle_class = mono_defaults.typehandle_class;
6728 type = mono_type_get_full (image, token, context);
6731 mono_class_init (mono_class_from_mono_type (type));
6732 /* We return a MonoType* as handle */
6735 case MONO_TOKEN_FIELD_DEF: {
6737 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
6741 *handle_class = mono_defaults.fieldhandle_class;
6742 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
6745 mono_class_init (class);
6746 return mono_class_get_field (class, token);
6748 case MONO_TOKEN_METHOD_DEF:
6749 case MONO_TOKEN_METHOD_SPEC: {
6751 meth = mono_get_method_full (image, token, NULL, context);
6753 *handle_class = mono_defaults.methodhandle_class;
6756 case MONO_TOKEN_MEMBER_REF: {
6757 guint32 cols [MONO_MEMBERREF_SIZE];
6759 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
6760 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6761 mono_metadata_decode_blob_size (sig, &sig);
6762 if (*sig == 0x6) { /* it's a field */
6764 MonoClassField *field;
6765 field = mono_field_from_token (image, token, &klass, context);
6767 *handle_class = mono_defaults.fieldhandle_class;
6771 meth = mono_get_method_full (image, token, NULL, context);
6773 *handle_class = mono_defaults.methodhandle_class;
6778 g_warning ("Unknown token 0x%08x in ldtoken", token);
6785 * This function might need to call runtime functions so it can't be part
6786 * of the metadata library.
6788 static MonoLookupDynamicToken lookup_dynamic = NULL;
6791 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
6793 lookup_dynamic = func;
6797 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
6799 MonoClass *handle_class;
6801 return lookup_dynamic (image, token, TRUE, &handle_class, context);
6805 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
6807 return lookup_dynamic (image, token, valid_token, handle_class, context);
6810 static MonoGetCachedClassInfo get_cached_class_info = NULL;
6813 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
6815 get_cached_class_info = func;
6819 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
6821 if (!get_cached_class_info)
6824 return get_cached_class_info (klass, res);
6828 mono_install_get_class_from_name (MonoGetClassFromName func)
6830 get_class_from_name = func;
6834 mono_class_get_image (MonoClass *klass)
6836 return klass->image;
6840 * mono_class_get_element_class:
6841 * @klass: the MonoClass to act on
6843 * Returns: the element class of an array or an enumeration.
6846 mono_class_get_element_class (MonoClass *klass)
6848 return klass->element_class;
6852 * mono_class_is_valuetype:
6853 * @klass: the MonoClass to act on
6855 * Returns: true if the MonoClass represents a ValueType.
6858 mono_class_is_valuetype (MonoClass *klass)
6860 return klass->valuetype;
6864 * mono_class_is_enum:
6865 * @klass: the MonoClass to act on
6867 * Returns: true if the MonoClass represents an enumeration.
6870 mono_class_is_enum (MonoClass *klass)
6872 return klass->enumtype;
6876 * mono_class_enum_basetype:
6877 * @klass: the MonoClass to act on
6879 * Returns: the underlying type representation for an enumeration.
6882 mono_class_enum_basetype (MonoClass *klass)
6884 if (klass->element_class == klass)
6885 /* SRE or broken types */
6888 return &klass->element_class->byval_arg;
6892 * mono_class_get_parent
6893 * @klass: the MonoClass to act on
6895 * Returns: the parent class for this class.
6898 mono_class_get_parent (MonoClass *klass)
6900 return klass->parent;
6904 * mono_class_get_nesting_type;
6905 * @klass: the MonoClass to act on
6907 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
6910 mono_class_get_nesting_type (MonoClass *klass)
6912 return klass->nested_in;
6916 * mono_class_get_rank:
6917 * @klass: the MonoClass to act on
6919 * Returns: the rank for the array (the number of dimensions).
6922 mono_class_get_rank (MonoClass *klass)
6928 * mono_class_get_flags:
6929 * @klass: the MonoClass to act on
6931 * The type flags from the TypeDef table from the metadata.
6932 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
6935 * Returns: the flags from the TypeDef table.
6938 mono_class_get_flags (MonoClass *klass)
6940 return klass->flags;
6944 * mono_class_get_name
6945 * @klass: the MonoClass to act on
6947 * Returns: the name of the class.
6950 mono_class_get_name (MonoClass *klass)
6956 * mono_class_get_namespace:
6957 * @klass: the MonoClass to act on
6959 * Returns: the namespace of the class.
6962 mono_class_get_namespace (MonoClass *klass)
6964 return klass->name_space;
6968 * mono_class_get_type:
6969 * @klass: the MonoClass to act on
6971 * This method returns the internal Type representation for the class.
6973 * Returns: the MonoType from the class.
6976 mono_class_get_type (MonoClass *klass)
6978 return &klass->byval_arg;
6982 * mono_class_get_type_token
6983 * @klass: the MonoClass to act on
6985 * This method returns type token for the class.
6987 * Returns: the type token for the class.
6990 mono_class_get_type_token (MonoClass *klass)
6992 return klass->type_token;
6996 * mono_class_get_byref_type:
6997 * @klass: the MonoClass to act on
7002 mono_class_get_byref_type (MonoClass *klass)
7004 return &klass->this_arg;
7008 * mono_class_num_fields:
7009 * @klass: the MonoClass to act on
7011 * Returns: the number of static and instance fields in the class.
7014 mono_class_num_fields (MonoClass *klass)
7016 return klass->field.count;
7020 * mono_class_num_methods:
7021 * @klass: the MonoClass to act on
7023 * Returns: the number of methods in the class.
7026 mono_class_num_methods (MonoClass *klass)
7028 return klass->method.count;
7032 * mono_class_num_properties
7033 * @klass: the MonoClass to act on
7035 * Returns: the number of properties in the class.
7038 mono_class_num_properties (MonoClass *klass)
7040 mono_class_setup_properties (klass);
7042 return klass->ext->property.count;
7046 * mono_class_num_events:
7047 * @klass: the MonoClass to act on
7049 * Returns: the number of events in the class.
7052 mono_class_num_events (MonoClass *klass)
7054 mono_class_setup_events (klass);
7056 return klass->ext->event.count;
7060 * mono_class_get_fields:
7061 * @klass: the MonoClass to act on
7063 * This routine is an iterator routine for retrieving the fields in a class.
7065 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7066 * iterate over all of the elements. When no more values are
7067 * available, the return value is NULL.
7069 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
7072 mono_class_get_fields (MonoClass* klass, gpointer *iter)
7074 MonoClassField* field;
7078 mono_class_setup_fields_locking (klass);
7079 if (klass->exception_type)
7081 /* start from the first */
7082 if (klass->field.count) {
7083 return *iter = &klass->fields [0];
7091 if (field < &klass->fields [klass->field.count]) {
7092 return *iter = field;
7098 * mono_class_get_methods
7099 * @klass: the MonoClass to act on
7101 * This routine is an iterator routine for retrieving the fields in a class.
7103 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7104 * iterate over all of the elements. When no more values are
7105 * available, the return value is NULL.
7107 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
7110 mono_class_get_methods (MonoClass* klass, gpointer *iter)
7112 MonoMethod** method;
7116 mono_class_init (klass);
7118 mono_class_setup_methods (klass);
7119 /* start from the first */
7120 if (klass->method.count) {
7121 *iter = &klass->methods [0];
7122 return klass->methods [0];
7130 if (method < &klass->methods [klass->method.count]) {
7138 * mono_class_get_virtual_methods:
7140 * Iterate over the virtual methods of KLASS.
7142 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
7145 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
7147 MonoMethod** method;
7150 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
7152 mono_class_setup_methods (klass);
7153 /* start from the first */
7154 method = &klass->methods [0];
7159 while (method < &klass->methods [klass->method.count]) {
7160 if (((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
7164 if (method < &klass->methods [klass->method.count]) {
7171 /* Search directly in metadata to avoid calling setup_methods () */
7172 MonoMethod *res = NULL;
7178 start_index = GPOINTER_TO_UINT (*iter);
7181 for (i = start_index; i < klass->method.count; ++i) {
7184 /* class->method.first points into the methodptr table */
7185 flags = mono_metadata_decode_table_row_col (klass->image, MONO_TABLE_METHOD, klass->method.first + i, MONO_METHOD_FLAGS);
7187 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
7191 if (i < klass->method.count) {
7192 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7193 /* Add 1 here so the if (*iter) check fails */
7194 *iter = GUINT_TO_POINTER (i + 1);
7203 * mono_class_get_properties:
7204 * @klass: the MonoClass to act on
7206 * This routine is an iterator routine for retrieving the properties in a class.
7208 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7209 * iterate over all of the elements. When no more values are
7210 * available, the return value is NULL.
7212 * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
7215 mono_class_get_properties (MonoClass* klass, gpointer *iter)
7217 MonoProperty* property;
7221 mono_class_init (klass);
7223 mono_class_setup_properties (klass);
7224 /* start from the first */
7225 if (klass->ext->property.count) {
7226 return *iter = &klass->ext->properties [0];
7234 if (property < &klass->ext->properties [klass->ext->property.count]) {
7235 return *iter = property;
7241 * mono_class_get_events:
7242 * @klass: the MonoClass to act on
7244 * This routine is an iterator routine for retrieving the properties in a class.
7246 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7247 * iterate over all of the elements. When no more values are
7248 * available, the return value is NULL.
7250 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
7253 mono_class_get_events (MonoClass* klass, gpointer *iter)
7259 mono_class_init (klass);
7261 mono_class_setup_events (klass);
7262 /* start from the first */
7263 if (klass->ext->event.count) {
7264 return *iter = &klass->ext->events [0];
7272 if (event < &klass->ext->events [klass->ext->event.count]) {
7273 return *iter = event;
7279 * mono_class_get_interfaces
7280 * @klass: the MonoClass to act on
7282 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
7284 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7285 * iterate over all of the elements. When no more values are
7286 * available, the return value is NULL.
7288 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7291 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
7298 mono_class_init (klass);
7299 if (!klass->interfaces_inited)
7300 mono_class_setup_interfaces (klass);
7301 /* start from the first */
7302 if (klass->interface_count) {
7303 *iter = &klass->interfaces [0];
7304 return klass->interfaces [0];
7312 if (iface < &klass->interfaces [klass->interface_count]) {
7320 * mono_class_get_nested_types
7321 * @klass: the MonoClass to act on
7323 * This routine is an iterator routine for retrieving the nested types of a class.
7324 * This works only if @klass is non-generic, or a generic type definition.
7326 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7327 * iterate over all of the elements. When no more values are
7328 * available, the return value is NULL.
7330 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7333 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
7341 mono_class_init (klass);
7342 if (!klass->nested_classes_inited) {
7343 if (!klass->type_token)
7344 klass->nested_classes_inited = TRUE;
7345 mono_loader_lock ();
7346 if (!klass->nested_classes_inited) {
7347 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
7350 guint32 cols [MONO_NESTED_CLASS_SIZE];
7351 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
7352 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
7355 mono_class_alloc_ext (klass);
7356 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
7358 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
7361 mono_memory_barrier ();
7362 klass->nested_classes_inited = TRUE;
7363 mono_loader_unlock ();
7367 /* start from the first */
7368 if (klass->ext && klass->ext->nested_classes) {
7369 *iter = klass->ext->nested_classes;
7370 return klass->ext->nested_classes->data;
7372 /* no nested types */
7386 * mono_field_get_name:
7387 * @field: the MonoClassField to act on
7389 * Returns: the name of the field.
7392 mono_field_get_name (MonoClassField *field)
7398 * mono_field_get_type:
7399 * @field: the MonoClassField to act on
7401 * Returns: MonoType of the field.
7404 mono_field_get_type (MonoClassField *field)
7410 * mono_field_get_parent:
7411 * @field: the MonoClassField to act on
7413 * Returns: MonoClass where the field was defined.
7416 mono_field_get_parent (MonoClassField *field)
7418 return field->parent;
7422 * mono_field_get_flags;
7423 * @field: the MonoClassField to act on
7425 * The metadata flags for a field are encoded using the
7426 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
7428 * Returns: the flags for the field.
7431 mono_field_get_flags (MonoClassField *field)
7433 return field->type->attrs;
7437 * mono_field_get_offset;
7438 * @field: the MonoClassField to act on
7440 * Returns: the field offset.
7443 mono_field_get_offset (MonoClassField *field)
7445 return field->offset;
7449 mono_field_get_rva (MonoClassField *field)
7453 MonoClass *klass = field->parent;
7455 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
7457 if (!klass->ext || !klass->ext->field_def_values) {
7458 mono_loader_lock ();
7459 mono_class_alloc_ext (klass);
7460 if (!klass->ext->field_def_values)
7461 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
7462 mono_loader_unlock ();
7465 field_index = mono_field_get_index (field);
7467 if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
7468 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
7470 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
7471 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
7474 return klass->ext->field_def_values [field_index].data;
7478 * mono_field_get_data;
7479 * @field: the MonoClassField to act on
7481 * Returns: pointer to the metadata constant value or to the field
7482 * data if it has an RVA flag.
7485 mono_field_get_data (MonoClassField *field)
7487 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
7488 MonoTypeEnum def_type;
7490 return mono_class_get_field_default_value (field, &def_type);
7491 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
7492 return mono_field_get_rva (field);
7499 * mono_property_get_name:
7500 * @prop: the MonoProperty to act on
7502 * Returns: the name of the property
7505 mono_property_get_name (MonoProperty *prop)
7511 * mono_property_get_set_method
7512 * @prop: the MonoProperty to act on.
7514 * Returns: the setter method of the property (A MonoMethod)
7517 mono_property_get_set_method (MonoProperty *prop)
7523 * mono_property_get_get_method
7524 * @prop: the MonoProperty to act on.
7526 * Returns: the setter method of the property (A MonoMethod)
7529 mono_property_get_get_method (MonoProperty *prop)
7535 * mono_property_get_parent:
7536 * @prop: the MonoProperty to act on.
7538 * Returns: the MonoClass where the property was defined.
7541 mono_property_get_parent (MonoProperty *prop)
7543 return prop->parent;
7547 * mono_property_get_flags:
7548 * @prop: the MonoProperty to act on.
7550 * The metadata flags for a property are encoded using the
7551 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
7553 * Returns: the flags for the property.
7556 mono_property_get_flags (MonoProperty *prop)
7562 * mono_event_get_name:
7563 * @event: the MonoEvent to act on
7565 * Returns: the name of the event.
7568 mono_event_get_name (MonoEvent *event)
7574 * mono_event_get_add_method:
7575 * @event: The MonoEvent to act on.
7577 * Returns: the @add' method for the event (a MonoMethod).
7580 mono_event_get_add_method (MonoEvent *event)
7586 * mono_event_get_remove_method:
7587 * @event: The MonoEvent to act on.
7589 * Returns: the @remove method for the event (a MonoMethod).
7592 mono_event_get_remove_method (MonoEvent *event)
7594 return event->remove;
7598 * mono_event_get_raise_method:
7599 * @event: The MonoEvent to act on.
7601 * Returns: the @raise method for the event (a MonoMethod).
7604 mono_event_get_raise_method (MonoEvent *event)
7606 return event->raise;
7610 * mono_event_get_parent:
7611 * @event: the MonoEvent to act on.
7613 * Returns: the MonoClass where the event is defined.
7616 mono_event_get_parent (MonoEvent *event)
7618 return event->parent;
7622 * mono_event_get_flags
7623 * @event: the MonoEvent to act on.
7625 * The metadata flags for an event are encoded using the
7626 * EVENT_* constants. See the tabledefs.h file for details.
7628 * Returns: the flags for the event.
7631 mono_event_get_flags (MonoEvent *event)
7633 return event->attrs;
7637 * mono_class_get_method_from_name:
7638 * @klass: where to look for the method
7639 * @name_space: name of the method
7640 * @param_count: number of parameters. -1 for any number.
7642 * Obtains a MonoMethod with a given name and number of parameters.
7643 * It only works if there are no multiple signatures for any given method name.
7646 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
7648 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
7652 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
7654 MonoMethod *res = NULL;
7657 /* Search directly in the metadata to avoid calling setup_methods () */
7658 for (i = 0; i < klass->method.count; ++i) {
7659 guint32 cols [MONO_METHOD_SIZE];
7662 /* class->method.first points into the methodptr table */
7663 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
7665 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
7666 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7667 if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
7678 * mono_class_get_method_from_name_flags:
7679 * @klass: where to look for the method
7680 * @name_space: name of the method
7681 * @param_count: number of parameters. -1 for any number.
7682 * @flags: flags which must be set in the method
7684 * Obtains a MonoMethod with a given name and number of parameters.
7685 * It only works if there are no multiple signatures for any given method name.
7688 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
7690 MonoMethod *res = NULL;
7693 mono_class_init (klass);
7695 if (klass->generic_class && !klass->methods) {
7696 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
7698 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
7702 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
7703 mono_class_setup_methods (klass);
7704 for (i = 0; i < klass->method.count; ++i) {
7705 MonoMethod *method = klass->methods [i];
7707 if (method->name[0] == name [0] &&
7708 !strcmp (name, method->name) &&
7709 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
7710 ((method->flags & flags) == flags)) {
7717 res = find_method_in_metadata (klass, name, param_count, flags);
7724 * mono_class_set_failure:
7725 * @klass: class in which the failure was detected
7726 * @ex_type: the kind of exception/error to be thrown (later)
7727 * @ex_data: exception data (specific to each type of exception/error)
7729 * Keep a detected failure informations in the class for later processing.
7730 * Note that only the first failure is kept.
7732 * LOCKING: Acquires the loader lock.
7735 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
7737 if (klass->exception_type)
7740 mono_loader_lock ();
7741 klass->exception_type = ex_type;
7743 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
7744 mono_loader_unlock ();
7750 * mono_class_get_exception_data:
7752 * Return the exception_data property of KLASS.
7754 * LOCKING: Acquires the loader lock.
7757 mono_class_get_exception_data (MonoClass *klass)
7759 return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
7763 * mono_classes_init:
7765 * Initialize the resources used by this module.
7768 mono_classes_init (void)
7770 mono_counters_register ("Inflated methods size",
7771 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
7772 mono_counters_register ("Inflated classes",
7773 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
7774 mono_counters_register ("Inflated classes size",
7775 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
7776 mono_counters_register ("MonoClass size",
7777 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
7778 mono_counters_register ("MonoClassExt size",
7779 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
7783 * mono_classes_cleanup:
7785 * Free the resources used by this module.
7788 mono_classes_cleanup (void)
7790 if (global_interface_bitset)
7791 mono_bitset_free (global_interface_bitset);
7795 * mono_class_get_exception_for_failure:
7796 * @klass: class in which the failure was detected
7798 * Return a constructed MonoException than the caller can then throw
7799 * using mono_raise_exception - or NULL if no failure is present (or
7800 * doesn't result in an exception).
7803 mono_class_get_exception_for_failure (MonoClass *klass)
7805 gpointer exception_data = mono_class_get_exception_data (klass);
7807 switch (klass->exception_type) {
7808 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
7809 MonoDomain *domain = mono_domain_get ();
7810 MonoSecurityManager* secman = mono_security_manager_get_methods ();
7811 MonoMethod *method = exception_data;
7812 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
7813 MonoObject *exc = NULL;
7817 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
7818 args [2] = mono_type_get_object (domain, &klass->byval_arg);
7819 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
7821 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
7822 return (MonoException*) exc;
7824 case MONO_EXCEPTION_TYPE_LOAD: {
7827 char *str = mono_type_get_full_name (klass);
7828 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
7829 name = mono_string_new (mono_domain_get (), str);
7831 ex = mono_get_exception_type_load (name, astr);
7835 case MONO_EXCEPTION_MISSING_METHOD: {
7836 char *class_name = exception_data;
7837 char *assembly_name = class_name + strlen (class_name) + 1;
7839 return mono_get_exception_missing_method (class_name, assembly_name);
7841 case MONO_EXCEPTION_MISSING_FIELD: {
7842 char *class_name = exception_data;
7843 char *member_name = class_name + strlen (class_name) + 1;
7845 return mono_get_exception_missing_field (class_name, member_name);
7847 case MONO_EXCEPTION_FILE_NOT_FOUND: {
7848 char *msg_format = exception_data;
7849 char *assembly_name = msg_format + strlen (msg_format) + 1;
7850 char *msg = g_strdup_printf (msg_format, assembly_name);
7853 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
7859 case MONO_EXCEPTION_BAD_IMAGE: {
7860 return mono_get_exception_bad_image_format (exception_data);
7863 MonoLoaderError *error;
7866 error = mono_loader_get_last_error ();
7868 ex = mono_loader_error_prepare_exception (error);
7872 /* TODO - handle other class related failures */
7879 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
7881 outer_klass = mono_class_get_generic_type_definition (outer_klass);
7882 inner_klass = mono_class_get_generic_type_definition (inner_klass);
7884 if (outer_klass == inner_klass)
7886 inner_klass = inner_klass->nested_in;
7887 } while (inner_klass);
7892 mono_class_get_generic_type_definition (MonoClass *klass)
7894 return klass->generic_class ? klass->generic_class->container_class : klass;
7898 * Check if @klass is a subtype of @parent ignoring generic instantiations.
7900 * Generic instantiations are ignored for all super types of @klass.
7902 * Visibility checks ignoring generic instantiations.
7905 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
7908 klass = mono_class_get_generic_type_definition (klass);
7909 parent = mono_class_get_generic_type_definition (parent);
7911 for (i = 0; i < klass->idepth; ++i) {
7912 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
7918 * Subtype can only access parent members with family protection if the site object
7919 * is subclass of Subtype. For example:
7920 * class A { protected int x; }
7922 * void valid_access () {
7926 * void invalid_access () {
7933 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
7935 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
7938 if (context_klass == NULL)
7940 /*if access_klass is not member_klass context_klass must be type compat*/
7941 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
7947 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
7950 if (accessing == accessed)
7952 if (!accessed || !accessing)
7955 /* extra safety under CoreCLR - the runtime does not verify the strongname signatures
7956 * anywhere so untrusted friends are not safe to access platform's code internals */
7957 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
7958 if (!mono_security_core_clr_can_access_internals (accessing->image, accessed->image))
7962 mono_assembly_load_friends (accessed);
7963 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
7964 MonoAssemblyName *friend = tmp->data;
7965 /* Be conservative with checks */
7968 if (strcmp (accessing->aname.name, friend->name))
7970 if (friend->public_key_token [0]) {
7971 if (!accessing->aname.public_key_token [0])
7973 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
7982 * If klass is a generic type or if it is derived from a generic type, return the
7983 * MonoClass of the generic definition
7984 * Returns NULL if not found
7987 get_generic_definition_class (MonoClass *klass)
7990 if (klass->generic_class && klass->generic_class->container_class)
7991 return klass->generic_class->container_class;
7992 klass = klass->parent;
7998 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
8001 for (i = 0; i < ginst->type_argc; ++i) {
8002 MonoType *type = ginst->type_argv[i];
8003 switch (type->type) {
8004 case MONO_TYPE_SZARRAY:
8005 if (!can_access_type (access_klass, type->data.klass))
8008 case MONO_TYPE_ARRAY:
8009 if (!can_access_type (access_klass, type->data.array->eklass))
8013 if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
8016 case MONO_TYPE_CLASS:
8017 case MONO_TYPE_VALUETYPE:
8018 case MONO_TYPE_GENERICINST:
8019 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
8027 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
8031 if (access_klass->element_class && !access_klass->enumtype)
8032 access_klass = access_klass->element_class;
8034 if (member_klass->element_class && !member_klass->enumtype)
8035 member_klass = member_klass->element_class;
8037 access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
8039 if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
8042 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
8045 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
8048 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
8051 /*Non nested type with nested visibility. We just fail it.*/
8052 if (access_level >= TYPE_ATTRIBUTE_NESTED_PRIVATE && access_level <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM && member_klass->nested_in == NULL)
8055 switch (access_level) {
8056 case TYPE_ATTRIBUTE_NOT_PUBLIC:
8057 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8059 case TYPE_ATTRIBUTE_PUBLIC:
8062 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
8065 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
8066 return is_nesting_type (member_klass, access_klass);
8068 case TYPE_ATTRIBUTE_NESTED_FAMILY:
8069 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
8071 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
8072 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8074 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
8075 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
8076 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
8078 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
8079 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
8080 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
8085 /* FIXME: check visibility of type, too */
8087 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
8089 MonoClass *member_generic_def;
8090 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
8091 access_klass->generic_container) &&
8092 (member_generic_def = get_generic_definition_class (member_klass))) {
8093 MonoClass *access_container;
8095 if (access_klass->generic_container)
8096 access_container = access_klass;
8098 access_container = access_klass->generic_class->container_class;
8100 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
8104 /* Partition I 8.5.3.2 */
8105 /* the access level values are the same for fields and methods */
8106 switch (access_level) {
8107 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
8108 /* same compilation unit */
8109 return access_klass->image == member_klass->image;
8110 case FIELD_ATTRIBUTE_PRIVATE:
8111 return access_klass == member_klass;
8112 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
8113 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
8114 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
8117 case FIELD_ATTRIBUTE_ASSEMBLY:
8118 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8119 case FIELD_ATTRIBUTE_FAMILY:
8120 if (is_valid_family_access (access_klass, member_klass, context_klass))
8123 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
8124 if (is_valid_family_access (access_klass, member_klass, context_klass))
8126 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8127 case FIELD_ATTRIBUTE_PUBLIC:
8134 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
8136 /* FIXME: check all overlapping fields */
8137 int can = can_access_member (method->klass, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8139 MonoClass *nested = method->klass->nested_in;
8141 can = can_access_member (nested, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8144 nested = nested->nested_in;
8151 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
8153 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8155 MonoClass *nested = method->klass->nested_in;
8157 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8160 nested = nested->nested_in;
8165 * with generics calls to explicit interface implementations can be expressed
8166 * directly: the method is private, but we must allow it. This may be opening
8167 * a hole or the generics code should handle this differently.
8168 * Maybe just ensure the interface type is public.
8170 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
8176 * mono_method_can_access_method_full:
8177 * @method: The caller method
8178 * @called: The called method
8179 * @context_klass: The static type on stack of the owner @called object used
8181 * This function must be used with instance calls, as they have more strict family accessibility.
8182 * It can be used with static methods, but context_klass should be NULL.
8184 * Returns: TRUE if caller have proper visibility and acessibility to @called
8187 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
8189 MonoClass *access_class = method->klass;
8190 MonoClass *member_class = called->klass;
8191 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8193 MonoClass *nested = access_class->nested_in;
8195 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8198 nested = nested->nested_in;
8205 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8208 if (called->is_inflated) {
8209 MonoMethodInflated * infl = (MonoMethodInflated*)called;
8210 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
8219 * mono_method_can_access_field_full:
8220 * @method: The caller method
8221 * @field: The accessed field
8222 * @context_klass: The static type on stack of the owner @field object used
8224 * This function must be used with instance fields, as they have more strict family accessibility.
8225 * It can be used with static fields, but context_klass should be NULL.
8227 * Returns: TRUE if caller have proper visibility and acessibility to @field
8230 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
8232 MonoClass *access_class = method->klass;
8233 MonoClass *member_class = field->parent;
8234 /* FIXME: check all overlapping fields */
8235 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8237 MonoClass *nested = access_class->nested_in;
8239 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8242 nested = nested->nested_in;
8249 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8255 * mono_type_is_valid_enum_basetype:
8256 * @type: The MonoType to check
8258 * Returns: TRUE if the type can be used as the basetype of an enum
8260 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
8261 switch (type->type) {
8264 case MONO_TYPE_BOOLEAN:
8267 case MONO_TYPE_CHAR:
8280 * mono_class_is_valid_enum:
8281 * @klass: An enum class to be validated
8283 * This method verify the required properties an enum should have.
8285 * Returns: TRUE if the informed enum class is valid
8287 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
8288 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
8289 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
8291 gboolean mono_class_is_valid_enum (MonoClass *klass) {
8292 MonoClassField * field;
8293 gpointer iter = NULL;
8294 gboolean found_base_field = FALSE;
8296 g_assert (klass->enumtype);
8297 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
8298 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
8302 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
8305 while ((field = mono_class_get_fields (klass, &iter))) {
8306 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
8307 if (found_base_field)
8309 found_base_field = TRUE;
8310 if (!mono_type_is_valid_enum_basetype (field->type))
8315 if (!found_base_field)
8318 if (klass->method.count > 0)
8325 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
8327 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
8330 static gboolean gshared_supported;
8333 mono_set_generic_sharing_supported (gboolean supported)
8335 gshared_supported = supported;
8339 * mono_class_generic_sharing_enabled:
8342 * Returns whether generic sharing is enabled for class.
8344 * This is a stop-gap measure to slowly introduce generic sharing
8345 * until we have all the issues sorted out, at which time this
8346 * function will disappear and generic sharing will always be enabled.
8349 mono_class_generic_sharing_enabled (MonoClass *class)
8351 static int generic_sharing = MONO_GENERIC_SHARING_NONE;
8352 static gboolean inited = FALSE;
8357 if (gshared_supported)
8358 generic_sharing = MONO_GENERIC_SHARING_ALL;
8360 generic_sharing = MONO_GENERIC_SHARING_NONE;
8362 if ((option = g_getenv ("MONO_GENERIC_SHARING"))) {
8363 if (strcmp (option, "corlib") == 0)
8364 generic_sharing = MONO_GENERIC_SHARING_CORLIB;
8365 else if (strcmp (option, "collections") == 0)
8366 generic_sharing = MONO_GENERIC_SHARING_COLLECTIONS;
8367 else if (strcmp (option, "all") == 0)
8368 generic_sharing = MONO_GENERIC_SHARING_ALL;
8369 else if (strcmp (option, "none") == 0)
8370 generic_sharing = MONO_GENERIC_SHARING_NONE;
8372 g_warning ("Unknown generic sharing option `%s'.", option);
8375 if (!gshared_supported)
8376 generic_sharing = MONO_GENERIC_SHARING_NONE;
8381 switch (generic_sharing) {
8382 case MONO_GENERIC_SHARING_NONE:
8384 case MONO_GENERIC_SHARING_ALL:
8386 case MONO_GENERIC_SHARING_CORLIB :
8387 return class->image == mono_defaults.corlib;
8388 case MONO_GENERIC_SHARING_COLLECTIONS:
8389 if (class->image != mono_defaults.corlib)
8391 while (class->nested_in)
8392 class = class->nested_in;
8393 return g_str_has_prefix (class->name_space, "System.Collections.Generic");
8395 g_assert_not_reached ();
8401 * mono_class_setup_interface_id:
8403 * Initializes MonoClass::interface_id if required.
8405 * LOCKING: Acquires the loader lock.
8408 mono_class_setup_interface_id (MonoClass *class)
8410 mono_loader_lock ();
8411 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
8412 class->interface_id = mono_get_unique_iid (class);
8413 mono_loader_unlock ();
8417 * mono_class_alloc_ext:
8419 * Allocate klass->ext if not already done.
8420 * LOCKING: Assumes the loader lock is held.
8423 mono_class_alloc_ext (MonoClass *klass)
8426 if (klass->generic_class) {
8427 klass->ext = g_new0 (MonoClassExt, 1);
8429 klass->ext = mono_image_alloc0 (klass->image, sizeof (MonoClassExt));
8431 class_ext_size += sizeof (MonoClassExt);
8436 * mono_class_setup_interfaces:
8438 * Initialize class->interfaces/interfaces_count.
8439 * LOCKING: Acquires the loader lock.
8442 mono_class_setup_interfaces (MonoClass *klass)
8446 if (klass->interfaces_inited)
8449 mono_loader_lock ();
8451 if (klass->interfaces_inited) {
8452 mono_loader_unlock ();
8456 if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
8459 /* generic IList, ICollection, IEnumerable */
8460 klass->interface_count = 1;
8461 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
8463 args [0] = &klass->element_class->byval_arg;
8464 klass->interfaces [0] = mono_class_bind_generic_parameters (
8465 mono_defaults.generic_ilist_class, 1, args, FALSE);
8466 } else if (klass->generic_class) {
8467 MonoClass *gklass = klass->generic_class->container_class;
8469 klass->interface_count = gklass->interface_count;
8470 klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
8471 for (i = 0; i < klass->interface_count; i++)
8472 klass->interfaces [i] = mono_class_inflate_generic_class (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class));
8475 mono_memory_barrier ();
8477 klass->interfaces_inited = TRUE;
8479 mono_loader_unlock ();