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);
72 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
73 void (*mono_debugger_class_loaded_methods_func) (MonoClass *klass) = NULL;
76 * mono_class_from_typeref:
78 * @type_token: a TypeRef token
80 * Creates the MonoClass* structure representing the type defined by
81 * the typeref token valid inside @image.
82 * Returns: the MonoClass* representing the typeref token, NULL ifcould
86 mono_class_from_typeref (MonoImage *image, guint32 type_token)
88 guint32 cols [MONO_TYPEREF_SIZE];
89 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
91 const char *name, *nspace;
95 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
97 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
98 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
100 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
101 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
102 case MONO_RESOLTION_SCOPE_MODULE:
104 g_error ("null ResolutionScope not yet handled");
105 /* a typedef in disguise */
106 return mono_class_from_name (image, nspace, name);
107 case MONO_RESOLTION_SCOPE_MODULEREF:
108 module = mono_image_load_module (image, idx);
110 return mono_class_from_name (module, nspace, name);
112 char *msg = g_strdup_printf ("%s%s%s", nspace, nspace [0] ? "." : "", name);
115 human_name = mono_stringify_assembly_name (&image->assembly->aname);
116 mono_loader_set_error_type_load (msg, human_name);
122 case MONO_RESOLTION_SCOPE_TYPEREF: {
123 MonoClass *enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
129 if (enclosing->nested_classes_inited && enclosing->ext) {
130 /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
131 for (tmp = enclosing->ext->nested_classes; tmp; tmp = tmp->next) {
133 if (strcmp (res->name, name) == 0)
137 /* Don't call mono_class_init as we might've been called by it recursively */
138 int i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, 1);
140 guint32 class_nested = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, MONO_NESTED_CLASS_NESTED);
141 guint32 string_offset = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_TYPEDEF], class_nested - 1, MONO_TYPEDEF_NAME);
142 const char *nname = mono_metadata_string_heap (enclosing->image, string_offset);
144 if (strcmp (nname, name) == 0)
145 return mono_class_create_from_typedef (enclosing->image, MONO_TOKEN_TYPE_DEF | class_nested);
147 i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, i + 1);
150 g_warning ("TypeRef ResolutionScope not yet handled (%d) for %s.%s in image %s", idx, nspace, name, image->name);
153 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
157 if (!image->references || !image->references [idx - 1])
158 mono_assembly_load_reference (image, idx - 1);
159 g_assert (image->references [idx - 1]);
161 /* If the assembly did not load, register this as a type load exception */
162 if (image->references [idx - 1] == REFERENCE_MISSING){
163 MonoAssemblyName aname;
166 mono_assembly_get_assemblyref (image, idx - 1, &aname);
167 human_name = mono_stringify_assembly_name (&aname);
168 mono_loader_set_error_assembly_load (human_name, image->assembly->ref_only);
174 return mono_class_from_name (image->references [idx - 1]->image, nspace, name);
179 mono_image_memdup (MonoImage *image, void *data, guint size)
181 void *res = mono_image_alloc (image, size);
182 memcpy (res, data, size);
186 /* Copy everything mono_metadata_free_array free. */
188 mono_dup_array_type (MonoImage *image, MonoArrayType *a)
191 a = mono_image_memdup (image, a, sizeof (MonoArrayType));
193 a->sizes = mono_image_memdup (image, a->sizes, a->numsizes * sizeof (int));
195 a->lobounds = mono_image_memdup (image, a->lobounds, a->numlobounds * sizeof (int));
197 a = g_memdup (a, sizeof (MonoArrayType));
199 a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
201 a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
206 /* Copy everything mono_metadata_free_method_signature free. */
208 mono_metadata_signature_deep_dup (MonoImage *image, MonoMethodSignature *sig)
212 sig = mono_metadata_signature_dup_full (image, sig);
214 sig->ret = mono_metadata_type_dup (image, sig->ret);
215 for (i = 0; i < sig->param_count; ++i)
216 sig->params [i] = mono_metadata_type_dup (image, sig->params [i]);
222 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
224 MonoAssembly *ta = klass->image->assembly;
226 g_string_append_printf (
227 str, ", %s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
229 ta->aname.major, ta->aname.minor, ta->aname.build, ta->aname.revision,
230 ta->aname.culture && *ta->aname.culture? ta->aname.culture: "neutral",
231 ta->aname.public_key_token [0] ? (char *)ta->aname.public_key_token : "null",
232 (ta->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
236 mono_type_name_check_byref (MonoType *type, GString *str)
239 g_string_append_c (str, '&');
243 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
244 MonoTypeNameFormat format)
248 switch (type->type) {
249 case MONO_TYPE_ARRAY: {
250 int i, rank = type->data.array->rank;
251 MonoTypeNameFormat nested_format;
253 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
254 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
256 mono_type_get_name_recurse (
257 &type->data.array->eklass->byval_arg, str, FALSE, nested_format);
258 g_string_append_c (str, '[');
260 g_string_append_c (str, '*');
261 for (i = 1; i < rank; i++)
262 g_string_append_c (str, ',');
263 g_string_append_c (str, ']');
265 mono_type_name_check_byref (type, str);
267 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
268 _mono_type_get_assembly_name (type->data.array->eklass, str);
271 case MONO_TYPE_SZARRAY: {
272 MonoTypeNameFormat nested_format;
274 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
275 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
277 mono_type_get_name_recurse (
278 &type->data.klass->byval_arg, str, FALSE, nested_format);
279 g_string_append (str, "[]");
281 mono_type_name_check_byref (type, str);
283 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
284 _mono_type_get_assembly_name (type->data.klass, str);
287 case MONO_TYPE_PTR: {
288 MonoTypeNameFormat nested_format;
290 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
291 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
293 mono_type_get_name_recurse (
294 type->data.type, str, FALSE, nested_format);
295 g_string_append_c (str, '*');
297 mono_type_name_check_byref (type, str);
299 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
300 _mono_type_get_assembly_name (mono_class_from_mono_type (type->data.type), str);
305 if (!mono_generic_param_info (type->data.generic_param))
306 g_string_append_printf (str, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", type->data.generic_param->num);
308 g_string_append (str, mono_generic_param_info (type->data.generic_param)->name);
310 mono_type_name_check_byref (type, str);
314 klass = mono_class_from_mono_type (type);
315 if (klass->nested_in) {
316 mono_type_get_name_recurse (
317 &klass->nested_in->byval_arg, str, TRUE, format);
318 if (format == MONO_TYPE_NAME_FORMAT_IL)
319 g_string_append_c (str, '.');
321 g_string_append_c (str, '+');
322 } else if (*klass->name_space) {
323 g_string_append (str, klass->name_space);
324 g_string_append_c (str, '.');
326 if (format == MONO_TYPE_NAME_FORMAT_IL) {
327 char *s = strchr (klass->name, '`');
328 int len = s ? s - klass->name : strlen (klass->name);
330 g_string_append_len (str, klass->name, len);
332 g_string_append (str, klass->name);
335 if (klass->generic_class) {
336 MonoGenericClass *gclass = klass->generic_class;
337 MonoGenericInst *inst = gclass->context.class_inst;
338 MonoTypeNameFormat nested_format;
341 nested_format = format == MONO_TYPE_NAME_FORMAT_FULL_NAME ?
342 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED : format;
344 if (format == MONO_TYPE_NAME_FORMAT_IL)
345 g_string_append_c (str, '<');
347 g_string_append_c (str, '[');
348 for (i = 0; i < inst->type_argc; i++) {
349 MonoType *t = inst->type_argv [i];
352 g_string_append_c (str, ',');
353 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
354 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
355 g_string_append_c (str, '[');
356 mono_type_get_name_recurse (inst->type_argv [i], str, FALSE, nested_format);
357 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
358 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
359 g_string_append_c (str, ']');
361 if (format == MONO_TYPE_NAME_FORMAT_IL)
362 g_string_append_c (str, '>');
364 g_string_append_c (str, ']');
365 } else if (klass->generic_container &&
366 (format != MONO_TYPE_NAME_FORMAT_FULL_NAME) &&
367 (format != MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)) {
370 if (format == MONO_TYPE_NAME_FORMAT_IL)
371 g_string_append_c (str, '<');
373 g_string_append_c (str, '[');
374 for (i = 0; i < klass->generic_container->type_argc; i++) {
376 g_string_append_c (str, ',');
377 g_string_append (str, mono_generic_container_get_param_info (klass->generic_container, i)->name);
379 if (format == MONO_TYPE_NAME_FORMAT_IL)
380 g_string_append_c (str, '>');
382 g_string_append_c (str, ']');
385 mono_type_name_check_byref (type, str);
387 if ((format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
388 (type->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
389 _mono_type_get_assembly_name (klass, str);
395 * mono_type_get_name_full:
397 * @format: the format for the return string.
400 * Returns: the string representation in a number of formats:
402 * if format is MONO_TYPE_NAME_FORMAT_REFLECTION, the return string is
403 * returned in the formatrequired by System.Reflection, this is the
404 * inverse of mono_reflection_parse_type ().
406 * if format is MONO_TYPE_NAME_FORMAT_IL, it returns a syntax that can
407 * be used by the IL assembler.
409 * if format is MONO_TYPE_NAME_FORMAT_FULL_NAME
411 * if format is MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED
414 mono_type_get_name_full (MonoType *type, MonoTypeNameFormat format)
418 result = g_string_new ("");
420 mono_type_get_name_recurse (type, result, FALSE, format);
422 return g_string_free (result, FALSE);
426 * mono_type_get_full_name:
429 * Returns: the string representation for type as required by System.Reflection.
430 * The inverse of mono_reflection_parse_type ().
433 mono_type_get_full_name (MonoClass *class)
435 return mono_type_get_name_full (mono_class_get_type (class), MONO_TYPE_NAME_FORMAT_REFLECTION);
439 * mono_type_get_name:
442 * Returns: the string representation for type as it would be represented in IL code.
445 mono_type_get_name (MonoType *type)
447 return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_IL);
451 * mono_type_get_underlying_type:
454 * Returns: the MonoType for the underlying integer type if @type
455 * is an enum and byref is false, otherwise the type itself.
458 mono_type_get_underlying_type (MonoType *type)
460 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype && !type->byref)
461 return mono_class_enum_basetype (type->data.klass);
462 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype && !type->byref)
463 return mono_class_enum_basetype (type->data.generic_class->container_class);
468 * mono_class_is_open_constructed_type:
471 * Returns TRUE if type represents a generics open constructed type
472 * (not all the type parameters required for the instantiation have
476 mono_class_is_open_constructed_type (MonoType *t)
482 case MONO_TYPE_SZARRAY:
483 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
484 case MONO_TYPE_ARRAY:
485 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
487 return mono_class_is_open_constructed_type (t->data.type);
488 case MONO_TYPE_GENERICINST:
489 return t->data.generic_class->context.class_inst->is_open;
496 inflate_generic_type (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
498 mono_error_init (error);
500 switch (type->type) {
501 case MONO_TYPE_MVAR: {
503 int num = mono_type_get_generic_param_num (type);
504 MonoGenericInst *inst = context->method_inst;
505 if (!inst || !inst->type_argv)
507 if (num >= inst->type_argc) {
508 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
509 mono_error_set_bad_image (error, image, "MVAR %d (%s) cannot be expanded in this context with %d instantiations",
510 num, info ? info->name : "", inst->type_argc);
515 * Note that the VAR/MVAR cases are different from the rest. The other cases duplicate @type,
516 * while the VAR/MVAR duplicates a type from the context. So, we need to ensure that the
517 * ->byref and ->attrs from @type are propagated to the returned type.
519 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
520 nt->byref = type->byref;
521 nt->attrs = type->attrs;
524 case MONO_TYPE_VAR: {
526 int num = mono_type_get_generic_param_num (type);
527 MonoGenericInst *inst = context->class_inst;
530 if (num >= inst->type_argc) {
531 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
532 mono_error_set_bad_image (error, image, "VAR %d (%s) cannot be expanded in this context with %d instantiations",
533 num, info ? info->name : "", inst->type_argc);
536 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
537 nt->byref = type->byref;
538 nt->attrs = type->attrs;
541 case MONO_TYPE_SZARRAY: {
542 MonoClass *eclass = type->data.klass;
543 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
544 if (!inflated || !mono_error_ok (error))
546 nt = mono_metadata_type_dup (image, type);
547 nt->data.klass = mono_class_from_mono_type (inflated);
548 mono_metadata_free_type (inflated);
551 case MONO_TYPE_ARRAY: {
552 MonoClass *eclass = type->data.array->eklass;
553 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
554 if (!inflated || !mono_error_ok (error))
556 nt = mono_metadata_type_dup (image, type);
557 nt->data.array = g_memdup (nt->data.array, sizeof (MonoArrayType));
558 nt->data.array->eklass = mono_class_from_mono_type (inflated);
559 mono_metadata_free_type (inflated);
562 case MONO_TYPE_GENERICINST: {
563 MonoGenericClass *gclass = type->data.generic_class;
564 MonoGenericInst *inst;
566 if (!gclass->context.class_inst->is_open)
569 inst = mono_metadata_inflate_generic_inst (gclass->context.class_inst, context);
570 if (inst != gclass->context.class_inst)
571 gclass = mono_metadata_lookup_generic_class (gclass->container_class, inst, gclass->is_dynamic);
573 if (gclass == type->data.generic_class)
576 nt = mono_metadata_type_dup (image, type);
577 nt->data.generic_class = gclass;
580 case MONO_TYPE_CLASS:
581 case MONO_TYPE_VALUETYPE: {
582 MonoClass *klass = type->data.klass;
583 MonoGenericContainer *container = klass->generic_container;
584 MonoGenericInst *inst;
585 MonoGenericClass *gclass = NULL;
591 /* We can't use context->class_inst directly, since it can have more elements */
592 inst = mono_metadata_inflate_generic_inst (container->context.class_inst, context);
593 if (inst == container->context.class_inst)
596 gclass = mono_metadata_lookup_generic_class (klass, inst, klass->image->dynamic);
598 nt = mono_metadata_type_dup (image, type);
599 nt->type = MONO_TYPE_GENERICINST;
600 nt->data.generic_class = gclass;
610 mono_generic_class_get_context (MonoGenericClass *gclass)
612 return &gclass->context;
616 mono_class_get_context (MonoClass *class)
618 return class->generic_class ? mono_generic_class_get_context (class->generic_class) : NULL;
622 * mono_class_get_generic_container:
624 * Return the generic container of KLASS which should be a generic type definition.
626 MonoGenericContainer*
627 mono_class_get_generic_container (MonoClass *klass)
629 g_assert (klass->is_generic);
631 return klass->generic_container;
635 * mono_class_get_generic_class:
637 * Return the MonoGenericClass of KLASS, which should be a generic instance.
640 mono_class_get_generic_class (MonoClass *klass)
642 g_assert (klass->is_inflated);
644 return klass->generic_class;
648 * mono_class_inflate_generic_type_with_mempool:
649 * @mempool: a mempool
651 * @context: a generics context
652 * @error: error context
654 * The same as mono_class_inflate_generic_type, but allocates the MonoType
655 * from mempool if it is non-NULL. If it is NULL, the MonoType is
656 * allocated on the heap and is owned by the caller.
657 * The returned type can potentially be the same as TYPE, so it should not be
658 * modified by the caller, and it should be freed using mono_metadata_free_type ().
661 mono_class_inflate_generic_type_with_mempool (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
663 MonoType *inflated = NULL;
664 mono_error_init (error);
667 inflated = inflate_generic_type (image, type, context, error);
668 if (!mono_error_ok (error))
672 MonoType *shared = mono_metadata_get_shared_type (type);
677 return mono_metadata_type_dup (image, type);
681 mono_stats.inflated_type_count++;
686 * mono_class_inflate_generic_type:
688 * @context: a generics context
690 * If @type is a generic type and @context is not NULL, instantiate it using the
691 * generics context @context.
693 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
694 * on the heap and is owned by the caller. Returns NULL on error.
696 * @deprecated Please use mono_class_inflate_generic_type_checked instead
699 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
703 result = mono_class_inflate_generic_type_checked (type, context, &error);
705 if (!mono_error_ok (&error)) {
706 mono_error_cleanup (&error);
713 * mono_class_inflate_generic_type:
715 * @context: a generics context
716 * @error: error context to use
718 * If @type is a generic type and @context is not NULL, instantiate it using the
719 * generics context @context.
721 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
722 * on the heap and is owned by the caller.
725 mono_class_inflate_generic_type_checked (MonoType *type, MonoGenericContext *context, MonoError *error)
727 return mono_class_inflate_generic_type_with_mempool (NULL, type, context, error);
731 * mono_class_inflate_generic_type_no_copy:
733 * Same as inflate_generic_type_with_mempool, but return TYPE if no inflation
737 mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context)
740 MonoType *inflated = NULL;
743 inflated = inflate_generic_type (image, type, context, &error);
744 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
750 mono_stats.inflated_type_count++;
755 * mono_class_inflate_generic_class:
757 * Inflate the class GKLASS with CONTEXT.
760 mono_class_inflate_generic_class (MonoClass *gklass, MonoGenericContext *context)
766 inflated = mono_class_inflate_generic_type_checked (&gklass->byval_arg, context, &error);
767 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
769 res = mono_class_from_mono_type (inflated);
770 mono_metadata_free_type (inflated);
775 static MonoGenericContext
776 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with)
778 MonoGenericInst *class_inst = NULL;
779 MonoGenericInst *method_inst = NULL;
780 MonoGenericContext res;
782 if (context->class_inst)
783 class_inst = mono_metadata_inflate_generic_inst (context->class_inst, inflate_with);
785 if (context->method_inst)
786 method_inst = mono_metadata_inflate_generic_inst (context->method_inst, inflate_with);
788 res.class_inst = class_inst;
789 res.method_inst = method_inst;
795 * mono_class_inflate_generic_method:
796 * @method: a generic method
797 * @context: a generics context
799 * Instantiate the generic method @method using the generics context @context.
801 * Returns: the new instantiated method
804 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
806 return mono_class_inflate_generic_method_full (method, NULL, context);
810 * mono_class_inflate_generic_method_full:
812 * Instantiate method @method with the generic context @context.
813 * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
814 * Use mono_method_signature () and mono_method_get_header () to get the correct values.
817 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
820 MonoMethodInflated *iresult, *cached;
821 MonoMethodSignature *sig;
822 MonoGenericContext tmp_context;
823 gboolean is_mb_open = FALSE;
825 /* The `method' has already been instantiated before => we need to peel out the instantiation and create a new context */
826 while (method->is_inflated) {
827 MonoGenericContext *method_context = mono_method_get_context (method);
828 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
830 tmp_context = inflate_generic_context (method_context, context);
831 context = &tmp_context;
833 if (mono_metadata_generic_context_equal (method_context, context))
836 method = imethod->declaring;
839 if (!method->is_generic && !method->klass->generic_container)
843 * The reason for this hack is to fix the behavior of inflating generic methods that come from a MethodBuilder.
844 * What happens is that instantiating a generic MethodBuilder with its own arguments should create a diferent object.
845 * This is opposite to the way non-SRE MethodInfos behave.
847 * This happens, for example, when we want to emit a recursive generic method. Given the following C# code:
849 * void Example<T> () {
853 * In Example, the method token must be encoded as: "void Example<!!0>()"
855 * The reference to the first generic argument, "!!0", must be explicit otherwise it won't be inflated
856 * properly. To get that we need to inflate the MethodBuilder with its own arguments.
858 * On the other hand, inflating a non-SRE generic method with its own arguments should
859 * return itself. For example:
861 * MethodInfo m = ... //m is a generic method definition
862 * MethodInfo res = m.MakeGenericMethod (m.GetGenericArguments ());
865 * To allow such scenarios we must allow inflation of MethodBuilder to happen in a diferent way than
866 * what happens with regular methods.
868 * There is one last touch to this madness, once a TypeBuilder is finished, IOW CreateType() is called,
869 * everything should behave like a regular type or method.
872 is_mb_open = method->is_generic &&
873 method->klass->image->dynamic && !method->klass->wastypebuilder && /* that is a MethodBuilder from an unfinished TypeBuilder */
874 context->method_inst == mono_method_get_generic_container (method)->context.method_inst; /* and it's been instantiated with its own arguments. */
876 iresult = g_new0 (MonoMethodInflated, 1);
877 iresult->context = *context;
878 iresult->declaring = method;
879 iresult->method.method.is_mb_open = is_mb_open;
881 if (!context->method_inst && method->is_generic)
882 iresult->context.method_inst = mono_method_get_generic_container (method)->context.method_inst;
884 if (!context->class_inst) {
885 g_assert (!iresult->declaring->klass->generic_class);
886 if (iresult->declaring->klass->generic_container)
887 iresult->context.class_inst = iresult->declaring->klass->generic_container->context.class_inst;
888 else if (iresult->declaring->klass->generic_class)
889 iresult->context.class_inst = iresult->declaring->klass->generic_class->context.class_inst;
893 cached = mono_method_inflated_lookup (iresult, FALSE);
895 mono_loader_unlock ();
897 return (MonoMethod*)cached;
900 mono_stats.inflated_method_count++;
902 inflated_methods_size += sizeof (MonoMethodInflated);
904 sig = mono_method_signature (method);
906 memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
908 memcpy (&iresult->method.normal, method, sizeof (MonoMethodNormal));
909 iresult->method.normal.header = NULL;
912 result = (MonoMethod *) iresult;
913 result->is_inflated = TRUE;
914 result->is_generic = FALSE;
915 result->signature = NULL;
916 result->is_mb_open = is_mb_open;
918 if (!context->method_inst) {
919 /* Set the generic_container of the result to the generic_container of method */
920 MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
922 if (generic_container) {
923 result->is_generic = 1;
924 mono_method_set_generic_container (result, generic_container);
928 if (!klass_hint || !klass_hint->generic_class ||
929 klass_hint->generic_class->container_class != method->klass ||
930 klass_hint->generic_class->context.class_inst != context->class_inst)
933 if (method->klass->generic_container)
934 result->klass = klass_hint;
936 if (!result->klass) {
938 MonoType *inflated = inflate_generic_type (NULL, &method->klass->byval_arg, context, &error);
940 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
942 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
944 mono_metadata_free_type (inflated);
947 mono_method_inflated_lookup (iresult, TRUE);
948 mono_loader_unlock ();
953 * mono_get_inflated_method:
955 * Obsolete. We keep it around since it's mentioned in the public API.
958 mono_get_inflated_method (MonoMethod *method)
964 * mono_method_get_context_general:
966 * @uninflated: handle uninflated methods?
968 * Returns the generic context of a method or NULL if it doesn't have
969 * one. For an inflated method that's the context stored in the
970 * method. Otherwise it's in the method's generic container or in the
971 * generic container of the method's class.
974 mono_method_get_context_general (MonoMethod *method, gboolean uninflated)
976 if (method->is_inflated) {
977 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
978 return &imethod->context;
982 if (method->is_generic)
983 return &(mono_method_get_generic_container (method)->context);
984 if (method->klass->generic_container)
985 return &method->klass->generic_container->context;
990 * mono_method_get_context:
993 * Returns the generic context for method if it's inflated, otherwise
997 mono_method_get_context (MonoMethod *method)
999 return mono_method_get_context_general (method, FALSE);
1003 * mono_method_get_generic_container:
1005 * Returns the generic container of METHOD, which should be a generic method definition.
1006 * Returns NULL if METHOD is not a generic method definition.
1007 * LOCKING: Acquires the loader lock.
1009 MonoGenericContainer*
1010 mono_method_get_generic_container (MonoMethod *method)
1012 MonoGenericContainer *container;
1014 if (!method->is_generic)
1017 container = mono_image_property_lookup (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER);
1018 g_assert (container);
1024 * mono_method_set_generic_container:
1026 * Sets the generic container of METHOD to CONTAINER.
1027 * LOCKING: Acquires the loader lock.
1030 mono_method_set_generic_container (MonoMethod *method, MonoGenericContainer* container)
1032 g_assert (method->is_generic);
1034 mono_image_property_insert (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER, container);
1038 * mono_class_find_enum_basetype:
1039 * @class: The enum class
1041 * Determine the basetype of an enum by iterating through its fields. We do this
1042 * in a separate function since it is cheaper than calling mono_class_setup_fields.
1045 mono_class_find_enum_basetype (MonoClass *class)
1047 MonoGenericContainer *container = NULL;
1048 MonoImage *m = class->image;
1049 const int top = class->field.count;
1052 g_assert (class->enumtype);
1054 if (class->generic_container)
1055 container = class->generic_container;
1056 else if (class->generic_class) {
1057 MonoClass *gklass = class->generic_class->container_class;
1059 container = gklass->generic_container;
1060 g_assert (container);
1064 * Fetch all the field information.
1066 for (i = 0; i < top; i++){
1068 guint32 cols [MONO_FIELD_SIZE];
1069 int idx = class->field.first + i;
1072 /* class->field.first and idx points into the fieldptr table */
1073 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1075 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC) //no need to decode static fields
1078 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL))
1081 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1082 mono_metadata_decode_value (sig, &sig);
1083 /* FIELD signature == 0x06 */
1087 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1090 if (class->generic_class) {
1091 //FIXME do we leak here?
1092 ftype = mono_class_inflate_generic_type (ftype, mono_class_get_context (class));
1093 ftype->attrs = cols [MONO_FIELD_FLAGS];
1103 * Checks for MonoClass::exception_type without resolving all MonoType's into MonoClass'es
1104 * It doesn't resolve generic instances, only check the GTD.
1107 mono_type_has_exceptions (MonoType *type)
1109 switch (type->type) {
1110 case MONO_TYPE_CLASS:
1111 case MONO_TYPE_VALUETYPE:
1112 case MONO_TYPE_SZARRAY:
1113 return type->data.klass->exception_type;
1114 case MONO_TYPE_ARRAY:
1115 return type->data.array->eklass->exception_type;
1116 case MONO_TYPE_GENERICINST:
1117 return type->data.generic_class->container_class->exception_type;
1123 * mono_class_setup_fields:
1124 * @class: The class to initialize
1126 * Initializes the class->fields.
1127 * LOCKING: Assumes the loader lock is held.
1130 mono_class_setup_fields (MonoClass *class)
1132 MonoImage *m = class->image;
1133 int top = class->field.count;
1134 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1135 int i, blittable = TRUE;
1136 guint32 real_size = 0;
1137 guint32 packing_size = 0;
1138 gboolean explicit_size;
1139 MonoClassField *field;
1140 MonoGenericContainer *container = NULL;
1141 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1143 if (class->size_inited)
1146 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1148 * This happens when a generic instance of an unfinished generic typebuilder
1149 * is used as an element type for creating an array type. We can't initialize
1150 * the fields of this class using the fields of gklass, since gklass is not
1151 * finished yet, fields could be added to it later.
1157 mono_class_setup_fields (gtd);
1158 if (gtd->exception_type) {
1159 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1163 top = gtd->field.count;
1164 class->field.first = gtd->field.first;
1165 class->field.count = gtd->field.count;
1168 class->instance_size = 0;
1170 class->sizes.class_size = 0;
1172 if (class->parent) {
1173 /* For generic instances, class->parent might not have been initialized */
1174 mono_class_init (class->parent);
1175 if (!class->parent->size_inited) {
1176 mono_class_setup_fields (class->parent);
1177 if (class->parent->exception_type) {
1178 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1182 class->instance_size += class->parent->instance_size;
1183 class->min_align = class->parent->min_align;
1184 /* we use |= since it may have been set already */
1185 class->has_references |= class->parent->has_references;
1186 blittable = class->parent->blittable;
1188 class->instance_size = sizeof (MonoObject);
1189 class->min_align = 1;
1192 /* We can't really enable 16 bytes alignment until the GC supports it.
1193 The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
1194 boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
1195 Bug #506144 is an example of this issue.
1197 if (class->simd_type)
1198 class->min_align = 16;
1200 /* Get the real size */
1201 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1203 if (explicit_size) {
1204 g_assert ((packing_size & 0xfffffff0) == 0);
1205 class->packing_size = packing_size;
1206 real_size += class->instance_size;
1210 if (explicit_size && real_size) {
1211 class->instance_size = MAX (real_size, class->instance_size);
1213 class->size_inited = 1;
1214 class->blittable = blittable;
1218 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1221 /* Prevent infinite loops if the class references itself */
1222 class->size_inited = 1;
1224 class->fields = mono_image_alloc0 (class->image, sizeof (MonoClassField) * top);
1226 if (class->generic_container) {
1227 container = class->generic_container;
1229 container = gtd->generic_container;
1230 g_assert (container);
1234 * Fetch all the field information.
1236 for (i = 0; i < top; i++){
1237 int idx = class->field.first + i;
1238 field = &class->fields [i];
1240 field->parent = class;
1243 MonoClassField *gfield = >d->fields [i];
1245 field->name = mono_field_get_name (gfield);
1246 /*This memory must come from the image mempool as we don't have a chance to free it.*/
1247 field->type = mono_class_inflate_generic_type_no_copy (class->image, gfield->type, mono_class_get_context (class));
1248 g_assert (field->type->attrs == gfield->type->attrs);
1249 if (mono_field_is_deleted (field))
1251 field->offset = gfield->offset;
1254 guint32 cols [MONO_FIELD_SIZE];
1256 /* class->field.first and idx points into the fieldptr table */
1257 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1258 /* The name is needed for fieldrefs */
1259 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
1260 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL)) {
1261 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1264 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1265 mono_metadata_decode_value (sig, &sig);
1266 /* FIELD signature == 0x06 */
1267 g_assert (*sig == 0x06);
1268 field->type = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1270 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1273 if (mono_field_is_deleted (field))
1275 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1277 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1278 field->offset = offset;
1279 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1280 g_warning ("%s not initialized correctly (missing field layout info for %s)",
1281 class->name, mono_field_get_name (field));
1285 /* Only do these checks if we still think this type is blittable */
1286 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1287 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1290 MonoClass *field_class = mono_class_from_mono_type (field->type);
1292 mono_class_setup_fields (field_class);
1293 if (field_class->exception_type) {
1294 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1298 if (!field_class || !field_class->blittable)
1303 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1304 class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1305 blittable = class->element_class->blittable;
1308 if (mono_type_has_exceptions (field->type)) {
1309 char *class_name = mono_type_get_full_name (class);
1310 char *type_name = mono_type_full_name (field->type);
1312 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1313 g_warning ("Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
1314 g_free (class_name);
1318 /* The def_value of fields is compute lazily during vtable creation */
1321 if (class == mono_defaults.string_class)
1324 class->blittable = blittable;
1326 if (class->enumtype && !mono_class_enum_basetype (class)) {
1327 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
1330 if (explicit_size && real_size) {
1331 class->instance_size = MAX (real_size, class->instance_size);
1334 if (class->exception_type)
1336 mono_class_layout_fields (class);
1340 * mono_class_setup_fields_locking:
1341 * @class: The class to initialize
1343 * Initializes the class->fields array of fields.
1344 * Aquires the loader lock.
1347 mono_class_setup_fields_locking (MonoClass *class)
1349 mono_loader_lock ();
1350 mono_class_setup_fields (class);
1351 mono_loader_unlock ();
1355 * mono_class_has_references:
1357 * Returns whenever @klass->has_references is set, initializing it if needed.
1358 * Aquires the loader lock.
1361 mono_class_has_references (MonoClass *klass)
1363 if (klass->init_pending) {
1364 /* Be conservative */
1367 mono_class_init (klass);
1369 return klass->has_references;
1373 /* useful until we keep track of gc-references in corlib etc. */
1375 #define IS_GC_REFERENCE(t) FALSE
1377 #define IS_GC_REFERENCE(t) ((t)->type == MONO_TYPE_U && class->image == mono_defaults.corlib)
1381 * mono_type_get_basic_type_from_generic:
1384 * Returns a closed type corresponding to the possibly open type
1388 mono_type_get_basic_type_from_generic (MonoType *type)
1390 /* When we do generic sharing we let type variables stand for reference types. */
1391 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1392 return &mono_defaults.object_class->byval_arg;
1397 * mono_class_layout_fields:
1400 * Compute the placement of fields inside an object or struct, according to
1401 * the layout rules and set the following fields in @class:
1402 * - has_references (if the class contains instance references firled or structs that contain references)
1403 * - has_static_refs (same, but for static fields)
1404 * - instance_size (size of the object in memory)
1405 * - class_size (size needed for the static fields)
1406 * - size_inited (flag set when the instance_size is set)
1408 * LOCKING: this is supposed to be called with the loader lock held.
1411 mono_class_layout_fields (MonoClass *class)
1414 const int top = class->field.count;
1415 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1416 guint32 pass, passes, real_size;
1417 gboolean gc_aware_layout = FALSE;
1418 MonoClassField *field;
1421 * When we do generic sharing we need to have layout
1422 * information for open generic classes (either with a generic
1423 * context containing type variables or with a generic
1424 * container), so we don't return in that case anymore.
1428 * Enable GC aware auto layout: in this mode, reference
1429 * fields are grouped together inside objects, increasing collector
1431 * Requires that all classes whose layout is known to native code be annotated
1432 * with [StructLayout (LayoutKind.Sequential)]
1433 * Value types have gc_aware_layout disabled by default, as per
1434 * what the default is for other runtimes.
1436 /* corlib is missing [StructLayout] directives in many places */
1437 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1438 if (class->image != mono_defaults.corlib &&
1439 class->byval_arg.type != MONO_TYPE_VALUETYPE)
1440 gc_aware_layout = TRUE;
1441 /* from System.dll, used in metadata/process.h */
1442 if (strcmp (class->name, "ProcessStartInfo") == 0)
1443 gc_aware_layout = FALSE;
1446 /* Compute klass->has_references */
1448 * Process non-static fields first, since static fields might recursively
1449 * refer to the class itself.
1451 for (i = 0; i < top; i++) {
1454 field = &class->fields [i];
1456 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1457 ftype = mono_type_get_underlying_type (field->type);
1458 ftype = mono_type_get_basic_type_from_generic (ftype);
1459 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1460 class->has_references = TRUE;
1464 for (i = 0; i < top; i++) {
1467 field = &class->fields [i];
1469 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1470 ftype = mono_type_get_underlying_type (field->type);
1471 ftype = mono_type_get_basic_type_from_generic (ftype);
1472 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1473 class->has_static_refs = TRUE;
1477 for (i = 0; i < top; i++) {
1480 field = &class->fields [i];
1482 ftype = mono_type_get_underlying_type (field->type);
1483 ftype = mono_type_get_basic_type_from_generic (ftype);
1484 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1485 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1486 class->has_static_refs = TRUE;
1488 class->has_references = TRUE;
1493 * Compute field layout and total size (not considering static fields)
1497 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1498 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1500 if (gc_aware_layout)
1505 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1509 real_size = class->parent->instance_size;
1511 real_size = sizeof (MonoObject);
1513 for (pass = 0; pass < passes; ++pass) {
1514 for (i = 0; i < top; i++){
1519 field = &class->fields [i];
1521 if (mono_field_is_deleted (field))
1523 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1526 ftype = mono_type_get_underlying_type (field->type);
1527 ftype = mono_type_get_basic_type_from_generic (ftype);
1528 if (gc_aware_layout) {
1529 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1538 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1539 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1540 /* This field is a hack inserted by MCS to empty structures */
1544 size = mono_type_size (field->type, &align);
1546 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1547 align = class->packing_size ? MIN (class->packing_size, align): align;
1548 /* if the field has managed references, we need to force-align it
1551 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1552 align = MAX (align, sizeof (gpointer));
1554 class->min_align = MAX (align, class->min_align);
1555 field->offset = real_size;
1556 field->offset += align - 1;
1557 field->offset &= ~(align - 1);
1558 real_size = field->offset + size;
1561 class->instance_size = MAX (real_size, class->instance_size);
1563 if (class->instance_size & (class->min_align - 1)) {
1564 class->instance_size += class->min_align - 1;
1565 class->instance_size &= ~(class->min_align - 1);
1569 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1571 for (i = 0; i < top; i++) {
1576 field = &class->fields [i];
1579 * There must be info about all the fields in a type if it
1580 * uses explicit layout.
1583 if (mono_field_is_deleted (field))
1585 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1588 size = mono_type_size (field->type, &align);
1589 class->min_align = MAX (align, class->min_align);
1592 * When we get here, field->offset is already set by the
1593 * loader (for either runtime fields or fields loaded from metadata).
1594 * The offset is from the start of the object: this works for both
1595 * classes and valuetypes.
1597 field->offset += sizeof (MonoObject);
1598 ftype = mono_type_get_underlying_type (field->type);
1599 ftype = mono_type_get_basic_type_from_generic (ftype);
1600 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1601 if (field->offset % sizeof (gpointer)) {
1602 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1609 real_size = MAX (real_size, size + field->offset);
1611 class->instance_size = MAX (real_size, class->instance_size);
1615 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1617 * For small structs, set min_align to at least the struct size to improve
1618 * performance, and since the JIT memset/memcpy code assumes this and generates
1619 * unaligned accesses otherwise. See #78990 for a testcase.
1621 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1622 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1625 class->size_inited = 1;
1628 * Compute static field layout and size
1630 for (i = 0; i < top; i++){
1634 field = &class->fields [i];
1636 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1638 if (mono_field_is_deleted (field))
1641 size = mono_type_size (field->type, &align);
1642 field->offset = class->sizes.class_size;
1643 field->offset += align - 1;
1644 field->offset &= ~(align - 1);
1645 class->sizes.class_size = field->offset + size;
1650 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1654 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1655 method->klass = class;
1656 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1657 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1658 method->signature = sig;
1659 method->name = name;
1662 if (name [0] == '.') {
1663 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1665 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1671 * mono_class_setup_methods:
1674 * Initializes the 'methods' array in the klass.
1675 * Calling this method should be avoided if possible since it allocates a lot
1676 * of long-living MonoMethod structures.
1677 * Methods belonging to an interface are assigned a sequential slot starting
1681 mono_class_setup_methods (MonoClass *class)
1684 MonoMethod **methods;
1689 mono_loader_lock ();
1691 if (class->methods) {
1692 mono_loader_unlock ();
1696 if (class->generic_class) {
1697 MonoClass *gklass = class->generic_class->container_class;
1699 mono_class_init (gklass);
1700 mono_class_setup_methods (gklass);
1702 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1703 class->method.count = gklass->method.count;
1704 methods = g_new0 (MonoMethod *, class->method.count + 1);
1706 for (i = 0; i < class->method.count; i++) {
1707 methods [i] = mono_class_inflate_generic_method_full (
1708 gklass->methods [i], class, mono_class_get_context (class));
1710 } else if (class->rank) {
1711 MonoMethod *amethod;
1712 MonoMethodSignature *sig;
1713 int count_generic = 0, first_generic = 0;
1716 class->method.count = 3 + (class->rank > 1? 2: 1);
1718 mono_class_setup_interfaces (class);
1720 if (class->interface_count) {
1721 count_generic = generic_array_methods (class);
1722 first_generic = class->method.count;
1723 class->method.count += class->interface_count * count_generic;
1726 methods = mono_image_alloc0 (class->image, sizeof (MonoMethod*) * class->method.count);
1728 sig = mono_metadata_signature_alloc (class->image, class->rank);
1729 sig->ret = &mono_defaults.void_class->byval_arg;
1730 sig->pinvoke = TRUE;
1731 sig->hasthis = TRUE;
1732 for (i = 0; i < class->rank; ++i)
1733 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1735 amethod = create_array_method (class, ".ctor", sig);
1736 methods [method_num++] = amethod;
1737 if (class->rank > 1) {
1738 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1739 sig->ret = &mono_defaults.void_class->byval_arg;
1740 sig->pinvoke = TRUE;
1741 sig->hasthis = TRUE;
1742 for (i = 0; i < class->rank * 2; ++i)
1743 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1745 amethod = create_array_method (class, ".ctor", sig);
1746 methods [method_num++] = amethod;
1748 /* element Get (idx11, [idx2, ...]) */
1749 sig = mono_metadata_signature_alloc (class->image, class->rank);
1750 sig->ret = &class->element_class->byval_arg;
1751 sig->pinvoke = TRUE;
1752 sig->hasthis = TRUE;
1753 for (i = 0; i < class->rank; ++i)
1754 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1755 amethod = create_array_method (class, "Get", sig);
1756 methods [method_num++] = amethod;
1757 /* element& Address (idx11, [idx2, ...]) */
1758 sig = mono_metadata_signature_alloc (class->image, class->rank);
1759 sig->ret = &class->element_class->this_arg;
1760 sig->pinvoke = TRUE;
1761 sig->hasthis = TRUE;
1762 for (i = 0; i < class->rank; ++i)
1763 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1764 amethod = create_array_method (class, "Address", sig);
1765 methods [method_num++] = amethod;
1766 /* void Set (idx11, [idx2, ...], element) */
1767 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1768 sig->ret = &mono_defaults.void_class->byval_arg;
1769 sig->pinvoke = TRUE;
1770 sig->hasthis = TRUE;
1771 for (i = 0; i < class->rank; ++i)
1772 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1773 sig->params [i] = &class->element_class->byval_arg;
1774 amethod = create_array_method (class, "Set", sig);
1775 methods [method_num++] = amethod;
1777 for (i = 0; i < class->interface_count; i++)
1778 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1780 methods = mono_image_alloc (class->image, sizeof (MonoMethod*) * class->method.count);
1781 for (i = 0; i < class->method.count; ++i) {
1782 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1783 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1787 if (MONO_CLASS_IS_INTERFACE (class)) {
1789 /*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
1790 for (i = 0; i < class->method.count; ++i) {
1791 if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
1792 methods [i]->slot = slot++;
1796 /* Needed because of the double-checking locking pattern */
1797 mono_memory_barrier ();
1799 class->methods = methods;
1801 if (mono_debugger_class_loaded_methods_func)
1802 mono_debugger_class_loaded_methods_func (class);
1804 mono_loader_unlock ();
1808 * mono_class_get_method_by_index:
1810 * Returns class->methods [index], initializing class->methods if neccesary.
1812 * LOCKING: Acquires the loader lock.
1815 mono_class_get_method_by_index (MonoClass *class, int index)
1817 /* Avoid calling setup_methods () if possible */
1818 if (class->generic_class && !class->methods) {
1819 MonoClass *gklass = class->generic_class->container_class;
1822 m = mono_class_inflate_generic_method_full (
1823 gklass->methods [index], class, mono_class_get_context (class));
1825 * If setup_methods () is called later for this class, no duplicates are created,
1826 * since inflate_generic_method guarantees that only one instance of a method
1827 * is created for each context.
1830 mono_class_setup_methods (class);
1831 g_assert (m == class->methods [index]);
1835 mono_class_setup_methods (class);
1836 g_assert (index >= 0 && index < class->method.count);
1837 return class->methods [index];
1842 * mono_class_get_inflated_method:
1844 * Given an inflated class CLASS and a method METHOD which should be a method of
1845 * CLASS's generic definition, return the inflated method corresponding to METHOD.
1848 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
1850 MonoClass *gklass = class->generic_class->container_class;
1853 mono_class_setup_methods (gklass);
1854 for (i = 0; i < gklass->method.count; ++i) {
1855 if (gklass->methods [i] == method) {
1857 return class->methods [i];
1859 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
1867 * mono_class_get_vtable_entry:
1869 * Returns class->vtable [offset], computing it if neccesary.
1870 * LOCKING: Acquires the loader lock.
1873 mono_class_get_vtable_entry (MonoClass *class, int offset)
1877 if (class->rank == 1) {
1879 * szarrays do not overwrite any methods of Array, so we can avoid
1880 * initializing their vtables in some cases.
1882 mono_class_setup_vtable (class->parent);
1883 if (offset < class->parent->vtable_size)
1884 return class->parent->vtable [offset];
1887 if (class->generic_class) {
1888 MonoClass *gklass = class->generic_class->container_class;
1889 mono_class_setup_vtable (gklass);
1890 m = gklass->vtable [offset];
1892 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
1894 mono_class_setup_vtable (class);
1895 m = class->vtable [offset];
1902 * mono_class_get_vtable_size:
1904 * Return the vtable size for KLASS.
1907 mono_class_get_vtable_size (MonoClass *klass)
1909 mono_class_setup_vtable (klass);
1911 return klass->vtable_size;
1915 mono_class_setup_properties (MonoClass *class)
1917 guint startm, endm, i, j;
1918 guint32 cols [MONO_PROPERTY_SIZE];
1919 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1920 MonoProperty *properties;
1923 if (class->ext && class->ext->properties)
1926 mono_loader_lock ();
1928 if (class->ext && class->ext->properties) {
1929 mono_loader_unlock ();
1933 mono_class_alloc_ext (class);
1935 if (class->generic_class) {
1936 MonoClass *gklass = class->generic_class->container_class;
1938 mono_class_init (gklass);
1939 mono_class_setup_properties (gklass);
1941 class->ext->property = gklass->ext->property;
1943 properties = g_new0 (MonoProperty, class->ext->property.count + 1);
1945 for (i = 0; i < class->ext->property.count; i++) {
1946 MonoProperty *prop = &properties [i];
1948 *prop = gklass->ext->properties [i];
1951 prop->get = mono_class_inflate_generic_method_full (
1952 prop->get, class, mono_class_get_context (class));
1954 prop->set = mono_class_inflate_generic_method_full (
1955 prop->set, class, mono_class_get_context (class));
1957 prop->parent = class;
1960 class->ext->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1961 class->ext->property.count = last - class->ext->property.first;
1963 if (class->ext->property.count)
1964 mono_class_setup_methods (class);
1966 properties = mono_image_alloc0 (class->image, sizeof (MonoProperty) * class->ext->property.count);
1967 for (i = class->ext->property.first; i < last; ++i) {
1968 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
1969 properties [i - class->ext->property.first].parent = class;
1970 properties [i - class->ext->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
1971 properties [i - class->ext->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
1973 startm = mono_metadata_methods_from_property (class->image, i, &endm);
1974 for (j = startm; j < endm; ++j) {
1977 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1979 if (class->image->uncompressed_metadata)
1980 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1981 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1983 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1985 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1986 case METHOD_SEMANTIC_SETTER:
1987 properties [i - class->ext->property.first].set = method;
1989 case METHOD_SEMANTIC_GETTER:
1990 properties [i - class->ext->property.first].get = method;
1998 /*Flush any pending writes as we do double checked locking on class->properties */
1999 mono_memory_barrier ();
2001 /* Leave this assignment as the last op in the function */
2002 class->ext->properties = properties;
2004 mono_loader_unlock ();
2008 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
2010 MonoMethod **om, **retval;
2013 for (om = methods, count = 0; *om; ++om, ++count)
2016 retval = g_new0 (MonoMethod*, count + 1);
2018 for (om = methods, count = 0; *om; ++om, ++count)
2019 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
2025 mono_class_setup_events (MonoClass *class)
2027 guint startm, endm, i, j;
2028 guint32 cols [MONO_EVENT_SIZE];
2029 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2033 if (class->ext && class->ext->events)
2036 mono_loader_lock ();
2038 if (class->ext && class->ext->events) {
2039 mono_loader_unlock ();
2043 mono_class_alloc_ext (class);
2045 if (class->generic_class) {
2046 MonoClass *gklass = class->generic_class->container_class;
2047 MonoGenericContext *context;
2049 mono_class_setup_events (gklass);
2050 class->ext->event = gklass->ext->event;
2052 class->ext->events = g_new0 (MonoEvent, class->ext->event.count);
2054 if (class->ext->event.count)
2055 context = mono_class_get_context (class);
2057 for (i = 0; i < class->ext->event.count; i++) {
2058 MonoEvent *event = &class->ext->events [i];
2059 MonoEvent *gevent = &gklass->ext->events [i];
2061 event->parent = class;
2062 event->name = gevent->name;
2063 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
2064 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
2065 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
2066 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
2067 event->attrs = gevent->attrs;
2070 mono_loader_unlock ();
2074 class->ext->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2075 class->ext->event.count = last - class->ext->event.first;
2077 if (class->ext->event.count)
2078 mono_class_setup_methods (class);
2080 events = mono_image_alloc0 (class->image, sizeof (MonoEvent) * class->ext->event.count);
2081 for (i = class->ext->event.first; i < last; ++i) {
2082 MonoEvent *event = &events [i - class->ext->event.first];
2084 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
2085 event->parent = class;
2086 event->attrs = cols [MONO_EVENT_FLAGS];
2087 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
2089 startm = mono_metadata_methods_from_event (class->image, i, &endm);
2090 for (j = startm; j < endm; ++j) {
2093 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2095 if (class->image->uncompressed_metadata)
2096 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2097 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2099 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2101 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2102 case METHOD_SEMANTIC_ADD_ON:
2103 event->add = method;
2105 case METHOD_SEMANTIC_REMOVE_ON:
2106 event->remove = method;
2108 case METHOD_SEMANTIC_FIRE:
2109 event->raise = method;
2111 case METHOD_SEMANTIC_OTHER: {
2114 if (event->other == NULL) {
2115 event->other = g_new0 (MonoMethod*, 2);
2117 while (event->other [n])
2119 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
2121 event->other [n] = method;
2122 /* NULL terminated */
2123 event->other [n + 1] = NULL;
2131 /*Flush any pending writes as we do double checked locking on class->properties */
2132 mono_memory_barrier ();
2134 /* Leave this assignment as the last op in the function */
2135 class->ext->events = events;
2137 mono_loader_unlock ();
2141 * Global pool of interface IDs, represented as a bitset.
2142 * LOCKING: this is supposed to be accessed with the loader lock held.
2144 static MonoBitSet *global_interface_bitset = NULL;
2147 * mono_unload_interface_ids:
2148 * @bitset: bit set of interface IDs
2150 * When an image is unloaded, the interface IDs associated with
2151 * the image are put back in the global pool of IDs so the numbers
2155 mono_unload_interface_ids (MonoBitSet *bitset)
2157 mono_loader_lock ();
2158 mono_bitset_sub (global_interface_bitset, bitset);
2159 mono_loader_unlock ();
2163 * mono_get_unique_iid:
2166 * Assign a unique integer ID to the interface represented by @class.
2167 * The ID will positive and as small as possible.
2168 * LOCKING: this is supposed to be called with the loader lock held.
2169 * Returns: the new ID.
2172 mono_get_unique_iid (MonoClass *class)
2176 g_assert (MONO_CLASS_IS_INTERFACE (class));
2178 if (!global_interface_bitset) {
2179 global_interface_bitset = mono_bitset_new (128, 0);
2182 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2184 int old_size = mono_bitset_size (global_interface_bitset);
2185 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2186 mono_bitset_free (global_interface_bitset);
2187 global_interface_bitset = new_set;
2190 mono_bitset_set (global_interface_bitset, iid);
2191 /* set the bit also in the per-image set */
2192 if (class->image->interface_bitset) {
2193 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2194 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2195 mono_bitset_free (class->image->interface_bitset);
2196 class->image->interface_bitset = new_set;
2199 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2201 mono_bitset_set (class->image->interface_bitset, iid);
2203 if (mono_print_vtable) {
2205 char *type_name = mono_type_full_name (&class->byval_arg);
2206 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2207 generic_id = class->generic_class->context.class_inst->id;
2208 g_assert (generic_id != 0);
2212 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2216 g_assert (iid <= 65535);
2221 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
2226 mono_class_setup_interfaces (klass);
2228 for (i = 0; i < klass->interface_count; i++) {
2229 ic = klass->interfaces [i];
2232 *res = g_ptr_array_new ();
2233 g_ptr_array_add (*res, ic);
2234 mono_class_init (ic);
2236 collect_implemented_interfaces_aux (ic, res);
2241 mono_class_get_implemented_interfaces (MonoClass *klass)
2243 GPtrArray *res = NULL;
2245 collect_implemented_interfaces_aux (klass, &res);
2250 compare_interface_ids (const void *p_key, const void *p_element) {
2251 const MonoClass *key = p_key;
2252 const MonoClass *element = *(MonoClass**) p_element;
2254 return (key->interface_id - element->interface_id);
2258 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2259 MonoClass **result = bsearch (
2261 klass->interfaces_packed,
2262 klass->interface_offsets_count,
2263 sizeof (MonoClass *),
2264 compare_interface_ids);
2266 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2273 print_implemented_interfaces (MonoClass *klass) {
2274 GPtrArray *ifaces = NULL;
2276 int ancestor_level = 0;
2278 printf ("Packed interface table for class %s has size %d\n", klass->name, klass->interface_offsets_count);
2279 for (i = 0; i < klass->interface_offsets_count; i++)
2280 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2281 klass->interfaces_packed [i]->interface_id,
2282 klass->interface_offsets_packed [i],
2283 klass->interfaces_packed [i]->method.count,
2284 klass->interfaces_packed [i]->name_space,
2285 klass->interfaces_packed [i]->name );
2286 printf ("Interface flags: ");
2287 for (i = 0; i <= klass->max_interface_id; i++)
2288 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2289 printf ("(%d,T)", i);
2291 printf ("(%d,F)", i);
2293 printf ("Dump interface flags:");
2294 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2295 printf (" %02X", klass->interface_bitmap [i]);
2297 while (klass != NULL) {
2298 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2299 ifaces = mono_class_get_implemented_interfaces (klass);
2301 for (i = 0; i < ifaces->len; i++) {
2302 MonoClass *ic = g_ptr_array_index (ifaces, i);
2303 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2304 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2306 mono_class_interface_offset (klass, ic),
2311 g_ptr_array_free (ifaces, TRUE);
2314 klass = klass->parent;
2319 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2322 args [0] = &arg0->byval_arg;
2324 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2328 array_class_get_if_rank (MonoClass *class, guint rank)
2330 return rank ? mono_array_class_get (class, rank) : class;
2334 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2336 valuetype_types [0] = eclass;
2337 if (eclass == mono_defaults.int16_class)
2338 valuetype_types [1] = mono_defaults.uint16_class;
2339 else if (eclass == mono_defaults.uint16_class)
2340 valuetype_types [1] = mono_defaults.int16_class;
2341 else if (eclass == mono_defaults.int32_class)
2342 valuetype_types [1] = mono_defaults.uint32_class;
2343 else if (eclass == mono_defaults.uint32_class)
2344 valuetype_types [1] = mono_defaults.int32_class;
2345 else if (eclass == mono_defaults.int64_class)
2346 valuetype_types [1] = mono_defaults.uint64_class;
2347 else if (eclass == mono_defaults.uint64_class)
2348 valuetype_types [1] = mono_defaults.int64_class;
2349 else if (eclass == mono_defaults.byte_class)
2350 valuetype_types [1] = mono_defaults.sbyte_class;
2351 else if (eclass == mono_defaults.sbyte_class)
2352 valuetype_types [1] = mono_defaults.byte_class;
2353 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2354 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2357 /* this won't be needed once bug #325495 is completely fixed
2358 * though we'll need something similar to know which interfaces to allow
2359 * in arrays when they'll be lazyly created
2361 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2362 * MS returns diferrent types based on which instance is called. For example:
2363 * object obj = new byte[10][];
2364 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2365 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2368 * Fixing this should kill quite some code, save some bits and improve compatibility.
2371 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2373 MonoClass *eclass = class->element_class;
2374 static MonoClass* generic_icollection_class = NULL;
2375 static MonoClass* generic_ienumerable_class = NULL;
2376 static MonoClass* generic_ienumerator_class = NULL;
2377 MonoClass *valuetype_types[2] = { NULL, NULL };
2378 MonoClass **interfaces = NULL;
2379 int i, interface_count, real_count, original_rank;
2381 gboolean internal_enumerator;
2382 gboolean eclass_is_valuetype;
2384 if (!mono_defaults.generic_ilist_class) {
2388 internal_enumerator = FALSE;
2389 eclass_is_valuetype = FALSE;
2390 original_rank = eclass->rank;
2391 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2392 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2394 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2396 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2397 original_rank = eclass->rank;
2398 eclass = eclass->element_class;
2399 internal_enumerator = TRUE;
2400 *is_enumerator = TRUE;
2408 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2409 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2411 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2413 if (!generic_icollection_class) {
2414 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2415 "System.Collections.Generic", "ICollection`1");
2416 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2417 "System.Collections.Generic", "IEnumerable`1");
2418 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2419 "System.Collections.Generic", "IEnumerator`1");
2422 mono_class_init (eclass);
2425 * Arrays in 2.0 need to implement a number of generic interfaces
2426 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2427 * on the element class). We collect the types needed to build the
2428 * instantiations in interfaces at intervals of 3, because 3 are
2429 * the generic interfaces needed to implement.
2431 if (eclass->valuetype) {
2432 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2434 /* IList, ICollection, IEnumerable */
2435 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2436 if (internal_enumerator) {
2438 if (valuetype_types [1])
2442 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2443 interfaces [0] = valuetype_types [0];
2444 if (valuetype_types [1])
2445 interfaces [3] = valuetype_types [1];
2447 eclass_is_valuetype = TRUE;
2450 int idepth = eclass->idepth;
2451 if (!internal_enumerator)
2453 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2454 /* we add object for interfaces and the supertypes for the other
2455 * types. The last of the supertypes is the element class itself which we
2456 * already created the explicit interfaces for (so we include it for IEnumerator
2457 * and exclude it for arrays).
2459 if (MONO_CLASS_IS_INTERFACE (eclass))
2462 interface_count += idepth;
2463 if (eclass->rank && eclass->element_class->valuetype) {
2464 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2465 if (valuetype_types [1])
2468 /* IList, ICollection, IEnumerable */
2469 interface_count *= 3;
2470 real_count = interface_count;
2471 if (internal_enumerator) {
2472 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2473 if (valuetype_types [1])
2476 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2477 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2478 interfaces [0] = mono_defaults.object_class;
2482 for (i = 0; i < idepth; i++) {
2483 mono_class_init (eclass->supertypes [i]);
2484 interfaces [j] = eclass->supertypes [i];
2488 if (all_interfaces) {
2489 for (i = 0; i < eclass->interface_offsets_count; i++) {
2490 interfaces [j] = eclass->interfaces_packed [i];
2494 for (i = 0; i < eclass->interface_count; i++) {
2495 interfaces [j] = eclass->interfaces [i];
2499 if (valuetype_types [1]) {
2500 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2505 /* instantiate the generic interfaces */
2506 for (i = 0; i < interface_count; i += 3) {
2507 MonoClass *iface = interfaces [i];
2509 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2510 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2511 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2513 if (internal_enumerator) {
2515 /* instantiate IEnumerator<iface> */
2516 for (i = 0; i < interface_count; i++) {
2517 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2519 j = interface_count;
2520 if (!eclass_is_valuetype) {
2521 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2522 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2525 for (i = 0; i < eclass->idepth; i++) {
2526 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2530 for (i = 0; i < eclass->interface_offsets_count; i++) {
2531 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2535 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2537 if (valuetype_types [1])
2538 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2542 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2543 for (i = 0; i < real_count; ++i) {
2544 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2545 g_print ("%s implements %s\n", type_name, name);
2556 find_array_interface (MonoClass *klass, const char *name)
2559 for (i = 0; i < klass->interface_count; ++i) {
2560 if (strcmp (klass->interfaces [i]->name, name) == 0)
2567 * Return the number of virtual methods.
2568 * Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
2569 * FIXME It would be nice if this information could be cached somewhere.
2572 count_virtual_methods (MonoClass *class)
2576 class = mono_class_get_generic_type_definition (class); /*We can find this information by looking at the GTD*/
2578 if (class->methods || !MONO_CLASS_HAS_STATIC_METADATA (class)) {
2579 mono_class_setup_methods (class);
2581 for (i = 0; i < class->method.count; ++i) {
2582 flags = class->methods [i]->flags;
2583 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2587 for (i = 0; i < class->method.count; ++i) {
2588 flags = mono_metadata_decode_table_row_col (class->image, MONO_TABLE_METHOD, class->method.first + i, MONO_METHOD_FLAGS);
2590 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2598 * LOCKING: this is supposed to be called with the loader lock held.
2601 setup_interface_offsets (MonoClass *class, int cur_slot)
2605 MonoClass **interfaces_full;
2606 int *interface_offsets_full;
2608 int interface_offsets_count;
2609 MonoClass **array_interfaces;
2610 int num_array_interfaces;
2611 int is_enumerator = FALSE;
2614 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
2615 * implicit interfaces have the property that they are assigned the same slot in the
2616 * vtables for compatible interfaces
2618 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
2620 /* compute maximum number of slots and maximum interface id */
2622 for (k = class; k ; k = k->parent) {
2623 for (i = 0; i < k->interface_count; i++) {
2624 ic = k->interfaces [i];
2627 mono_class_init (ic);
2629 if (max_iid < ic->interface_id)
2630 max_iid = ic->interface_id;
2632 ifaces = mono_class_get_implemented_interfaces (k);
2634 for (i = 0; i < ifaces->len; ++i) {
2635 ic = g_ptr_array_index (ifaces, i);
2636 if (max_iid < ic->interface_id)
2637 max_iid = ic->interface_id;
2639 g_ptr_array_free (ifaces, TRUE);
2642 for (i = 0; i < num_array_interfaces; ++i) {
2643 ic = array_interfaces [i];
2644 mono_class_init (ic);
2645 if (max_iid < ic->interface_id)
2646 max_iid = ic->interface_id;
2649 if (MONO_CLASS_IS_INTERFACE (class)) {
2650 if (max_iid < class->interface_id)
2651 max_iid = class->interface_id;
2653 class->max_interface_id = max_iid;
2654 /* compute vtable offset for interfaces */
2655 interfaces_full = g_malloc (sizeof (MonoClass*) * (max_iid + 1));
2656 interface_offsets_full = g_malloc (sizeof (int) * (max_iid + 1));
2658 for (i = 0; i <= max_iid; i++) {
2659 interfaces_full [i] = NULL;
2660 interface_offsets_full [i] = -1;
2663 for (k = class->parent; k ; k = k->parent) {
2664 ifaces = mono_class_get_implemented_interfaces (k);
2666 for (i = 0; i < ifaces->len; ++i) {
2668 ic = g_ptr_array_index (ifaces, i);
2670 /*Force the sharing of interface offsets between parent and subtypes.*/
2671 io = mono_class_interface_offset (k, ic);
2673 interfaces_full [ic->interface_id] = ic;
2674 interface_offsets_full [ic->interface_id] = io;
2676 g_ptr_array_free (ifaces, TRUE);
2681 ifaces = mono_class_get_implemented_interfaces (class);
2683 for (i = 0; i < ifaces->len; ++i) {
2684 ic = g_ptr_array_index (ifaces, i);
2685 if (interfaces_full [ic->interface_id] != NULL)
2687 interfaces_full [ic->interface_id] = ic;
2688 interface_offsets_full [ic->interface_id] = cur_slot;
2689 cur_slot += count_virtual_methods (ic);
2691 g_ptr_array_free (ifaces, TRUE);
2694 if (MONO_CLASS_IS_INTERFACE (class)) {
2695 interfaces_full [class->interface_id] = class;
2696 interface_offsets_full [class->interface_id] = cur_slot;
2699 if (num_array_interfaces) {
2700 if (is_enumerator) {
2701 int ienumerator_offset;
2702 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
2703 ienumerator_offset = interface_offsets_full [class->interfaces [ienumerator_idx]->interface_id];
2704 for (i = 0; i < num_array_interfaces; ++i) {
2705 ic = array_interfaces [i];
2706 interfaces_full [ic->interface_id] = ic;
2707 if (strcmp (ic->name, "IEnumerator`1") == 0)
2708 interface_offsets_full [ic->interface_id] = ienumerator_offset;
2710 g_assert_not_reached ();
2711 /*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);*/
2714 int ilist_offset, icollection_offset, ienumerable_offset;
2715 int ilist_iface_idx = find_array_interface (class, "IList`1");
2716 int icollection_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "ICollection`1");
2717 int ienumerable_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "IEnumerable`1");
2718 ilist_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interface_id];
2719 icollection_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [icollection_iface_idx]->interface_id];
2720 ienumerable_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [ienumerable_iface_idx]->interface_id];
2721 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
2722 for (i = 0; i < num_array_interfaces; ++i) {
2723 ic = array_interfaces [i];
2724 interfaces_full [ic->interface_id] = ic;
2725 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
2726 interface_offsets_full [ic->interface_id] = ilist_offset;
2727 else if (strcmp (ic->name, "ICollection`1") == 0)
2728 interface_offsets_full [ic->interface_id] = icollection_offset;
2729 else if (strcmp (ic->name, "IEnumerable`1") == 0)
2730 interface_offsets_full [ic->interface_id] = ienumerable_offset;
2732 g_assert_not_reached ();
2733 /*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);*/
2738 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2739 if (interface_offsets_full [i] != -1) {
2740 interface_offsets_count ++;
2745 * We might get called twice: once from mono_class_init () then once from
2746 * mono_class_setup_vtable ().
2748 if (class->interfaces_packed) {
2749 g_assert (class->interface_offsets_count == interface_offsets_count);
2751 class->interface_offsets_count = interface_offsets_count;
2752 class->interfaces_packed = mono_image_alloc (class->image, sizeof (MonoClass*) * interface_offsets_count);
2753 class->interface_offsets_packed = mono_image_alloc (class->image, sizeof (guint16) * interface_offsets_count);
2754 class->interface_bitmap = mono_image_alloc0 (class->image, (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0));
2755 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2756 if (interface_offsets_full [i] != -1) {
2757 class->interface_bitmap [i >> 3] |= (1 << (i & 7));
2758 class->interfaces_packed [interface_offsets_count] = interfaces_full [i];
2759 class->interface_offsets_packed [interface_offsets_count] = interface_offsets_full [i];
2760 /*if (num_array_interfaces)
2761 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]);*/
2762 interface_offsets_count ++;
2767 g_free (interfaces_full);
2768 g_free (interface_offsets_full);
2769 g_free (array_interfaces);
2771 //printf ("JUST DONE: ");
2772 //print_implemented_interfaces (class);
2778 * Setup interface offsets for interfaces.
2780 * - class->max_interface_id
2781 * - class->interface_offsets_count
2782 * - class->interfaces_packed
2783 * - class->interface_offsets_packed
2784 * - class->interface_bitmap
2787 mono_class_setup_interface_offsets (MonoClass *class)
2789 mono_loader_lock ();
2791 setup_interface_offsets (class, 0);
2793 mono_loader_unlock ();
2797 * mono_class_setup_vtable:
2799 * Creates the generic vtable of CLASS.
2800 * Initializes the following fields in MonoClass:
2803 * Plus all the fields initialized by setup_interface_offsets ().
2804 * If there is an error during vtable construction, class->exception_type is set.
2806 * LOCKING: Acquires the loader lock.
2809 mono_class_setup_vtable (MonoClass *class)
2811 MonoMethod **overrides;
2812 MonoGenericContext *context;
2821 if (mono_debug_using_mono_debugger ())
2822 /* The debugger currently depends on this */
2823 mono_class_setup_methods (class);
2825 if (MONO_CLASS_IS_INTERFACE (class)) {
2826 /* This sets method->slot for all methods if this is an interface */
2827 mono_class_setup_methods (class);
2831 mono_loader_lock ();
2833 if (class->vtable) {
2834 mono_loader_unlock ();
2838 mono_stats.generic_vtable_count ++;
2840 if (class->generic_class) {
2841 context = mono_class_get_context (class);
2842 type_token = class->generic_class->container_class->type_token;
2844 context = (MonoGenericContext *) class->generic_container;
2845 type_token = class->type_token;
2848 if (class->image->dynamic) {
2849 if (class->generic_class) {
2850 MonoClass *gklass = class->generic_class->container_class;
2852 mono_reflection_get_dynamic_overrides (gklass, &overrides, &onum);
2853 for (i = 0; i < onum; ++i) {
2854 MonoMethod *override = overrides [(i * 2) + 1];
2855 MonoMethod *inflated = NULL;
2858 for (j = 0; j < class->method.count; ++j) {
2859 if (gklass->methods [j] == override) {
2860 inflated = class->methods [j];
2864 g_assert (inflated);
2866 overrides [(i * 2) + 1] = inflated;
2869 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
2872 /* The following call fails if there are missing methods in the type */
2873 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
2877 mono_class_setup_vtable_general (class, overrides, onum);
2881 mono_loader_unlock ();
2886 #define DEBUG_INTERFACE_VTABLE_CODE 0
2887 #define TRACE_INTERFACE_VTABLE_CODE 0
2888 #define VERIFY_INTERFACE_VTABLE_CODE 0
2889 #define VTABLE_SELECTOR (1)
2891 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2892 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
2893 if (!(VTABLE_SELECTOR)) break; \
2897 #define DEBUG_INTERFACE_VTABLE(stmt)
2900 #if TRACE_INTERFACE_VTABLE_CODE
2901 #define TRACE_INTERFACE_VTABLE(stmt) do {\
2902 if (!(VTABLE_SELECTOR)) break; \
2906 #define TRACE_INTERFACE_VTABLE(stmt)
2909 #if VERIFY_INTERFACE_VTABLE_CODE
2910 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
2911 if (!(VTABLE_SELECTOR)) break; \
2915 #define VERIFY_INTERFACE_VTABLE(stmt)
2919 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2921 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
2925 GString *res = g_string_new ("");
2927 g_string_append_c (res, '(');
2928 for (i = 0; i < sig->param_count; ++i) {
2930 g_string_append_c (res, ',');
2931 mono_type_get_desc (res, sig->params [i], include_namespace);
2933 g_string_append (res, ")=>");
2934 if (sig->ret != NULL) {
2935 mono_type_get_desc (res, sig->ret, include_namespace);
2937 g_string_append (res, "NULL");
2940 g_string_free (res, FALSE);
2944 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
2945 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
2946 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
2947 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
2955 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) {
2956 MonoMethodSignature *cmsig, *imsig;
2957 if (strcmp (im->name, cm->name) == 0) {
2958 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
2959 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
2962 if (! slot_is_empty) {
2963 if (require_newslot) {
2964 if (! interface_is_explicitly_implemented_by_class) {
2965 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
2968 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
2969 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
2973 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
2976 cmsig = mono_method_signature (cm);
2977 imsig = mono_method_signature (im);
2978 if (!cmsig || !imsig) {
2979 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not resolve the signature of a virtual method"));
2983 if (! mono_metadata_signature_equal (cmsig, imsig)) {
2984 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
2985 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2986 TRACE_INTERFACE_VTABLE (printf ("]"));
2989 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
2990 /* CAS - SecurityAction.InheritanceDemand on interface */
2991 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2992 mono_secman_inheritancedemand_method (cm, im);
2995 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
2996 mono_security_core_clr_check_override (class, cm, im);
2997 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
3000 MonoClass *ic = im->klass;
3001 const char *ic_name_space = ic->name_space;
3002 const char *ic_name = ic->name;
3005 if (! require_newslot) {
3006 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
3009 if (cm->klass->rank == 0) {
3010 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
3013 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
3014 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
3015 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3016 TRACE_INTERFACE_VTABLE (printf ("]"));
3019 if (mono_class_get_image (ic) != mono_defaults.corlib) {
3020 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
3023 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
3024 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
3027 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
3028 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
3032 subname = strstr (cm->name, ic_name_space);
3033 if (subname != cm->name) {
3034 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
3037 subname += strlen (ic_name_space);
3038 if (subname [0] != '.') {
3039 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
3043 if (strstr (subname, ic_name) != subname) {
3044 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
3047 subname += strlen (ic_name);
3048 if (subname [0] != '.') {
3049 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
3053 if (strcmp (subname, im->name) != 0) {
3054 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
3058 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
3059 /* CAS - SecurityAction.InheritanceDemand on interface */
3060 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3061 mono_secman_inheritancedemand_method (cm, im);
3064 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3065 mono_security_core_clr_check_override (class, cm, im);
3067 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
3072 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3074 foreach_override (gpointer key, gpointer value, gpointer user_data) {
3075 MonoMethod *method = key;
3076 MonoMethod *override = value;
3077 MonoClass *method_class = mono_method_get_class (method);
3078 MonoClass *override_class = mono_method_get_class (override);
3080 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
3081 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
3082 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
3085 print_overrides (GHashTable *override_map, const char *message) {
3087 printf ("Override map \"%s\" START:\n", message);
3088 g_hash_table_foreach (override_map, foreach_override, NULL);
3089 printf ("Override map \"%s\" END.\n", message);
3091 printf ("Override map \"%s\" EMPTY.\n", message);
3095 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
3096 char *full_name = mono_type_full_name (&class->byval_arg);
3100 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
3102 if (print_interfaces) {
3103 print_implemented_interfaces (class);
3104 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
3107 if (class->parent) {
3108 parent_size = class->parent->vtable_size;
3112 for (i = 0; i < size; ++i) {
3113 MonoMethod *cm = vtable [i];
3115 char *cm_name = mono_method_full_name (cm, TRUE);
3116 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
3117 printf (" [%c][%03d][INDEX %03d] %s\n", newness, i, cm->slot, cm_name);
3126 #if VERIFY_INTERFACE_VTABLE_CODE
3128 mono_method_try_get_vtable_index (MonoMethod *method)
3130 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3131 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3132 if (imethod->declaring->is_generic)
3133 return imethod->declaring->slot;
3135 return method->slot;
3139 mono_class_verify_vtable (MonoClass *class)
3142 char *full_name = mono_type_full_name (&class->byval_arg);
3144 printf ("*** Verifying VTable of class '%s' \n", full_name);
3148 if (!class->methods)
3151 for (i = 0; i < class->method.count; ++i) {
3152 MonoMethod *cm = class->methods [i];
3155 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
3159 full_name = mono_method_full_name (cm, TRUE);
3161 slot = mono_method_try_get_vtable_index (cm);
3163 if (slot >= class->vtable_size) {
3164 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
3168 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
3169 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3170 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3171 g_free (other_name);
3174 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3181 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3183 char *method_signature;
3186 for (index = 0; index < onum; ++index) {
3187 g_print (" at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
3188 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3190 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3191 type_name = mono_type_full_name (&class->byval_arg);
3192 printf ("no implementation for interface method %s::%s(%s) in class %s\n",
3193 mono_type_get_name (&ic->byval_arg), im->name, method_signature, type_name);
3194 g_free (method_signature);
3196 mono_class_setup_methods (class);
3197 for (index = 0; index < class->method.count; ++index) {
3198 MonoMethod *cm = class->methods [index];
3199 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3201 printf ("METHOD %s(%s)\n", cm->name, method_signature);
3202 g_free (method_signature);
3207 verify_class_overrides (MonoClass *class, MonoMethod **overrides, int onum)
3211 for (i = 0; i < onum; ++i) {
3212 MonoMethod *decl = overrides [i * 2];
3213 MonoMethod *body = overrides [i * 2 + 1];
3215 if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (class)) {
3216 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method belongs to a different class than the declared one"));
3220 if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
3221 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3222 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must not be static to override a base type"));
3224 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must be virtual to override a base type"));
3228 if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
3229 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3230 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a static method in a base type"));
3232 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a non virtual method in a base type"));
3236 if (!mono_class_is_assignable_from_slow (decl->klass, class)) {
3237 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method overrides a class or interface that extended or implemented by this type"));
3244 * LOCKING: this is supposed to be called with the loader lock held.
3247 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
3250 MonoMethod **vtable;
3251 int i, max_vtsize = 0, max_iid, cur_slot = 0;
3252 GPtrArray *ifaces = NULL;
3253 GHashTable *override_map = NULL;
3254 gboolean security_enabled = mono_is_security_manager_active ();
3256 gpointer class_iter;
3257 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3258 int first_non_interface_slot;
3260 GSList *virt_methods, *l;
3265 if (overrides && !verify_class_overrides (class, overrides, onum))
3268 ifaces = mono_class_get_implemented_interfaces (class);
3271 for (i = 0; i < ifaces->len; i++) {
3272 MonoClass *ic = g_ptr_array_index (ifaces, i);
3273 max_vtsize += ic->method.count;
3275 g_ptr_array_free (ifaces, TRUE);
3279 if (class->parent) {
3280 mono_class_init (class->parent);
3281 mono_class_setup_vtable (class->parent);
3282 max_vtsize += class->parent->vtable_size;
3283 cur_slot = class->parent->vtable_size;
3286 max_vtsize += class->method.count;
3288 vtable = alloca (sizeof (gpointer) * max_vtsize);
3289 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3291 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3293 cur_slot = setup_interface_offsets (class, cur_slot);
3294 max_iid = class->max_interface_id;
3295 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3297 /* Optimized version for generic instances */
3298 if (class->generic_class) {
3299 MonoClass *gklass = class->generic_class->container_class;
3302 mono_class_setup_vtable (gklass);
3303 if (gklass->exception_type != MONO_EXCEPTION_NONE) {
3304 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3308 tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * gklass->vtable_size);
3309 class->vtable_size = gklass->vtable_size;
3310 for (i = 0; i < gklass->vtable_size; ++i)
3311 if (gklass->vtable [i]) {
3312 tmp [i] = mono_class_inflate_generic_method_full (gklass->vtable [i], class, mono_class_get_context (class));
3313 tmp [i]->slot = gklass->vtable [i]->slot;
3315 mono_memory_barrier ();
3316 class->vtable = tmp;
3318 /* Have to set method->slot for abstract virtual methods */
3319 if (class->methods && gklass->methods) {
3320 for (i = 0; i < class->method.count; ++i)
3321 if (class->methods [i]->slot == -1)
3322 class->methods [i]->slot = gklass->methods [i]->slot;
3328 if (class->parent && class->parent->vtable_size) {
3329 MonoClass *parent = class->parent;
3332 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
3334 // Also inherit parent interface vtables, just as a starting point.
3335 // This is needed otherwise bug-77127.exe fails when the property methods
3336 // have different names in the iterface and the class, because for child
3337 // classes the ".override" information is not used anymore.
3338 for (i = 0; i < parent->interface_offsets_count; i++) {
3339 MonoClass *parent_interface = parent->interfaces_packed [i];
3340 int interface_offset = mono_class_interface_offset (class, parent_interface);
3341 /*FIXME this is now dead code as this condition will never hold true.
3342 Since interface offsets are inherited then the offset of an interface implemented
3343 by a parent will never be the out of it's vtable boundary.
3345 if (interface_offset >= parent->vtable_size) {
3346 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
3349 mono_class_setup_methods (parent_interface);
3350 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
3351 for (j = 0; j < parent_interface->method.count; j++) {
3352 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
3353 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
3354 parent_interface_offset + j, parent_interface_offset, j,
3355 interface_offset + j, interface_offset, j));
3362 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
3363 /* override interface methods */
3364 for (i = 0; i < onum; i++) {
3365 MonoMethod *decl = overrides [i*2];
3366 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
3368 dslot = mono_method_get_vtable_slot (decl);
3370 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3374 dslot += mono_class_interface_offset (class, decl->klass);
3375 vtable [dslot] = overrides [i*2 + 1];
3376 vtable [dslot]->slot = dslot;
3378 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3380 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
3382 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3383 mono_security_core_clr_check_override (class, vtable [dslot], decl);
3386 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
3387 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
3390 * Create a list of virtual methods to avoid calling
3391 * mono_class_get_virtual_methods () which is slow because of the metadata
3395 gpointer iter = NULL;
3398 virt_methods = NULL;
3399 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
3400 virt_methods = g_slist_prepend (virt_methods, cm);
3404 // Loop on all implemented interfaces...
3405 for (i = 0; i < class->interface_offsets_count; i++) {
3406 MonoClass *parent = class->parent;
3408 gboolean interface_is_explicitly_implemented_by_class;
3411 ic = class->interfaces_packed [i];
3412 ic_offset = mono_class_interface_offset (class, ic);
3414 mono_class_setup_methods (ic);
3416 // Check if this interface is explicitly implemented (instead of just inherited)
3417 if (parent != NULL) {
3418 int implemented_interfaces_index;
3419 interface_is_explicitly_implemented_by_class = FALSE;
3420 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
3421 if (ic == class->interfaces [implemented_interfaces_index]) {
3422 interface_is_explicitly_implemented_by_class = TRUE;
3427 interface_is_explicitly_implemented_by_class = TRUE;
3430 // Loop on all interface methods...
3431 for (im_index = 0; im_index < ic->method.count; im_index++) {
3432 MonoMethod *im = ic->methods [im_index];
3433 int im_slot = ic_offset + im->slot;
3434 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
3436 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3439 // If there is an explicit implementation, just use it right away,
3440 // otherwise look for a matching method
3441 if (override_im == NULL) {
3446 // First look for a suitable method among the class methods
3448 for (l = virt_methods; l; l = l->next) {
3450 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)));
3451 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
3452 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
3453 vtable [im_slot] = cm;
3454 /* Why do we need this? */
3459 TRACE_INTERFACE_VTABLE (printf ("\n"));
3460 if (class->exception_type) /*Might be set by check_interface_method_override*/
3464 // If the slot is still empty, look in all the inherited virtual methods...
3465 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
3466 MonoClass *parent = class->parent;
3467 // Reverse order, so that last added methods are preferred
3468 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
3469 MonoMethod *cm = parent->vtable [cm_index];
3471 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));
3472 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
3473 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
3474 vtable [im_slot] = cm;
3475 /* Why do we need this? */
3481 if (class->exception_type) /*Might be set by check_interface_method_override*/
3483 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
3487 g_assert (vtable [im_slot] == override_im);
3492 // If the class is not abstract, check that all its interface slots are full.
3493 // The check is done here and not directly at the end of the loop above because
3494 // it can happen (for injected generic array interfaces) that the same slot is
3495 // processed multiple times (those interfaces have overlapping slots), and it
3496 // will not always be the first pass the one that fills the slot.
3497 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3498 for (i = 0; i < class->interface_offsets_count; i++) {
3502 ic = class->interfaces_packed [i];
3503 ic_offset = mono_class_interface_offset (class, ic);
3505 for (im_index = 0; im_index < ic->method.count; im_index++) {
3506 MonoMethod *im = ic->methods [im_index];
3507 int im_slot = ic_offset + im->slot;
3509 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3512 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
3513 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
3514 if (vtable [im_slot] == NULL) {
3515 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
3516 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3518 g_hash_table_destroy (override_map);
3525 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
3527 for (l = virt_methods; l; l = l->next) {
3530 * If the method is REUSE_SLOT, we must check in the
3531 * base class for a method to override.
3533 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3535 for (k = class->parent; k ; k = k->parent) {
3540 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
3541 MonoMethodSignature *cmsig, *m1sig;
3543 cmsig = mono_method_signature (cm);
3544 m1sig = mono_method_signature (m1);
3546 if (!cmsig || !m1sig) {
3547 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3551 if (!strcmp(cm->name, m1->name) &&
3552 mono_metadata_signature_equal (cmsig, m1sig)) {
3554 /* CAS - SecurityAction.InheritanceDemand */
3555 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3556 mono_secman_inheritancedemand_method (cm, m1);
3559 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3560 mono_security_core_clr_check_override (class, cm, m1);
3562 slot = mono_method_get_vtable_slot (m1);
3564 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3568 g_assert (cm->slot < max_vtsize);
3570 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3571 g_hash_table_insert (override_map, m1, cm);
3582 /*Non final newslot methods must be given a non-interface vtable slot*/
3583 if ((cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && !(cm->flags & METHOD_ATTRIBUTE_FINAL) && cm->slot >= 0)
3587 cm->slot = cur_slot++;
3589 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
3590 vtable [cm->slot] = cm;
3593 /* override non interface methods */
3594 for (i = 0; i < onum; i++) {
3595 MonoMethod *decl = overrides [i*2];
3596 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
3597 g_assert (decl->slot != -1);
3598 vtable [decl->slot] = overrides [i*2 + 1];
3599 overrides [i * 2 + 1]->slot = decl->slot;
3601 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3602 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
3604 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3605 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
3610 * If a method occupies more than one place in the vtable, and it is
3611 * overriden, then change the other occurances too.
3614 for (i = 0; i < max_vtsize; ++i)
3616 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
3621 g_hash_table_destroy (override_map);
3624 g_slist_free (virt_methods);
3626 /* Ensure that all vtable slots are filled with concrete instance methods */
3627 if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3628 for (i = 0; i < cur_slot; ++i) {
3629 if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
3630 char *type_name = mono_type_get_full_name (class);
3631 char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
3632 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));
3634 g_free (method_name);
3640 if (class->generic_class) {
3641 MonoClass *gklass = class->generic_class->container_class;
3643 mono_class_init (gklass);
3645 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
3647 /* Check that the vtable_size value computed in mono_class_init () is correct */
3648 if (class->vtable_size)
3649 g_assert (cur_slot == class->vtable_size);
3650 class->vtable_size = cur_slot;
3653 /* Try to share the vtable with our parent. */
3654 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
3655 mono_memory_barrier ();
3656 class->vtable = class->parent->vtable;
3658 MonoMethod **tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * class->vtable_size);
3659 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
3660 mono_memory_barrier ();
3661 class->vtable = tmp;
3664 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
3665 if (mono_print_vtable) {
3668 print_implemented_interfaces (class);
3670 for (i = 0; i <= max_iid; i++)
3671 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
3674 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
3675 class->vtable_size, icount);
3677 for (i = 0; i < cur_slot; ++i) {
3682 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
3683 mono_method_full_name (cm, TRUE));
3689 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
3690 class->name, max_iid);
3692 for (i = 0; i < class->interface_count; i++) {
3693 ic = class->interfaces [i];
3694 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
3695 mono_class_interface_offset (class, ic),
3696 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
3699 for (k = class->parent; k ; k = k->parent) {
3700 for (i = 0; i < k->interface_count; i++) {
3701 ic = k->interfaces [i];
3702 printf (" parent slot offset: %03d, method count: %03d, iid: %03d %s\n",
3703 mono_class_interface_offset (class, ic),
3704 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
3710 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
3714 * mono_method_get_vtable_slot:
3716 * Returns method->slot, computing it if neccesary. Return -1 on failure.
3717 * LOCKING: Acquires the loader lock.
3719 * FIXME Use proper MonoError machinery here.
3722 mono_method_get_vtable_slot (MonoMethod *method)
3724 if (method->slot == -1) {
3725 mono_class_setup_vtable (method->klass);
3726 if (method->klass->exception_type)
3728 g_assert (method->slot != -1);
3730 return method->slot;
3734 * mono_method_get_vtable_index:
3737 * Returns the index into the runtime vtable to access the method or,
3738 * in the case of a virtual generic method, the virtual generic method
3739 * thunk. Returns -1 on failure.
3741 * FIXME Use proper MonoError machinery here.
3744 mono_method_get_vtable_index (MonoMethod *method)
3746 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3747 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3748 if (imethod->declaring->is_generic)
3749 return mono_method_get_vtable_slot (imethod->declaring);
3751 return mono_method_get_vtable_slot (method);
3754 static MonoMethod *default_ghc = NULL;
3755 static MonoMethod *default_finalize = NULL;
3756 static int finalize_slot = -1;
3757 static int ghc_slot = -1;
3760 initialize_object_slots (MonoClass *class)
3765 if (class == mono_defaults.object_class) {
3766 mono_class_setup_vtable (class);
3767 for (i = 0; i < class->vtable_size; ++i) {
3768 MonoMethod *cm = class->vtable [i];
3770 if (!strcmp (cm->name, "GetHashCode"))
3772 else if (!strcmp (cm->name, "Finalize"))
3776 g_assert (ghc_slot > 0);
3777 default_ghc = class->vtable [ghc_slot];
3779 g_assert (finalize_slot > 0);
3780 default_finalize = class->vtable [finalize_slot];
3785 MonoMethod *array_method;
3787 } GenericArrayMethodInfo;
3789 static int generic_array_method_num = 0;
3790 static GenericArrayMethodInfo *generic_array_method_info = NULL;
3793 generic_array_methods (MonoClass *class)
3795 int i, count_generic = 0;
3796 GList *list = NULL, *tmp;
3797 if (generic_array_method_num)
3798 return generic_array_method_num;
3799 mono_class_setup_methods (class->parent);
3800 for (i = 0; i < class->parent->method.count; i++) {
3801 MonoMethod *m = class->parent->methods [i];
3802 if (!strncmp (m->name, "InternalArray__", 15)) {
3804 list = g_list_prepend (list, m);
3807 list = g_list_reverse (list);
3808 generic_array_method_info = g_malloc (sizeof (GenericArrayMethodInfo) * count_generic);
3810 for (tmp = list; tmp; tmp = tmp->next) {
3811 const char *mname, *iname;
3813 MonoMethod *m = tmp->data;
3814 generic_array_method_info [i].array_method = m;
3815 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
3816 iname = "System.Collections.Generic.ICollection`1.";
3817 mname = m->name + 27;
3818 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
3819 iname = "System.Collections.Generic.IEnumerable`1.";
3820 mname = m->name + 27;
3821 } else if (!strncmp (m->name, "InternalArray__", 15)) {
3822 iname = "System.Collections.Generic.IList`1.";
3823 mname = m->name + 15;
3825 g_assert_not_reached ();
3828 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
3829 strcpy (name, iname);
3830 strcpy (name + strlen (iname), mname);
3831 generic_array_method_info [i].name = name;
3834 /*g_print ("array generic methods: %d\n", count_generic);*/
3836 generic_array_method_num = count_generic;
3838 return generic_array_method_num;
3842 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
3844 MonoGenericContext tmp_context;
3847 tmp_context.class_inst = NULL;
3848 tmp_context.method_inst = iface->generic_class->context.class_inst;
3849 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
3851 for (i = 0; i < generic_array_method_num; i++) {
3852 MonoMethod *m = generic_array_method_info [i].array_method;
3853 MonoMethod *inflated;
3855 inflated = mono_class_inflate_generic_method (m, &tmp_context);
3856 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
3861 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
3863 int len = strlen (s1) + strlen (s2) + 2;
3864 char *s = mono_image_alloc (image, len);
3867 result = g_snprintf (s, len, "%s%c%s", s1, '\0', s2);
3868 g_assert (result == len - 1);
3874 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
3876 gpointer exception_data = NULL;
3878 switch (error->exception_type) {
3879 case MONO_EXCEPTION_TYPE_LOAD:
3880 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
3883 case MONO_EXCEPTION_MISSING_METHOD:
3884 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
3887 case MONO_EXCEPTION_MISSING_FIELD: {
3888 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
3889 const char *class_name;
3892 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
3894 class_name = error->klass->name;
3896 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
3899 g_free ((void*)class_name);
3903 case MONO_EXCEPTION_FILE_NOT_FOUND: {
3906 if (error->ref_only)
3907 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.";
3909 msg = "Could not load file or assembly '%s' or one of its dependencies.";
3911 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
3915 case MONO_EXCEPTION_BAD_IMAGE:
3916 exception_data = error->msg;
3920 g_assert_not_reached ();
3923 mono_class_set_failure (class, error->exception_type, exception_data);
3928 * @class: the class to initialize
3930 * Compute the instance_size, class_size and other infos that cannot be
3931 * computed at mono_class_get() time. Also compute vtable_size if possible.
3932 * Returns TRUE on success or FALSE if there was a problem in loading
3933 * the type (incorrect assemblies, missing assemblies, methods, etc).
3935 * LOCKING: Acquires the loader lock.
3938 mono_class_init (MonoClass *class)
3941 MonoCachedClassInfo cached_info;
3942 gboolean has_cached_info;
3943 int class_init_ok = TRUE;
3947 /* Double-checking locking pattern */
3949 return class->exception_type == MONO_EXCEPTION_NONE;
3951 /*g_print ("Init class %s\n", class->name);*/
3953 /* We do everything inside the lock to prevent races */
3954 mono_loader_lock ();
3956 if (class->inited) {
3957 mono_loader_unlock ();
3958 /* Somebody might have gotten in before us */
3959 return class->exception_type == MONO_EXCEPTION_NONE;
3962 if (class->init_pending) {
3963 mono_loader_unlock ();
3964 /* this indicates a cyclic dependency */
3965 g_error ("pending init %s.%s\n", class->name_space, class->name);
3968 class->init_pending = 1;
3970 if (class->byval_arg.type == MONO_TYPE_ARRAY || class->byval_arg.type == MONO_TYPE_SZARRAY) {
3971 MonoClass *element_class = class->element_class;
3972 if (!element_class->inited)
3973 mono_class_init (element_class);
3974 if (element_class->exception_type != MONO_EXCEPTION_NONE) {
3975 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3980 /* CAS - SecurityAction.InheritanceDemand */
3981 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
3982 mono_secman_inheritancedemand_class (class, class->parent);
3985 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3986 mono_security_core_clr_check_inheritance (class);
3988 mono_stats.initialized_class_count++;
3990 if (class->generic_class && !class->generic_class->is_dynamic) {
3991 MonoClass *gklass = class->generic_class->container_class;
3993 mono_stats.generic_class_count++;
3995 class->method = gklass->method;
3996 class->field = gklass->field;
3998 mono_class_init (gklass);
3999 // FIXME: Why is this needed ?
4000 mono_class_setup_methods (gklass);
4002 if (MONO_CLASS_IS_INTERFACE (class))
4003 class->interface_id = mono_get_unique_iid (class);
4006 if (class->parent && !class->parent->inited)
4007 mono_class_init (class->parent);
4009 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
4011 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
4012 class->nested_classes_inited = TRUE;
4015 * Computes the size used by the fields, and their locations
4017 if (has_cached_info) {
4018 class->instance_size = cached_info.instance_size;
4019 class->sizes.class_size = cached_info.class_size;
4020 class->packing_size = cached_info.packing_size;
4021 class->min_align = cached_info.min_align;
4022 class->blittable = cached_info.blittable;
4023 class->has_references = cached_info.has_references;
4024 class->has_static_refs = cached_info.has_static_refs;
4025 class->no_special_static_fields = cached_info.no_special_static_fields;
4028 if (!class->size_inited){
4029 mono_class_setup_fields (class);
4030 if (class->exception_type || mono_loader_get_last_error ()){
4031 class_init_ok = FALSE;
4036 /* Initialize arrays */
4038 class->method.count = 3 + (class->rank > 1? 2: 1);
4040 if (class->interface_count) {
4041 int count_generic = generic_array_methods (class);
4042 class->method.count += class->interface_count * count_generic;
4046 mono_class_setup_supertypes (class);
4049 initialize_object_slots (class);
4052 * Initialize the rest of the data without creating a generic vtable if possible.
4053 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
4054 * also avoid computing a generic vtable.
4056 if (has_cached_info) {
4058 class->vtable_size = cached_info.vtable_size;
4059 class->has_finalize = cached_info.has_finalize;
4060 class->ghcimpl = cached_info.ghcimpl;
4061 class->has_cctor = cached_info.has_cctor;
4062 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
4063 static int szarray_vtable_size = 0;
4066 if (!szarray_vtable_size) {
4067 mono_class_setup_vtable (class);
4068 szarray_vtable_size = class->vtable_size;
4070 class->vtable_size = szarray_vtable_size;
4072 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
4073 MonoClass *gklass = class->generic_class->container_class;
4075 /* Generic instance case */
4076 class->ghcimpl = gklass->ghcimpl;
4077 class->has_finalize = gklass->has_finalize;
4078 class->has_cctor = gklass->has_cctor;
4080 mono_class_setup_vtable (gklass);
4081 if (gklass->exception_type) {
4082 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4086 class->vtable_size = gklass->vtable_size;
4090 /* ghcimpl is not currently used
4092 if (class->parent) {
4093 MonoMethod *cmethod = class->vtable [ghc_slot];
4094 if (cmethod->is_inflated)
4095 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4096 if (cmethod == default_ghc) {
4102 /* Interfaces and valuetypes are not supposed to have finalizers */
4103 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
4104 MonoMethod *cmethod = NULL;
4106 if (class->parent && class->parent->has_finalize) {
4107 class->has_finalize = 1;
4109 if (class->type_token) {
4110 cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
4111 } else if (class->parent) {
4112 /* FIXME: Optimize this */
4113 mono_class_setup_vtable (class);
4114 if (class->exception_type || mono_loader_get_last_error ())
4116 cmethod = class->vtable [finalize_slot];
4120 /* Check that this is really the finalizer method */
4121 mono_class_setup_vtable (class);
4122 if (class->exception_type || mono_loader_get_last_error ())
4125 class->has_finalize = 0;
4126 if (class->parent) {
4127 cmethod = class->vtable [finalize_slot];
4128 if (cmethod->is_inflated)
4129 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4130 if (cmethod != default_finalize) {
4131 class->has_finalize = 1;
4138 /* C# doesn't allow interfaces to have cctors */
4139 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
4140 MonoMethod *cmethod = NULL;
4142 if (class->type_token) {
4143 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
4144 /* The find_method function ignores the 'flags' argument */
4145 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
4146 class->has_cctor = 1;
4148 mono_class_setup_methods (class);
4150 for (i = 0; i < class->method.count; ++i) {
4151 MonoMethod *method = class->methods [i];
4152 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4153 (strcmp (".cctor", method->name) == 0)) {
4154 class->has_cctor = 1;
4162 if (!mono_setup_vtable_in_class_init) {
4164 * This is an embedding API break, since the caller might assume that
4165 * mono_class_init () constructs a generic vtable, so vtable construction errors
4166 * are visible right after the mono_class_init (), and not after
4167 * mono_class_vtable ().
4169 if (class->parent) {
4170 /* This will compute class->parent->vtable_size for some classes */
4171 mono_class_init (class->parent);
4172 if (class->parent->exception_type) {
4173 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4176 if (mono_loader_get_last_error ())
4178 if (!class->parent->vtable_size) {
4179 /* FIXME: Get rid of this somehow */
4180 mono_class_setup_vtable (class->parent);
4181 if (class->parent->exception_type) {
4182 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4185 if (mono_loader_get_last_error ())
4188 setup_interface_offsets (class, class->parent->vtable_size);
4190 setup_interface_offsets (class, 0);
4193 mono_class_setup_vtable (class);
4195 if (MONO_CLASS_IS_INTERFACE (class))
4196 setup_interface_offsets (class, 0);
4199 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
4200 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
4201 class_init_ok = FALSE;
4207 class_init_ok = FALSE;
4210 /* Because of the double-checking locking pattern */
4211 mono_memory_barrier ();
4213 class->init_pending = 0;
4215 if (mono_loader_get_last_error ()) {
4216 if (class->exception_type == MONO_EXCEPTION_NONE)
4217 set_failure_from_loader_error (class, mono_loader_get_last_error ());
4219 mono_loader_clear_error ();
4222 mono_loader_unlock ();
4224 if (mono_debugger_class_init_func)
4225 mono_debugger_class_init_func (class);
4227 return class_init_ok;
4231 is_corlib_image (MonoImage *image)
4233 /* FIXME: allow the dynamic case for our compilers and with full trust */
4235 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
4237 return image == mono_defaults.corlib;
4241 * LOCKING: this assumes the loader lock is held
4244 mono_class_setup_mono_type (MonoClass *class)
4246 const char *name = class->name;
4247 const char *nspace = class->name_space;
4248 gboolean is_corlib = is_corlib_image (class->image);
4250 class->this_arg.byref = 1;
4251 class->this_arg.data.klass = class;
4252 class->this_arg.type = MONO_TYPE_CLASS;
4253 class->byval_arg.data.klass = class;
4254 class->byval_arg.type = MONO_TYPE_CLASS;
4256 if (is_corlib && !strcmp (nspace, "System")) {
4257 if (!strcmp (name, "ValueType")) {
4259 * do not set the valuetype bit for System.ValueType.
4260 * class->valuetype = 1;
4262 class->blittable = TRUE;
4263 } else if (!strcmp (name, "Enum")) {
4265 * do not set the valuetype bit for System.Enum.
4266 * class->valuetype = 1;
4268 class->valuetype = 0;
4269 class->enumtype = 0;
4270 } else if (!strcmp (name, "Object")) {
4271 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
4272 } else if (!strcmp (name, "String")) {
4273 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
4274 } else if (!strcmp (name, "TypedReference")) {
4275 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
4279 if (class->valuetype) {
4280 int t = MONO_TYPE_VALUETYPE;
4282 if (is_corlib && !strcmp (nspace, "System")) {
4285 if (!strcmp (name, "Boolean")) {
4286 t = MONO_TYPE_BOOLEAN;
4287 } else if (!strcmp(name, "Byte")) {
4289 class->blittable = TRUE;
4293 if (!strcmp (name, "Char")) {
4298 if (!strcmp (name, "Double")) {
4300 class->blittable = TRUE;
4304 if (!strcmp (name, "Int32")) {
4306 class->blittable = TRUE;
4307 } else if (!strcmp(name, "Int16")) {
4309 class->blittable = TRUE;
4310 } else if (!strcmp(name, "Int64")) {
4312 class->blittable = TRUE;
4313 } else if (!strcmp(name, "IntPtr")) {
4315 class->blittable = TRUE;
4319 if (!strcmp (name, "Single")) {
4321 class->blittable = TRUE;
4322 } else if (!strcmp(name, "SByte")) {
4324 class->blittable = TRUE;
4328 if (!strcmp (name, "UInt32")) {
4330 class->blittable = TRUE;
4331 } else if (!strcmp(name, "UInt16")) {
4333 class->blittable = TRUE;
4334 } else if (!strcmp(name, "UInt64")) {
4336 class->blittable = TRUE;
4337 } else if (!strcmp(name, "UIntPtr")) {
4339 class->blittable = TRUE;
4343 if (!strcmp (name, "TypedReference")) {
4344 t = MONO_TYPE_TYPEDBYREF;
4345 class->blittable = TRUE;
4349 if (!strcmp (name, "Void")) {
4357 class->this_arg.type = class->byval_arg.type = t;
4360 if (MONO_CLASS_IS_INTERFACE (class))
4361 class->interface_id = mono_get_unique_iid (class);
4366 * COM initialization (using mono_init_com_types) is delayed until needed.
4367 * However when a [ComImport] attribute is present on a type it will trigger
4368 * the initialization. This is not a problem unless the BCL being executed
4369 * lacks the types that COM depends on (e.g. Variant on Silverlight).
4372 init_com_from_comimport (MonoClass *class)
4374 /* we don't always allow COM initialization under the CoreCLR (e.g. Moonlight does not require it) */
4375 if ((mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)) {
4376 /* but some other CoreCLR user could requires it for their platform (i.e. trusted) code */
4377 if (!mono_security_core_clr_determine_platform_image (class->image)) {
4378 /* but it can not be made available for application (i.e. user code) since all COM calls
4379 * are considered native calls. In this case we fail with a TypeLoadException (just like
4380 * Silverlight 2 does */
4381 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4385 /* FIXME : we should add an extra checks to ensure COM can be initialized properly before continuing */
4386 mono_init_com_types ();
4390 * LOCKING: this assumes the loader lock is held
4393 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
4395 gboolean system_namespace;
4396 gboolean is_corlib = is_corlib_image (class->image);
4398 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
4400 /* if root of the hierarchy */
4401 if (system_namespace && !strcmp (class->name, "Object")) {
4402 class->parent = NULL;
4403 class->instance_size = sizeof (MonoObject);
4406 if (!strcmp (class->name, "<Module>")) {
4407 class->parent = NULL;
4408 class->instance_size = 0;
4412 if (!MONO_CLASS_IS_INTERFACE (class)) {
4413 /* Imported COM Objects always derive from __ComObject. */
4414 if (MONO_CLASS_IS_IMPORT (class)) {
4415 init_com_from_comimport (class);
4416 if (parent == mono_defaults.object_class)
4417 parent = mono_defaults.com_object_class;
4420 /* set the parent to something useful and safe, but mark the type as broken */
4421 parent = mono_defaults.object_class;
4422 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4425 class->parent = parent;
4427 if (parent->generic_class && !parent->name) {
4429 * If the parent is a generic instance, we may get
4430 * called before it is fully initialized, especially
4431 * before it has its name.
4436 class->marshalbyref = parent->marshalbyref;
4437 class->contextbound = parent->contextbound;
4438 class->delegate = parent->delegate;
4439 if (MONO_CLASS_IS_IMPORT (class))
4440 class->is_com_object = 1;
4442 class->is_com_object = parent->is_com_object;
4444 if (system_namespace) {
4445 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
4446 class->marshalbyref = 1;
4448 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
4449 class->contextbound = 1;
4451 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
4452 class->delegate = 1;
4455 if (class->parent->enumtype || (is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
4456 (strcmp (class->parent->name_space, "System") == 0)))
4457 class->valuetype = 1;
4458 if (is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
4459 class->valuetype = class->enumtype = 1;
4461 /*class->enumtype = class->parent->enumtype; */
4462 mono_class_setup_supertypes (class);
4464 /* initialize com types if COM interfaces are present */
4465 if (MONO_CLASS_IS_IMPORT (class))
4466 init_com_from_comimport (class);
4467 class->parent = NULL;
4473 * mono_class_setup_supertypes:
4476 * Build the data structure needed to make fast type checks work.
4477 * This currently sets two fields in @class:
4478 * - idepth: distance between @class and System.Object in the type
4480 * - supertypes: array of classes: each element has a class in the hierarchy
4481 * starting from @class up to System.Object
4483 * LOCKING: this assumes the loader lock is held
4486 mono_class_setup_supertypes (MonoClass *class)
4490 if (class->supertypes)
4493 if (class->parent && !class->parent->supertypes)
4494 mono_class_setup_supertypes (class->parent);
4496 class->idepth = class->parent->idepth + 1;
4500 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
4501 class->supertypes = mono_image_alloc0 (class->image, sizeof (MonoClass *) * ms);
4503 if (class->parent) {
4504 class->supertypes [class->idepth - 1] = class;
4505 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
4507 class->supertypes [0] = class;
4512 * mono_class_create_from_typedef:
4513 * @image: image where the token is valid
4514 * @type_token: typedef token
4516 * Create the MonoClass* representing the specified type token.
4517 * @type_token must be a TypeDef token.
4520 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
4522 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
4523 MonoClass *class, *parent = NULL;
4524 guint32 cols [MONO_TYPEDEF_SIZE];
4525 guint32 cols_next [MONO_TYPEDEF_SIZE];
4526 guint tidx = mono_metadata_token_index (type_token);
4527 MonoGenericContext *context = NULL;
4528 const char *name, *nspace;
4530 MonoClass **interfaces;
4531 guint32 field_last, method_last;
4532 guint32 nesting_tokeen;
4534 mono_loader_lock ();
4536 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
4537 mono_loader_unlock ();
4541 g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
4543 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
4545 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
4546 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
4548 class = mono_image_alloc0 (image, sizeof (MonoClass));
4551 class->name_space = nspace;
4553 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4555 class->image = image;
4556 class->type_token = type_token;
4557 class->flags = cols [MONO_TYPEDEF_FLAGS];
4559 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
4561 classes_size += sizeof (MonoClass);
4564 * Check whether we're a generic type definition.
4566 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
4567 if (class->generic_container) {
4568 class->is_generic = 1;
4569 class->generic_container->owner.klass = class;
4570 context = &class->generic_container->context;
4573 if (cols [MONO_TYPEDEF_EXTENDS]) {
4574 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
4576 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
4577 /*WARNING: this must satisfy mono_metadata_type_hash*/
4578 class->this_arg.byref = 1;
4579 class->this_arg.data.klass = class;
4580 class->this_arg.type = MONO_TYPE_CLASS;
4581 class->byval_arg.data.klass = class;
4582 class->byval_arg.type = MONO_TYPE_CLASS;
4584 parent = mono_class_get_full (image, parent_token, context);
4586 if (parent == NULL){
4587 mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
4588 mono_loader_unlock ();
4589 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4594 /* do this early so it's available for interfaces in setup_mono_type () */
4595 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token)))
4596 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
4598 mono_class_setup_parent (class, parent);
4600 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
4601 mono_class_setup_mono_type (class);
4603 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
4607 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
4611 class->cast_class = class->element_class = class;
4613 if (!class->enumtype) {
4614 if (!mono_metadata_interfaces_from_typedef_full (
4615 image, type_token, &interfaces, &icount, FALSE, context)){
4616 mono_loader_unlock ();
4617 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4621 class->interfaces = interfaces;
4622 class->interface_count = icount;
4623 class->interfaces_inited = 1;
4626 /*g_print ("Load class %s\n", name);*/
4629 * Compute the field and method lists
4631 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
4632 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
4634 if (tt->rows > tidx){
4635 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
4636 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
4637 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
4639 field_last = image->tables [MONO_TABLE_FIELD].rows;
4640 method_last = image->tables [MONO_TABLE_METHOD].rows;
4643 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
4644 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
4645 class->field.count = field_last - class->field.first;
4647 class->field.count = 0;
4649 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
4650 class->method.count = method_last - class->method.first;
4652 class->method.count = 0;
4654 /* reserve space to store vector pointer in arrays */
4655 if (is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
4656 class->instance_size += 2 * sizeof (gpointer);
4657 g_assert (class->field.count == 0);
4660 if (class->enumtype) {
4661 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
4662 if (!enum_basetype) {
4663 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4664 mono_loader_unlock ();
4665 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4668 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
4672 * If we're a generic type definition, load the constraints.
4673 * We must do this after the class has been constructed to make certain recursive scenarios
4676 if (class->generic_container && !mono_metadata_load_generic_param_constraints_full (image, type_token, class->generic_container)){
4677 char *class_name = g_strdup_printf("%s.%s", class->name_space, class->name);
4678 char *error = concat_two_strings_with_zero (class->image, class_name, class->image->assembly_name);
4679 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, error);
4680 g_free (class_name);
4681 mono_loader_unlock ();
4682 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4686 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
4687 if (!strncmp (name, "Vector", 6))
4688 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");
4691 mono_loader_unlock ();
4693 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4698 /** is klass Nullable<T>? */
4700 mono_class_is_nullable (MonoClass *klass)
4702 return klass->generic_class != NULL &&
4703 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
4707 /** if klass is T? return T */
4709 mono_class_get_nullable_param (MonoClass *klass)
4711 g_assert (mono_class_is_nullable (klass));
4712 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4716 * Create the `MonoClass' for an instantiation of a generic type.
4717 * We only do this if we actually need it.
4720 mono_generic_class_get_class (MonoGenericClass *gclass)
4722 MonoClass *klass, *gklass;
4724 mono_loader_lock ();
4725 if (gclass->cached_class) {
4726 mono_loader_unlock ();
4727 return gclass->cached_class;
4730 gclass->cached_class = g_malloc0 (sizeof (MonoClass));
4731 klass = gclass->cached_class;
4733 gklass = gclass->container_class;
4735 if (gklass->nested_in) {
4737 * FIXME: the nested type context should include everything the
4738 * nesting context should have, but it may also have additional
4739 * generic parameters...
4741 klass->nested_in = mono_class_inflate_generic_class (gklass->nested_in,
4742 mono_generic_class_get_context (gclass));
4745 klass->name = gklass->name;
4746 klass->name_space = gklass->name_space;
4748 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4750 klass->image = gklass->image;
4751 klass->flags = gklass->flags;
4752 klass->type_token = gklass->type_token;
4753 klass->field.count = gklass->field.count;
4755 klass->is_inflated = 1;
4756 klass->generic_class = gclass;
4758 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
4759 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
4760 klass->this_arg.byref = TRUE;
4761 klass->enumtype = gklass->enumtype;
4762 klass->valuetype = gklass->valuetype;
4764 klass->cast_class = klass->element_class = klass;
4766 if (mono_class_is_nullable (klass))
4767 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
4770 * We're not interested in the nested classes of a generic instance.
4771 * We use the generic type definition to look for nested classes.
4774 if (gklass->parent) {
4775 klass->parent = mono_class_inflate_generic_class (gklass->parent, mono_generic_class_get_context (gclass));
4779 mono_class_setup_parent (klass, klass->parent);
4781 if (klass->enumtype) {
4782 klass->cast_class = gklass->cast_class;
4783 klass->element_class = gklass->element_class;
4786 if (gclass->is_dynamic) {
4789 mono_class_setup_supertypes (klass);
4791 if (klass->enumtype) {
4793 * For enums, gklass->fields might not been set, but instance_size etc. is
4794 * already set in mono_reflection_create_internal_class (). For non-enums,
4795 * these will be computed normally in mono_class_layout_fields ().
4797 klass->instance_size = gklass->instance_size;
4798 klass->sizes.class_size = gklass->sizes.class_size;
4799 klass->size_inited = 1;
4803 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4805 inflated_classes ++;
4806 inflated_classes_size += sizeof (MonoClass);
4808 mono_loader_unlock ();
4814 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
4816 MonoClass *klass, **ptr;
4818 MonoGenericContainer *container = mono_generic_param_owner (param);
4822 image = mono_defaults.corlib;
4824 klass = mono_image_alloc0 (image, sizeof (MonoClass));
4825 classes_size += sizeof (MonoClass);
4828 klass->name = pinfo->name;
4830 int n = mono_generic_param_num (param);
4831 klass->name = mono_image_alloc0 (image, 16);
4832 sprintf ((char*)klass->name, "%d", n);
4837 MonoMethod *omethod = container->owner.method;
4838 klass->name_space = (omethod && omethod->klass) ? omethod->klass->name_space : "";
4840 MonoClass *oklass = container->owner.klass;
4841 klass->name_space = oklass ? oklass->name_space : "";
4844 klass->name_space = "";
4847 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4851 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
4855 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
4856 klass->parent = pinfo->constraints [0];
4858 } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
4859 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
4861 klass->parent = mono_defaults.object_class;
4864 if (count - pos > 0) {
4865 klass->interface_count = count - pos;
4866 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
4867 for (i = pos; i < count; i++)
4868 klass->interfaces [i - pos] = pinfo->constraints [i];
4871 klass->image = image;
4873 klass->inited = TRUE;
4874 klass->cast_class = klass->element_class = klass;
4875 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
4877 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
4878 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
4879 klass->this_arg.byref = TRUE;
4881 /* FIXME: shouldn't this be ->type_token? */
4882 klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
4884 mono_class_setup_supertypes (klass);
4889 #define FAST_CACHE_SIZE 1024
4890 static MonoClass *var_cache_fast [FAST_CACHE_SIZE];
4891 static MonoClass *mvar_cache_fast [FAST_CACHE_SIZE];
4892 static GHashTable *var_cache_slow;
4893 static GHashTable *mvar_cache_slow;
4896 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
4898 int n = mono_generic_param_num (param);
4901 if (n < FAST_CACHE_SIZE)
4902 return (is_mvar ? mvar_cache_fast : var_cache_fast) [n];
4903 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4904 return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
4908 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
4910 int n = mono_generic_param_num (param);
4913 if (n < FAST_CACHE_SIZE) {
4914 (is_mvar ? mvar_cache_fast : var_cache_fast) [n] = klass;
4917 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4919 ht = g_hash_table_new (NULL, NULL);
4921 mvar_cache_slow = ht;
4923 var_cache_slow = ht;
4926 g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
4930 * LOCKING: Acquires the loader lock.
4933 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
4935 MonoGenericContainer *container = mono_generic_param_owner (param);
4936 MonoGenericParamInfo *pinfo;
4939 mono_loader_lock ();
4942 pinfo = mono_generic_param_info (param);
4943 if (pinfo->pklass) {
4944 mono_loader_unlock ();
4945 return pinfo->pklass;
4951 klass = get_anon_gparam_class (param, is_mvar);
4953 mono_loader_unlock ();
4958 if (!image && container) {
4960 MonoMethod *method = container->owner.method;
4961 image = (method && method->klass) ? method->klass->image : NULL;
4963 MonoClass *klass = container->owner.klass;
4964 // FIXME: 'klass' should not be null
4965 // But, monodis creates GenericContainers without associating a owner to it
4966 image = klass ? klass->image : NULL;
4970 klass = make_generic_param_class (param, image, is_mvar, pinfo);
4972 mono_memory_barrier ();
4975 pinfo->pklass = klass;
4977 set_anon_gparam_class (param, is_mvar, klass);
4979 mono_loader_unlock ();
4981 /* FIXME: Should this go inside 'make_generic_param_klass'? */
4982 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4988 mono_ptr_class_get (MonoType *type)
4991 MonoClass *el_class;
4995 el_class = mono_class_from_mono_type (type);
4996 image = el_class->image;
4998 mono_loader_lock ();
5000 if (!image->ptr_cache)
5001 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5003 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
5004 mono_loader_unlock ();
5007 result = mono_image_alloc0 (image, sizeof (MonoClass));
5009 classes_size += sizeof (MonoClass);
5011 result->parent = NULL; /* no parent for PTR types */
5012 result->name_space = el_class->name_space;
5013 name = g_strdup_printf ("%s*", el_class->name);
5014 result->name = mono_image_strdup (image, name);
5017 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5019 result->image = el_class->image;
5020 result->inited = TRUE;
5021 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5022 /* Can pointers get boxed? */
5023 result->instance_size = sizeof (gpointer);
5024 result->cast_class = result->element_class = el_class;
5025 result->blittable = TRUE;
5027 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
5028 result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
5029 result->this_arg.byref = TRUE;
5031 mono_class_setup_supertypes (result);
5033 g_hash_table_insert (image->ptr_cache, el_class, result);
5035 mono_loader_unlock ();
5037 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5043 mono_fnptr_class_get (MonoMethodSignature *sig)
5046 static GHashTable *ptr_hash = NULL;
5048 /* FIXME: These should be allocate from a mempool as well, but which one ? */
5050 mono_loader_lock ();
5053 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5055 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
5056 mono_loader_unlock ();
5059 result = g_new0 (MonoClass, 1);
5061 result->parent = NULL; /* no parent for PTR types */
5062 result->name_space = "System";
5063 result->name = "MonoFNPtrFakeClass";
5065 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5067 result->image = mono_defaults.corlib; /* need to fix... */
5068 result->inited = TRUE;
5069 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
5070 /* Can pointers get boxed? */
5071 result->instance_size = sizeof (gpointer);
5072 result->cast_class = result->element_class = result;
5073 result->blittable = TRUE;
5075 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
5076 result->this_arg.data.method = result->byval_arg.data.method = sig;
5077 result->this_arg.byref = TRUE;
5078 result->blittable = TRUE;
5080 mono_class_setup_supertypes (result);
5082 g_hash_table_insert (ptr_hash, sig, result);
5084 mono_loader_unlock ();
5086 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5092 mono_class_from_mono_type (MonoType *type)
5094 switch (type->type) {
5095 case MONO_TYPE_OBJECT:
5096 return type->data.klass? type->data.klass: mono_defaults.object_class;
5097 case MONO_TYPE_VOID:
5098 return type->data.klass? type->data.klass: mono_defaults.void_class;
5099 case MONO_TYPE_BOOLEAN:
5100 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
5101 case MONO_TYPE_CHAR:
5102 return type->data.klass? type->data.klass: mono_defaults.char_class;
5104 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
5106 return type->data.klass? type->data.klass: mono_defaults.byte_class;
5108 return type->data.klass? type->data.klass: mono_defaults.int16_class;
5110 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
5112 return type->data.klass? type->data.klass: mono_defaults.int32_class;
5114 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
5116 return type->data.klass? type->data.klass: mono_defaults.int_class;
5118 return type->data.klass? type->data.klass: mono_defaults.uint_class;
5120 return type->data.klass? type->data.klass: mono_defaults.int64_class;
5122 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
5124 return type->data.klass? type->data.klass: mono_defaults.single_class;
5126 return type->data.klass? type->data.klass: mono_defaults.double_class;
5127 case MONO_TYPE_STRING:
5128 return type->data.klass? type->data.klass: mono_defaults.string_class;
5129 case MONO_TYPE_TYPEDBYREF:
5130 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
5131 case MONO_TYPE_ARRAY:
5132 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
5134 return mono_ptr_class_get (type->data.type);
5135 case MONO_TYPE_FNPTR:
5136 return mono_fnptr_class_get (type->data.method);
5137 case MONO_TYPE_SZARRAY:
5138 return mono_array_class_get (type->data.klass, 1);
5139 case MONO_TYPE_CLASS:
5140 case MONO_TYPE_VALUETYPE:
5141 return type->data.klass;
5142 case MONO_TYPE_GENERICINST:
5143 return mono_generic_class_get_class (type->data.generic_class);
5145 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
5146 case MONO_TYPE_MVAR:
5147 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
5149 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
5150 g_assert_not_reached ();
5157 * mono_type_retrieve_from_typespec
5158 * @image: context where the image is created
5159 * @type_spec: typespec token
5160 * @context: the generic context used to evaluate generic instantiations in
5163 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate)
5166 MonoType *t = mono_type_create_from_typespec (image, type_spec);
5169 if (context && (context->class_inst || context->method_inst)) {
5170 MonoType *inflated = inflate_generic_type (NULL, t, context, &error);
5171 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
5175 *did_inflate = TRUE;
5182 * mono_class_create_from_typespec
5183 * @image: context where the image is created
5184 * @type_spec: typespec token
5185 * @context: the generic context used to evaluate generic instantiations in
5188 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
5191 gboolean inflated = FALSE;
5192 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated);
5195 ret = mono_class_from_mono_type (t);
5197 mono_metadata_free_type (t);
5202 * mono_bounded_array_class_get:
5203 * @element_class: element class
5204 * @rank: the dimension of the array class
5205 * @bounded: whenever the array has non-zero bounds
5207 * Returns: a class object describing the array with element type @element_type and
5211 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
5215 MonoClass *parent = NULL;
5216 GSList *list, *rootlist = NULL;
5219 gboolean corlib_type = FALSE;
5221 g_assert (rank <= 255);
5224 /* bounded only matters for one-dimensional arrays */
5227 image = eclass->image;
5229 if (rank == 1 && !bounded) {
5231 * This case is very frequent not just during compilation because of calls
5232 * from mono_class_from_mono_type (), mono_array_new (),
5233 * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
5235 EnterCriticalSection (&image->szarray_cache_lock);
5236 if (!image->szarray_cache)
5237 image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5238 class = g_hash_table_lookup (image->szarray_cache, eclass);
5239 LeaveCriticalSection (&image->szarray_cache_lock);
5243 mono_loader_lock ();
5245 mono_loader_lock ();
5247 if (!image->array_cache)
5248 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5250 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
5251 for (; list; list = list->next) {
5253 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
5254 mono_loader_unlock ();
5261 /* for the building corlib use System.Array from it */
5262 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
5263 parent = mono_class_from_name (image, "System", "Array");
5266 parent = mono_defaults.array_class;
5267 if (!parent->inited)
5268 mono_class_init (parent);
5271 class = mono_image_alloc0 (image, sizeof (MonoClass));
5273 class->image = image;
5274 class->name_space = eclass->name_space;
5275 nsize = strlen (eclass->name);
5276 name = g_malloc (nsize + 2 + rank + 1);
5277 memcpy (name, eclass->name, nsize);
5280 memset (name + nsize + 1, ',', rank - 1);
5282 name [nsize + rank] = '*';
5283 name [nsize + rank + bounded] = ']';
5284 name [nsize + rank + bounded + 1] = 0;
5285 class->name = mono_image_strdup (image, name);
5288 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
5290 classes_size += sizeof (MonoClass);
5292 class->type_token = 0;
5293 /* all arrays are marked serializable and sealed, bug #42779 */
5294 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
5295 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5296 class->parent = parent;
5297 class->instance_size = mono_class_instance_size (class->parent);
5299 if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
5300 if (!eclass->reflection_info || eclass->wastypebuilder) {
5301 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
5302 g_assert (eclass->reflection_info && !eclass->wastypebuilder);
5304 /* element_size -1 is ok as this is not an instantitable type*/
5305 class->sizes.element_size = -1;
5307 class->sizes.element_size = mono_class_array_element_size (eclass);
5309 mono_class_setup_supertypes (class);
5311 if (eclass->generic_class)
5312 mono_class_init (eclass);
5313 if (!eclass->size_inited)
5314 mono_class_setup_fields (eclass);
5315 if (eclass->exception_type) /*FIXME we fail the array type, but we have to let other fields be set.*/
5316 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5318 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
5322 if (eclass->enumtype)
5323 class->cast_class = eclass->element_class;
5325 class->cast_class = eclass;
5327 class->element_class = eclass;
5329 if ((rank > 1) || bounded) {
5330 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
5331 class->byval_arg.type = MONO_TYPE_ARRAY;
5332 class->byval_arg.data.array = at;
5333 at->eklass = eclass;
5335 /* FIXME: complete.... */
5337 class->byval_arg.type = MONO_TYPE_SZARRAY;
5338 class->byval_arg.data.klass = eclass;
5340 class->this_arg = class->byval_arg;
5341 class->this_arg.byref = 1;
5346 class->generic_container = eclass->generic_container;
5348 if (rank == 1 && !bounded) {
5349 MonoClass *prev_class;
5351 EnterCriticalSection (&image->szarray_cache_lock);
5352 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
5354 /* Someone got in before us */
5357 g_hash_table_insert (image->szarray_cache, eclass, class);
5358 LeaveCriticalSection (&image->szarray_cache_lock);
5360 list = g_slist_append (rootlist, class);
5361 g_hash_table_insert (image->array_cache, eclass, list);
5364 mono_loader_unlock ();
5366 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5372 * mono_array_class_get:
5373 * @element_class: element class
5374 * @rank: the dimension of the array class
5376 * Returns: a class object describing the array with element type @element_type and
5380 mono_array_class_get (MonoClass *eclass, guint32 rank)
5382 return mono_bounded_array_class_get (eclass, rank, FALSE);
5386 * mono_class_instance_size:
5389 * Returns: the size of an object instance
5392 mono_class_instance_size (MonoClass *klass)
5394 if (!klass->size_inited)
5395 mono_class_init (klass);
5397 return klass->instance_size;
5401 * mono_class_min_align:
5404 * Returns: minimm alignment requirements
5407 mono_class_min_align (MonoClass *klass)
5409 if (!klass->size_inited)
5410 mono_class_init (klass);
5412 return klass->min_align;
5416 * mono_class_value_size:
5419 * This function is used for value types, and return the
5420 * space and the alignment to store that kind of value object.
5422 * Returns: the size of a value of kind @klass
5425 mono_class_value_size (MonoClass *klass, guint32 *align)
5429 /* fixme: check disable, because we still have external revereces to
5430 * mscorlib and Dummy Objects
5432 /*g_assert (klass->valuetype);*/
5434 size = mono_class_instance_size (klass) - sizeof (MonoObject);
5437 *align = klass->min_align;
5443 * mono_class_data_size:
5446 * Returns: the size of the static class data
5449 mono_class_data_size (MonoClass *klass)
5452 mono_class_init (klass);
5454 /* in arrays, sizes.class_size is unioned with element_size
5455 * and arrays have no static fields
5459 return klass->sizes.class_size;
5463 * Auxiliary routine to mono_class_get_field
5465 * Takes a field index instead of a field token.
5467 static MonoClassField *
5468 mono_class_get_field_idx (MonoClass *class, int idx)
5470 mono_class_setup_fields_locking (class);
5471 if (class->exception_type)
5475 if (class->image->uncompressed_metadata) {
5477 * class->field.first points to the FieldPtr table, while idx points into the
5478 * Field table, so we have to do a search.
5480 /*FIXME this is broken for types with multiple fields with the same name.*/
5481 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
5484 for (i = 0; i < class->field.count; ++i)
5485 if (mono_field_get_name (&class->fields [i]) == name)
5486 return &class->fields [i];
5487 g_assert_not_reached ();
5489 if (class->field.count) {
5490 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
5491 return &class->fields [idx - class->field.first];
5495 class = class->parent;
5501 * mono_class_get_field:
5502 * @class: the class to lookup the field.
5503 * @field_token: the field token
5505 * Returns: A MonoClassField representing the type and offset of
5506 * the field, or a NULL value if the field does not belong to this
5510 mono_class_get_field (MonoClass *class, guint32 field_token)
5512 int idx = mono_metadata_token_index (field_token);
5514 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
5516 return mono_class_get_field_idx (class, idx - 1);
5520 * mono_class_get_field_from_name:
5521 * @klass: the class to lookup the field.
5522 * @name: the field name
5524 * Search the class @klass and it's parents for a field with the name @name.
5526 * Returns: the MonoClassField pointer of the named field or NULL
5529 mono_class_get_field_from_name (MonoClass *klass, const char *name)
5531 return mono_class_get_field_from_name_full (klass, name, NULL);
5535 * mono_class_get_field_from_name_full:
5536 * @klass: the class to lookup the field.
5537 * @name: the field name
5538 * @type: the type of the fields. This optional.
5540 * Search the class @klass and it's parents for a field with the name @name and type @type.
5542 * If @klass is an inflated generic type, the type comparison is done with the equivalent field
5543 * of its generic type definition.
5545 * Returns: the MonoClassField pointer of the named field or NULL
5548 mono_class_get_field_from_name_full (MonoClass *klass, const char *name, MonoType *type)
5552 mono_class_setup_fields_locking (klass);
5553 if (klass->exception_type)
5557 for (i = 0; i < klass->field.count; ++i) {
5558 MonoClassField *field = &klass->fields [i];
5560 if (strcmp (name, mono_field_get_name (field)) != 0)
5564 MonoType *field_type = mono_metadata_get_corresponding_field_from_generic_type_definition (field)->type;
5565 if (!mono_metadata_type_equal_full (type, field_type, TRUE))
5570 klass = klass->parent;
5576 * mono_class_get_field_token:
5577 * @field: the field we need the token of
5579 * Get the token of a field. Note that the tokesn is only valid for the image
5580 * the field was loaded from. Don't use this function for fields in dynamic types.
5582 * Returns: the token representing the field in the image it was loaded from.
5585 mono_class_get_field_token (MonoClassField *field)
5587 MonoClass *klass = field->parent;
5590 mono_class_setup_fields_locking (klass);
5591 if (klass->exception_type)
5595 for (i = 0; i < klass->field.count; ++i) {
5596 if (&klass->fields [i] == field) {
5597 int idx = klass->field.first + i + 1;
5599 if (klass->image->uncompressed_metadata)
5600 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
5601 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
5604 klass = klass->parent;
5607 g_assert_not_reached ();
5612 mono_field_get_index (MonoClassField *field)
5614 int index = field - field->parent->fields;
5616 g_assert (index >= 0 && index < field->parent->field.count);
5622 * mono_class_get_field_default_value:
5624 * Return the default value of the field as a pointer into the metadata blob.
5627 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
5630 guint32 constant_cols [MONO_CONSTANT_SIZE];
5632 MonoClass *klass = field->parent;
5634 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
5636 if (!klass->ext || !klass->ext->field_def_values) {
5637 mono_loader_lock ();
5638 mono_class_alloc_ext (klass);
5639 if (!klass->ext->field_def_values)
5640 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
5641 mono_loader_unlock ();
5644 field_index = mono_field_get_index (field);
5646 if (!klass->ext->field_def_values [field_index].data) {
5647 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
5649 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
5651 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
5652 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
5653 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
5656 *def_type = klass->ext->field_def_values [field_index].def_type;
5657 return klass->ext->field_def_values [field_index].data;
5661 mono_class_get_event_token (MonoEvent *event)
5663 MonoClass *klass = event->parent;
5668 for (i = 0; i < klass->ext->event.count; ++i) {
5669 if (&klass->ext->events [i] == event)
5670 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
5673 klass = klass->parent;
5676 g_assert_not_reached ();
5681 mono_class_get_property_from_name (MonoClass *klass, const char *name)
5685 gpointer iter = NULL;
5686 while ((p = mono_class_get_properties (klass, &iter))) {
5687 if (! strcmp (name, p->name))
5690 klass = klass->parent;
5696 mono_class_get_property_token (MonoProperty *prop)
5698 MonoClass *klass = prop->parent;
5702 gpointer iter = NULL;
5703 while ((p = mono_class_get_properties (klass, &iter))) {
5704 if (&klass->ext->properties [i] == prop)
5705 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
5709 klass = klass->parent;
5712 g_assert_not_reached ();
5717 mono_class_name_from_token (MonoImage *image, guint32 type_token)
5719 const char *name, *nspace;
5721 return g_strdup_printf ("DynamicType 0x%08x", type_token);
5723 switch (type_token & 0xff000000){
5724 case MONO_TOKEN_TYPE_DEF: {
5725 guint32 cols [MONO_TYPEDEF_SIZE];
5726 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5727 guint tidx = mono_metadata_token_index (type_token);
5729 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5730 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5731 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5732 if (strlen (nspace) == 0)
5733 return g_strdup_printf ("%s", name);
5735 return g_strdup_printf ("%s.%s", nspace, name);
5738 case MONO_TOKEN_TYPE_REF: {
5739 guint32 cols [MONO_TYPEREF_SIZE];
5740 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5742 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5743 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
5744 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
5745 if (strlen (nspace) == 0)
5746 return g_strdup_printf ("%s", name);
5748 return g_strdup_printf ("%s.%s", nspace, name);
5751 case MONO_TOKEN_TYPE_SPEC:
5752 return g_strdup_printf ("Typespec 0x%08x", type_token);
5754 g_assert_not_reached ();
5761 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
5764 return g_strdup_printf ("DynamicAssembly %s", image->name);
5766 switch (type_token & 0xff000000){
5767 case MONO_TOKEN_TYPE_DEF:
5768 return mono_stringify_assembly_name (&image->assembly->aname);
5770 case MONO_TOKEN_TYPE_REF: {
5771 MonoAssemblyName aname;
5772 guint32 cols [MONO_TYPEREF_SIZE];
5773 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5776 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5778 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
5779 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
5780 case MONO_RESOLTION_SCOPE_MODULE:
5782 return g_strdup ("");
5783 case MONO_RESOLTION_SCOPE_MODULEREF:
5785 return g_strdup ("");
5786 case MONO_RESOLTION_SCOPE_TYPEREF:
5788 return g_strdup ("");
5789 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
5790 mono_assembly_get_assemblyref (image, idx - 1, &aname);
5791 return mono_stringify_assembly_name (&aname);
5793 g_assert_not_reached ();
5797 case MONO_TOKEN_TYPE_SPEC:
5799 return g_strdup ("");
5801 g_assert_not_reached ();
5808 * mono_class_get_full:
5809 * @image: the image where the class resides
5810 * @type_token: the token for the class
5811 * @context: the generic context used to evaluate generic instantiations in
5813 * Returns: the MonoClass that represents @type_token in @image
5816 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5818 MonoClass *class = NULL;
5820 if (image->dynamic) {
5821 int table = mono_metadata_token_table (type_token);
5823 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
5824 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
5827 return mono_lookup_dynamic_token (image, type_token, context);
5830 switch (type_token & 0xff000000){
5831 case MONO_TOKEN_TYPE_DEF:
5832 class = mono_class_create_from_typedef (image, type_token);
5834 case MONO_TOKEN_TYPE_REF:
5835 class = mono_class_from_typeref (image, type_token);
5837 case MONO_TOKEN_TYPE_SPEC:
5838 class = mono_class_create_from_typespec (image, type_token, context);
5841 g_warning ("unknown token type %x", type_token & 0xff000000);
5842 g_assert_not_reached ();
5846 char *name = mono_class_name_from_token (image, type_token);
5847 char *assembly = mono_assembly_name_from_token (image, type_token);
5848 mono_loader_set_error_type_load (name, assembly);
5856 * mono_type_get_full:
5857 * @image: the image where the type resides
5858 * @type_token: the token for the type
5859 * @context: the generic context used to evaluate generic instantiations in
5861 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
5863 * Returns: the MonoType that represents @type_token in @image
5866 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5868 MonoType *type = NULL;
5869 gboolean inflated = FALSE;
5871 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
5873 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
5875 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
5876 MonoClass *class = mono_class_get_full (image, type_token, context);
5877 return class ? mono_class_get_type (class) : NULL;
5880 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated);
5883 char *name = mono_class_name_from_token (image, type_token);
5884 char *assembly = mono_assembly_name_from_token (image, type_token);
5885 mono_loader_set_error_type_load (name, assembly);
5890 MonoType *tmp = type;
5891 type = mono_class_get_type (mono_class_from_mono_type (type));
5892 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
5893 * A MonoClass::byval_arg of a generic type definion has type CLASS.
5894 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
5896 * The long term solution is to chaise this places and make then set MonoType::type correctly.
5898 if (type->type != tmp->type)
5901 mono_metadata_free_type (tmp);
5908 mono_class_get (MonoImage *image, guint32 type_token)
5910 return mono_class_get_full (image, type_token, NULL);
5914 * mono_image_init_name_cache:
5916 * Initializes the class name cache stored in image->name_cache.
5918 * LOCKING: Acquires the corresponding image lock.
5921 mono_image_init_name_cache (MonoImage *image)
5923 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5924 guint32 cols [MONO_TYPEDEF_SIZE];
5927 guint32 i, visib, nspace_index;
5928 GHashTable *name_cache2, *nspace_table;
5930 mono_image_lock (image);
5932 if (image->name_cache) {
5933 mono_image_unlock (image);
5937 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
5939 if (image->dynamic) {
5940 mono_image_unlock (image);
5944 /* Temporary hash table to avoid lookups in the nspace_table */
5945 name_cache2 = g_hash_table_new (NULL, NULL);
5947 for (i = 1; i <= t->rows; ++i) {
5948 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5949 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5951 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5952 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5954 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5956 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5957 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5959 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
5960 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5961 if (!nspace_table) {
5962 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5963 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5964 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5967 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
5970 /* Load type names from EXPORTEDTYPES table */
5972 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5973 guint32 cols [MONO_EXP_TYPE_SIZE];
5976 for (i = 0; i < t->rows; ++i) {
5977 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
5978 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
5979 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
5981 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
5982 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5983 if (!nspace_table) {
5984 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5985 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5986 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5989 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
5993 g_hash_table_destroy (name_cache2);
5994 mono_image_unlock (image);
5997 /*FIXME Only dynamic assemblies should allow this operation.*/
5999 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
6000 const char *name, guint32 index)
6002 GHashTable *nspace_table;
6003 GHashTable *name_cache;
6006 mono_image_lock (image);
6008 if (!image->name_cache)
6009 mono_image_init_name_cache (image);
6011 name_cache = image->name_cache;
6012 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
6013 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6014 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
6017 if ((old_index = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, (char*) name))))
6018 g_error ("overrwritting old token %x on image %s for type %s::%s", old_index, image->name, nspace, name);
6020 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
6022 mono_image_unlock (image);
6031 find_nocase (gpointer key, gpointer value, gpointer user_data)
6033 char *name = (char*)key;
6034 FindUserData *data = (FindUserData*)user_data;
6036 if (!data->value && (mono_utf8_strcasecmp (name, (char*)data->key) == 0))
6037 data->value = value;
6041 * mono_class_from_name_case:
6042 * @image: The MonoImage where the type is looked up in
6043 * @name_space: the type namespace
6044 * @name: the type short name.
6046 * Obtains a MonoClass with a given namespace and a given name which
6047 * is located in the given MonoImage. The namespace and name
6048 * lookups are case insensitive.
6051 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
6053 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
6054 guint32 cols [MONO_TYPEDEF_SIZE];
6059 if (image->dynamic) {
6061 FindUserData user_data;
6063 mono_image_lock (image);
6065 if (!image->name_cache)
6066 mono_image_init_name_cache (image);
6068 user_data.key = name_space;
6069 user_data.value = NULL;
6070 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
6072 if (user_data.value) {
6073 GHashTable *nspace_table = (GHashTable*)user_data.value;
6075 user_data.key = name;
6076 user_data.value = NULL;
6078 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
6080 if (user_data.value)
6081 token = GPOINTER_TO_UINT (user_data.value);
6084 mono_image_unlock (image);
6087 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
6093 /* add a cache if needed */
6094 for (i = 1; i <= t->rows; ++i) {
6095 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
6096 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
6098 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
6099 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
6101 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
6103 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6104 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6105 if (mono_utf8_strcasecmp (n, name) == 0 && mono_utf8_strcasecmp (nspace, name_space) == 0)
6106 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
6112 return_nested_in (MonoClass *class, char *nested)
6115 char *s = strchr (nested, '/');
6116 gpointer iter = NULL;
6123 while ((found = mono_class_get_nested_types (class, &iter))) {
6124 if (strcmp (found->name, nested) == 0) {
6126 return return_nested_in (found, s);
6134 search_modules (MonoImage *image, const char *name_space, const char *name)
6136 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
6137 MonoImage *file_image;
6142 * The EXPORTEDTYPES table only contains public types, so have to search the
6144 * Note: image->modules contains the contents of the MODULEREF table, while
6145 * the real module list is in the FILE table.
6147 for (i = 0; i < file_table->rows; i++) {
6148 guint32 cols [MONO_FILE_SIZE];
6149 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
6150 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
6153 file_image = mono_image_load_file_for_image (image, i + 1);
6155 class = mono_class_from_name (file_image, name_space, name);
6165 * mono_class_from_name:
6166 * @image: The MonoImage where the type is looked up in
6167 * @name_space: the type namespace
6168 * @name: the type short name.
6170 * Obtains a MonoClass with a given namespace and a given name which
6171 * is located in the given MonoImage.
6174 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
6176 GHashTable *nspace_table;
6177 MonoImage *loaded_image;
6184 if ((nested = strchr (name, '/'))) {
6185 int pos = nested - name;
6186 int len = strlen (name);
6189 memcpy (buf, name, len + 1);
6191 nested = buf + pos + 1;
6195 if (get_class_from_name) {
6196 gboolean res = get_class_from_name (image, name_space, name, &class);
6199 class = search_modules (image, name_space, name);
6201 return class ? return_nested_in (class, nested) : NULL;
6207 mono_image_lock (image);
6209 if (!image->name_cache)
6210 mono_image_init_name_cache (image);
6212 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
6215 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
6217 mono_image_unlock (image);
6219 if (!token && image->dynamic && image->modules) {
6220 /* Search modules as well */
6221 for (i = 0; i < image->module_count; ++i) {
6222 MonoImage *module = image->modules [i];
6224 class = mono_class_from_name (module, name_space, name);
6231 class = search_modules (image, name_space, name);
6239 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
6240 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6241 guint32 cols [MONO_EXP_TYPE_SIZE];
6244 idx = mono_metadata_token_index (token);
6246 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
6248 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
6249 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
6250 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
6253 class = mono_class_from_name (loaded_image, name_space, name);
6255 return return_nested_in (class, nested);
6257 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
6258 guint32 assembly_idx;
6260 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
6262 mono_assembly_load_reference (image, assembly_idx - 1);
6263 g_assert (image->references [assembly_idx - 1]);
6264 if (image->references [assembly_idx - 1] == (gpointer)-1)
6267 /* FIXME: Cycle detection */
6268 return mono_class_from_name (image->references [assembly_idx - 1]->image, name_space, name);
6270 g_error ("not yet implemented");
6274 token = MONO_TOKEN_TYPE_DEF | token;
6276 class = mono_class_get (image, token);
6278 return return_nested_in (class, nested);
6283 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
6284 gboolean check_interfaces)
6286 g_assert (klassc->idepth > 0);
6287 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
6288 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
6290 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
6293 for (i = 0; i < klass->interface_count; i ++) {
6294 MonoClass *ic = klass->interfaces [i];
6299 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
6304 * MS.NET thinks interfaces are a subclass of Object, so we think it as
6307 if (klassc == mono_defaults.object_class)
6314 mono_class_has_variant_generic_params (MonoClass *klass)
6317 MonoGenericContainer *container;
6319 if (!klass->generic_class)
6322 container = klass->generic_class->container_class->generic_container;
6324 for (i = 0; i < container->type_argc; ++i)
6325 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
6332 * mono_class_is_assignable_from:
6333 * @klass: the class to be assigned to
6334 * @oklass: the source class
6336 * Return: true if an instance of object oklass can be assigned to an
6337 * instance of object @klass
6340 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
6343 mono_class_init (klass);
6345 if (!oklass->inited)
6346 mono_class_init (oklass);
6348 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
6349 return klass == oklass;
6351 if (MONO_CLASS_IS_INTERFACE (klass)) {
6352 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
6355 /* interface_offsets might not be set for dynamic classes */
6356 if (oklass->reflection_info && !oklass->interface_bitmap)
6358 * oklass might be a generic type parameter but they have
6359 * interface_offsets set.
6361 return mono_reflection_call_is_assignable_to (oklass, klass);
6362 if (!oklass->interface_bitmap)
6363 /* Happens with generic instances of not-yet created dynamic types */
6365 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
6368 if (mono_class_has_variant_generic_params (klass)) {
6369 if (oklass->generic_class) {
6371 gboolean match = FALSE;
6372 MonoClass *container_class1 = klass->generic_class->container_class;
6373 MonoClass *container_class2 = oklass->generic_class->container_class;
6376 * Check whenever the generic definition of oklass implements the
6377 * generic definition of klass. The IMPLEMENTS_INTERFACE stuff is not usable
6378 * here since the relevant tables are not set up.
6380 for (i = 0; i < container_class2->interface_offsets_count; ++i)
6381 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)))
6385 MonoGenericContainer *container;
6387 container = klass->generic_class->container_class->generic_container;
6390 for (i = 0; i < container->type_argc; ++i) {
6391 MonoClass *param1_class = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [i]);
6392 MonoClass *param2_class = mono_class_from_mono_type (oklass->generic_class->context.class_inst->type_argv [i]);
6394 if (param1_class->valuetype != param2_class->valuetype) {
6399 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
6400 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
6402 if (param1_class != param2_class) {
6403 if ((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_VARIANT) && mono_class_is_assignable_from (param1_class, param2_class))
6405 else if (((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_COVARIANT) && mono_class_is_assignable_from (param2_class, param1_class)))
6419 } else if (klass->rank) {
6420 MonoClass *eclass, *eoclass;
6422 if (oklass->rank != klass->rank)
6425 /* vectors vs. one dimensional arrays */
6426 if (oklass->byval_arg.type != klass->byval_arg.type)
6429 eclass = klass->cast_class;
6430 eoclass = oklass->cast_class;
6433 * a is b does not imply a[] is b[] when a is a valuetype, and
6434 * b is a reference type.
6437 if (eoclass->valuetype) {
6438 if ((eclass == mono_defaults.enum_class) ||
6439 (eclass == mono_defaults.enum_class->parent) ||
6440 (eclass == mono_defaults.object_class))
6444 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6445 } else if (mono_class_is_nullable (klass)) {
6446 if (mono_class_is_nullable (oklass))
6447 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6449 return mono_class_is_assignable_from (klass->cast_class, oklass);
6450 } else if (klass == mono_defaults.object_class)
6453 return mono_class_has_parent (oklass, klass);
6456 /*Check if @candidate implements the interface @target*/
6458 mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
6463 if (candidate == target)
6466 /*A TypeBuilder can have more interfaces on tb->interfaces than on candidate->interfaces*/
6467 if (candidate->image->dynamic && !candidate->wastypebuilder) {
6468 MonoReflectionTypeBuilder *tb = candidate->reflection_info;
6470 if (tb->interfaces) {
6471 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
6472 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
6473 MonoClass *iface_class = mono_class_from_mono_type (iface->type);
6474 if (iface_class == target || mono_class_implement_interface_slow (target, iface_class))
6479 /*setup_interfaces don't mono_class_init anything*/
6480 mono_class_setup_interfaces (candidate);
6481 for (i = 0; i < candidate->interface_count; ++i) {
6482 if (candidate->interfaces [i] == target || mono_class_implement_interface_slow (target, candidate->interfaces [i]))
6486 candidate = candidate->parent;
6487 } while (candidate);
6493 * Check if @oklass can be assigned to @klass.
6494 * This function does the same as mono_class_is_assignable_from but is safe to be used from mono_class_init context.
6497 mono_class_is_assignable_from_slow (MonoClass *target, MonoClass *candidate)
6499 if (candidate == target)
6501 if (target == mono_defaults.object_class)
6504 /*setup_supertypes don't mono_class_init anything */
6505 mono_class_setup_supertypes (candidate);
6506 mono_class_setup_supertypes (target);
6508 if (mono_class_has_parent (candidate, target))
6511 /*If target is not an interface there is no need to check them.*/
6512 if (!MONO_CLASS_IS_INTERFACE (target))
6514 return mono_class_implement_interface_slow (target, candidate);
6518 * mono_class_get_cctor:
6519 * @klass: A MonoClass pointer
6521 * Returns: the static constructor of @klass if it exists, NULL otherwise.
6524 mono_class_get_cctor (MonoClass *klass)
6526 MonoCachedClassInfo cached_info;
6528 if (!klass->has_cctor)
6531 if (mono_class_get_cached_class_info (klass, &cached_info))
6532 return mono_get_method (klass->image, cached_info.cctor_token, klass);
6534 if (klass->generic_class && !klass->methods)
6535 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
6537 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
6541 * mono_class_get_finalizer:
6542 * @klass: The MonoClass pointer
6544 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
6547 mono_class_get_finalizer (MonoClass *klass)
6549 MonoCachedClassInfo cached_info;
6552 mono_class_init (klass);
6553 if (!klass->has_finalize)
6556 if (mono_class_get_cached_class_info (klass, &cached_info))
6557 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
6559 mono_class_setup_vtable (klass);
6560 return klass->vtable [finalize_slot];
6565 * mono_class_needs_cctor_run:
6566 * @klass: the MonoClass pointer
6567 * @caller: a MonoMethod describing the caller
6569 * Determines whenever the class has a static constructor and whenever it
6570 * needs to be called when executing CALLER.
6573 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
6577 method = mono_class_get_cctor (klass);
6579 return (method == caller) ? FALSE : TRUE;
6585 * mono_class_array_element_size:
6588 * Returns: the number of bytes an element of type @klass
6589 * uses when stored into an array.
6592 mono_class_array_element_size (MonoClass *klass)
6594 MonoType *type = &klass->byval_arg;
6597 switch (type->type) {
6600 case MONO_TYPE_BOOLEAN:
6604 case MONO_TYPE_CHAR:
6613 case MONO_TYPE_CLASS:
6614 case MONO_TYPE_STRING:
6615 case MONO_TYPE_OBJECT:
6616 case MONO_TYPE_SZARRAY:
6617 case MONO_TYPE_ARRAY:
6619 case MONO_TYPE_MVAR:
6620 return sizeof (gpointer);
6625 case MONO_TYPE_VALUETYPE:
6626 if (type->data.klass->enumtype) {
6627 type = mono_class_enum_basetype (type->data.klass);
6628 klass = klass->element_class;
6631 return mono_class_instance_size (klass) - sizeof (MonoObject);
6632 case MONO_TYPE_GENERICINST:
6633 type = &type->data.generic_class->container_class->byval_arg;
6636 case MONO_TYPE_VOID:
6640 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
6646 * mono_array_element_size:
6647 * @ac: pointer to a #MonoArrayClass
6649 * Returns: the size of single array element.
6652 mono_array_element_size (MonoClass *ac)
6654 g_assert (ac->rank);
6655 return ac->sizes.element_size;
6659 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
6660 MonoGenericContext *context)
6662 if (image->dynamic) {
6663 MonoClass *tmp_handle_class;
6664 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
6666 g_assert (tmp_handle_class);
6668 *handle_class = tmp_handle_class;
6670 if (tmp_handle_class == mono_defaults.typehandle_class)
6671 return &((MonoClass*)obj)->byval_arg;
6676 switch (token & 0xff000000) {
6677 case MONO_TOKEN_TYPE_DEF:
6678 case MONO_TOKEN_TYPE_REF:
6679 case MONO_TOKEN_TYPE_SPEC: {
6682 *handle_class = mono_defaults.typehandle_class;
6683 type = mono_type_get_full (image, token, context);
6686 mono_class_init (mono_class_from_mono_type (type));
6687 /* We return a MonoType* as handle */
6690 case MONO_TOKEN_FIELD_DEF: {
6692 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
6694 *handle_class = mono_defaults.fieldhandle_class;
6695 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
6698 mono_class_init (class);
6699 return mono_class_get_field (class, token);
6701 case MONO_TOKEN_METHOD_DEF:
6702 case MONO_TOKEN_METHOD_SPEC: {
6704 meth = mono_get_method_full (image, token, NULL, context);
6706 *handle_class = mono_defaults.methodhandle_class;
6709 case MONO_TOKEN_MEMBER_REF: {
6710 guint32 cols [MONO_MEMBERREF_SIZE];
6712 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
6713 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6714 mono_metadata_decode_blob_size (sig, &sig);
6715 if (*sig == 0x6) { /* it's a field */
6717 MonoClassField *field;
6718 field = mono_field_from_token (image, token, &klass, context);
6720 *handle_class = mono_defaults.fieldhandle_class;
6724 meth = mono_get_method_full (image, token, NULL, context);
6726 *handle_class = mono_defaults.methodhandle_class;
6731 g_warning ("Unknown token 0x%08x in ldtoken", token);
6738 * This function might need to call runtime functions so it can't be part
6739 * of the metadata library.
6741 static MonoLookupDynamicToken lookup_dynamic = NULL;
6744 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
6746 lookup_dynamic = func;
6750 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
6752 MonoClass *handle_class;
6754 return lookup_dynamic (image, token, TRUE, &handle_class, context);
6758 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
6760 return lookup_dynamic (image, token, valid_token, handle_class, context);
6763 static MonoGetCachedClassInfo get_cached_class_info = NULL;
6766 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
6768 get_cached_class_info = func;
6772 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
6774 if (!get_cached_class_info)
6777 return get_cached_class_info (klass, res);
6781 mono_install_get_class_from_name (MonoGetClassFromName func)
6783 get_class_from_name = func;
6787 mono_class_get_image (MonoClass *klass)
6789 return klass->image;
6793 * mono_class_get_element_class:
6794 * @klass: the MonoClass to act on
6796 * Returns: the element class of an array or an enumeration.
6799 mono_class_get_element_class (MonoClass *klass)
6801 return klass->element_class;
6805 * mono_class_is_valuetype:
6806 * @klass: the MonoClass to act on
6808 * Returns: true if the MonoClass represents a ValueType.
6811 mono_class_is_valuetype (MonoClass *klass)
6813 return klass->valuetype;
6817 * mono_class_is_enum:
6818 * @klass: the MonoClass to act on
6820 * Returns: true if the MonoClass represents an enumeration.
6823 mono_class_is_enum (MonoClass *klass)
6825 return klass->enumtype;
6829 * mono_class_enum_basetype:
6830 * @klass: the MonoClass to act on
6832 * Returns: the underlying type representation for an enumeration.
6835 mono_class_enum_basetype (MonoClass *klass)
6837 if (klass->element_class == klass)
6838 /* SRE or broken types */
6841 return &klass->element_class->byval_arg;
6845 * mono_class_get_parent
6846 * @klass: the MonoClass to act on
6848 * Returns: the parent class for this class.
6851 mono_class_get_parent (MonoClass *klass)
6853 return klass->parent;
6857 * mono_class_get_nesting_type;
6858 * @klass: the MonoClass to act on
6860 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
6863 mono_class_get_nesting_type (MonoClass *klass)
6865 return klass->nested_in;
6869 * mono_class_get_rank:
6870 * @klass: the MonoClass to act on
6872 * Returns: the rank for the array (the number of dimensions).
6875 mono_class_get_rank (MonoClass *klass)
6881 * mono_class_get_flags:
6882 * @klass: the MonoClass to act on
6884 * The type flags from the TypeDef table from the metadata.
6885 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
6888 * Returns: the flags from the TypeDef table.
6891 mono_class_get_flags (MonoClass *klass)
6893 return klass->flags;
6897 * mono_class_get_name
6898 * @klass: the MonoClass to act on
6900 * Returns: the name of the class.
6903 mono_class_get_name (MonoClass *klass)
6909 * mono_class_get_namespace:
6910 * @klass: the MonoClass to act on
6912 * Returns: the namespace of the class.
6915 mono_class_get_namespace (MonoClass *klass)
6917 return klass->name_space;
6921 * mono_class_get_type:
6922 * @klass: the MonoClass to act on
6924 * This method returns the internal Type representation for the class.
6926 * Returns: the MonoType from the class.
6929 mono_class_get_type (MonoClass *klass)
6931 return &klass->byval_arg;
6935 * mono_class_get_type_token
6936 * @klass: the MonoClass to act on
6938 * This method returns type token for the class.
6940 * Returns: the type token for the class.
6943 mono_class_get_type_token (MonoClass *klass)
6945 return klass->type_token;
6949 * mono_class_get_byref_type:
6950 * @klass: the MonoClass to act on
6955 mono_class_get_byref_type (MonoClass *klass)
6957 return &klass->this_arg;
6961 * mono_class_num_fields:
6962 * @klass: the MonoClass to act on
6964 * Returns: the number of static and instance fields in the class.
6967 mono_class_num_fields (MonoClass *klass)
6969 return klass->field.count;
6973 * mono_class_num_methods:
6974 * @klass: the MonoClass to act on
6976 * Returns: the number of methods in the class.
6979 mono_class_num_methods (MonoClass *klass)
6981 return klass->method.count;
6985 * mono_class_num_properties
6986 * @klass: the MonoClass to act on
6988 * Returns: the number of properties in the class.
6991 mono_class_num_properties (MonoClass *klass)
6993 mono_class_setup_properties (klass);
6995 return klass->ext->property.count;
6999 * mono_class_num_events:
7000 * @klass: the MonoClass to act on
7002 * Returns: the number of events in the class.
7005 mono_class_num_events (MonoClass *klass)
7007 mono_class_setup_events (klass);
7009 return klass->ext->event.count;
7013 * mono_class_get_fields:
7014 * @klass: the MonoClass to act on
7016 * This routine is an iterator routine for retrieving the fields in a class.
7018 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7019 * iterate over all of the elements. When no more values are
7020 * available, the return value is NULL.
7022 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
7025 mono_class_get_fields (MonoClass* klass, gpointer *iter)
7027 MonoClassField* field;
7031 mono_class_setup_fields_locking (klass);
7032 if (klass->exception_type)
7034 /* start from the first */
7035 if (klass->field.count) {
7036 return *iter = &klass->fields [0];
7044 if (field < &klass->fields [klass->field.count]) {
7045 return *iter = field;
7051 * mono_class_get_methods
7052 * @klass: the MonoClass to act on
7054 * This routine is an iterator routine for retrieving the fields in a class.
7056 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7057 * iterate over all of the elements. When no more values are
7058 * available, the return value is NULL.
7060 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
7063 mono_class_get_methods (MonoClass* klass, gpointer *iter)
7065 MonoMethod** method;
7069 mono_class_init (klass);
7071 mono_class_setup_methods (klass);
7072 /* start from the first */
7073 if (klass->method.count) {
7074 *iter = &klass->methods [0];
7075 return klass->methods [0];
7083 if (method < &klass->methods [klass->method.count]) {
7091 * mono_class_get_virtual_methods:
7093 * Iterate over the virtual methods of KLASS.
7095 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
7098 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
7100 MonoMethod** method;
7103 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
7105 mono_class_setup_methods (klass);
7106 /* start from the first */
7107 method = &klass->methods [0];
7112 while (method < &klass->methods [klass->method.count]) {
7113 if (((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
7117 if (method < &klass->methods [klass->method.count]) {
7124 /* Search directly in metadata to avoid calling setup_methods () */
7125 MonoMethod *res = NULL;
7131 start_index = GPOINTER_TO_UINT (*iter);
7134 for (i = start_index; i < klass->method.count; ++i) {
7137 /* class->method.first points into the methodptr table */
7138 flags = mono_metadata_decode_table_row_col (klass->image, MONO_TABLE_METHOD, klass->method.first + i, MONO_METHOD_FLAGS);
7140 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
7144 if (i < klass->method.count) {
7145 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7146 /* Add 1 here so the if (*iter) check fails */
7147 *iter = GUINT_TO_POINTER (i + 1);
7156 * mono_class_get_properties:
7157 * @klass: the MonoClass to act on
7159 * This routine is an iterator routine for retrieving the properties in a class.
7161 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7162 * iterate over all of the elements. When no more values are
7163 * available, the return value is NULL.
7165 * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
7168 mono_class_get_properties (MonoClass* klass, gpointer *iter)
7170 MonoProperty* property;
7174 mono_class_init (klass);
7176 mono_class_setup_properties (klass);
7177 /* start from the first */
7178 if (klass->ext->property.count) {
7179 return *iter = &klass->ext->properties [0];
7187 if (property < &klass->ext->properties [klass->ext->property.count]) {
7188 return *iter = property;
7194 * mono_class_get_events:
7195 * @klass: the MonoClass to act on
7197 * This routine is an iterator routine for retrieving the properties in a class.
7199 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7200 * iterate over all of the elements. When no more values are
7201 * available, the return value is NULL.
7203 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
7206 mono_class_get_events (MonoClass* klass, gpointer *iter)
7212 mono_class_init (klass);
7214 mono_class_setup_events (klass);
7215 /* start from the first */
7216 if (klass->ext->event.count) {
7217 return *iter = &klass->ext->events [0];
7225 if (event < &klass->ext->events [klass->ext->event.count]) {
7226 return *iter = event;
7232 * mono_class_get_interfaces
7233 * @klass: the MonoClass to act on
7235 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
7237 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7238 * iterate over all of the elements. When no more values are
7239 * available, the return value is NULL.
7241 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7244 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
7251 mono_class_init (klass);
7252 if (!klass->interfaces_inited)
7253 mono_class_setup_interfaces (klass);
7254 /* start from the first */
7255 if (klass->interface_count) {
7256 *iter = &klass->interfaces [0];
7257 return klass->interfaces [0];
7265 if (iface < &klass->interfaces [klass->interface_count]) {
7273 * mono_class_get_nested_types
7274 * @klass: the MonoClass to act on
7276 * This routine is an iterator routine for retrieving the nested types of a class.
7277 * This works only if @klass is non-generic, or a generic type definition.
7279 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7280 * iterate over all of the elements. When no more values are
7281 * available, the return value is NULL.
7283 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7286 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
7294 mono_class_init (klass);
7295 if (!klass->nested_classes_inited) {
7296 if (!klass->type_token)
7297 klass->nested_classes_inited = TRUE;
7298 mono_loader_lock ();
7299 if (!klass->nested_classes_inited) {
7300 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
7303 guint32 cols [MONO_NESTED_CLASS_SIZE];
7304 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
7305 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
7306 mono_class_alloc_ext (klass);
7307 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
7309 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
7312 mono_memory_barrier ();
7313 klass->nested_classes_inited = TRUE;
7314 mono_loader_unlock ();
7318 /* start from the first */
7319 if (klass->ext && klass->ext->nested_classes) {
7320 *iter = klass->ext->nested_classes;
7321 return klass->ext->nested_classes->data;
7323 /* no nested types */
7337 * mono_field_get_name:
7338 * @field: the MonoClassField to act on
7340 * Returns: the name of the field.
7343 mono_field_get_name (MonoClassField *field)
7349 * mono_field_get_type:
7350 * @field: the MonoClassField to act on
7352 * Returns: MonoType of the field.
7355 mono_field_get_type (MonoClassField *field)
7361 * mono_field_get_parent:
7362 * @field: the MonoClassField to act on
7364 * Returns: MonoClass where the field was defined.
7367 mono_field_get_parent (MonoClassField *field)
7369 return field->parent;
7373 * mono_field_get_flags;
7374 * @field: the MonoClassField to act on
7376 * The metadata flags for a field are encoded using the
7377 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
7379 * Returns: the flags for the field.
7382 mono_field_get_flags (MonoClassField *field)
7384 return field->type->attrs;
7388 * mono_field_get_offset;
7389 * @field: the MonoClassField to act on
7391 * Returns: the field offset.
7394 mono_field_get_offset (MonoClassField *field)
7396 return field->offset;
7400 mono_field_get_rva (MonoClassField *field)
7404 MonoClass *klass = field->parent;
7406 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
7408 if (!klass->ext || !klass->ext->field_def_values) {
7409 mono_loader_lock ();
7410 mono_class_alloc_ext (klass);
7411 if (!klass->ext->field_def_values)
7412 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
7413 mono_loader_unlock ();
7416 field_index = mono_field_get_index (field);
7418 if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
7419 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
7421 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
7422 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
7425 return klass->ext->field_def_values [field_index].data;
7429 * mono_field_get_data;
7430 * @field: the MonoClassField to act on
7432 * Returns: pointer to the metadata constant value or to the field
7433 * data if it has an RVA flag.
7436 mono_field_get_data (MonoClassField *field)
7438 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
7439 MonoTypeEnum def_type;
7441 return mono_class_get_field_default_value (field, &def_type);
7442 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
7443 return mono_field_get_rva (field);
7450 * mono_property_get_name:
7451 * @prop: the MonoProperty to act on
7453 * Returns: the name of the property
7456 mono_property_get_name (MonoProperty *prop)
7462 * mono_property_get_set_method
7463 * @prop: the MonoProperty to act on.
7465 * Returns: the setter method of the property (A MonoMethod)
7468 mono_property_get_set_method (MonoProperty *prop)
7474 * mono_property_get_get_method
7475 * @prop: the MonoProperty to act on.
7477 * Returns: the setter method of the property (A MonoMethod)
7480 mono_property_get_get_method (MonoProperty *prop)
7486 * mono_property_get_parent:
7487 * @prop: the MonoProperty to act on.
7489 * Returns: the MonoClass where the property was defined.
7492 mono_property_get_parent (MonoProperty *prop)
7494 return prop->parent;
7498 * mono_property_get_flags:
7499 * @prop: the MonoProperty to act on.
7501 * The metadata flags for a property are encoded using the
7502 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
7504 * Returns: the flags for the property.
7507 mono_property_get_flags (MonoProperty *prop)
7513 * mono_event_get_name:
7514 * @event: the MonoEvent to act on
7516 * Returns: the name of the event.
7519 mono_event_get_name (MonoEvent *event)
7525 * mono_event_get_add_method:
7526 * @event: The MonoEvent to act on.
7528 * Returns: the @add' method for the event (a MonoMethod).
7531 mono_event_get_add_method (MonoEvent *event)
7537 * mono_event_get_remove_method:
7538 * @event: The MonoEvent to act on.
7540 * Returns: the @remove method for the event (a MonoMethod).
7543 mono_event_get_remove_method (MonoEvent *event)
7545 return event->remove;
7549 * mono_event_get_raise_method:
7550 * @event: The MonoEvent to act on.
7552 * Returns: the @raise method for the event (a MonoMethod).
7555 mono_event_get_raise_method (MonoEvent *event)
7557 return event->raise;
7561 * mono_event_get_parent:
7562 * @event: the MonoEvent to act on.
7564 * Returns: the MonoClass where the event is defined.
7567 mono_event_get_parent (MonoEvent *event)
7569 return event->parent;
7573 * mono_event_get_flags
7574 * @event: the MonoEvent to act on.
7576 * The metadata flags for an event are encoded using the
7577 * EVENT_* constants. See the tabledefs.h file for details.
7579 * Returns: the flags for the event.
7582 mono_event_get_flags (MonoEvent *event)
7584 return event->attrs;
7588 * mono_class_get_method_from_name:
7589 * @klass: where to look for the method
7590 * @name_space: name of the method
7591 * @param_count: number of parameters. -1 for any number.
7593 * Obtains a MonoMethod with a given name and number of parameters.
7594 * It only works if there are no multiple signatures for any given method name.
7597 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
7599 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
7603 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
7605 MonoMethod *res = NULL;
7608 /* Search directly in the metadata to avoid calling setup_methods () */
7609 for (i = 0; i < klass->method.count; ++i) {
7610 guint32 cols [MONO_METHOD_SIZE];
7613 /* class->method.first points into the methodptr table */
7614 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
7616 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
7617 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7618 if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
7629 * mono_class_get_method_from_name_flags:
7630 * @klass: where to look for the method
7631 * @name_space: name of the method
7632 * @param_count: number of parameters. -1 for any number.
7633 * @flags: flags which must be set in the method
7635 * Obtains a MonoMethod with a given name and number of parameters.
7636 * It only works if there are no multiple signatures for any given method name.
7639 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
7641 MonoMethod *res = NULL;
7644 mono_class_init (klass);
7646 if (klass->generic_class && !klass->methods) {
7647 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
7649 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
7653 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
7654 mono_class_setup_methods (klass);
7655 for (i = 0; i < klass->method.count; ++i) {
7656 MonoMethod *method = klass->methods [i];
7658 if (method->name[0] == name [0] &&
7659 !strcmp (name, method->name) &&
7660 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
7661 ((method->flags & flags) == flags)) {
7668 res = find_method_in_metadata (klass, name, param_count, flags);
7675 * mono_class_set_failure:
7676 * @klass: class in which the failure was detected
7677 * @ex_type: the kind of exception/error to be thrown (later)
7678 * @ex_data: exception data (specific to each type of exception/error)
7680 * Keep a detected failure informations in the class for later processing.
7681 * Note that only the first failure is kept.
7683 * LOCKING: Acquires the loader lock.
7686 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
7688 if (klass->exception_type)
7691 mono_loader_lock ();
7692 klass->exception_type = ex_type;
7694 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
7695 mono_loader_unlock ();
7701 * mono_class_get_exception_data:
7703 * Return the exception_data property of KLASS.
7705 * LOCKING: Acquires the loader lock.
7708 mono_class_get_exception_data (MonoClass *klass)
7710 return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
7714 * mono_classes_init:
7716 * Initialize the resources used by this module.
7719 mono_classes_init (void)
7721 mono_counters_register ("Inflated methods size",
7722 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
7723 mono_counters_register ("Inflated classes",
7724 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
7725 mono_counters_register ("Inflated classes size",
7726 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
7727 mono_counters_register ("MonoClass size",
7728 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
7729 mono_counters_register ("MonoClassExt size",
7730 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
7734 * mono_classes_cleanup:
7736 * Free the resources used by this module.
7739 mono_classes_cleanup (void)
7741 if (global_interface_bitset)
7742 mono_bitset_free (global_interface_bitset);
7746 * mono_class_get_exception_for_failure:
7747 * @klass: class in which the failure was detected
7749 * Return a constructed MonoException than the caller can then throw
7750 * using mono_raise_exception - or NULL if no failure is present (or
7751 * doesn't result in an exception).
7754 mono_class_get_exception_for_failure (MonoClass *klass)
7756 gpointer exception_data = mono_class_get_exception_data (klass);
7758 switch (klass->exception_type) {
7759 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
7760 MonoDomain *domain = mono_domain_get ();
7761 MonoSecurityManager* secman = mono_security_manager_get_methods ();
7762 MonoMethod *method = exception_data;
7763 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
7764 MonoObject *exc = NULL;
7768 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
7769 args [2] = mono_type_get_object (domain, &klass->byval_arg);
7770 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
7772 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
7773 return (MonoException*) exc;
7775 case MONO_EXCEPTION_TYPE_LOAD: {
7778 char *str = mono_type_get_full_name (klass);
7779 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
7780 name = mono_string_new (mono_domain_get (), str);
7782 ex = mono_get_exception_type_load (name, astr);
7786 case MONO_EXCEPTION_MISSING_METHOD: {
7787 char *class_name = exception_data;
7788 char *assembly_name = class_name + strlen (class_name) + 1;
7790 return mono_get_exception_missing_method (class_name, assembly_name);
7792 case MONO_EXCEPTION_MISSING_FIELD: {
7793 char *class_name = exception_data;
7794 char *member_name = class_name + strlen (class_name) + 1;
7796 return mono_get_exception_missing_field (class_name, member_name);
7798 case MONO_EXCEPTION_FILE_NOT_FOUND: {
7799 char *msg_format = exception_data;
7800 char *assembly_name = msg_format + strlen (msg_format) + 1;
7801 char *msg = g_strdup_printf (msg_format, assembly_name);
7804 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
7810 case MONO_EXCEPTION_BAD_IMAGE: {
7811 return mono_get_exception_bad_image_format (exception_data);
7814 MonoLoaderError *error;
7817 error = mono_loader_get_last_error ();
7819 ex = mono_loader_error_prepare_exception (error);
7823 /* TODO - handle other class related failures */
7830 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
7832 outer_klass = mono_class_get_generic_type_definition (outer_klass);
7833 inner_klass = mono_class_get_generic_type_definition (inner_klass);
7835 if (outer_klass == inner_klass)
7837 inner_klass = inner_klass->nested_in;
7838 } while (inner_klass);
7843 mono_class_get_generic_type_definition (MonoClass *klass)
7845 return klass->generic_class ? klass->generic_class->container_class : klass;
7849 * Check if @klass is a subtype of @parent ignoring generic instantiations.
7851 * Generic instantiations are ignored for all super types of @klass.
7853 * Visibility checks ignoring generic instantiations.
7856 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
7859 klass = mono_class_get_generic_type_definition (klass);
7860 parent = mono_class_get_generic_type_definition (parent);
7862 for (i = 0; i < klass->idepth; ++i) {
7863 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
7869 * Subtype can only access parent members with family protection if the site object
7870 * is subclass of Subtype. For example:
7871 * class A { protected int x; }
7873 * void valid_access () {
7877 * void invalid_access () {
7884 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
7886 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
7889 if (context_klass == NULL)
7891 /*if access_klass is not member_klass context_klass must be type compat*/
7892 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
7898 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
7901 if (accessing == accessed)
7903 if (!accessed || !accessing)
7906 /* extra safety under CoreCLR - the runtime does not verify the strongname signatures
7907 * anywhere so untrusted friends are not safe to access platform's code internals */
7908 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
7909 if (!mono_security_core_clr_can_access_internals (accessing->image, accessed->image))
7913 mono_assembly_load_friends (accessed);
7914 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
7915 MonoAssemblyName *friend = tmp->data;
7916 /* Be conservative with checks */
7919 if (strcmp (accessing->aname.name, friend->name))
7921 if (friend->public_key_token [0]) {
7922 if (!accessing->aname.public_key_token [0])
7924 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
7933 * If klass is a generic type or if it is derived from a generic type, return the
7934 * MonoClass of the generic definition
7935 * Returns NULL if not found
7938 get_generic_definition_class (MonoClass *klass)
7941 if (klass->generic_class && klass->generic_class->container_class)
7942 return klass->generic_class->container_class;
7943 klass = klass->parent;
7949 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
7952 for (i = 0; i < ginst->type_argc; ++i) {
7953 MonoType *type = ginst->type_argv[i];
7954 switch (type->type) {
7955 case MONO_TYPE_SZARRAY:
7956 if (!can_access_type (access_klass, type->data.klass))
7959 case MONO_TYPE_ARRAY:
7960 if (!can_access_type (access_klass, type->data.array->eklass))
7964 if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
7967 case MONO_TYPE_CLASS:
7968 case MONO_TYPE_VALUETYPE:
7969 case MONO_TYPE_GENERICINST:
7970 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
7978 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
7982 if (access_klass->element_class && !access_klass->enumtype)
7983 access_klass = access_klass->element_class;
7985 if (member_klass->element_class && !member_klass->enumtype)
7986 member_klass = member_klass->element_class;
7988 access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
7990 if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
7993 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
7996 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
7999 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
8002 /*Non nested type with nested visibility. We just fail it.*/
8003 if (access_level >= TYPE_ATTRIBUTE_NESTED_PRIVATE && access_level <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM && member_klass->nested_in == NULL)
8006 switch (access_level) {
8007 case TYPE_ATTRIBUTE_NOT_PUBLIC:
8008 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8010 case TYPE_ATTRIBUTE_PUBLIC:
8013 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
8016 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
8017 return is_nesting_type (member_klass, access_klass);
8019 case TYPE_ATTRIBUTE_NESTED_FAMILY:
8020 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
8022 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
8023 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8025 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
8026 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
8027 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
8029 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
8030 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
8031 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
8036 /* FIXME: check visibility of type, too */
8038 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
8040 MonoClass *member_generic_def;
8041 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
8042 access_klass->generic_container) &&
8043 (member_generic_def = get_generic_definition_class (member_klass))) {
8044 MonoClass *access_container;
8046 if (access_klass->generic_container)
8047 access_container = access_klass;
8049 access_container = access_klass->generic_class->container_class;
8051 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
8055 /* Partition I 8.5.3.2 */
8056 /* the access level values are the same for fields and methods */
8057 switch (access_level) {
8058 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
8059 /* same compilation unit */
8060 return access_klass->image == member_klass->image;
8061 case FIELD_ATTRIBUTE_PRIVATE:
8062 return access_klass == member_klass;
8063 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
8064 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
8065 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
8068 case FIELD_ATTRIBUTE_ASSEMBLY:
8069 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8070 case FIELD_ATTRIBUTE_FAMILY:
8071 if (is_valid_family_access (access_klass, member_klass, context_klass))
8074 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
8075 if (is_valid_family_access (access_klass, member_klass, context_klass))
8077 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8078 case FIELD_ATTRIBUTE_PUBLIC:
8085 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
8087 /* FIXME: check all overlapping fields */
8088 int can = can_access_member (method->klass, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8090 MonoClass *nested = method->klass->nested_in;
8092 can = can_access_member (nested, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8095 nested = nested->nested_in;
8102 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
8104 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8106 MonoClass *nested = method->klass->nested_in;
8108 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8111 nested = nested->nested_in;
8116 * with generics calls to explicit interface implementations can be expressed
8117 * directly: the method is private, but we must allow it. This may be opening
8118 * a hole or the generics code should handle this differently.
8119 * Maybe just ensure the interface type is public.
8121 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
8127 * mono_method_can_access_method_full:
8128 * @method: The caller method
8129 * @called: The called method
8130 * @context_klass: The static type on stack of the owner @called object used
8132 * This function must be used with instance calls, as they have more strict family accessibility.
8133 * It can be used with static methods, but context_klass should be NULL.
8135 * Returns: TRUE if caller have proper visibility and acessibility to @called
8138 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
8140 MonoClass *access_class = method->klass;
8141 MonoClass *member_class = called->klass;
8142 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8144 MonoClass *nested = access_class->nested_in;
8146 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8149 nested = nested->nested_in;
8156 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8159 if (called->is_inflated) {
8160 MonoMethodInflated * infl = (MonoMethodInflated*)called;
8161 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
8170 * mono_method_can_access_field_full:
8171 * @method: The caller method
8172 * @field: The accessed field
8173 * @context_klass: The static type on stack of the owner @field object used
8175 * This function must be used with instance fields, as they have more strict family accessibility.
8176 * It can be used with static fields, but context_klass should be NULL.
8178 * Returns: TRUE if caller have proper visibility and acessibility to @field
8181 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
8183 MonoClass *access_class = method->klass;
8184 MonoClass *member_class = field->parent;
8185 /* FIXME: check all overlapping fields */
8186 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8188 MonoClass *nested = access_class->nested_in;
8190 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8193 nested = nested->nested_in;
8200 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8206 * mono_type_is_valid_enum_basetype:
8207 * @type: The MonoType to check
8209 * Returns: TRUE if the type can be used as the basetype of an enum
8211 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
8212 switch (type->type) {
8215 case MONO_TYPE_BOOLEAN:
8218 case MONO_TYPE_CHAR:
8231 * mono_class_is_valid_enum:
8232 * @klass: An enum class to be validated
8234 * This method verify the required properties an enum should have.
8236 * Returns: TRUE if the informed enum class is valid
8238 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
8239 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
8240 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
8242 gboolean mono_class_is_valid_enum (MonoClass *klass) {
8243 MonoClassField * field;
8244 gpointer iter = NULL;
8245 gboolean found_base_field = FALSE;
8247 g_assert (klass->enumtype);
8248 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
8249 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
8253 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
8256 while ((field = mono_class_get_fields (klass, &iter))) {
8257 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
8258 if (found_base_field)
8260 found_base_field = TRUE;
8261 if (!mono_type_is_valid_enum_basetype (field->type))
8266 if (!found_base_field)
8269 if (klass->method.count > 0)
8276 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
8278 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
8281 static gboolean gshared_supported;
8284 mono_set_generic_sharing_supported (gboolean supported)
8286 gshared_supported = supported;
8290 * mono_class_generic_sharing_enabled:
8293 * Returns whether generic sharing is enabled for class.
8295 * This is a stop-gap measure to slowly introduce generic sharing
8296 * until we have all the issues sorted out, at which time this
8297 * function will disappear and generic sharing will always be enabled.
8300 mono_class_generic_sharing_enabled (MonoClass *class)
8302 static int generic_sharing = MONO_GENERIC_SHARING_NONE;
8303 static gboolean inited = FALSE;
8308 if (gshared_supported)
8309 generic_sharing = MONO_GENERIC_SHARING_ALL;
8311 generic_sharing = MONO_GENERIC_SHARING_NONE;
8313 if ((option = g_getenv ("MONO_GENERIC_SHARING"))) {
8314 if (strcmp (option, "corlib") == 0)
8315 generic_sharing = MONO_GENERIC_SHARING_CORLIB;
8316 else if (strcmp (option, "collections") == 0)
8317 generic_sharing = MONO_GENERIC_SHARING_COLLECTIONS;
8318 else if (strcmp (option, "all") == 0)
8319 generic_sharing = MONO_GENERIC_SHARING_ALL;
8320 else if (strcmp (option, "none") == 0)
8321 generic_sharing = MONO_GENERIC_SHARING_NONE;
8323 g_warning ("Unknown generic sharing option `%s'.", option);
8326 if (!gshared_supported)
8327 generic_sharing = MONO_GENERIC_SHARING_NONE;
8332 switch (generic_sharing) {
8333 case MONO_GENERIC_SHARING_NONE:
8335 case MONO_GENERIC_SHARING_ALL:
8337 case MONO_GENERIC_SHARING_CORLIB :
8338 return class->image == mono_defaults.corlib;
8339 case MONO_GENERIC_SHARING_COLLECTIONS:
8340 if (class->image != mono_defaults.corlib)
8342 while (class->nested_in)
8343 class = class->nested_in;
8344 return g_str_has_prefix (class->name_space, "System.Collections.Generic");
8346 g_assert_not_reached ();
8352 * mono_class_setup_interface_id:
8354 * Initializes MonoClass::interface_id if required.
8356 * LOCKING: Acquires the loader lock.
8359 mono_class_setup_interface_id (MonoClass *class)
8361 mono_loader_lock ();
8362 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
8363 class->interface_id = mono_get_unique_iid (class);
8364 mono_loader_unlock ();
8368 * mono_class_alloc_ext:
8370 * Allocate klass->ext if not already done.
8371 * LOCKING: Assumes the loader lock is held.
8374 mono_class_alloc_ext (MonoClass *klass)
8377 if (klass->generic_class) {
8378 klass->ext = g_new0 (MonoClassExt, 1);
8380 klass->ext = mono_image_alloc0 (klass->image, sizeof (MonoClassExt));
8382 class_ext_size += sizeof (MonoClassExt);
8387 * mono_class_setup_interfaces:
8389 * Initialize class->interfaces/interfaces_count.
8390 * LOCKING: Acquires the loader lock.
8393 mono_class_setup_interfaces (MonoClass *klass)
8397 if (klass->interfaces_inited)
8400 mono_loader_lock ();
8402 if (klass->interfaces_inited) {
8403 mono_loader_unlock ();
8407 if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
8410 /* generic IList, ICollection, IEnumerable */
8411 klass->interface_count = 1;
8412 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
8414 args [0] = &klass->element_class->byval_arg;
8415 klass->interfaces [0] = mono_class_bind_generic_parameters (
8416 mono_defaults.generic_ilist_class, 1, args, FALSE);
8417 } else if (klass->generic_class) {
8418 MonoClass *gklass = klass->generic_class->container_class;
8420 klass->interface_count = gklass->interface_count;
8421 klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
8422 for (i = 0; i < klass->interface_count; i++)
8423 klass->interfaces [i] = mono_class_inflate_generic_class (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class));
8426 mono_memory_barrier ();
8428 klass->interfaces_inited = TRUE;
8430 mono_loader_unlock ();