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->module_name, "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->module_name, "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 * mono_class_setup_fields:
1104 * @class: The class to initialize
1106 * Initializes the class->fields.
1107 * LOCKING: Assumes the loader lock is held.
1110 mono_class_setup_fields (MonoClass *class)
1112 MonoImage *m = class->image;
1113 int top = class->field.count;
1114 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1115 int i, blittable = TRUE;
1116 guint32 real_size = 0;
1117 guint32 packing_size = 0;
1118 gboolean explicit_size;
1119 MonoClassField *field;
1120 MonoGenericContainer *container = NULL;
1121 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1123 if (class->size_inited)
1126 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1128 * This happens when a generic instance of an unfinished generic typebuilder
1129 * is used as an element type for creating an array type. We can't initialize
1130 * the fields of this class using the fields of gklass, since gklass is not
1131 * finished yet, fields could be added to it later.
1137 mono_class_setup_fields (gtd);
1138 if (gtd->exception_type) {
1139 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1143 top = gtd->field.count;
1144 class->field.first = gtd->field.first;
1145 class->field.count = gtd->field.count;
1148 class->instance_size = 0;
1150 class->sizes.class_size = 0;
1152 if (class->parent) {
1153 /* For generic instances, class->parent might not have been initialized */
1154 mono_class_init (class->parent);
1155 if (!class->parent->size_inited) {
1156 mono_class_setup_fields (class->parent);
1157 if (class->parent->exception_type) {
1158 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1162 class->instance_size += class->parent->instance_size;
1163 class->min_align = class->parent->min_align;
1164 /* we use |= since it may have been set already */
1165 class->has_references |= class->parent->has_references;
1166 blittable = class->parent->blittable;
1168 class->instance_size = sizeof (MonoObject);
1169 class->min_align = 1;
1172 /* We can't really enable 16 bytes alignment until the GC supports it.
1173 The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
1174 boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
1175 Bug #506144 is an example of this issue.
1177 if (class->simd_type)
1178 class->min_align = 16;
1180 /* Get the real size */
1181 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1183 if (explicit_size) {
1184 g_assert ((packing_size & 0xfffffff0) == 0);
1185 class->packing_size = packing_size;
1186 real_size += class->instance_size;
1190 if (explicit_size && real_size) {
1191 class->instance_size = MAX (real_size, class->instance_size);
1193 class->size_inited = 1;
1194 class->blittable = blittable;
1198 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1201 /* Prevent infinite loops if the class references itself */
1202 class->size_inited = 1;
1204 class->fields = mono_image_alloc0 (class->image, sizeof (MonoClassField) * top);
1206 if (class->generic_container) {
1207 container = class->generic_container;
1209 container = gtd->generic_container;
1210 g_assert (container);
1214 * Fetch all the field information.
1216 for (i = 0; i < top; i++){
1217 int idx = class->field.first + i;
1218 field = &class->fields [i];
1220 field->parent = class;
1223 MonoClassField *gfield = >d->fields [i];
1225 field->name = mono_field_get_name (gfield);
1226 /*This memory must come from the image mempool as we don't have a chance to free it.*/
1227 field->type = mono_class_inflate_generic_type_no_copy (class->image, gfield->type, mono_class_get_context (class));
1228 g_assert (field->type->attrs == gfield->type->attrs);
1229 if (mono_field_is_deleted (field))
1231 field->offset = gfield->offset;
1234 guint32 cols [MONO_FIELD_SIZE];
1236 /* class->field.first and idx points into the fieldptr table */
1237 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1238 /* The name is needed for fieldrefs */
1239 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
1240 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL)) {
1241 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1244 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1245 mono_metadata_decode_value (sig, &sig);
1246 /* FIELD signature == 0x06 */
1247 g_assert (*sig == 0x06);
1248 field->type = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1250 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1253 if (mono_field_is_deleted (field))
1255 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1257 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1258 field->offset = offset;
1259 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1260 g_warning ("%s not initialized correctly (missing field layout info for %s)",
1261 class->name, mono_field_get_name (field));
1265 /* Only do these checks if we still think this type is blittable */
1266 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1267 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1270 MonoClass *field_class = mono_class_from_mono_type (field->type);
1272 mono_class_setup_fields (field_class);
1273 if (field_class->exception_type) {
1274 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1278 if (!field_class || !field_class->blittable)
1283 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1284 class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1285 blittable = class->element_class->blittable;
1288 /* The def_value of fields is compute lazily during vtable creation */
1291 if (class == mono_defaults.string_class)
1294 class->blittable = blittable;
1296 if (class->enumtype && !mono_class_enum_basetype (class)) {
1297 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
1300 if (explicit_size && real_size) {
1301 class->instance_size = MAX (real_size, class->instance_size);
1304 if (class->exception_type)
1306 mono_class_layout_fields (class);
1310 * mono_class_setup_fields_locking:
1311 * @class: The class to initialize
1313 * Initializes the class->fields array of fields.
1314 * Aquires the loader lock.
1317 mono_class_setup_fields_locking (MonoClass *class)
1319 mono_loader_lock ();
1320 mono_class_setup_fields (class);
1321 mono_loader_unlock ();
1325 * mono_class_has_references:
1327 * Returns whenever @klass->has_references is set, initializing it if needed.
1328 * Aquires the loader lock.
1331 mono_class_has_references (MonoClass *klass)
1333 if (klass->init_pending) {
1334 /* Be conservative */
1337 mono_class_init (klass);
1339 return klass->has_references;
1343 /* useful until we keep track of gc-references in corlib etc. */
1345 #define IS_GC_REFERENCE(t) FALSE
1347 #define IS_GC_REFERENCE(t) ((t)->type == MONO_TYPE_U && class->image == mono_defaults.corlib)
1351 * mono_type_get_basic_type_from_generic:
1354 * Returns a closed type corresponding to the possibly open type
1358 mono_type_get_basic_type_from_generic (MonoType *type)
1360 /* When we do generic sharing we let type variables stand for reference types. */
1361 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1362 return &mono_defaults.object_class->byval_arg;
1367 * mono_class_layout_fields:
1370 * Compute the placement of fields inside an object or struct, according to
1371 * the layout rules and set the following fields in @class:
1372 * - has_references (if the class contains instance references firled or structs that contain references)
1373 * - has_static_refs (same, but for static fields)
1374 * - instance_size (size of the object in memory)
1375 * - class_size (size needed for the static fields)
1376 * - size_inited (flag set when the instance_size is set)
1378 * LOCKING: this is supposed to be called with the loader lock held.
1381 mono_class_layout_fields (MonoClass *class)
1384 const int top = class->field.count;
1385 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1386 guint32 pass, passes, real_size;
1387 gboolean gc_aware_layout = FALSE;
1388 MonoClassField *field;
1391 * When we do generic sharing we need to have layout
1392 * information for open generic classes (either with a generic
1393 * context containing type variables or with a generic
1394 * container), so we don't return in that case anymore.
1398 * Enable GC aware auto layout: in this mode, reference
1399 * fields are grouped together inside objects, increasing collector
1401 * Requires that all classes whose layout is known to native code be annotated
1402 * with [StructLayout (LayoutKind.Sequential)]
1403 * Value types have gc_aware_layout disabled by default, as per
1404 * what the default is for other runtimes.
1406 /* corlib is missing [StructLayout] directives in many places */
1407 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1408 if (class->image != mono_defaults.corlib &&
1409 class->byval_arg.type != MONO_TYPE_VALUETYPE)
1410 gc_aware_layout = TRUE;
1411 /* from System.dll, used in metadata/process.h */
1412 if (strcmp (class->name, "ProcessStartInfo") == 0)
1413 gc_aware_layout = FALSE;
1416 /* Compute klass->has_references */
1418 * Process non-static fields first, since static fields might recursively
1419 * refer to the class itself.
1421 for (i = 0; i < top; i++) {
1424 field = &class->fields [i];
1426 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1427 ftype = mono_type_get_underlying_type (field->type);
1428 ftype = mono_type_get_basic_type_from_generic (ftype);
1429 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1430 class->has_references = TRUE;
1434 for (i = 0; i < top; i++) {
1437 field = &class->fields [i];
1439 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1440 ftype = mono_type_get_underlying_type (field->type);
1441 ftype = mono_type_get_basic_type_from_generic (ftype);
1442 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1443 class->has_static_refs = TRUE;
1447 for (i = 0; i < top; i++) {
1450 field = &class->fields [i];
1452 ftype = mono_type_get_underlying_type (field->type);
1453 ftype = mono_type_get_basic_type_from_generic (ftype);
1454 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1455 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1456 class->has_static_refs = TRUE;
1458 class->has_references = TRUE;
1463 * Compute field layout and total size (not considering static fields)
1467 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1468 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1470 if (gc_aware_layout)
1475 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1479 real_size = class->parent->instance_size;
1481 real_size = sizeof (MonoObject);
1483 for (pass = 0; pass < passes; ++pass) {
1484 for (i = 0; i < top; i++){
1489 field = &class->fields [i];
1491 if (mono_field_is_deleted (field))
1493 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1496 ftype = mono_type_get_underlying_type (field->type);
1497 ftype = mono_type_get_basic_type_from_generic (ftype);
1498 if (gc_aware_layout) {
1499 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1508 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1509 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1510 /* This field is a hack inserted by MCS to empty structures */
1514 size = mono_type_size (field->type, &align);
1516 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1517 align = class->packing_size ? MIN (class->packing_size, align): align;
1518 /* if the field has managed references, we need to force-align it
1521 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1522 align = MAX (align, sizeof (gpointer));
1524 class->min_align = MAX (align, class->min_align);
1525 field->offset = real_size;
1526 field->offset += align - 1;
1527 field->offset &= ~(align - 1);
1528 real_size = field->offset + size;
1531 class->instance_size = MAX (real_size, class->instance_size);
1533 if (class->instance_size & (class->min_align - 1)) {
1534 class->instance_size += class->min_align - 1;
1535 class->instance_size &= ~(class->min_align - 1);
1539 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1541 for (i = 0; i < top; i++) {
1546 field = &class->fields [i];
1549 * There must be info about all the fields in a type if it
1550 * uses explicit layout.
1553 if (mono_field_is_deleted (field))
1555 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1558 size = mono_type_size (field->type, &align);
1559 class->min_align = MAX (align, class->min_align);
1562 * When we get here, field->offset is already set by the
1563 * loader (for either runtime fields or fields loaded from metadata).
1564 * The offset is from the start of the object: this works for both
1565 * classes and valuetypes.
1567 field->offset += sizeof (MonoObject);
1568 ftype = mono_type_get_underlying_type (field->type);
1569 ftype = mono_type_get_basic_type_from_generic (ftype);
1570 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1571 if (field->offset % sizeof (gpointer)) {
1572 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1579 real_size = MAX (real_size, size + field->offset);
1581 class->instance_size = MAX (real_size, class->instance_size);
1585 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1587 * For small structs, set min_align to at least the struct size to improve
1588 * performance, and since the JIT memset/memcpy code assumes this and generates
1589 * unaligned accesses otherwise. See #78990 for a testcase.
1591 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1592 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1595 class->size_inited = 1;
1598 * Compute static field layout and size
1600 for (i = 0; i < top; i++){
1604 field = &class->fields [i];
1606 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1608 if (mono_field_is_deleted (field))
1611 size = mono_type_size (field->type, &align);
1612 field->offset = class->sizes.class_size;
1613 field->offset += align - 1;
1614 field->offset &= ~(align - 1);
1615 class->sizes.class_size = field->offset + size;
1620 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1624 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1625 method->klass = class;
1626 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1627 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1628 method->signature = sig;
1629 method->name = name;
1632 if (name [0] == '.') {
1633 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1635 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1641 * mono_class_setup_methods:
1644 * Initializes the 'methods' array in the klass.
1645 * Calling this method should be avoided if possible since it allocates a lot
1646 * of long-living MonoMethod structures.
1647 * Methods belonging to an interface are assigned a sequential slot starting
1651 mono_class_setup_methods (MonoClass *class)
1654 MonoMethod **methods;
1659 mono_loader_lock ();
1661 if (class->methods) {
1662 mono_loader_unlock ();
1666 if (class->generic_class) {
1667 MonoClass *gklass = class->generic_class->container_class;
1669 mono_class_init (gklass);
1670 mono_class_setup_methods (gklass);
1672 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1673 class->method.count = gklass->method.count;
1674 methods = g_new0 (MonoMethod *, class->method.count + 1);
1676 for (i = 0; i < class->method.count; i++) {
1677 methods [i] = mono_class_inflate_generic_method_full (
1678 gklass->methods [i], class, mono_class_get_context (class));
1680 } else if (class->rank) {
1681 MonoMethod *amethod;
1682 MonoMethodSignature *sig;
1683 int count_generic = 0, first_generic = 0;
1686 class->method.count = 3 + (class->rank > 1? 2: 1);
1688 mono_class_setup_interfaces (class);
1690 if (class->interface_count) {
1691 count_generic = generic_array_methods (class);
1692 first_generic = class->method.count;
1693 class->method.count += class->interface_count * count_generic;
1696 methods = mono_image_alloc0 (class->image, sizeof (MonoMethod*) * class->method.count);
1698 sig = mono_metadata_signature_alloc (class->image, class->rank);
1699 sig->ret = &mono_defaults.void_class->byval_arg;
1700 sig->pinvoke = TRUE;
1701 sig->hasthis = TRUE;
1702 for (i = 0; i < class->rank; ++i)
1703 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1705 amethod = create_array_method (class, ".ctor", sig);
1706 methods [method_num++] = amethod;
1707 if (class->rank > 1) {
1708 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1709 sig->ret = &mono_defaults.void_class->byval_arg;
1710 sig->pinvoke = TRUE;
1711 sig->hasthis = TRUE;
1712 for (i = 0; i < class->rank * 2; ++i)
1713 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1715 amethod = create_array_method (class, ".ctor", sig);
1716 methods [method_num++] = amethod;
1718 /* element Get (idx11, [idx2, ...]) */
1719 sig = mono_metadata_signature_alloc (class->image, class->rank);
1720 sig->ret = &class->element_class->byval_arg;
1721 sig->pinvoke = TRUE;
1722 sig->hasthis = TRUE;
1723 for (i = 0; i < class->rank; ++i)
1724 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1725 amethod = create_array_method (class, "Get", sig);
1726 methods [method_num++] = amethod;
1727 /* element& Address (idx11, [idx2, ...]) */
1728 sig = mono_metadata_signature_alloc (class->image, class->rank);
1729 sig->ret = &class->element_class->this_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;
1734 amethod = create_array_method (class, "Address", sig);
1735 methods [method_num++] = amethod;
1736 /* void Set (idx11, [idx2, ...], element) */
1737 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1738 sig->ret = &mono_defaults.void_class->byval_arg;
1739 sig->pinvoke = TRUE;
1740 sig->hasthis = TRUE;
1741 for (i = 0; i < class->rank; ++i)
1742 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1743 sig->params [i] = &class->element_class->byval_arg;
1744 amethod = create_array_method (class, "Set", sig);
1745 methods [method_num++] = amethod;
1747 for (i = 0; i < class->interface_count; i++)
1748 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1750 methods = mono_image_alloc (class->image, sizeof (MonoMethod*) * class->method.count);
1751 for (i = 0; i < class->method.count; ++i) {
1752 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1753 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1757 if (MONO_CLASS_IS_INTERFACE (class)) {
1759 /*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
1760 for (i = 0; i < class->method.count; ++i) {
1761 if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
1762 methods [i]->slot = slot++;
1766 /* Needed because of the double-checking locking pattern */
1767 mono_memory_barrier ();
1769 class->methods = methods;
1771 if (mono_debugger_class_loaded_methods_func)
1772 mono_debugger_class_loaded_methods_func (class);
1774 mono_loader_unlock ();
1778 * mono_class_get_method_by_index:
1780 * Returns class->methods [index], initializing class->methods if neccesary.
1782 * LOCKING: Acquires the loader lock.
1785 mono_class_get_method_by_index (MonoClass *class, int index)
1787 /* Avoid calling setup_methods () if possible */
1788 if (class->generic_class && !class->methods) {
1789 MonoClass *gklass = class->generic_class->container_class;
1792 m = mono_class_inflate_generic_method_full (
1793 gklass->methods [index], class, mono_class_get_context (class));
1795 * If setup_methods () is called later for this class, no duplicates are created,
1796 * since inflate_generic_method guarantees that only one instance of a method
1797 * is created for each context.
1800 mono_class_setup_methods (class);
1801 g_assert (m == class->methods [index]);
1805 mono_class_setup_methods (class);
1806 g_assert (index >= 0 && index < class->method.count);
1807 return class->methods [index];
1812 * mono_class_get_inflated_method:
1814 * Given an inflated class CLASS and a method METHOD which should be a method of
1815 * CLASS's generic definition, return the inflated method corresponding to METHOD.
1818 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
1820 MonoClass *gklass = class->generic_class->container_class;
1823 mono_class_setup_methods (gklass);
1824 for (i = 0; i < gklass->method.count; ++i) {
1825 if (gklass->methods [i] == method) {
1827 return class->methods [i];
1829 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
1837 * mono_class_get_vtable_entry:
1839 * Returns class->vtable [offset], computing it if neccesary.
1840 * LOCKING: Acquires the loader lock.
1843 mono_class_get_vtable_entry (MonoClass *class, int offset)
1847 if (class->rank == 1) {
1849 * szarrays do not overwrite any methods of Array, so we can avoid
1850 * initializing their vtables in some cases.
1852 mono_class_setup_vtable (class->parent);
1853 if (offset < class->parent->vtable_size)
1854 return class->parent->vtable [offset];
1857 if (class->generic_class) {
1858 MonoClass *gklass = class->generic_class->container_class;
1859 mono_class_setup_vtable (gklass);
1860 m = gklass->vtable [offset];
1862 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
1864 mono_class_setup_vtable (class);
1865 m = class->vtable [offset];
1872 * mono_class_get_vtable_size:
1874 * Return the vtable size for KLASS.
1877 mono_class_get_vtable_size (MonoClass *klass)
1879 mono_class_setup_vtable (klass);
1881 return klass->vtable_size;
1885 mono_class_setup_properties (MonoClass *class)
1887 guint startm, endm, i, j;
1888 guint32 cols [MONO_PROPERTY_SIZE];
1889 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1890 MonoProperty *properties;
1893 if (class->ext && class->ext->properties)
1896 mono_loader_lock ();
1898 if (class->ext && class->ext->properties) {
1899 mono_loader_unlock ();
1903 mono_class_alloc_ext (class);
1905 if (class->generic_class) {
1906 MonoClass *gklass = class->generic_class->container_class;
1908 mono_class_init (gklass);
1909 mono_class_setup_properties (gklass);
1911 class->ext->property = gklass->ext->property;
1913 properties = g_new0 (MonoProperty, class->ext->property.count + 1);
1915 for (i = 0; i < class->ext->property.count; i++) {
1916 MonoProperty *prop = &properties [i];
1918 *prop = gklass->ext->properties [i];
1921 prop->get = mono_class_inflate_generic_method_full (
1922 prop->get, class, mono_class_get_context (class));
1924 prop->set = mono_class_inflate_generic_method_full (
1925 prop->set, class, mono_class_get_context (class));
1927 prop->parent = class;
1930 class->ext->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1931 class->ext->property.count = last - class->ext->property.first;
1933 if (class->ext->property.count)
1934 mono_class_setup_methods (class);
1936 properties = mono_image_alloc0 (class->image, sizeof (MonoProperty) * class->ext->property.count);
1937 for (i = class->ext->property.first; i < last; ++i) {
1938 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
1939 properties [i - class->ext->property.first].parent = class;
1940 properties [i - class->ext->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
1941 properties [i - class->ext->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
1943 startm = mono_metadata_methods_from_property (class->image, i, &endm);
1944 for (j = startm; j < endm; ++j) {
1947 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1949 if (class->image->uncompressed_metadata)
1950 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1951 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1953 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1955 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1956 case METHOD_SEMANTIC_SETTER:
1957 properties [i - class->ext->property.first].set = method;
1959 case METHOD_SEMANTIC_GETTER:
1960 properties [i - class->ext->property.first].get = method;
1968 /*Flush any pending writes as we do double checked locking on class->properties */
1969 mono_memory_barrier ();
1971 /* Leave this assignment as the last op in the function */
1972 class->ext->properties = properties;
1974 mono_loader_unlock ();
1978 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
1980 MonoMethod **om, **retval;
1983 for (om = methods, count = 0; *om; ++om, ++count)
1986 retval = g_new0 (MonoMethod*, count + 1);
1988 for (om = methods, count = 0; *om; ++om, ++count)
1989 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
1995 mono_class_setup_events (MonoClass *class)
1997 guint startm, endm, i, j;
1998 guint32 cols [MONO_EVENT_SIZE];
1999 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2003 if (class->ext && class->ext->events)
2006 mono_loader_lock ();
2008 if (class->ext && class->ext->events) {
2009 mono_loader_unlock ();
2013 mono_class_alloc_ext (class);
2015 if (class->generic_class) {
2016 MonoClass *gklass = class->generic_class->container_class;
2017 MonoGenericContext *context;
2019 mono_class_setup_events (gklass);
2020 class->ext->event = gklass->ext->event;
2022 class->ext->events = g_new0 (MonoEvent, class->ext->event.count);
2024 if (class->ext->event.count)
2025 context = mono_class_get_context (class);
2027 for (i = 0; i < class->ext->event.count; i++) {
2028 MonoEvent *event = &class->ext->events [i];
2029 MonoEvent *gevent = &gklass->ext->events [i];
2031 event->parent = class;
2032 event->name = gevent->name;
2033 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
2034 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
2035 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
2036 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
2037 event->attrs = gevent->attrs;
2040 mono_loader_unlock ();
2044 class->ext->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2045 class->ext->event.count = last - class->ext->event.first;
2047 if (class->ext->event.count)
2048 mono_class_setup_methods (class);
2050 events = mono_image_alloc0 (class->image, sizeof (MonoEvent) * class->ext->event.count);
2051 for (i = class->ext->event.first; i < last; ++i) {
2052 MonoEvent *event = &events [i - class->ext->event.first];
2054 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
2055 event->parent = class;
2056 event->attrs = cols [MONO_EVENT_FLAGS];
2057 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
2059 startm = mono_metadata_methods_from_event (class->image, i, &endm);
2060 for (j = startm; j < endm; ++j) {
2063 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2065 if (class->image->uncompressed_metadata)
2066 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2067 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2069 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2071 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2072 case METHOD_SEMANTIC_ADD_ON:
2073 event->add = method;
2075 case METHOD_SEMANTIC_REMOVE_ON:
2076 event->remove = method;
2078 case METHOD_SEMANTIC_FIRE:
2079 event->raise = method;
2081 case METHOD_SEMANTIC_OTHER: {
2084 if (event->other == NULL) {
2085 event->other = g_new0 (MonoMethod*, 2);
2087 while (event->other [n])
2089 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
2091 event->other [n] = method;
2092 /* NULL terminated */
2093 event->other [n + 1] = NULL;
2101 /*Flush any pending writes as we do double checked locking on class->properties */
2102 mono_memory_barrier ();
2104 /* Leave this assignment as the last op in the function */
2105 class->ext->events = events;
2107 mono_loader_unlock ();
2111 * Global pool of interface IDs, represented as a bitset.
2112 * LOCKING: this is supposed to be accessed with the loader lock held.
2114 static MonoBitSet *global_interface_bitset = NULL;
2117 * mono_unload_interface_ids:
2118 * @bitset: bit set of interface IDs
2120 * When an image is unloaded, the interface IDs associated with
2121 * the image are put back in the global pool of IDs so the numbers
2125 mono_unload_interface_ids (MonoBitSet *bitset)
2127 mono_loader_lock ();
2128 mono_bitset_sub (global_interface_bitset, bitset);
2129 mono_loader_unlock ();
2133 * mono_get_unique_iid:
2136 * Assign a unique integer ID to the interface represented by @class.
2137 * The ID will positive and as small as possible.
2138 * LOCKING: this is supposed to be called with the loader lock held.
2139 * Returns: the new ID.
2142 mono_get_unique_iid (MonoClass *class)
2146 g_assert (MONO_CLASS_IS_INTERFACE (class));
2148 if (!global_interface_bitset) {
2149 global_interface_bitset = mono_bitset_new (128, 0);
2152 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2154 int old_size = mono_bitset_size (global_interface_bitset);
2155 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2156 mono_bitset_free (global_interface_bitset);
2157 global_interface_bitset = new_set;
2160 mono_bitset_set (global_interface_bitset, iid);
2161 /* set the bit also in the per-image set */
2162 if (class->image->interface_bitset) {
2163 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2164 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2165 mono_bitset_free (class->image->interface_bitset);
2166 class->image->interface_bitset = new_set;
2169 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2171 mono_bitset_set (class->image->interface_bitset, iid);
2173 if (mono_print_vtable) {
2175 char *type_name = mono_type_full_name (&class->byval_arg);
2176 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2177 generic_id = class->generic_class->context.class_inst->id;
2178 g_assert (generic_id != 0);
2182 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2186 g_assert (iid <= 65535);
2191 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
2196 mono_class_setup_interfaces (klass);
2198 for (i = 0; i < klass->interface_count; i++) {
2199 ic = klass->interfaces [i];
2202 *res = g_ptr_array_new ();
2203 g_ptr_array_add (*res, ic);
2204 mono_class_init (ic);
2206 collect_implemented_interfaces_aux (ic, res);
2211 mono_class_get_implemented_interfaces (MonoClass *klass)
2213 GPtrArray *res = NULL;
2215 collect_implemented_interfaces_aux (klass, &res);
2220 compare_interface_ids (const void *p_key, const void *p_element) {
2221 const MonoClass *key = p_key;
2222 const MonoClass *element = *(MonoClass**) p_element;
2224 return (key->interface_id - element->interface_id);
2228 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2229 MonoClass **result = bsearch (
2231 klass->interfaces_packed,
2232 klass->interface_offsets_count,
2233 sizeof (MonoClass *),
2234 compare_interface_ids);
2236 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2243 print_implemented_interfaces (MonoClass *klass) {
2244 GPtrArray *ifaces = NULL;
2246 int ancestor_level = 0;
2248 printf ("Packed interface table for class %s has size %d\n", klass->name, klass->interface_offsets_count);
2249 for (i = 0; i < klass->interface_offsets_count; i++)
2250 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2251 klass->interfaces_packed [i]->interface_id,
2252 klass->interface_offsets_packed [i],
2253 klass->interfaces_packed [i]->method.count,
2254 klass->interfaces_packed [i]->name_space,
2255 klass->interfaces_packed [i]->name );
2256 printf ("Interface flags: ");
2257 for (i = 0; i <= klass->max_interface_id; i++)
2258 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2259 printf ("(%d,T)", i);
2261 printf ("(%d,F)", i);
2263 printf ("Dump interface flags:");
2264 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2265 printf (" %02X", klass->interface_bitmap [i]);
2267 while (klass != NULL) {
2268 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2269 ifaces = mono_class_get_implemented_interfaces (klass);
2271 for (i = 0; i < ifaces->len; i++) {
2272 MonoClass *ic = g_ptr_array_index (ifaces, i);
2273 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2274 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2276 mono_class_interface_offset (klass, ic),
2281 g_ptr_array_free (ifaces, TRUE);
2284 klass = klass->parent;
2289 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2292 args [0] = &arg0->byval_arg;
2294 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2298 array_class_get_if_rank (MonoClass *class, guint rank)
2300 return rank ? mono_array_class_get (class, rank) : class;
2304 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2306 valuetype_types [0] = eclass;
2307 if (eclass == mono_defaults.int16_class)
2308 valuetype_types [1] = mono_defaults.uint16_class;
2309 else if (eclass == mono_defaults.uint16_class)
2310 valuetype_types [1] = mono_defaults.int16_class;
2311 else if (eclass == mono_defaults.int32_class)
2312 valuetype_types [1] = mono_defaults.uint32_class;
2313 else if (eclass == mono_defaults.uint32_class)
2314 valuetype_types [1] = mono_defaults.int32_class;
2315 else if (eclass == mono_defaults.int64_class)
2316 valuetype_types [1] = mono_defaults.uint64_class;
2317 else if (eclass == mono_defaults.uint64_class)
2318 valuetype_types [1] = mono_defaults.int64_class;
2319 else if (eclass == mono_defaults.byte_class)
2320 valuetype_types [1] = mono_defaults.sbyte_class;
2321 else if (eclass == mono_defaults.sbyte_class)
2322 valuetype_types [1] = mono_defaults.byte_class;
2323 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2324 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2327 /* this won't be needed once bug #325495 is completely fixed
2328 * though we'll need something similar to know which interfaces to allow
2329 * in arrays when they'll be lazyly created
2331 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2332 * MS returns diferrent types based on which instance is called. For example:
2333 * object obj = new byte[10][];
2334 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2335 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2338 * Fixing this should kill quite some code, save some bits and improve compatibility.
2341 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2343 MonoClass *eclass = class->element_class;
2344 static MonoClass* generic_icollection_class = NULL;
2345 static MonoClass* generic_ienumerable_class = NULL;
2346 static MonoClass* generic_ienumerator_class = NULL;
2347 MonoClass *valuetype_types[2] = { NULL, NULL };
2348 MonoClass **interfaces = NULL;
2349 int i, interface_count, real_count, original_rank;
2351 gboolean internal_enumerator;
2352 gboolean eclass_is_valuetype;
2354 if (!mono_defaults.generic_ilist_class) {
2358 internal_enumerator = FALSE;
2359 eclass_is_valuetype = FALSE;
2360 original_rank = eclass->rank;
2361 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2362 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2364 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2366 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2367 original_rank = eclass->rank;
2368 eclass = eclass->element_class;
2369 internal_enumerator = TRUE;
2370 *is_enumerator = TRUE;
2378 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2379 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2381 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2383 if (!generic_icollection_class) {
2384 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2385 "System.Collections.Generic", "ICollection`1");
2386 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2387 "System.Collections.Generic", "IEnumerable`1");
2388 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2389 "System.Collections.Generic", "IEnumerator`1");
2392 mono_class_init (eclass);
2395 * Arrays in 2.0 need to implement a number of generic interfaces
2396 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2397 * on the element class). We collect the types needed to build the
2398 * instantiations in interfaces at intervals of 3, because 3 are
2399 * the generic interfaces needed to implement.
2401 if (eclass->valuetype) {
2402 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2404 /* IList, ICollection, IEnumerable */
2405 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2406 if (internal_enumerator) {
2408 if (valuetype_types [1])
2412 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2413 interfaces [0] = valuetype_types [0];
2414 if (valuetype_types [1])
2415 interfaces [3] = valuetype_types [1];
2417 eclass_is_valuetype = TRUE;
2420 int idepth = eclass->idepth;
2421 if (!internal_enumerator)
2423 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2424 /* we add object for interfaces and the supertypes for the other
2425 * types. The last of the supertypes is the element class itself which we
2426 * already created the explicit interfaces for (so we include it for IEnumerator
2427 * and exclude it for arrays).
2429 if (MONO_CLASS_IS_INTERFACE (eclass))
2432 interface_count += idepth;
2433 if (eclass->rank && eclass->element_class->valuetype) {
2434 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2435 if (valuetype_types [1])
2438 /* IList, ICollection, IEnumerable */
2439 interface_count *= 3;
2440 real_count = interface_count;
2441 if (internal_enumerator) {
2442 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2443 if (valuetype_types [1])
2446 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2447 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2448 interfaces [0] = mono_defaults.object_class;
2452 for (i = 0; i < idepth; i++) {
2453 mono_class_init (eclass->supertypes [i]);
2454 interfaces [j] = eclass->supertypes [i];
2458 if (all_interfaces) {
2459 for (i = 0; i < eclass->interface_offsets_count; i++) {
2460 interfaces [j] = eclass->interfaces_packed [i];
2464 for (i = 0; i < eclass->interface_count; i++) {
2465 interfaces [j] = eclass->interfaces [i];
2469 if (valuetype_types [1]) {
2470 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2475 /* instantiate the generic interfaces */
2476 for (i = 0; i < interface_count; i += 3) {
2477 MonoClass *iface = interfaces [i];
2479 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2480 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2481 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2483 if (internal_enumerator) {
2485 /* instantiate IEnumerator<iface> */
2486 for (i = 0; i < interface_count; i++) {
2487 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2489 j = interface_count;
2490 if (!eclass_is_valuetype) {
2491 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2492 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2495 for (i = 0; i < eclass->idepth; i++) {
2496 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2500 for (i = 0; i < eclass->interface_offsets_count; i++) {
2501 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2505 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2507 if (valuetype_types [1])
2508 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2512 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2513 for (i = 0; i < real_count; ++i) {
2514 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2515 g_print ("%s implements %s\n", type_name, name);
2526 find_array_interface (MonoClass *klass, const char *name)
2529 for (i = 0; i < klass->interface_count; ++i) {
2530 if (strcmp (klass->interfaces [i]->name, name) == 0)
2537 * Return the number of virtual methods.
2538 * Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
2539 * FIXME It would be nice if this information could be cached somewhere.
2542 count_virtual_methods (MonoClass *class)
2546 class = mono_class_get_generic_type_definition (class); /*We can find this information by looking at the GTD*/
2548 if (class->methods || !MONO_CLASS_HAS_STATIC_METADATA (class)) {
2549 mono_class_setup_methods (class);
2551 for (i = 0; i < class->method.count; ++i) {
2552 flags = class->methods [i]->flags;
2553 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2557 for (i = 0; i < class->method.count; ++i) {
2558 flags = mono_metadata_decode_table_row_col (class->image, MONO_TABLE_METHOD, class->method.first + i, MONO_METHOD_FLAGS);
2560 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2568 * LOCKING: this is supposed to be called with the loader lock held.
2571 setup_interface_offsets (MonoClass *class, int cur_slot)
2575 MonoClass **interfaces_full;
2576 int *interface_offsets_full;
2578 int interface_offsets_count;
2579 MonoClass **array_interfaces;
2580 int num_array_interfaces;
2581 int is_enumerator = FALSE;
2584 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
2585 * implicit interfaces have the property that they are assigned the same slot in the
2586 * vtables for compatible interfaces
2588 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
2590 /* compute maximum number of slots and maximum interface id */
2592 for (k = class; k ; k = k->parent) {
2593 for (i = 0; i < k->interface_count; i++) {
2594 ic = k->interfaces [i];
2597 mono_class_init (ic);
2599 if (max_iid < ic->interface_id)
2600 max_iid = ic->interface_id;
2602 ifaces = mono_class_get_implemented_interfaces (k);
2604 for (i = 0; i < ifaces->len; ++i) {
2605 ic = g_ptr_array_index (ifaces, i);
2606 if (max_iid < ic->interface_id)
2607 max_iid = ic->interface_id;
2609 g_ptr_array_free (ifaces, TRUE);
2612 for (i = 0; i < num_array_interfaces; ++i) {
2613 ic = array_interfaces [i];
2614 mono_class_init (ic);
2615 if (max_iid < ic->interface_id)
2616 max_iid = ic->interface_id;
2619 if (MONO_CLASS_IS_INTERFACE (class)) {
2620 if (max_iid < class->interface_id)
2621 max_iid = class->interface_id;
2623 class->max_interface_id = max_iid;
2624 /* compute vtable offset for interfaces */
2625 interfaces_full = g_malloc (sizeof (MonoClass*) * (max_iid + 1));
2626 interface_offsets_full = g_malloc (sizeof (int) * (max_iid + 1));
2628 for (i = 0; i <= max_iid; i++) {
2629 interfaces_full [i] = NULL;
2630 interface_offsets_full [i] = -1;
2633 for (k = class->parent; k ; k = k->parent) {
2634 ifaces = mono_class_get_implemented_interfaces (k);
2636 for (i = 0; i < ifaces->len; ++i) {
2638 ic = g_ptr_array_index (ifaces, i);
2640 /*Force the sharing of interface offsets between parent and subtypes.*/
2641 io = mono_class_interface_offset (k, ic);
2643 interfaces_full [ic->interface_id] = ic;
2644 interface_offsets_full [ic->interface_id] = io;
2646 g_ptr_array_free (ifaces, TRUE);
2651 ifaces = mono_class_get_implemented_interfaces (class);
2653 for (i = 0; i < ifaces->len; ++i) {
2654 ic = g_ptr_array_index (ifaces, i);
2655 if (interfaces_full [ic->interface_id] != NULL)
2657 interfaces_full [ic->interface_id] = ic;
2658 interface_offsets_full [ic->interface_id] = cur_slot;
2659 cur_slot += count_virtual_methods (ic);
2661 g_ptr_array_free (ifaces, TRUE);
2664 if (MONO_CLASS_IS_INTERFACE (class)) {
2665 interfaces_full [class->interface_id] = class;
2666 interface_offsets_full [class->interface_id] = cur_slot;
2669 if (num_array_interfaces) {
2670 if (is_enumerator) {
2671 int ienumerator_offset;
2672 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
2673 ienumerator_offset = interface_offsets_full [class->interfaces [ienumerator_idx]->interface_id];
2674 for (i = 0; i < num_array_interfaces; ++i) {
2675 ic = array_interfaces [i];
2676 interfaces_full [ic->interface_id] = ic;
2677 if (strcmp (ic->name, "IEnumerator`1") == 0)
2678 interface_offsets_full [ic->interface_id] = ienumerator_offset;
2680 g_assert_not_reached ();
2681 /*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);*/
2684 int ilist_offset, icollection_offset, ienumerable_offset;
2685 int ilist_iface_idx = find_array_interface (class, "IList`1");
2686 int icollection_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "ICollection`1");
2687 int ienumerable_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "IEnumerable`1");
2688 ilist_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interface_id];
2689 icollection_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [icollection_iface_idx]->interface_id];
2690 ienumerable_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [ienumerable_iface_idx]->interface_id];
2691 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
2692 for (i = 0; i < num_array_interfaces; ++i) {
2693 ic = array_interfaces [i];
2694 interfaces_full [ic->interface_id] = ic;
2695 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
2696 interface_offsets_full [ic->interface_id] = ilist_offset;
2697 else if (strcmp (ic->name, "ICollection`1") == 0)
2698 interface_offsets_full [ic->interface_id] = icollection_offset;
2699 else if (strcmp (ic->name, "IEnumerable`1") == 0)
2700 interface_offsets_full [ic->interface_id] = ienumerable_offset;
2702 g_assert_not_reached ();
2703 /*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);*/
2708 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2709 if (interface_offsets_full [i] != -1) {
2710 interface_offsets_count ++;
2715 * We might get called twice: once from mono_class_init () then once from
2716 * mono_class_setup_vtable ().
2718 if (class->interfaces_packed) {
2719 g_assert (class->interface_offsets_count == interface_offsets_count);
2721 class->interface_offsets_count = interface_offsets_count;
2722 class->interfaces_packed = mono_image_alloc (class->image, sizeof (MonoClass*) * interface_offsets_count);
2723 class->interface_offsets_packed = mono_image_alloc (class->image, sizeof (guint16) * interface_offsets_count);
2724 class->interface_bitmap = mono_image_alloc0 (class->image, (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0));
2725 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2726 if (interface_offsets_full [i] != -1) {
2727 class->interface_bitmap [i >> 3] |= (1 << (i & 7));
2728 class->interfaces_packed [interface_offsets_count] = interfaces_full [i];
2729 class->interface_offsets_packed [interface_offsets_count] = interface_offsets_full [i];
2730 /*if (num_array_interfaces)
2731 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]);*/
2732 interface_offsets_count ++;
2737 g_free (interfaces_full);
2738 g_free (interface_offsets_full);
2739 g_free (array_interfaces);
2741 //printf ("JUST DONE: ");
2742 //print_implemented_interfaces (class);
2748 * Setup interface offsets for interfaces.
2750 * - class->max_interface_id
2751 * - class->interface_offsets_count
2752 * - class->interfaces_packed
2753 * - class->interface_offsets_packed
2754 * - class->interface_bitmap
2757 mono_class_setup_interface_offsets (MonoClass *class)
2759 mono_loader_lock ();
2761 setup_interface_offsets (class, 0);
2763 mono_loader_unlock ();
2767 * mono_class_setup_vtable:
2769 * Creates the generic vtable of CLASS.
2770 * Initializes the following fields in MonoClass:
2773 * Plus all the fields initialized by setup_interface_offsets ().
2774 * If there is an error during vtable construction, class->exception_type is set.
2776 * LOCKING: Acquires the loader lock.
2779 mono_class_setup_vtable (MonoClass *class)
2781 MonoMethod **overrides;
2782 MonoGenericContext *context;
2791 if (mono_debug_using_mono_debugger ())
2792 /* The debugger currently depends on this */
2793 mono_class_setup_methods (class);
2795 if (MONO_CLASS_IS_INTERFACE (class)) {
2796 /* This sets method->slot for all methods if this is an interface */
2797 mono_class_setup_methods (class);
2801 mono_loader_lock ();
2803 if (class->vtable) {
2804 mono_loader_unlock ();
2808 mono_stats.generic_vtable_count ++;
2810 if (class->generic_class) {
2811 context = mono_class_get_context (class);
2812 type_token = class->generic_class->container_class->type_token;
2814 context = (MonoGenericContext *) class->generic_container;
2815 type_token = class->type_token;
2818 if (class->image->dynamic) {
2819 if (class->generic_class) {
2820 MonoClass *gklass = class->generic_class->container_class;
2822 mono_reflection_get_dynamic_overrides (gklass, &overrides, &onum);
2823 for (i = 0; i < onum; ++i) {
2824 MonoMethod *override = overrides [(i * 2) + 1];
2825 MonoMethod *inflated = NULL;
2828 for (j = 0; j < class->method.count; ++j) {
2829 if (gklass->methods [j] == override) {
2830 inflated = class->methods [j];
2834 g_assert (inflated);
2836 overrides [(i * 2) + 1] = inflated;
2839 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
2842 /* The following call fails if there are missing methods in the type */
2843 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
2847 mono_class_setup_vtable_general (class, overrides, onum);
2851 mono_loader_unlock ();
2856 #define DEBUG_INTERFACE_VTABLE_CODE 0
2857 #define TRACE_INTERFACE_VTABLE_CODE 0
2858 #define VERIFY_INTERFACE_VTABLE_CODE 0
2859 #define VTABLE_SELECTOR (1)
2861 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2862 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
2863 if (!(VTABLE_SELECTOR)) break; \
2867 #define DEBUG_INTERFACE_VTABLE(stmt)
2870 #if TRACE_INTERFACE_VTABLE_CODE
2871 #define TRACE_INTERFACE_VTABLE(stmt) do {\
2872 if (!(VTABLE_SELECTOR)) break; \
2876 #define TRACE_INTERFACE_VTABLE(stmt)
2879 #if VERIFY_INTERFACE_VTABLE_CODE
2880 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
2881 if (!(VTABLE_SELECTOR)) break; \
2885 #define VERIFY_INTERFACE_VTABLE(stmt)
2889 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2891 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
2895 GString *res = g_string_new ("");
2897 g_string_append_c (res, '(');
2898 for (i = 0; i < sig->param_count; ++i) {
2900 g_string_append_c (res, ',');
2901 mono_type_get_desc (res, sig->params [i], include_namespace);
2903 g_string_append (res, ")=>");
2904 if (sig->ret != NULL) {
2905 mono_type_get_desc (res, sig->ret, include_namespace);
2907 g_string_append (res, "NULL");
2910 g_string_free (res, FALSE);
2914 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
2915 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
2916 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
2917 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
2925 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) {
2926 if (strcmp (im->name, cm->name) == 0) {
2927 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
2928 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
2931 if (! slot_is_empty) {
2932 if (require_newslot) {
2933 if (! interface_is_explicitly_implemented_by_class) {
2934 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
2937 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
2938 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
2942 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
2945 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2946 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
2947 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2948 TRACE_INTERFACE_VTABLE (printf ("]"));
2951 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
2952 /* CAS - SecurityAction.InheritanceDemand on interface */
2953 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2954 mono_secman_inheritancedemand_method (cm, im);
2957 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
2958 mono_security_core_clr_check_override (class, cm, im);
2959 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
2962 MonoClass *ic = im->klass;
2963 const char *ic_name_space = ic->name_space;
2964 const char *ic_name = ic->name;
2967 if (! require_newslot) {
2968 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
2971 if (cm->klass->rank == 0) {
2972 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
2975 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2976 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
2977 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2978 TRACE_INTERFACE_VTABLE (printf ("]"));
2981 if (mono_class_get_image (ic) != mono_defaults.corlib) {
2982 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
2985 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
2986 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
2989 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
2990 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
2994 subname = strstr (cm->name, ic_name_space);
2995 if (subname != cm->name) {
2996 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
2999 subname += strlen (ic_name_space);
3000 if (subname [0] != '.') {
3001 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
3005 if (strstr (subname, ic_name) != subname) {
3006 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
3009 subname += strlen (ic_name);
3010 if (subname [0] != '.') {
3011 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
3015 if (strcmp (subname, im->name) != 0) {
3016 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
3020 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
3021 /* CAS - SecurityAction.InheritanceDemand on interface */
3022 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3023 mono_secman_inheritancedemand_method (cm, im);
3026 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3027 mono_security_core_clr_check_override (class, cm, im);
3029 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
3034 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3036 foreach_override (gpointer key, gpointer value, gpointer user_data) {
3037 MonoMethod *method = key;
3038 MonoMethod *override = value;
3039 MonoClass *method_class = mono_method_get_class (method);
3040 MonoClass *override_class = mono_method_get_class (override);
3042 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
3043 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
3044 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
3047 print_overrides (GHashTable *override_map, const char *message) {
3049 printf ("Override map \"%s\" START:\n", message);
3050 g_hash_table_foreach (override_map, foreach_override, NULL);
3051 printf ("Override map \"%s\" END.\n", message);
3053 printf ("Override map \"%s\" EMPTY.\n", message);
3057 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
3058 char *full_name = mono_type_full_name (&class->byval_arg);
3062 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
3064 if (print_interfaces) {
3065 print_implemented_interfaces (class);
3066 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
3069 if (class->parent) {
3070 parent_size = class->parent->vtable_size;
3074 for (i = 0; i < size; ++i) {
3075 MonoMethod *cm = vtable [i];
3077 char *cm_name = mono_method_full_name (cm, TRUE);
3078 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
3079 printf (" [%c][%03d][INDEX %03d] %s\n", newness, i, cm->slot, cm_name);
3088 #if VERIFY_INTERFACE_VTABLE_CODE
3090 mono_method_try_get_vtable_index (MonoMethod *method)
3092 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3093 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3094 if (imethod->declaring->is_generic)
3095 return imethod->declaring->slot;
3097 return method->slot;
3101 mono_class_verify_vtable (MonoClass *class)
3104 char *full_name = mono_type_full_name (&class->byval_arg);
3106 printf ("*** Verifying VTable of class '%s' \n", full_name);
3110 if (!class->methods)
3113 for (i = 0; i < class->method.count; ++i) {
3114 MonoMethod *cm = class->methods [i];
3117 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
3121 full_name = mono_method_full_name (cm, TRUE);
3123 slot = mono_method_try_get_vtable_index (cm);
3125 if (slot >= class->vtable_size) {
3126 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
3130 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
3131 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3132 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3133 g_free (other_name);
3136 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3143 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3145 char *method_signature;
3148 for (index = 0; index < onum; ++index) {
3149 g_print (" at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
3150 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3152 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3153 type_name = mono_type_full_name (&class->byval_arg);
3154 printf ("no implementation for interface method %s::%s(%s) in class %s\n",
3155 mono_type_get_name (&ic->byval_arg), im->name, method_signature, type_name);
3156 g_free (method_signature);
3158 mono_class_setup_methods (class);
3159 for (index = 0; index < class->method.count; ++index) {
3160 MonoMethod *cm = class->methods [index];
3161 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3163 printf ("METHOD %s(%s)\n", cm->name, method_signature);
3164 g_free (method_signature);
3169 verify_class_overrides (MonoClass *class, MonoMethod **overrides, int onum)
3173 for (i = 0; i < onum; ++i) {
3174 MonoMethod *decl = overrides [i * 2];
3175 MonoMethod *body = overrides [i * 2 + 1];
3177 if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (class)) {
3178 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method belongs to a different class than the declared one"));
3182 if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
3183 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3184 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must not be static to override a base type"));
3186 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must be virtual to override a base type"));
3190 if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
3191 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3192 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a static method in a base type"));
3194 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a non virtual method in a base type"));
3198 if (!mono_class_is_assignable_from_slow (decl->klass, class)) {
3199 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method overrides a class or interface that extended or implemented by this type"));
3206 * LOCKING: this is supposed to be called with the loader lock held.
3209 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
3212 MonoMethod **vtable;
3213 int i, max_vtsize = 0, max_iid, cur_slot = 0;
3214 GPtrArray *ifaces = NULL;
3215 GHashTable *override_map = NULL;
3216 gboolean security_enabled = mono_is_security_manager_active ();
3218 gpointer class_iter;
3219 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3220 int first_non_interface_slot;
3226 if (overrides && !verify_class_overrides (class, overrides, onum))
3229 ifaces = mono_class_get_implemented_interfaces (class);
3232 for (i = 0; i < ifaces->len; i++) {
3233 MonoClass *ic = g_ptr_array_index (ifaces, i);
3234 max_vtsize += ic->method.count;
3236 g_ptr_array_free (ifaces, TRUE);
3240 if (class->parent) {
3241 mono_class_init (class->parent);
3242 mono_class_setup_vtable (class->parent);
3243 max_vtsize += class->parent->vtable_size;
3244 cur_slot = class->parent->vtable_size;
3247 max_vtsize += class->method.count;
3249 vtable = alloca (sizeof (gpointer) * max_vtsize);
3250 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3252 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3254 cur_slot = setup_interface_offsets (class, cur_slot);
3255 max_iid = class->max_interface_id;
3256 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3258 /* Optimized version for generic instances */
3259 if (class->generic_class) {
3260 MonoClass *gklass = class->generic_class->container_class;
3263 mono_class_setup_vtable (gklass);
3264 if (gklass->exception_type != MONO_EXCEPTION_NONE) {
3265 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3269 tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * gklass->vtable_size);
3270 class->vtable_size = gklass->vtable_size;
3271 for (i = 0; i < gklass->vtable_size; ++i)
3272 if (gklass->vtable [i]) {
3273 tmp [i] = mono_class_inflate_generic_method_full (gklass->vtable [i], class, mono_class_get_context (class));
3274 tmp [i]->slot = gklass->vtable [i]->slot;
3276 mono_memory_barrier ();
3277 class->vtable = tmp;
3279 /* Have to set method->slot for abstract virtual methods */
3280 if (class->methods && gklass->methods) {
3281 for (i = 0; i < class->method.count; ++i)
3282 if (class->methods [i]->slot == -1)
3283 class->methods [i]->slot = gklass->methods [i]->slot;
3289 if (class->parent && class->parent->vtable_size) {
3290 MonoClass *parent = class->parent;
3293 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
3295 // Also inherit parent interface vtables, just as a starting point.
3296 // This is needed otherwise bug-77127.exe fails when the property methods
3297 // have different names in the iterface and the class, because for child
3298 // classes the ".override" information is not used anymore.
3299 for (i = 0; i < parent->interface_offsets_count; i++) {
3300 MonoClass *parent_interface = parent->interfaces_packed [i];
3301 int interface_offset = mono_class_interface_offset (class, parent_interface);
3302 /*FIXME this is now dead code as this condition will never hold true.
3303 Since interface offsets are inherited then the offset of an interface implemented
3304 by a parent will never be the out of it's vtable boundary.
3306 if (interface_offset >= parent->vtable_size) {
3307 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
3310 mono_class_setup_methods (parent_interface);
3311 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
3312 for (j = 0; j < parent_interface->method.count; j++) {
3313 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
3314 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
3315 parent_interface_offset + j, parent_interface_offset, j,
3316 interface_offset + j, interface_offset, j));
3323 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
3324 /* override interface methods */
3325 for (i = 0; i < onum; i++) {
3326 MonoMethod *decl = overrides [i*2];
3327 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
3329 dslot = mono_method_get_vtable_slot (decl) + mono_class_interface_offset (class, decl->klass);
3330 vtable [dslot] = overrides [i*2 + 1];
3331 vtable [dslot]->slot = dslot;
3333 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3335 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
3337 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3338 mono_security_core_clr_check_override (class, vtable [dslot], decl);
3341 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
3342 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
3344 // Loop on all implemented interfaces...
3345 for (i = 0; i < class->interface_offsets_count; i++) {
3346 MonoClass *parent = class->parent;
3348 gboolean interface_is_explicitly_implemented_by_class;
3351 ic = class->interfaces_packed [i];
3352 ic_offset = mono_class_interface_offset (class, ic);
3354 mono_class_setup_methods (ic);
3356 // Check if this interface is explicitly implemented (instead of just inherited)
3357 if (parent != NULL) {
3358 int implemented_interfaces_index;
3359 interface_is_explicitly_implemented_by_class = FALSE;
3360 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
3361 if (ic == class->interfaces [implemented_interfaces_index]) {
3362 interface_is_explicitly_implemented_by_class = TRUE;
3367 interface_is_explicitly_implemented_by_class = TRUE;
3370 // Loop on all interface methods...
3371 for (im_index = 0; im_index < ic->method.count; im_index++) {
3372 MonoMethod *im = ic->methods [im_index];
3373 int im_slot = ic_offset + im->slot;
3374 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
3376 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3379 // If there is an explicit implementation, just use it right away,
3380 // otherwise look for a matching method
3381 if (override_im == NULL) {
3386 // First look for a suitable method among the class methods
3388 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
3389 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)));
3390 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
3391 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
3392 vtable [im_slot] = cm;
3393 /* Why do we need this? */
3398 TRACE_INTERFACE_VTABLE (printf ("\n"));
3401 // If the slot is still empty, look in all the inherited virtual methods...
3402 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
3403 MonoClass *parent = class->parent;
3404 // Reverse order, so that last added methods are preferred
3405 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
3406 MonoMethod *cm = parent->vtable [cm_index];
3408 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));
3409 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
3410 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
3411 vtable [im_slot] = cm;
3412 /* Why do we need this? */
3418 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
3422 g_assert (vtable [im_slot] == override_im);
3427 // If the class is not abstract, check that all its interface slots are full.
3428 // The check is done here and not directly at the end of the loop above because
3429 // it can happen (for injected generic array interfaces) that the same slot is
3430 // processed multiple times (those interfaces have overlapping slots), and it
3431 // will not always be the first pass the one that fills the slot.
3432 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3433 for (i = 0; i < class->interface_offsets_count; i++) {
3437 ic = class->interfaces_packed [i];
3438 ic_offset = mono_class_interface_offset (class, ic);
3440 for (im_index = 0; im_index < ic->method.count; im_index++) {
3441 MonoMethod *im = ic->methods [im_index];
3442 int im_slot = ic_offset + im->slot;
3444 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3447 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
3448 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
3449 if (vtable [im_slot] == NULL) {
3450 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
3451 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3453 g_hash_table_destroy (override_map);
3460 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
3462 while ((cm = mono_class_get_virtual_methods (class, &class_iter))) {
3464 * If the method is REUSE_SLOT, we must check in the
3465 * base class for a method to override.
3467 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3469 for (k = class->parent; k ; k = k->parent) {
3474 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
3475 MonoMethodSignature *cmsig, *m1sig;
3477 cmsig = mono_method_signature (cm);
3478 m1sig = mono_method_signature (m1);
3480 if (!cmsig || !m1sig) {
3481 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3485 if (!strcmp(cm->name, m1->name) &&
3486 mono_metadata_signature_equal (cmsig, m1sig)) {
3488 /* CAS - SecurityAction.InheritanceDemand */
3489 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3490 mono_secman_inheritancedemand_method (cm, m1);
3493 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3494 mono_security_core_clr_check_override (class, cm, m1);
3496 slot = mono_method_get_vtable_slot (m1);
3497 g_assert (cm->slot < max_vtsize);
3499 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3500 g_hash_table_insert (override_map, m1, cm);
3511 /*Non final newslot methods must be given a non-interface vtable slot*/
3512 if ((cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && !(cm->flags & METHOD_ATTRIBUTE_FINAL) && cm->slot >= 0)
3516 cm->slot = cur_slot++;
3518 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
3519 vtable [cm->slot] = cm;
3522 /* override non interface methods */
3523 for (i = 0; i < onum; i++) {
3524 MonoMethod *decl = overrides [i*2];
3525 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
3526 g_assert (decl->slot != -1);
3527 vtable [decl->slot] = overrides [i*2 + 1];
3528 overrides [i * 2 + 1]->slot = decl->slot;
3530 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3531 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
3533 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3534 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
3539 * If a method occupies more than one place in the vtable, and it is
3540 * overriden, then change the other occurances too.
3543 for (i = 0; i < max_vtsize; ++i)
3545 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
3550 g_hash_table_destroy (override_map);
3553 /* Ensure that all vtable slots are filled with concrete instance methods */
3554 if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3555 for (i = 0; i < cur_slot; ++i) {
3556 if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
3557 char *type_name = mono_type_get_full_name (class);
3558 char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
3559 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));
3561 g_free (method_name);
3567 if (class->generic_class) {
3568 MonoClass *gklass = class->generic_class->container_class;
3570 mono_class_init (gklass);
3572 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
3574 /* Check that the vtable_size value computed in mono_class_init () is correct */
3575 if (class->vtable_size)
3576 g_assert (cur_slot == class->vtable_size);
3577 class->vtable_size = cur_slot;
3580 /* Try to share the vtable with our parent. */
3581 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
3582 mono_memory_barrier ();
3583 class->vtable = class->parent->vtable;
3585 MonoMethod **tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * class->vtable_size);
3586 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
3587 mono_memory_barrier ();
3588 class->vtable = tmp;
3591 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
3592 if (mono_print_vtable) {
3595 print_implemented_interfaces (class);
3597 for (i = 0; i <= max_iid; i++)
3598 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
3601 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
3602 class->vtable_size, icount);
3604 for (i = 0; i < cur_slot; ++i) {
3609 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
3610 mono_method_full_name (cm, TRUE));
3616 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
3617 class->name, max_iid);
3619 for (i = 0; i < class->interface_count; i++) {
3620 ic = class->interfaces [i];
3621 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
3622 mono_class_interface_offset (class, ic),
3623 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
3626 for (k = class->parent; k ; k = k->parent) {
3627 for (i = 0; i < k->interface_count; i++) {
3628 ic = k->interfaces [i];
3629 printf (" parent slot offset: %03d, method count: %03d, iid: %03d %s\n",
3630 mono_class_interface_offset (class, ic),
3631 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
3637 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
3641 * mono_method_get_vtable_slot:
3643 * Returns method->slot, computing it if neccesary.
3644 * LOCKING: Acquires the loader lock.
3647 mono_method_get_vtable_slot (MonoMethod *method)
3649 if (method->slot == -1) {
3650 mono_class_setup_vtable (method->klass);
3651 g_assert (method->slot != -1);
3653 return method->slot;
3657 * mono_method_get_vtable_index:
3660 * Returns the index into the runtime vtable to access the method or,
3661 * in the case of a virtual generic method, the virtual generic method
3665 mono_method_get_vtable_index (MonoMethod *method)
3667 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3668 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3669 if (imethod->declaring->is_generic)
3670 return mono_method_get_vtable_slot (imethod->declaring);
3672 return mono_method_get_vtable_slot (method);
3675 static MonoMethod *default_ghc = NULL;
3676 static MonoMethod *default_finalize = NULL;
3677 static int finalize_slot = -1;
3678 static int ghc_slot = -1;
3681 initialize_object_slots (MonoClass *class)
3686 if (class == mono_defaults.object_class) {
3687 mono_class_setup_vtable (class);
3688 for (i = 0; i < class->vtable_size; ++i) {
3689 MonoMethod *cm = class->vtable [i];
3691 if (!strcmp (cm->name, "GetHashCode"))
3693 else if (!strcmp (cm->name, "Finalize"))
3697 g_assert (ghc_slot > 0);
3698 default_ghc = class->vtable [ghc_slot];
3700 g_assert (finalize_slot > 0);
3701 default_finalize = class->vtable [finalize_slot];
3706 MonoMethod *array_method;
3708 } GenericArrayMethodInfo;
3710 static int generic_array_method_num = 0;
3711 static GenericArrayMethodInfo *generic_array_method_info = NULL;
3714 generic_array_methods (MonoClass *class)
3716 int i, count_generic = 0;
3717 GList *list = NULL, *tmp;
3718 if (generic_array_method_num)
3719 return generic_array_method_num;
3720 mono_class_setup_methods (class->parent);
3721 for (i = 0; i < class->parent->method.count; i++) {
3722 MonoMethod *m = class->parent->methods [i];
3723 if (!strncmp (m->name, "InternalArray__", 15)) {
3725 list = g_list_prepend (list, m);
3728 list = g_list_reverse (list);
3729 generic_array_method_info = g_malloc (sizeof (GenericArrayMethodInfo) * count_generic);
3731 for (tmp = list; tmp; tmp = tmp->next) {
3732 const char *mname, *iname;
3734 MonoMethod *m = tmp->data;
3735 generic_array_method_info [i].array_method = m;
3736 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
3737 iname = "System.Collections.Generic.ICollection`1.";
3738 mname = m->name + 27;
3739 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
3740 iname = "System.Collections.Generic.IEnumerable`1.";
3741 mname = m->name + 27;
3742 } else if (!strncmp (m->name, "InternalArray__", 15)) {
3743 iname = "System.Collections.Generic.IList`1.";
3744 mname = m->name + 15;
3746 g_assert_not_reached ();
3749 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
3750 strcpy (name, iname);
3751 strcpy (name + strlen (iname), mname);
3752 generic_array_method_info [i].name = name;
3755 /*g_print ("array generic methods: %d\n", count_generic);*/
3757 generic_array_method_num = count_generic;
3759 return generic_array_method_num;
3763 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
3765 MonoGenericContext tmp_context;
3768 tmp_context.class_inst = NULL;
3769 tmp_context.method_inst = iface->generic_class->context.class_inst;
3770 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
3772 for (i = 0; i < generic_array_method_num; i++) {
3773 MonoMethod *m = generic_array_method_info [i].array_method;
3774 MonoMethod *inflated;
3776 inflated = mono_class_inflate_generic_method (m, &tmp_context);
3777 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
3782 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
3784 int len = strlen (s1) + strlen (s2) + 2;
3785 char *s = mono_image_alloc (image, len);
3788 result = g_snprintf (s, len, "%s%c%s", s1, '\0', s2);
3789 g_assert (result == len - 1);
3795 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
3797 gpointer exception_data = NULL;
3799 switch (error->exception_type) {
3800 case MONO_EXCEPTION_TYPE_LOAD:
3801 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
3804 case MONO_EXCEPTION_MISSING_METHOD:
3805 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
3808 case MONO_EXCEPTION_MISSING_FIELD: {
3809 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
3810 const char *class_name;
3813 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
3815 class_name = error->klass->name;
3817 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
3820 g_free ((void*)class_name);
3824 case MONO_EXCEPTION_FILE_NOT_FOUND: {
3827 if (error->ref_only)
3828 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.";
3830 msg = "Could not load file or assembly '%s' or one of its dependencies.";
3832 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
3836 case MONO_EXCEPTION_BAD_IMAGE:
3837 exception_data = error->msg;
3841 g_assert_not_reached ();
3844 mono_class_set_failure (class, error->exception_type, exception_data);
3849 * @class: the class to initialize
3851 * Compute the instance_size, class_size and other infos that cannot be
3852 * computed at mono_class_get() time. Also compute vtable_size if possible.
3853 * Returns TRUE on success or FALSE if there was a problem in loading
3854 * the type (incorrect assemblies, missing assemblies, methods, etc).
3856 * LOCKING: Acquires the loader lock.
3859 mono_class_init (MonoClass *class)
3862 MonoCachedClassInfo cached_info;
3863 gboolean has_cached_info;
3864 int class_init_ok = TRUE;
3868 /* Double-checking locking pattern */
3870 return class->exception_type == MONO_EXCEPTION_NONE;
3872 /*g_print ("Init class %s\n", class->name);*/
3874 /* We do everything inside the lock to prevent races */
3875 mono_loader_lock ();
3877 if (class->inited) {
3878 mono_loader_unlock ();
3879 /* Somebody might have gotten in before us */
3880 return class->exception_type == MONO_EXCEPTION_NONE;
3883 if (class->init_pending) {
3884 mono_loader_unlock ();
3885 /* this indicates a cyclic dependency */
3886 g_error ("pending init %s.%s\n", class->name_space, class->name);
3889 class->init_pending = 1;
3891 if (class->byval_arg.type == MONO_TYPE_ARRAY || class->byval_arg.type == MONO_TYPE_SZARRAY) {
3892 MonoClass *element_class = class->element_class;
3893 if (!element_class->inited)
3894 mono_class_init (element_class);
3895 if (element_class->exception_type != MONO_EXCEPTION_NONE) {
3896 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3901 /* CAS - SecurityAction.InheritanceDemand */
3902 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
3903 mono_secman_inheritancedemand_class (class, class->parent);
3906 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3907 mono_security_core_clr_check_inheritance (class);
3909 mono_stats.initialized_class_count++;
3911 if (class->generic_class && !class->generic_class->is_dynamic) {
3912 MonoClass *gklass = class->generic_class->container_class;
3914 mono_stats.generic_class_count++;
3916 class->method = gklass->method;
3917 class->field = gklass->field;
3919 mono_class_init (gklass);
3920 // FIXME: Why is this needed ?
3921 mono_class_setup_methods (gklass);
3923 if (MONO_CLASS_IS_INTERFACE (class))
3924 class->interface_id = mono_get_unique_iid (class);
3927 if (class->parent && !class->parent->inited)
3928 mono_class_init (class->parent);
3930 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
3932 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
3933 class->nested_classes_inited = TRUE;
3936 * Computes the size used by the fields, and their locations
3938 if (has_cached_info) {
3939 class->instance_size = cached_info.instance_size;
3940 class->sizes.class_size = cached_info.class_size;
3941 class->packing_size = cached_info.packing_size;
3942 class->min_align = cached_info.min_align;
3943 class->blittable = cached_info.blittable;
3944 class->has_references = cached_info.has_references;
3945 class->has_static_refs = cached_info.has_static_refs;
3946 class->no_special_static_fields = cached_info.no_special_static_fields;
3949 if (!class->size_inited){
3950 mono_class_setup_fields (class);
3951 if (class->exception_type || mono_loader_get_last_error ()){
3952 class_init_ok = FALSE;
3957 /* Initialize arrays */
3959 class->method.count = 3 + (class->rank > 1? 2: 1);
3961 if (class->interface_count) {
3962 int count_generic = generic_array_methods (class);
3963 class->method.count += class->interface_count * count_generic;
3967 mono_class_setup_supertypes (class);
3970 initialize_object_slots (class);
3973 * Initialize the rest of the data without creating a generic vtable if possible.
3974 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
3975 * also avoid computing a generic vtable.
3977 if (has_cached_info) {
3979 class->vtable_size = cached_info.vtable_size;
3980 class->has_finalize = cached_info.has_finalize;
3981 class->ghcimpl = cached_info.ghcimpl;
3982 class->has_cctor = cached_info.has_cctor;
3983 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
3984 static int szarray_vtable_size = 0;
3987 if (!szarray_vtable_size) {
3988 mono_class_setup_vtable (class);
3989 szarray_vtable_size = class->vtable_size;
3991 class->vtable_size = szarray_vtable_size;
3993 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
3994 MonoClass *gklass = class->generic_class->container_class;
3996 /* Generic instance case */
3997 class->ghcimpl = gklass->ghcimpl;
3998 class->has_finalize = gklass->has_finalize;
3999 class->has_cctor = gklass->has_cctor;
4001 mono_class_setup_vtable (gklass);
4002 if (gklass->exception_type) {
4003 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4007 class->vtable_size = gklass->vtable_size;
4011 /* ghcimpl is not currently used
4013 if (class->parent) {
4014 MonoMethod *cmethod = class->vtable [ghc_slot];
4015 if (cmethod->is_inflated)
4016 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4017 if (cmethod == default_ghc) {
4023 /* Interfaces and valuetypes are not supposed to have finalizers */
4024 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
4025 MonoMethod *cmethod = NULL;
4027 if (class->parent && class->parent->has_finalize) {
4028 class->has_finalize = 1;
4030 if (class->type_token) {
4031 cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
4032 } else if (class->parent) {
4033 /* FIXME: Optimize this */
4034 mono_class_setup_vtable (class);
4035 if (class->exception_type || mono_loader_get_last_error ())
4037 cmethod = class->vtable [finalize_slot];
4041 /* Check that this is really the finalizer method */
4042 mono_class_setup_vtable (class);
4043 if (class->exception_type || mono_loader_get_last_error ())
4046 class->has_finalize = 0;
4047 if (class->parent) {
4048 cmethod = class->vtable [finalize_slot];
4049 if (cmethod->is_inflated)
4050 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4051 if (cmethod != default_finalize) {
4052 class->has_finalize = 1;
4059 /* C# doesn't allow interfaces to have cctors */
4060 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
4061 MonoMethod *cmethod = NULL;
4063 if (class->type_token) {
4064 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
4065 /* The find_method function ignores the 'flags' argument */
4066 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
4067 class->has_cctor = 1;
4069 mono_class_setup_methods (class);
4071 for (i = 0; i < class->method.count; ++i) {
4072 MonoMethod *method = class->methods [i];
4073 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4074 (strcmp (".cctor", method->name) == 0)) {
4075 class->has_cctor = 1;
4083 if (!mono_setup_vtable_in_class_init) {
4085 * This is an embedding API break, since the caller might assume that
4086 * mono_class_init () constructs a generic vtable, so vtable construction errors
4087 * are visible right after the mono_class_init (), and not after
4088 * mono_class_vtable ().
4090 if (class->parent) {
4091 /* This will compute class->parent->vtable_size for some classes */
4092 mono_class_init (class->parent);
4093 if (class->parent->exception_type) {
4094 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4097 if (mono_loader_get_last_error ())
4099 if (!class->parent->vtable_size) {
4100 /* FIXME: Get rid of this somehow */
4101 mono_class_setup_vtable (class->parent);
4102 if (class->parent->exception_type) {
4103 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4106 if (mono_loader_get_last_error ())
4109 setup_interface_offsets (class, class->parent->vtable_size);
4111 setup_interface_offsets (class, 0);
4114 mono_class_setup_vtable (class);
4116 if (MONO_CLASS_IS_INTERFACE (class))
4117 setup_interface_offsets (class, 0);
4120 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
4121 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
4122 class_init_ok = FALSE;
4128 class_init_ok = FALSE;
4131 /* Because of the double-checking locking pattern */
4132 mono_memory_barrier ();
4134 class->init_pending = 0;
4136 if (mono_loader_get_last_error ()) {
4137 if (class->exception_type == MONO_EXCEPTION_NONE)
4138 set_failure_from_loader_error (class, mono_loader_get_last_error ());
4140 mono_loader_clear_error ();
4143 mono_loader_unlock ();
4145 if (mono_debugger_class_init_func)
4146 mono_debugger_class_init_func (class);
4148 return class_init_ok;
4152 is_corlib_image (MonoImage *image)
4154 /* FIXME: allow the dynamic case for our compilers and with full trust */
4156 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
4158 return image == mono_defaults.corlib;
4162 * LOCKING: this assumes the loader lock is held
4165 mono_class_setup_mono_type (MonoClass *class)
4167 const char *name = class->name;
4168 const char *nspace = class->name_space;
4169 gboolean is_corlib = is_corlib_image (class->image);
4171 class->this_arg.byref = 1;
4172 class->this_arg.data.klass = class;
4173 class->this_arg.type = MONO_TYPE_CLASS;
4174 class->byval_arg.data.klass = class;
4175 class->byval_arg.type = MONO_TYPE_CLASS;
4177 if (is_corlib && !strcmp (nspace, "System")) {
4178 if (!strcmp (name, "ValueType")) {
4180 * do not set the valuetype bit for System.ValueType.
4181 * class->valuetype = 1;
4183 class->blittable = TRUE;
4184 } else if (!strcmp (name, "Enum")) {
4186 * do not set the valuetype bit for System.Enum.
4187 * class->valuetype = 1;
4189 class->valuetype = 0;
4190 class->enumtype = 0;
4191 } else if (!strcmp (name, "Object")) {
4192 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
4193 } else if (!strcmp (name, "String")) {
4194 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
4195 } else if (!strcmp (name, "TypedReference")) {
4196 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
4200 if (class->valuetype) {
4201 int t = MONO_TYPE_VALUETYPE;
4203 if (is_corlib && !strcmp (nspace, "System")) {
4206 if (!strcmp (name, "Boolean")) {
4207 t = MONO_TYPE_BOOLEAN;
4208 } else if (!strcmp(name, "Byte")) {
4210 class->blittable = TRUE;
4214 if (!strcmp (name, "Char")) {
4219 if (!strcmp (name, "Double")) {
4221 class->blittable = TRUE;
4225 if (!strcmp (name, "Int32")) {
4227 class->blittable = TRUE;
4228 } else if (!strcmp(name, "Int16")) {
4230 class->blittable = TRUE;
4231 } else if (!strcmp(name, "Int64")) {
4233 class->blittable = TRUE;
4234 } else if (!strcmp(name, "IntPtr")) {
4236 class->blittable = TRUE;
4240 if (!strcmp (name, "Single")) {
4242 class->blittable = TRUE;
4243 } else if (!strcmp(name, "SByte")) {
4245 class->blittable = TRUE;
4249 if (!strcmp (name, "UInt32")) {
4251 class->blittable = TRUE;
4252 } else if (!strcmp(name, "UInt16")) {
4254 class->blittable = TRUE;
4255 } else if (!strcmp(name, "UInt64")) {
4257 class->blittable = TRUE;
4258 } else if (!strcmp(name, "UIntPtr")) {
4260 class->blittable = TRUE;
4264 if (!strcmp (name, "TypedReference")) {
4265 t = MONO_TYPE_TYPEDBYREF;
4266 class->blittable = TRUE;
4270 if (!strcmp (name, "Void")) {
4278 class->this_arg.type = class->byval_arg.type = t;
4281 if (MONO_CLASS_IS_INTERFACE (class))
4282 class->interface_id = mono_get_unique_iid (class);
4287 * LOCKING: this assumes the loader lock is held
4290 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
4292 gboolean system_namespace;
4293 gboolean is_corlib = is_corlib_image (class->image);
4295 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
4297 /* if root of the hierarchy */
4298 if (system_namespace && !strcmp (class->name, "Object")) {
4299 class->parent = NULL;
4300 class->instance_size = sizeof (MonoObject);
4303 if (!strcmp (class->name, "<Module>")) {
4304 class->parent = NULL;
4305 class->instance_size = 0;
4309 if (!MONO_CLASS_IS_INTERFACE (class)) {
4310 /* Imported COM Objects always derive from __ComObject. */
4311 if (MONO_CLASS_IS_IMPORT (class)) {
4312 mono_init_com_types ();
4313 if (parent == mono_defaults.object_class)
4314 parent = mono_defaults.com_object_class;
4317 /* set the parent to something useful and safe, but mark the type as broken */
4318 parent = mono_defaults.object_class;
4319 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4322 class->parent = parent;
4324 if (parent->generic_class && !parent->name) {
4326 * If the parent is a generic instance, we may get
4327 * called before it is fully initialized, especially
4328 * before it has its name.
4333 class->marshalbyref = parent->marshalbyref;
4334 class->contextbound = parent->contextbound;
4335 class->delegate = parent->delegate;
4336 if (MONO_CLASS_IS_IMPORT (class))
4337 class->is_com_object = 1;
4339 class->is_com_object = parent->is_com_object;
4341 if (system_namespace) {
4342 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
4343 class->marshalbyref = 1;
4345 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
4346 class->contextbound = 1;
4348 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
4349 class->delegate = 1;
4352 if (class->parent->enumtype || (is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
4353 (strcmp (class->parent->name_space, "System") == 0)))
4354 class->valuetype = 1;
4355 if (is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
4356 class->valuetype = class->enumtype = 1;
4358 /*class->enumtype = class->parent->enumtype; */
4359 mono_class_setup_supertypes (class);
4361 /* initialize com types if COM interfaces are present */
4362 if (MONO_CLASS_IS_IMPORT (class))
4363 mono_init_com_types ();
4364 class->parent = NULL;
4370 * mono_class_setup_supertypes:
4373 * Build the data structure needed to make fast type checks work.
4374 * This currently sets two fields in @class:
4375 * - idepth: distance between @class and System.Object in the type
4377 * - supertypes: array of classes: each element has a class in the hierarchy
4378 * starting from @class up to System.Object
4380 * LOCKING: this assumes the loader lock is held
4383 mono_class_setup_supertypes (MonoClass *class)
4387 if (class->supertypes)
4390 if (class->parent && !class->parent->supertypes)
4391 mono_class_setup_supertypes (class->parent);
4393 class->idepth = class->parent->idepth + 1;
4397 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
4398 class->supertypes = mono_image_alloc0 (class->image, sizeof (MonoClass *) * ms);
4400 if (class->parent) {
4401 class->supertypes [class->idepth - 1] = class;
4402 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
4404 class->supertypes [0] = class;
4409 * mono_class_create_from_typedef:
4410 * @image: image where the token is valid
4411 * @type_token: typedef token
4413 * Create the MonoClass* representing the specified type token.
4414 * @type_token must be a TypeDef token.
4417 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
4419 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
4420 MonoClass *class, *parent = NULL;
4421 guint32 cols [MONO_TYPEDEF_SIZE];
4422 guint32 cols_next [MONO_TYPEDEF_SIZE];
4423 guint tidx = mono_metadata_token_index (type_token);
4424 MonoGenericContext *context = NULL;
4425 const char *name, *nspace;
4427 MonoClass **interfaces;
4428 guint32 field_last, method_last;
4429 guint32 nesting_tokeen;
4431 mono_loader_lock ();
4433 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
4434 mono_loader_unlock ();
4438 g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
4440 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
4442 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
4443 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
4445 class = mono_image_alloc0 (image, sizeof (MonoClass));
4448 class->name_space = nspace;
4450 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4452 class->image = image;
4453 class->type_token = type_token;
4454 class->flags = cols [MONO_TYPEDEF_FLAGS];
4456 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
4458 classes_size += sizeof (MonoClass);
4461 * Check whether we're a generic type definition.
4463 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
4464 if (class->generic_container) {
4465 class->is_generic = 1;
4466 class->generic_container->owner.klass = class;
4467 context = &class->generic_container->context;
4470 if (cols [MONO_TYPEDEF_EXTENDS]) {
4471 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
4473 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
4474 /*WARNING: this must satisfy mono_metadata_type_hash*/
4475 class->this_arg.byref = 1;
4476 class->this_arg.data.klass = class;
4477 class->this_arg.type = MONO_TYPE_CLASS;
4478 class->byval_arg.data.klass = class;
4479 class->byval_arg.type = MONO_TYPE_CLASS;
4481 parent = mono_class_get_full (image, parent_token, context);
4483 if (parent == NULL){
4484 mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
4485 mono_loader_unlock ();
4486 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4491 /* do this early so it's available for interfaces in setup_mono_type () */
4492 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token)))
4493 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
4495 mono_class_setup_parent (class, parent);
4497 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
4498 mono_class_setup_mono_type (class);
4500 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
4503 #ifdef PLATFORM_WIN32
4504 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
4508 class->cast_class = class->element_class = class;
4510 if (!class->enumtype) {
4511 if (!mono_metadata_interfaces_from_typedef_full (
4512 image, type_token, &interfaces, &icount, FALSE, context)){
4513 mono_loader_unlock ();
4514 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4518 class->interfaces = interfaces;
4519 class->interface_count = icount;
4520 class->interfaces_inited = 1;
4523 /*g_print ("Load class %s\n", name);*/
4526 * Compute the field and method lists
4528 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
4529 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
4531 if (tt->rows > tidx){
4532 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
4533 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
4534 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
4536 field_last = image->tables [MONO_TABLE_FIELD].rows;
4537 method_last = image->tables [MONO_TABLE_METHOD].rows;
4540 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
4541 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
4542 class->field.count = field_last - class->field.first;
4544 class->field.count = 0;
4546 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
4547 class->method.count = method_last - class->method.first;
4549 class->method.count = 0;
4551 /* reserve space to store vector pointer in arrays */
4552 if (is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
4553 class->instance_size += 2 * sizeof (gpointer);
4554 g_assert (class->field.count == 0);
4557 if (class->enumtype) {
4558 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
4559 if (!enum_basetype) {
4560 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4561 mono_loader_unlock ();
4562 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4565 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
4569 * If we're a generic type definition, load the constraints.
4570 * We must do this after the class has been constructed to make certain recursive scenarios
4573 if (class->generic_container && !mono_metadata_load_generic_param_constraints_full (image, type_token, class->generic_container)){
4574 char *class_name = g_strdup_printf("%s.%s", class->name_space, class->name);
4575 char *error = concat_two_strings_with_zero (class->image, class_name, class->image->assembly_name);
4576 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, error);
4577 g_free (class_name);
4578 mono_loader_unlock ();
4579 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4583 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
4584 if (!strncmp (name, "Vector", 6))
4585 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");
4588 mono_loader_unlock ();
4590 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4595 /** is klass Nullable<T>? */
4597 mono_class_is_nullable (MonoClass *klass)
4599 return klass->generic_class != NULL &&
4600 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
4604 /** if klass is T? return T */
4606 mono_class_get_nullable_param (MonoClass *klass)
4608 g_assert (mono_class_is_nullable (klass));
4609 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4613 * Create the `MonoClass' for an instantiation of a generic type.
4614 * We only do this if we actually need it.
4617 mono_generic_class_get_class (MonoGenericClass *gclass)
4619 MonoClass *klass, *gklass;
4621 mono_loader_lock ();
4622 if (gclass->cached_class) {
4623 mono_loader_unlock ();
4624 return gclass->cached_class;
4627 gclass->cached_class = g_malloc0 (sizeof (MonoClass));
4628 klass = gclass->cached_class;
4630 gklass = gclass->container_class;
4632 if (gklass->nested_in) {
4634 * FIXME: the nested type context should include everything the
4635 * nesting context should have, but it may also have additional
4636 * generic parameters...
4638 klass->nested_in = mono_class_inflate_generic_class (gklass->nested_in,
4639 mono_generic_class_get_context (gclass));
4642 klass->name = gklass->name;
4643 klass->name_space = gklass->name_space;
4645 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4647 klass->image = gklass->image;
4648 klass->flags = gklass->flags;
4649 klass->type_token = gklass->type_token;
4650 klass->field.count = gklass->field.count;
4652 klass->is_inflated = 1;
4653 klass->generic_class = gclass;
4655 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
4656 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
4657 klass->this_arg.byref = TRUE;
4658 klass->enumtype = gklass->enumtype;
4659 klass->valuetype = gklass->valuetype;
4661 klass->cast_class = klass->element_class = klass;
4663 if (mono_class_is_nullable (klass))
4664 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
4667 * We're not interested in the nested classes of a generic instance.
4668 * We use the generic type definition to look for nested classes.
4671 if (gklass->parent) {
4672 klass->parent = mono_class_inflate_generic_class (gklass->parent, mono_generic_class_get_context (gclass));
4676 mono_class_setup_parent (klass, klass->parent);
4678 if (klass->enumtype) {
4679 klass->cast_class = gklass->cast_class;
4680 klass->element_class = gklass->element_class;
4683 if (gclass->is_dynamic) {
4686 mono_class_setup_supertypes (klass);
4688 if (klass->enumtype) {
4690 * For enums, gklass->fields might not been set, but instance_size etc. is
4691 * already set in mono_reflection_create_internal_class (). For non-enums,
4692 * these will be computed normally in mono_class_layout_fields ().
4694 klass->instance_size = gklass->instance_size;
4695 klass->sizes.class_size = gklass->sizes.class_size;
4696 klass->size_inited = 1;
4700 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4702 inflated_classes ++;
4703 inflated_classes_size += sizeof (MonoClass);
4705 mono_loader_unlock ();
4711 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
4713 MonoClass *klass, **ptr;
4718 image = mono_defaults.corlib;
4720 klass = mono_image_alloc0 (image, sizeof (MonoClass));
4721 classes_size += sizeof (MonoClass);
4724 klass->name = pinfo->name;
4726 int n = mono_generic_param_num (param);
4727 klass->name = mono_image_alloc0 (image, 16);
4728 sprintf ((char*)klass->name, "%d", n);
4731 klass->name_space = "";
4732 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4736 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
4740 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
4741 klass->parent = pinfo->constraints [0];
4743 } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
4744 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
4746 klass->parent = mono_defaults.object_class;
4749 if (count - pos > 0) {
4750 klass->interface_count = count - pos;
4751 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
4752 for (i = pos; i < count; i++)
4753 klass->interfaces [i - pos] = pinfo->constraints [i];
4756 klass->image = image;
4758 klass->inited = TRUE;
4759 klass->cast_class = klass->element_class = klass;
4760 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
4762 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
4763 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
4764 klass->this_arg.byref = TRUE;
4766 /* FIXME: shouldn't this be ->type_token? */
4767 klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
4769 mono_class_setup_supertypes (klass);
4774 #define FAST_CACHE_SIZE 1024
4775 static MonoClass *var_cache_fast [FAST_CACHE_SIZE];
4776 static MonoClass *mvar_cache_fast [FAST_CACHE_SIZE];
4777 static GHashTable *var_cache_slow;
4778 static GHashTable *mvar_cache_slow;
4781 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
4783 int n = mono_generic_param_num (param);
4786 if (n < FAST_CACHE_SIZE)
4787 return (is_mvar ? mvar_cache_fast : var_cache_fast) [n];
4788 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4789 return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
4793 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
4795 int n = mono_generic_param_num (param);
4798 if (n < FAST_CACHE_SIZE) {
4799 (is_mvar ? mvar_cache_fast : var_cache_fast) [n] = klass;
4802 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4804 ht = g_hash_table_new (NULL, NULL);
4806 mvar_cache_slow = ht;
4808 var_cache_slow = ht;
4811 g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
4815 * LOCKING: Acquires the loader lock.
4818 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
4820 MonoGenericContainer *container = mono_generic_param_owner (param);
4821 MonoGenericParamInfo *pinfo;
4824 mono_loader_lock ();
4827 pinfo = mono_generic_param_info (param);
4828 if (pinfo->pklass) {
4829 mono_loader_unlock ();
4830 return pinfo->pklass;
4836 klass = get_anon_gparam_class (param, is_mvar);
4838 mono_loader_unlock ();
4843 if (!image && container) {
4845 MonoMethod *method = container->owner.method;
4846 image = (method && method->klass) ? method->klass->image : NULL;
4848 MonoClass *klass = container->owner.klass;
4849 // FIXME: 'klass' should not be null
4850 // But, monodis creates GenericContainers without associating a owner to it
4851 image = klass ? klass->image : NULL;
4855 klass = make_generic_param_class (param, image, is_mvar, pinfo);
4857 mono_memory_barrier ();
4860 pinfo->pklass = klass;
4862 set_anon_gparam_class (param, is_mvar, klass);
4864 mono_loader_unlock ();
4866 /* FIXME: Should this go inside 'make_generic_param_klass'? */
4867 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4873 mono_ptr_class_get (MonoType *type)
4876 MonoClass *el_class;
4880 el_class = mono_class_from_mono_type (type);
4881 image = el_class->image;
4883 mono_loader_lock ();
4885 if (!image->ptr_cache)
4886 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4888 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
4889 mono_loader_unlock ();
4892 result = mono_image_alloc0 (image, sizeof (MonoClass));
4894 classes_size += sizeof (MonoClass);
4896 result->parent = NULL; /* no parent for PTR types */
4897 result->name_space = el_class->name_space;
4898 name = g_strdup_printf ("%s*", el_class->name);
4899 result->name = mono_image_strdup (image, name);
4902 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4904 result->image = el_class->image;
4905 result->inited = TRUE;
4906 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4907 /* Can pointers get boxed? */
4908 result->instance_size = sizeof (gpointer);
4909 result->cast_class = result->element_class = el_class;
4910 result->blittable = TRUE;
4912 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
4913 result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
4914 result->this_arg.byref = TRUE;
4916 mono_class_setup_supertypes (result);
4918 g_hash_table_insert (image->ptr_cache, el_class, result);
4920 mono_loader_unlock ();
4922 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4928 mono_fnptr_class_get (MonoMethodSignature *sig)
4931 static GHashTable *ptr_hash = NULL;
4933 /* FIXME: These should be allocate from a mempool as well, but which one ? */
4935 mono_loader_lock ();
4938 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
4940 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
4941 mono_loader_unlock ();
4944 result = g_new0 (MonoClass, 1);
4946 result->parent = NULL; /* no parent for PTR types */
4947 result->name_space = "System";
4948 result->name = "MonoFNPtrFakeClass";
4950 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4952 result->image = mono_defaults.corlib; /* need to fix... */
4953 result->inited = TRUE;
4954 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
4955 /* Can pointers get boxed? */
4956 result->instance_size = sizeof (gpointer);
4957 result->cast_class = result->element_class = result;
4958 result->blittable = TRUE;
4960 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
4961 result->this_arg.data.method = result->byval_arg.data.method = sig;
4962 result->this_arg.byref = TRUE;
4963 result->blittable = TRUE;
4965 mono_class_setup_supertypes (result);
4967 g_hash_table_insert (ptr_hash, sig, result);
4969 mono_loader_unlock ();
4971 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4977 mono_class_from_mono_type (MonoType *type)
4979 switch (type->type) {
4980 case MONO_TYPE_OBJECT:
4981 return type->data.klass? type->data.klass: mono_defaults.object_class;
4982 case MONO_TYPE_VOID:
4983 return type->data.klass? type->data.klass: mono_defaults.void_class;
4984 case MONO_TYPE_BOOLEAN:
4985 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
4986 case MONO_TYPE_CHAR:
4987 return type->data.klass? type->data.klass: mono_defaults.char_class;
4989 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
4991 return type->data.klass? type->data.klass: mono_defaults.byte_class;
4993 return type->data.klass? type->data.klass: mono_defaults.int16_class;
4995 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
4997 return type->data.klass? type->data.klass: mono_defaults.int32_class;
4999 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
5001 return type->data.klass? type->data.klass: mono_defaults.int_class;
5003 return type->data.klass? type->data.klass: mono_defaults.uint_class;
5005 return type->data.klass? type->data.klass: mono_defaults.int64_class;
5007 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
5009 return type->data.klass? type->data.klass: mono_defaults.single_class;
5011 return type->data.klass? type->data.klass: mono_defaults.double_class;
5012 case MONO_TYPE_STRING:
5013 return type->data.klass? type->data.klass: mono_defaults.string_class;
5014 case MONO_TYPE_TYPEDBYREF:
5015 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
5016 case MONO_TYPE_ARRAY:
5017 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
5019 return mono_ptr_class_get (type->data.type);
5020 case MONO_TYPE_FNPTR:
5021 return mono_fnptr_class_get (type->data.method);
5022 case MONO_TYPE_SZARRAY:
5023 return mono_array_class_get (type->data.klass, 1);
5024 case MONO_TYPE_CLASS:
5025 case MONO_TYPE_VALUETYPE:
5026 return type->data.klass;
5027 case MONO_TYPE_GENERICINST:
5028 return mono_generic_class_get_class (type->data.generic_class);
5030 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
5031 case MONO_TYPE_MVAR:
5032 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
5034 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
5035 g_assert_not_reached ();
5042 * mono_type_retrieve_from_typespec
5043 * @image: context where the image is created
5044 * @type_spec: typespec token
5045 * @context: the generic context used to evaluate generic instantiations in
5048 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate)
5051 MonoType *t = mono_type_create_from_typespec (image, type_spec);
5054 if (context && (context->class_inst || context->method_inst)) {
5055 MonoType *inflated = inflate_generic_type (NULL, t, context, &error);
5056 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
5060 *did_inflate = TRUE;
5067 * mono_class_create_from_typespec
5068 * @image: context where the image is created
5069 * @type_spec: typespec token
5070 * @context: the generic context used to evaluate generic instantiations in
5073 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
5076 gboolean inflated = FALSE;
5077 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated);
5080 ret = mono_class_from_mono_type (t);
5082 mono_metadata_free_type (t);
5087 * mono_bounded_array_class_get:
5088 * @element_class: element class
5089 * @rank: the dimension of the array class
5090 * @bounded: whenever the array has non-zero bounds
5092 * Returns: a class object describing the array with element type @element_type and
5096 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
5100 MonoClass *parent = NULL;
5101 GSList *list, *rootlist = NULL;
5104 gboolean corlib_type = FALSE;
5106 g_assert (rank <= 255);
5109 /* bounded only matters for one-dimensional arrays */
5112 image = eclass->image;
5114 if (rank == 1 && !bounded) {
5116 * This case is very frequent not just during compilation because of calls
5117 * from mono_class_from_mono_type (), mono_array_new (),
5118 * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
5120 EnterCriticalSection (&image->szarray_cache_lock);
5121 if (!image->szarray_cache)
5122 image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5123 class = g_hash_table_lookup (image->szarray_cache, eclass);
5124 LeaveCriticalSection (&image->szarray_cache_lock);
5128 mono_loader_lock ();
5130 mono_loader_lock ();
5132 if (!image->array_cache)
5133 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5135 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
5136 for (; list; list = list->next) {
5138 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
5139 mono_loader_unlock ();
5146 /* for the building corlib use System.Array from it */
5147 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
5148 parent = mono_class_from_name (image, "System", "Array");
5151 parent = mono_defaults.array_class;
5152 if (!parent->inited)
5153 mono_class_init (parent);
5156 class = mono_image_alloc0 (image, sizeof (MonoClass));
5158 class->image = image;
5159 class->name_space = eclass->name_space;
5160 nsize = strlen (eclass->name);
5161 name = g_malloc (nsize + 2 + rank + 1);
5162 memcpy (name, eclass->name, nsize);
5165 memset (name + nsize + 1, ',', rank - 1);
5167 name [nsize + rank] = '*';
5168 name [nsize + rank + bounded] = ']';
5169 name [nsize + rank + bounded + 1] = 0;
5170 class->name = mono_image_strdup (image, name);
5173 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
5175 classes_size += sizeof (MonoClass);
5177 class->type_token = 0;
5178 /* all arrays are marked serializable and sealed, bug #42779 */
5179 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
5180 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5181 class->parent = parent;
5182 class->instance_size = mono_class_instance_size (class->parent);
5184 if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
5185 if (!eclass->reflection_info || eclass->wastypebuilder) {
5186 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
5187 g_assert (eclass->reflection_info && !eclass->wastypebuilder);
5189 /* element_size -1 is ok as this is not an instantitable type*/
5190 class->sizes.element_size = -1;
5192 class->sizes.element_size = mono_class_array_element_size (eclass);
5194 mono_class_setup_supertypes (class);
5196 if (eclass->generic_class)
5197 mono_class_init (eclass);
5198 if (!eclass->size_inited)
5199 mono_class_setup_fields (eclass);
5200 if (eclass->exception_type) /*FIXME we fail the array type, but we have to let other fields be set.*/
5201 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5203 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
5207 if (eclass->enumtype)
5208 class->cast_class = eclass->element_class;
5210 class->cast_class = eclass;
5212 class->element_class = eclass;
5214 if ((rank > 1) || bounded) {
5215 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
5216 class->byval_arg.type = MONO_TYPE_ARRAY;
5217 class->byval_arg.data.array = at;
5218 at->eklass = eclass;
5220 /* FIXME: complete.... */
5222 class->byval_arg.type = MONO_TYPE_SZARRAY;
5223 class->byval_arg.data.klass = eclass;
5225 class->this_arg = class->byval_arg;
5226 class->this_arg.byref = 1;
5231 class->generic_container = eclass->generic_container;
5233 if (rank == 1 && !bounded) {
5234 MonoClass *prev_class;
5236 EnterCriticalSection (&image->szarray_cache_lock);
5237 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
5239 /* Someone got in before us */
5242 g_hash_table_insert (image->szarray_cache, eclass, class);
5243 LeaveCriticalSection (&image->szarray_cache_lock);
5245 list = g_slist_append (rootlist, class);
5246 g_hash_table_insert (image->array_cache, eclass, list);
5249 mono_loader_unlock ();
5251 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5257 * mono_array_class_get:
5258 * @element_class: element class
5259 * @rank: the dimension of the array class
5261 * Returns: a class object describing the array with element type @element_type and
5265 mono_array_class_get (MonoClass *eclass, guint32 rank)
5267 return mono_bounded_array_class_get (eclass, rank, FALSE);
5271 * mono_class_instance_size:
5274 * Returns: the size of an object instance
5277 mono_class_instance_size (MonoClass *klass)
5279 if (!klass->size_inited)
5280 mono_class_init (klass);
5282 return klass->instance_size;
5286 * mono_class_min_align:
5289 * Returns: minimm alignment requirements
5292 mono_class_min_align (MonoClass *klass)
5294 if (!klass->size_inited)
5295 mono_class_init (klass);
5297 return klass->min_align;
5301 * mono_class_value_size:
5304 * This function is used for value types, and return the
5305 * space and the alignment to store that kind of value object.
5307 * Returns: the size of a value of kind @klass
5310 mono_class_value_size (MonoClass *klass, guint32 *align)
5314 /* fixme: check disable, because we still have external revereces to
5315 * mscorlib and Dummy Objects
5317 /*g_assert (klass->valuetype);*/
5319 size = mono_class_instance_size (klass) - sizeof (MonoObject);
5322 *align = klass->min_align;
5328 * mono_class_data_size:
5331 * Returns: the size of the static class data
5334 mono_class_data_size (MonoClass *klass)
5337 mono_class_init (klass);
5339 /* in arrays, sizes.class_size is unioned with element_size
5340 * and arrays have no static fields
5344 return klass->sizes.class_size;
5348 * Auxiliary routine to mono_class_get_field
5350 * Takes a field index instead of a field token.
5352 static MonoClassField *
5353 mono_class_get_field_idx (MonoClass *class, int idx)
5355 mono_class_setup_fields_locking (class);
5356 if (class->exception_type)
5360 if (class->image->uncompressed_metadata) {
5362 * class->field.first points to the FieldPtr table, while idx points into the
5363 * Field table, so we have to do a search.
5365 /*FIXME this is broken for types with multiple fields with the same name.*/
5366 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
5369 for (i = 0; i < class->field.count; ++i)
5370 if (mono_field_get_name (&class->fields [i]) == name)
5371 return &class->fields [i];
5372 g_assert_not_reached ();
5374 if (class->field.count) {
5375 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
5376 return &class->fields [idx - class->field.first];
5380 class = class->parent;
5386 * mono_class_get_field:
5387 * @class: the class to lookup the field.
5388 * @field_token: the field token
5390 * Returns: A MonoClassField representing the type and offset of
5391 * the field, or a NULL value if the field does not belong to this
5395 mono_class_get_field (MonoClass *class, guint32 field_token)
5397 int idx = mono_metadata_token_index (field_token);
5399 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
5401 return mono_class_get_field_idx (class, idx - 1);
5405 * mono_class_get_field_from_name:
5406 * @klass: the class to lookup the field.
5407 * @name: the field name
5409 * Search the class @klass and it's parents for a field with the name @name.
5411 * Returns: the MonoClassField pointer of the named field or NULL
5414 mono_class_get_field_from_name (MonoClass *klass, const char *name)
5416 return mono_class_get_field_from_name_full (klass, name, NULL);
5420 * mono_class_get_field_from_name_full:
5421 * @klass: the class to lookup the field.
5422 * @name: the field name
5423 * @type: the type of the fields. This optional.
5425 * Search the class @klass and it's parents for a field with the name @name and type @type.
5427 * If @klass is an inflated generic type, the type comparison is done with the equivalent field
5428 * of its generic type definition.
5430 * Returns: the MonoClassField pointer of the named field or NULL
5433 mono_class_get_field_from_name_full (MonoClass *klass, const char *name, MonoType *type)
5437 mono_class_setup_fields_locking (klass);
5438 if (klass->exception_type)
5442 for (i = 0; i < klass->field.count; ++i) {
5443 MonoClassField *field = &klass->fields [i];
5445 if (strcmp (name, mono_field_get_name (field)) != 0)
5449 MonoType *field_type = mono_metadata_get_corresponding_field_from_generic_type_definition (field)->type;
5450 if (!mono_metadata_type_equal_full (type, field_type, TRUE))
5455 klass = klass->parent;
5461 * mono_class_get_field_token:
5462 * @field: the field we need the token of
5464 * Get the token of a field. Note that the tokesn is only valid for the image
5465 * the field was loaded from. Don't use this function for fields in dynamic types.
5467 * Returns: the token representing the field in the image it was loaded from.
5470 mono_class_get_field_token (MonoClassField *field)
5472 MonoClass *klass = field->parent;
5475 mono_class_setup_fields_locking (klass);
5476 if (klass->exception_type)
5480 for (i = 0; i < klass->field.count; ++i) {
5481 if (&klass->fields [i] == field) {
5482 int idx = klass->field.first + i + 1;
5484 if (klass->image->uncompressed_metadata)
5485 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
5486 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
5489 klass = klass->parent;
5492 g_assert_not_reached ();
5497 mono_field_get_index (MonoClassField *field)
5499 int index = field - field->parent->fields;
5501 g_assert (index >= 0 && index < field->parent->field.count);
5507 * mono_class_get_field_default_value:
5509 * Return the default value of the field as a pointer into the metadata blob.
5512 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
5515 guint32 constant_cols [MONO_CONSTANT_SIZE];
5517 MonoClass *klass = field->parent;
5519 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
5521 if (!klass->ext || !klass->ext->field_def_values) {
5522 mono_loader_lock ();
5523 mono_class_alloc_ext (klass);
5524 if (!klass->ext->field_def_values)
5525 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
5526 mono_loader_unlock ();
5529 field_index = mono_field_get_index (field);
5531 if (!klass->ext->field_def_values [field_index].data) {
5532 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
5534 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
5536 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
5537 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
5538 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
5541 *def_type = klass->ext->field_def_values [field_index].def_type;
5542 return klass->ext->field_def_values [field_index].data;
5546 mono_class_get_event_token (MonoEvent *event)
5548 MonoClass *klass = event->parent;
5553 for (i = 0; i < klass->ext->event.count; ++i) {
5554 if (&klass->ext->events [i] == event)
5555 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
5558 klass = klass->parent;
5561 g_assert_not_reached ();
5566 mono_class_get_property_from_name (MonoClass *klass, const char *name)
5570 gpointer iter = NULL;
5571 while ((p = mono_class_get_properties (klass, &iter))) {
5572 if (! strcmp (name, p->name))
5575 klass = klass->parent;
5581 mono_class_get_property_token (MonoProperty *prop)
5583 MonoClass *klass = prop->parent;
5587 gpointer iter = NULL;
5588 while ((p = mono_class_get_properties (klass, &iter))) {
5589 if (&klass->ext->properties [i] == prop)
5590 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
5594 klass = klass->parent;
5597 g_assert_not_reached ();
5602 mono_class_name_from_token (MonoImage *image, guint32 type_token)
5604 const char *name, *nspace;
5606 return g_strdup_printf ("DynamicType 0x%08x", type_token);
5608 switch (type_token & 0xff000000){
5609 case MONO_TOKEN_TYPE_DEF: {
5610 guint32 cols [MONO_TYPEDEF_SIZE];
5611 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5612 guint tidx = mono_metadata_token_index (type_token);
5614 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5615 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5616 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5617 if (strlen (nspace) == 0)
5618 return g_strdup_printf ("%s", name);
5620 return g_strdup_printf ("%s.%s", nspace, name);
5623 case MONO_TOKEN_TYPE_REF: {
5624 guint32 cols [MONO_TYPEREF_SIZE];
5625 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5627 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5628 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
5629 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
5630 if (strlen (nspace) == 0)
5631 return g_strdup_printf ("%s", name);
5633 return g_strdup_printf ("%s.%s", nspace, name);
5636 case MONO_TOKEN_TYPE_SPEC:
5637 return g_strdup_printf ("Typespec 0x%08x", type_token);
5639 g_assert_not_reached ();
5646 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
5649 return g_strdup_printf ("DynamicAssembly %s", image->name);
5651 switch (type_token & 0xff000000){
5652 case MONO_TOKEN_TYPE_DEF:
5653 return mono_stringify_assembly_name (&image->assembly->aname);
5655 case MONO_TOKEN_TYPE_REF: {
5656 MonoAssemblyName aname;
5657 guint32 cols [MONO_TYPEREF_SIZE];
5658 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5661 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5663 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
5664 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
5665 case MONO_RESOLTION_SCOPE_MODULE:
5667 return g_strdup ("");
5668 case MONO_RESOLTION_SCOPE_MODULEREF:
5670 return g_strdup ("");
5671 case MONO_RESOLTION_SCOPE_TYPEREF:
5673 return g_strdup ("");
5674 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
5675 mono_assembly_get_assemblyref (image, idx - 1, &aname);
5676 return mono_stringify_assembly_name (&aname);
5678 g_assert_not_reached ();
5682 case MONO_TOKEN_TYPE_SPEC:
5684 return g_strdup ("");
5686 g_assert_not_reached ();
5693 * mono_class_get_full:
5694 * @image: the image where the class resides
5695 * @type_token: the token for the class
5696 * @context: the generic context used to evaluate generic instantiations in
5698 * Returns: the MonoClass that represents @type_token in @image
5701 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5703 MonoClass *class = NULL;
5705 if (image->dynamic) {
5706 int table = mono_metadata_token_table (type_token);
5708 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
5709 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
5712 return mono_lookup_dynamic_token (image, type_token, context);
5715 switch (type_token & 0xff000000){
5716 case MONO_TOKEN_TYPE_DEF:
5717 class = mono_class_create_from_typedef (image, type_token);
5719 case MONO_TOKEN_TYPE_REF:
5720 class = mono_class_from_typeref (image, type_token);
5722 case MONO_TOKEN_TYPE_SPEC:
5723 class = mono_class_create_from_typespec (image, type_token, context);
5726 g_warning ("unknown token type %x", type_token & 0xff000000);
5727 g_assert_not_reached ();
5731 char *name = mono_class_name_from_token (image, type_token);
5732 char *assembly = mono_assembly_name_from_token (image, type_token);
5733 mono_loader_set_error_type_load (name, assembly);
5741 * mono_type_get_full:
5742 * @image: the image where the type resides
5743 * @type_token: the token for the type
5744 * @context: the generic context used to evaluate generic instantiations in
5746 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
5748 * Returns: the MonoType that represents @type_token in @image
5751 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5753 MonoType *type = NULL;
5754 gboolean inflated = FALSE;
5756 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
5758 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
5760 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
5761 MonoClass *class = mono_class_get_full (image, type_token, context);
5762 return class ? mono_class_get_type (class) : NULL;
5765 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated);
5768 char *name = mono_class_name_from_token (image, type_token);
5769 char *assembly = mono_assembly_name_from_token (image, type_token);
5770 mono_loader_set_error_type_load (name, assembly);
5775 MonoType *tmp = type;
5776 type = mono_class_get_type (mono_class_from_mono_type (type));
5777 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
5778 * A MonoClass::byval_arg of a generic type definion has type CLASS.
5779 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
5781 * The long term solution is to chaise this places and make then set MonoType::type correctly.
5783 if (type->type != tmp->type)
5786 mono_metadata_free_type (tmp);
5793 mono_class_get (MonoImage *image, guint32 type_token)
5795 return mono_class_get_full (image, type_token, NULL);
5799 * mono_image_init_name_cache:
5801 * Initializes the class name cache stored in image->name_cache.
5803 * LOCKING: Acquires the corresponding image lock.
5806 mono_image_init_name_cache (MonoImage *image)
5808 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5809 guint32 cols [MONO_TYPEDEF_SIZE];
5812 guint32 i, visib, nspace_index;
5813 GHashTable *name_cache2, *nspace_table;
5815 mono_image_lock (image);
5817 if (image->name_cache) {
5818 mono_image_unlock (image);
5822 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
5824 if (image->dynamic) {
5825 mono_image_unlock (image);
5829 /* Temporary hash table to avoid lookups in the nspace_table */
5830 name_cache2 = g_hash_table_new (NULL, NULL);
5832 for (i = 1; i <= t->rows; ++i) {
5833 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5834 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5836 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5837 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5839 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5841 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5842 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5844 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
5845 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5846 if (!nspace_table) {
5847 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5848 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5849 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5852 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
5855 /* Load type names from EXPORTEDTYPES table */
5857 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5858 guint32 cols [MONO_EXP_TYPE_SIZE];
5861 for (i = 0; i < t->rows; ++i) {
5862 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
5863 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
5864 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
5866 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
5867 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5868 if (!nspace_table) {
5869 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5870 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5871 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5874 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
5878 g_hash_table_destroy (name_cache2);
5879 mono_image_unlock (image);
5882 /*FIXME Only dynamic assemblies should allow this operation.*/
5884 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
5885 const char *name, guint32 index)
5887 GHashTable *nspace_table;
5888 GHashTable *name_cache;
5891 mono_image_lock (image);
5893 if (!image->name_cache)
5894 mono_image_init_name_cache (image);
5896 name_cache = image->name_cache;
5897 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
5898 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5899 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
5902 if ((old_index = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, (char*) name))))
5903 g_error ("overrwritting old token %x on image %s for type %s::%s", old_index, image->name, nspace, name);
5905 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
5907 mono_image_unlock (image);
5916 find_nocase (gpointer key, gpointer value, gpointer user_data)
5918 char *name = (char*)key;
5919 FindUserData *data = (FindUserData*)user_data;
5921 if (!data->value && (mono_utf8_strcasecmp (name, (char*)data->key) == 0))
5922 data->value = value;
5926 * mono_class_from_name_case:
5927 * @image: The MonoImage where the type is looked up in
5928 * @name_space: the type namespace
5929 * @name: the type short name.
5931 * Obtains a MonoClass with a given namespace and a given name which
5932 * is located in the given MonoImage. The namespace and name
5933 * lookups are case insensitive.
5936 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
5938 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5939 guint32 cols [MONO_TYPEDEF_SIZE];
5944 if (image->dynamic) {
5946 FindUserData user_data;
5948 mono_image_lock (image);
5950 if (!image->name_cache)
5951 mono_image_init_name_cache (image);
5953 user_data.key = name_space;
5954 user_data.value = NULL;
5955 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
5957 if (user_data.value) {
5958 GHashTable *nspace_table = (GHashTable*)user_data.value;
5960 user_data.key = name;
5961 user_data.value = NULL;
5963 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
5965 if (user_data.value)
5966 token = GPOINTER_TO_UINT (user_data.value);
5969 mono_image_unlock (image);
5972 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
5978 /* add a cache if needed */
5979 for (i = 1; i <= t->rows; ++i) {
5980 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5981 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5983 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5984 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5986 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5988 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5989 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5990 if (mono_utf8_strcasecmp (n, name) == 0 && mono_utf8_strcasecmp (nspace, name_space) == 0)
5991 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
5997 return_nested_in (MonoClass *class, char *nested)
6000 char *s = strchr (nested, '/');
6001 gpointer iter = NULL;
6008 while ((found = mono_class_get_nested_types (class, &iter))) {
6009 if (strcmp (found->name, nested) == 0) {
6011 return return_nested_in (found, s);
6019 search_modules (MonoImage *image, const char *name_space, const char *name)
6021 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
6022 MonoImage *file_image;
6027 * The EXPORTEDTYPES table only contains public types, so have to search the
6029 * Note: image->modules contains the contents of the MODULEREF table, while
6030 * the real module list is in the FILE table.
6032 for (i = 0; i < file_table->rows; i++) {
6033 guint32 cols [MONO_FILE_SIZE];
6034 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
6035 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
6038 file_image = mono_image_load_file_for_image (image, i + 1);
6040 class = mono_class_from_name (file_image, name_space, name);
6050 * mono_class_from_name:
6051 * @image: The MonoImage where the type is looked up in
6052 * @name_space: the type namespace
6053 * @name: the type short name.
6055 * Obtains a MonoClass with a given namespace and a given name which
6056 * is located in the given MonoImage.
6059 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
6061 GHashTable *nspace_table;
6062 MonoImage *loaded_image;
6069 if ((nested = strchr (name, '/'))) {
6070 int pos = nested - name;
6071 int len = strlen (name);
6074 memcpy (buf, name, len + 1);
6076 nested = buf + pos + 1;
6080 if (get_class_from_name) {
6081 gboolean res = get_class_from_name (image, name_space, name, &class);
6084 class = search_modules (image, name_space, name);
6086 return class ? return_nested_in (class, nested) : NULL;
6092 mono_image_lock (image);
6094 if (!image->name_cache)
6095 mono_image_init_name_cache (image);
6097 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
6100 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
6102 mono_image_unlock (image);
6104 if (!token && image->dynamic && image->modules) {
6105 /* Search modules as well */
6106 for (i = 0; i < image->module_count; ++i) {
6107 MonoImage *module = image->modules [i];
6109 class = mono_class_from_name (module, name_space, name);
6116 class = search_modules (image, name_space, name);
6124 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
6125 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6126 guint32 cols [MONO_EXP_TYPE_SIZE];
6129 idx = mono_metadata_token_index (token);
6131 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
6133 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
6134 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
6135 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
6138 class = mono_class_from_name (loaded_image, name_space, name);
6140 return return_nested_in (class, nested);
6142 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
6143 guint32 assembly_idx;
6145 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
6147 mono_assembly_load_reference (image, assembly_idx - 1);
6148 g_assert (image->references [assembly_idx - 1]);
6149 if (image->references [assembly_idx - 1] == (gpointer)-1)
6152 /* FIXME: Cycle detection */
6153 return mono_class_from_name (image->references [assembly_idx - 1]->image, name_space, name);
6155 g_error ("not yet implemented");
6159 token = MONO_TOKEN_TYPE_DEF | token;
6161 class = mono_class_get (image, token);
6163 return return_nested_in (class, nested);
6168 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
6169 gboolean check_interfaces)
6171 g_assert (klassc->idepth > 0);
6172 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
6173 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
6175 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
6178 for (i = 0; i < klass->interface_count; i ++) {
6179 MonoClass *ic = klass->interfaces [i];
6184 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
6189 * MS.NET thinks interfaces are a subclass of Object, so we think it as
6192 if (klassc == mono_defaults.object_class)
6199 mono_class_has_variant_generic_params (MonoClass *klass)
6202 MonoGenericContainer *container;
6204 if (!klass->generic_class)
6207 container = klass->generic_class->container_class->generic_container;
6209 for (i = 0; i < container->type_argc; ++i)
6210 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
6217 * mono_class_is_assignable_from:
6218 * @klass: the class to be assigned to
6219 * @oklass: the source class
6221 * Return: true if an instance of object oklass can be assigned to an
6222 * instance of object @klass
6225 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
6228 mono_class_init (klass);
6230 if (!oklass->inited)
6231 mono_class_init (oklass);
6233 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
6234 return klass == oklass;
6236 if (MONO_CLASS_IS_INTERFACE (klass)) {
6237 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
6240 /* interface_offsets might not be set for dynamic classes */
6241 if (oklass->reflection_info && !oklass->interface_bitmap)
6243 * oklass might be a generic type parameter but they have
6244 * interface_offsets set.
6246 return mono_reflection_call_is_assignable_to (oklass, klass);
6247 if (!oklass->interface_bitmap)
6248 /* Happens with generic instances of not-yet created dynamic types */
6250 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
6253 if (mono_class_has_variant_generic_params (klass)) {
6254 if (oklass->generic_class) {
6256 gboolean match = FALSE;
6257 MonoClass *container_class1 = klass->generic_class->container_class;
6258 MonoClass *container_class2 = oklass->generic_class->container_class;
6261 * Check whenever the generic definition of oklass implements the
6262 * generic definition of klass. The IMPLEMENTS_INTERFACE stuff is not usable
6263 * here since the relevant tables are not set up.
6265 for (i = 0; i < container_class2->interface_offsets_count; ++i)
6266 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)))
6270 MonoGenericContainer *container;
6272 container = klass->generic_class->container_class->generic_container;
6275 for (i = 0; i < container->type_argc; ++i) {
6276 MonoClass *param1_class = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [i]);
6277 MonoClass *param2_class = mono_class_from_mono_type (oklass->generic_class->context.class_inst->type_argv [i]);
6279 if (param1_class->valuetype != param2_class->valuetype) {
6284 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
6285 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
6287 if (param1_class != param2_class) {
6288 if ((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_VARIANT) && mono_class_is_assignable_from (param1_class, param2_class))
6290 else if (((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_COVARIANT) && mono_class_is_assignable_from (param2_class, param1_class)))
6304 } else if (klass->rank) {
6305 MonoClass *eclass, *eoclass;
6307 if (oklass->rank != klass->rank)
6310 /* vectors vs. one dimensional arrays */
6311 if (oklass->byval_arg.type != klass->byval_arg.type)
6314 eclass = klass->cast_class;
6315 eoclass = oklass->cast_class;
6318 * a is b does not imply a[] is b[] when a is a valuetype, and
6319 * b is a reference type.
6322 if (eoclass->valuetype) {
6323 if ((eclass == mono_defaults.enum_class) ||
6324 (eclass == mono_defaults.enum_class->parent) ||
6325 (eclass == mono_defaults.object_class))
6329 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6330 } else if (mono_class_is_nullable (klass)) {
6331 if (mono_class_is_nullable (oklass))
6332 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6334 return mono_class_is_assignable_from (klass->cast_class, oklass);
6335 } else if (klass == mono_defaults.object_class)
6338 return mono_class_has_parent (oklass, klass);
6341 /*Check if @candidate implements the interface @target*/
6343 mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
6348 if (candidate == target)
6351 /*A TypeBuilder can have more interfaces on tb->interfaces than on candidate->interfaces*/
6352 if (candidate->image->dynamic && !candidate->wastypebuilder) {
6353 MonoReflectionTypeBuilder *tb = candidate->reflection_info;
6355 if (tb->interfaces) {
6356 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
6357 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
6358 MonoClass *iface_class = mono_class_from_mono_type (iface->type);
6359 if (iface_class == target || mono_class_implement_interface_slow (target, iface_class))
6364 /*setup_interfaces don't mono_class_init anything*/
6365 mono_class_setup_interfaces (candidate);
6366 for (i = 0; i < candidate->interface_count; ++i) {
6367 if (candidate->interfaces [i] == target || mono_class_implement_interface_slow (target, candidate->interfaces [i]))
6371 candidate = candidate->parent;
6372 } while (candidate);
6378 * Check if @oklass can be assigned to @klass.
6379 * This function does the same as mono_class_is_assignable_from but is safe to be used from mono_class_init context.
6382 mono_class_is_assignable_from_slow (MonoClass *target, MonoClass *candidate)
6384 if (candidate == target)
6386 if (target == mono_defaults.object_class)
6389 /*setup_supertypes don't mono_class_init anything */
6390 mono_class_setup_supertypes (candidate);
6391 mono_class_setup_supertypes (target);
6393 if (mono_class_has_parent (candidate, target))
6396 /*If target is not an interface there is no need to check them.*/
6397 if (!MONO_CLASS_IS_INTERFACE (target))
6399 return mono_class_implement_interface_slow (target, candidate);
6403 * mono_class_get_cctor:
6404 * @klass: A MonoClass pointer
6406 * Returns: the static constructor of @klass if it exists, NULL otherwise.
6409 mono_class_get_cctor (MonoClass *klass)
6411 MonoCachedClassInfo cached_info;
6413 if (!klass->has_cctor)
6416 if (mono_class_get_cached_class_info (klass, &cached_info))
6417 return mono_get_method (klass->image, cached_info.cctor_token, klass);
6419 if (klass->generic_class && !klass->methods)
6420 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
6422 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
6426 * mono_class_get_finalizer:
6427 * @klass: The MonoClass pointer
6429 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
6432 mono_class_get_finalizer (MonoClass *klass)
6434 MonoCachedClassInfo cached_info;
6437 mono_class_init (klass);
6438 if (!klass->has_finalize)
6441 if (mono_class_get_cached_class_info (klass, &cached_info))
6442 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
6444 mono_class_setup_vtable (klass);
6445 return klass->vtable [finalize_slot];
6450 * mono_class_needs_cctor_run:
6451 * @klass: the MonoClass pointer
6452 * @caller: a MonoMethod describing the caller
6454 * Determines whenever the class has a static constructor and whenever it
6455 * needs to be called when executing CALLER.
6458 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
6462 method = mono_class_get_cctor (klass);
6464 return (method == caller) ? FALSE : TRUE;
6470 * mono_class_array_element_size:
6473 * Returns: the number of bytes an element of type @klass
6474 * uses when stored into an array.
6477 mono_class_array_element_size (MonoClass *klass)
6479 MonoType *type = &klass->byval_arg;
6482 switch (type->type) {
6485 case MONO_TYPE_BOOLEAN:
6489 case MONO_TYPE_CHAR:
6498 case MONO_TYPE_CLASS:
6499 case MONO_TYPE_STRING:
6500 case MONO_TYPE_OBJECT:
6501 case MONO_TYPE_SZARRAY:
6502 case MONO_TYPE_ARRAY:
6504 case MONO_TYPE_MVAR:
6505 return sizeof (gpointer);
6510 case MONO_TYPE_VALUETYPE:
6511 if (type->data.klass->enumtype) {
6512 type = mono_class_enum_basetype (type->data.klass);
6513 klass = klass->element_class;
6516 return mono_class_instance_size (klass) - sizeof (MonoObject);
6517 case MONO_TYPE_GENERICINST:
6518 type = &type->data.generic_class->container_class->byval_arg;
6521 case MONO_TYPE_VOID:
6525 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
6531 * mono_array_element_size:
6532 * @ac: pointer to a #MonoArrayClass
6534 * Returns: the size of single array element.
6537 mono_array_element_size (MonoClass *ac)
6539 g_assert (ac->rank);
6540 return ac->sizes.element_size;
6544 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
6545 MonoGenericContext *context)
6547 if (image->dynamic) {
6548 MonoClass *tmp_handle_class;
6549 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
6551 g_assert (tmp_handle_class);
6553 *handle_class = tmp_handle_class;
6555 if (tmp_handle_class == mono_defaults.typehandle_class)
6556 return &((MonoClass*)obj)->byval_arg;
6561 switch (token & 0xff000000) {
6562 case MONO_TOKEN_TYPE_DEF:
6563 case MONO_TOKEN_TYPE_REF:
6564 case MONO_TOKEN_TYPE_SPEC: {
6567 *handle_class = mono_defaults.typehandle_class;
6568 type = mono_type_get_full (image, token, context);
6571 mono_class_init (mono_class_from_mono_type (type));
6572 /* We return a MonoType* as handle */
6575 case MONO_TOKEN_FIELD_DEF: {
6577 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
6579 *handle_class = mono_defaults.fieldhandle_class;
6580 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
6583 mono_class_init (class);
6584 return mono_class_get_field (class, token);
6586 case MONO_TOKEN_METHOD_DEF:
6587 case MONO_TOKEN_METHOD_SPEC: {
6589 meth = mono_get_method_full (image, token, NULL, context);
6591 *handle_class = mono_defaults.methodhandle_class;
6594 case MONO_TOKEN_MEMBER_REF: {
6595 guint32 cols [MONO_MEMBERREF_SIZE];
6597 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
6598 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6599 mono_metadata_decode_blob_size (sig, &sig);
6600 if (*sig == 0x6) { /* it's a field */
6602 MonoClassField *field;
6603 field = mono_field_from_token (image, token, &klass, context);
6605 *handle_class = mono_defaults.fieldhandle_class;
6609 meth = mono_get_method_full (image, token, NULL, context);
6611 *handle_class = mono_defaults.methodhandle_class;
6616 g_warning ("Unknown token 0x%08x in ldtoken", token);
6623 * This function might need to call runtime functions so it can't be part
6624 * of the metadata library.
6626 static MonoLookupDynamicToken lookup_dynamic = NULL;
6629 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
6631 lookup_dynamic = func;
6635 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
6637 MonoClass *handle_class;
6639 return lookup_dynamic (image, token, TRUE, &handle_class, context);
6643 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
6645 return lookup_dynamic (image, token, valid_token, handle_class, context);
6648 static MonoGetCachedClassInfo get_cached_class_info = NULL;
6651 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
6653 get_cached_class_info = func;
6657 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
6659 if (!get_cached_class_info)
6662 return get_cached_class_info (klass, res);
6666 mono_install_get_class_from_name (MonoGetClassFromName func)
6668 get_class_from_name = func;
6672 mono_class_get_image (MonoClass *klass)
6674 return klass->image;
6678 * mono_class_get_element_class:
6679 * @klass: the MonoClass to act on
6681 * Returns: the element class of an array or an enumeration.
6684 mono_class_get_element_class (MonoClass *klass)
6686 return klass->element_class;
6690 * mono_class_is_valuetype:
6691 * @klass: the MonoClass to act on
6693 * Returns: true if the MonoClass represents a ValueType.
6696 mono_class_is_valuetype (MonoClass *klass)
6698 return klass->valuetype;
6702 * mono_class_is_enum:
6703 * @klass: the MonoClass to act on
6705 * Returns: true if the MonoClass represents an enumeration.
6708 mono_class_is_enum (MonoClass *klass)
6710 return klass->enumtype;
6714 * mono_class_enum_basetype:
6715 * @klass: the MonoClass to act on
6717 * Returns: the underlying type representation for an enumeration.
6720 mono_class_enum_basetype (MonoClass *klass)
6722 if (klass->element_class == klass)
6726 return &klass->element_class->byval_arg;
6730 * mono_class_get_parent
6731 * @klass: the MonoClass to act on
6733 * Returns: the parent class for this class.
6736 mono_class_get_parent (MonoClass *klass)
6738 return klass->parent;
6742 * mono_class_get_nesting_type;
6743 * @klass: the MonoClass to act on
6745 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
6748 mono_class_get_nesting_type (MonoClass *klass)
6750 return klass->nested_in;
6754 * mono_class_get_rank:
6755 * @klass: the MonoClass to act on
6757 * Returns: the rank for the array (the number of dimensions).
6760 mono_class_get_rank (MonoClass *klass)
6766 * mono_class_get_flags:
6767 * @klass: the MonoClass to act on
6769 * The type flags from the TypeDef table from the metadata.
6770 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
6773 * Returns: the flags from the TypeDef table.
6776 mono_class_get_flags (MonoClass *klass)
6778 return klass->flags;
6782 * mono_class_get_name
6783 * @klass: the MonoClass to act on
6785 * Returns: the name of the class.
6788 mono_class_get_name (MonoClass *klass)
6794 * mono_class_get_namespace:
6795 * @klass: the MonoClass to act on
6797 * Returns: the namespace of the class.
6800 mono_class_get_namespace (MonoClass *klass)
6802 return klass->name_space;
6806 * mono_class_get_type:
6807 * @klass: the MonoClass to act on
6809 * This method returns the internal Type representation for the class.
6811 * Returns: the MonoType from the class.
6814 mono_class_get_type (MonoClass *klass)
6816 return &klass->byval_arg;
6820 * mono_class_get_type_token
6821 * @klass: the MonoClass to act on
6823 * This method returns type token for the class.
6825 * Returns: the type token for the class.
6828 mono_class_get_type_token (MonoClass *klass)
6830 return klass->type_token;
6834 * mono_class_get_byref_type:
6835 * @klass: the MonoClass to act on
6840 mono_class_get_byref_type (MonoClass *klass)
6842 return &klass->this_arg;
6846 * mono_class_num_fields:
6847 * @klass: the MonoClass to act on
6849 * Returns: the number of static and instance fields in the class.
6852 mono_class_num_fields (MonoClass *klass)
6854 return klass->field.count;
6858 * mono_class_num_methods:
6859 * @klass: the MonoClass to act on
6861 * Returns: the number of methods in the class.
6864 mono_class_num_methods (MonoClass *klass)
6866 return klass->method.count;
6870 * mono_class_num_properties
6871 * @klass: the MonoClass to act on
6873 * Returns: the number of properties in the class.
6876 mono_class_num_properties (MonoClass *klass)
6878 mono_class_setup_properties (klass);
6880 return klass->ext->property.count;
6884 * mono_class_num_events:
6885 * @klass: the MonoClass to act on
6887 * Returns: the number of events in the class.
6890 mono_class_num_events (MonoClass *klass)
6892 mono_class_setup_events (klass);
6894 return klass->ext->event.count;
6898 * mono_class_get_fields:
6899 * @klass: the MonoClass to act on
6901 * This routine is an iterator routine for retrieving the fields in a class.
6903 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6904 * iterate over all of the elements. When no more values are
6905 * available, the return value is NULL.
6907 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
6910 mono_class_get_fields (MonoClass* klass, gpointer *iter)
6912 MonoClassField* field;
6916 mono_class_setup_fields_locking (klass);
6917 if (klass->exception_type)
6919 /* start from the first */
6920 if (klass->field.count) {
6921 return *iter = &klass->fields [0];
6929 if (field < &klass->fields [klass->field.count]) {
6930 return *iter = field;
6936 * mono_class_get_methods
6937 * @klass: the MonoClass to act on
6939 * This routine is an iterator routine for retrieving the fields in a class.
6941 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6942 * iterate over all of the elements. When no more values are
6943 * available, the return value is NULL.
6945 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
6948 mono_class_get_methods (MonoClass* klass, gpointer *iter)
6950 MonoMethod** method;
6954 mono_class_init (klass);
6956 mono_class_setup_methods (klass);
6957 /* start from the first */
6958 if (klass->method.count) {
6959 *iter = &klass->methods [0];
6960 return klass->methods [0];
6968 if (method < &klass->methods [klass->method.count]) {
6976 * mono_class_get_virtual_methods:
6978 * Iterate over the virtual methods of KLASS.
6980 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
6983 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
6985 MonoMethod** method;
6988 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
6990 mono_class_setup_methods (klass);
6991 /* start from the first */
6992 method = &klass->methods [0];
6997 while (method < &klass->methods [klass->method.count]) {
6998 if (((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
7002 if (method < &klass->methods [klass->method.count]) {
7009 /* Search directly in metadata to avoid calling setup_methods () */
7010 MonoMethod *res = NULL;
7016 start_index = GPOINTER_TO_UINT (*iter);
7019 for (i = start_index; i < klass->method.count; ++i) {
7020 guint32 cols [MONO_METHOD_SIZE];
7022 /* class->method.first points into the methodptr table */
7023 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
7025 if (cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_VIRTUAL)
7029 if (i < klass->method.count) {
7030 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7031 /* Add 1 here so the if (*iter) check fails */
7032 *iter = GUINT_TO_POINTER (i + 1);
7041 * mono_class_get_properties:
7042 * @klass: the MonoClass to act on
7044 * This routine is an iterator routine for retrieving the properties in a class.
7046 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7047 * iterate over all of the elements. When no more values are
7048 * available, the return value is NULL.
7050 * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
7053 mono_class_get_properties (MonoClass* klass, gpointer *iter)
7055 MonoProperty* property;
7059 mono_class_init (klass);
7061 mono_class_setup_properties (klass);
7062 /* start from the first */
7063 if (klass->ext->property.count) {
7064 return *iter = &klass->ext->properties [0];
7072 if (property < &klass->ext->properties [klass->ext->property.count]) {
7073 return *iter = property;
7079 * mono_class_get_events:
7080 * @klass: the MonoClass to act on
7082 * This routine is an iterator routine for retrieving the properties in a class.
7084 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7085 * iterate over all of the elements. When no more values are
7086 * available, the return value is NULL.
7088 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
7091 mono_class_get_events (MonoClass* klass, gpointer *iter)
7097 mono_class_init (klass);
7099 mono_class_setup_events (klass);
7100 /* start from the first */
7101 if (klass->ext->event.count) {
7102 return *iter = &klass->ext->events [0];
7110 if (event < &klass->ext->events [klass->ext->event.count]) {
7111 return *iter = event;
7117 * mono_class_get_interfaces
7118 * @klass: the MonoClass to act on
7120 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
7122 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7123 * iterate over all of the elements. When no more values are
7124 * available, the return value is NULL.
7126 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7129 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
7136 mono_class_init (klass);
7137 if (!klass->interfaces_inited)
7138 mono_class_setup_interfaces (klass);
7139 /* start from the first */
7140 if (klass->interface_count) {
7141 *iter = &klass->interfaces [0];
7142 return klass->interfaces [0];
7150 if (iface < &klass->interfaces [klass->interface_count]) {
7158 * mono_class_get_nested_types
7159 * @klass: the MonoClass to act on
7161 * This routine is an iterator routine for retrieving the nested types of a class.
7162 * This works only if @klass is non-generic, or a generic type definition.
7164 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7165 * iterate over all of the elements. When no more values are
7166 * available, the return value is NULL.
7168 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7171 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
7179 mono_class_init (klass);
7180 if (!klass->nested_classes_inited) {
7181 if (!klass->type_token)
7182 klass->nested_classes_inited = TRUE;
7183 mono_loader_lock ();
7184 if (!klass->nested_classes_inited) {
7185 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
7188 guint32 cols [MONO_NESTED_CLASS_SIZE];
7189 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
7190 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
7191 mono_class_alloc_ext (klass);
7192 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
7194 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
7197 mono_memory_barrier ();
7198 klass->nested_classes_inited = TRUE;
7199 mono_loader_unlock ();
7203 /* start from the first */
7204 if (klass->ext && klass->ext->nested_classes) {
7205 *iter = klass->ext->nested_classes;
7206 return klass->ext->nested_classes->data;
7208 /* no nested types */
7222 * mono_field_get_name:
7223 * @field: the MonoClassField to act on
7225 * Returns: the name of the field.
7228 mono_field_get_name (MonoClassField *field)
7234 * mono_field_get_type:
7235 * @field: the MonoClassField to act on
7237 * Returns: MonoType of the field.
7240 mono_field_get_type (MonoClassField *field)
7246 * mono_field_get_parent:
7247 * @field: the MonoClassField to act on
7249 * Returns: MonoClass where the field was defined.
7252 mono_field_get_parent (MonoClassField *field)
7254 return field->parent;
7258 * mono_field_get_flags;
7259 * @field: the MonoClassField to act on
7261 * The metadata flags for a field are encoded using the
7262 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
7264 * Returns: the flags for the field.
7267 mono_field_get_flags (MonoClassField *field)
7269 return field->type->attrs;
7273 * mono_field_get_offset;
7274 * @field: the MonoClassField to act on
7276 * Returns: the field offset.
7279 mono_field_get_offset (MonoClassField *field)
7281 return field->offset;
7285 mono_field_get_rva (MonoClassField *field)
7289 MonoClass *klass = field->parent;
7291 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
7293 if (!klass->ext || !klass->ext->field_def_values) {
7294 mono_loader_lock ();
7295 mono_class_alloc_ext (klass);
7296 if (!klass->ext->field_def_values)
7297 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
7298 mono_loader_unlock ();
7301 field_index = mono_field_get_index (field);
7303 if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
7304 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
7306 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
7307 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
7310 return klass->ext->field_def_values [field_index].data;
7314 * mono_field_get_data;
7315 * @field: the MonoClassField to act on
7317 * Returns: pointer to the metadata constant value or to the field
7318 * data if it has an RVA flag.
7321 mono_field_get_data (MonoClassField *field)
7323 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
7324 MonoTypeEnum def_type;
7326 return mono_class_get_field_default_value (field, &def_type);
7327 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
7328 return mono_field_get_rva (field);
7335 * mono_property_get_name:
7336 * @prop: the MonoProperty to act on
7338 * Returns: the name of the property
7341 mono_property_get_name (MonoProperty *prop)
7347 * mono_property_get_set_method
7348 * @prop: the MonoProperty to act on.
7350 * Returns: the setter method of the property (A MonoMethod)
7353 mono_property_get_set_method (MonoProperty *prop)
7359 * mono_property_get_get_method
7360 * @prop: the MonoProperty to act on.
7362 * Returns: the setter method of the property (A MonoMethod)
7365 mono_property_get_get_method (MonoProperty *prop)
7371 * mono_property_get_parent:
7372 * @prop: the MonoProperty to act on.
7374 * Returns: the MonoClass where the property was defined.
7377 mono_property_get_parent (MonoProperty *prop)
7379 return prop->parent;
7383 * mono_property_get_flags:
7384 * @prop: the MonoProperty to act on.
7386 * The metadata flags for a property are encoded using the
7387 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
7389 * Returns: the flags for the property.
7392 mono_property_get_flags (MonoProperty *prop)
7398 * mono_event_get_name:
7399 * @event: the MonoEvent to act on
7401 * Returns: the name of the event.
7404 mono_event_get_name (MonoEvent *event)
7410 * mono_event_get_add_method:
7411 * @event: The MonoEvent to act on.
7413 * Returns: the @add' method for the event (a MonoMethod).
7416 mono_event_get_add_method (MonoEvent *event)
7422 * mono_event_get_remove_method:
7423 * @event: The MonoEvent to act on.
7425 * Returns: the @remove method for the event (a MonoMethod).
7428 mono_event_get_remove_method (MonoEvent *event)
7430 return event->remove;
7434 * mono_event_get_raise_method:
7435 * @event: The MonoEvent to act on.
7437 * Returns: the @raise method for the event (a MonoMethod).
7440 mono_event_get_raise_method (MonoEvent *event)
7442 return event->raise;
7446 * mono_event_get_parent:
7447 * @event: the MonoEvent to act on.
7449 * Returns: the MonoClass where the event is defined.
7452 mono_event_get_parent (MonoEvent *event)
7454 return event->parent;
7458 * mono_event_get_flags
7459 * @event: the MonoEvent to act on.
7461 * The metadata flags for an event are encoded using the
7462 * EVENT_* constants. See the tabledefs.h file for details.
7464 * Returns: the flags for the event.
7467 mono_event_get_flags (MonoEvent *event)
7469 return event->attrs;
7473 * mono_class_get_method_from_name:
7474 * @klass: where to look for the method
7475 * @name_space: name of the method
7476 * @param_count: number of parameters. -1 for any number.
7478 * Obtains a MonoMethod with a given name and number of parameters.
7479 * It only works if there are no multiple signatures for any given method name.
7482 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
7484 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
7488 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
7490 MonoMethod *res = NULL;
7493 /* Search directly in the metadata to avoid calling setup_methods () */
7494 for (i = 0; i < klass->method.count; ++i) {
7495 guint32 cols [MONO_METHOD_SIZE];
7498 /* class->method.first points into the methodptr table */
7499 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
7501 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
7502 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7503 if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
7514 * mono_class_get_method_from_name_flags:
7515 * @klass: where to look for the method
7516 * @name_space: name of the method
7517 * @param_count: number of parameters. -1 for any number.
7518 * @flags: flags which must be set in the method
7520 * Obtains a MonoMethod with a given name and number of parameters.
7521 * It only works if there are no multiple signatures for any given method name.
7524 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
7526 MonoMethod *res = NULL;
7529 mono_class_init (klass);
7531 if (klass->generic_class && !klass->methods) {
7532 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
7534 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
7538 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
7539 mono_class_setup_methods (klass);
7540 for (i = 0; i < klass->method.count; ++i) {
7541 MonoMethod *method = klass->methods [i];
7543 if (method->name[0] == name [0] &&
7544 !strcmp (name, method->name) &&
7545 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
7546 ((method->flags & flags) == flags)) {
7553 res = find_method_in_metadata (klass, name, param_count, flags);
7560 * mono_class_set_failure:
7561 * @klass: class in which the failure was detected
7562 * @ex_type: the kind of exception/error to be thrown (later)
7563 * @ex_data: exception data (specific to each type of exception/error)
7565 * Keep a detected failure informations in the class for later processing.
7566 * Note that only the first failure is kept.
7568 * LOCKING: Acquires the loader lock.
7571 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
7573 if (klass->exception_type)
7576 mono_loader_lock ();
7577 klass->exception_type = ex_type;
7579 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
7580 mono_loader_unlock ();
7586 * mono_class_get_exception_data:
7588 * Return the exception_data property of KLASS.
7590 * LOCKING: Acquires the loader lock.
7593 mono_class_get_exception_data (MonoClass *klass)
7595 return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
7599 * mono_classes_init:
7601 * Initialize the resources used by this module.
7604 mono_classes_init (void)
7606 mono_counters_register ("Inflated methods size",
7607 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
7608 mono_counters_register ("Inflated classes",
7609 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
7610 mono_counters_register ("Inflated classes size",
7611 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
7612 mono_counters_register ("MonoClass size",
7613 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
7614 mono_counters_register ("MonoClassExt size",
7615 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
7619 * mono_classes_cleanup:
7621 * Free the resources used by this module.
7624 mono_classes_cleanup (void)
7626 if (global_interface_bitset)
7627 mono_bitset_free (global_interface_bitset);
7631 * mono_class_get_exception_for_failure:
7632 * @klass: class in which the failure was detected
7634 * Return a constructed MonoException than the caller can then throw
7635 * using mono_raise_exception - or NULL if no failure is present (or
7636 * doesn't result in an exception).
7639 mono_class_get_exception_for_failure (MonoClass *klass)
7641 gpointer exception_data = mono_class_get_exception_data (klass);
7643 switch (klass->exception_type) {
7644 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
7645 MonoDomain *domain = mono_domain_get ();
7646 MonoSecurityManager* secman = mono_security_manager_get_methods ();
7647 MonoMethod *method = exception_data;
7648 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
7649 MonoObject *exc = NULL;
7653 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
7654 args [2] = mono_type_get_object (domain, &klass->byval_arg);
7655 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
7657 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
7658 return (MonoException*) exc;
7660 case MONO_EXCEPTION_TYPE_LOAD: {
7663 char *str = mono_type_get_full_name (klass);
7664 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
7665 name = mono_string_new (mono_domain_get (), str);
7667 ex = mono_get_exception_type_load (name, astr);
7671 case MONO_EXCEPTION_MISSING_METHOD: {
7672 char *class_name = exception_data;
7673 char *assembly_name = class_name + strlen (class_name) + 1;
7675 return mono_get_exception_missing_method (class_name, assembly_name);
7677 case MONO_EXCEPTION_MISSING_FIELD: {
7678 char *class_name = exception_data;
7679 char *member_name = class_name + strlen (class_name) + 1;
7681 return mono_get_exception_missing_field (class_name, member_name);
7683 case MONO_EXCEPTION_FILE_NOT_FOUND: {
7684 char *msg_format = exception_data;
7685 char *assembly_name = msg_format + strlen (msg_format) + 1;
7686 char *msg = g_strdup_printf (msg_format, assembly_name);
7689 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
7695 case MONO_EXCEPTION_BAD_IMAGE: {
7696 return mono_get_exception_bad_image_format (exception_data);
7699 MonoLoaderError *error;
7702 error = mono_loader_get_last_error ();
7704 ex = mono_loader_error_prepare_exception (error);
7708 /* TODO - handle other class related failures */
7715 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
7717 outer_klass = mono_class_get_generic_type_definition (outer_klass);
7718 inner_klass = mono_class_get_generic_type_definition (inner_klass);
7720 if (outer_klass == inner_klass)
7722 inner_klass = inner_klass->nested_in;
7723 } while (inner_klass);
7728 mono_class_get_generic_type_definition (MonoClass *klass)
7730 return klass->generic_class ? klass->generic_class->container_class : klass;
7734 * Check if @klass is a subtype of @parent ignoring generic instantiations.
7736 * Generic instantiations are ignored for all super types of @klass.
7738 * Visibility checks ignoring generic instantiations.
7741 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
7744 klass = mono_class_get_generic_type_definition (klass);
7745 parent = mono_class_get_generic_type_definition (parent);
7747 for (i = 0; i < klass->idepth; ++i) {
7748 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
7754 * Subtype can only access parent members with family protection if the site object
7755 * is subclass of Subtype. For example:
7756 * class A { protected int x; }
7758 * void valid_access () {
7762 * void invalid_access () {
7769 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
7771 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
7774 if (context_klass == NULL)
7776 /*if access_klass is not member_klass context_klass must be type compat*/
7777 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
7783 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
7786 if (accessing == accessed)
7788 if (!accessed || !accessing)
7790 mono_assembly_load_friends (accessed);
7791 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
7792 MonoAssemblyName *friend = tmp->data;
7793 /* Be conservative with checks */
7796 if (strcmp (accessing->aname.name, friend->name))
7798 if (friend->public_key_token [0]) {
7799 if (!accessing->aname.public_key_token [0])
7801 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
7810 * If klass is a generic type or if it is derived from a generic type, return the
7811 * MonoClass of the generic definition
7812 * Returns NULL if not found
7815 get_generic_definition_class (MonoClass *klass)
7818 if (klass->generic_class && klass->generic_class->container_class)
7819 return klass->generic_class->container_class;
7820 klass = klass->parent;
7826 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
7829 for (i = 0; i < ginst->type_argc; ++i) {
7830 MonoType *type = ginst->type_argv[i];
7831 switch (type->type) {
7832 case MONO_TYPE_SZARRAY:
7833 if (!can_access_type (access_klass, type->data.klass))
7836 case MONO_TYPE_ARRAY:
7837 if (!can_access_type (access_klass, type->data.array->eklass))
7841 if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
7844 case MONO_TYPE_CLASS:
7845 case MONO_TYPE_VALUETYPE:
7846 case MONO_TYPE_GENERICINST:
7847 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
7855 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
7859 if (access_klass->element_class && !access_klass->enumtype)
7860 access_klass = access_klass->element_class;
7862 if (member_klass->element_class && !member_klass->enumtype)
7863 member_klass = member_klass->element_class;
7865 access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
7867 if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
7870 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
7873 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
7876 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
7879 /*Non nested type with nested visibility. We just fail it.*/
7880 if (access_level >= TYPE_ATTRIBUTE_NESTED_PRIVATE && access_level <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM && member_klass->nested_in == NULL)
7883 switch (access_level) {
7884 case TYPE_ATTRIBUTE_NOT_PUBLIC:
7885 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7887 case TYPE_ATTRIBUTE_PUBLIC:
7890 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
7893 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
7894 return is_nesting_type (member_klass, access_klass);
7896 case TYPE_ATTRIBUTE_NESTED_FAMILY:
7897 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7899 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
7900 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7902 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
7903 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
7904 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7906 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
7907 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
7908 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7913 /* FIXME: check visibility of type, too */
7915 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
7917 MonoClass *member_generic_def;
7918 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
7919 access_klass->generic_container) &&
7920 (member_generic_def = get_generic_definition_class (member_klass))) {
7921 MonoClass *access_container;
7923 if (access_klass->generic_container)
7924 access_container = access_klass;
7926 access_container = access_klass->generic_class->container_class;
7928 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
7932 /* Partition I 8.5.3.2 */
7933 /* the access level values are the same for fields and methods */
7934 switch (access_level) {
7935 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
7936 /* same compilation unit */
7937 return access_klass->image == member_klass->image;
7938 case FIELD_ATTRIBUTE_PRIVATE:
7939 return access_klass == member_klass;
7940 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
7941 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
7942 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
7945 case FIELD_ATTRIBUTE_ASSEMBLY:
7946 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7947 case FIELD_ATTRIBUTE_FAMILY:
7948 if (is_valid_family_access (access_klass, member_klass, context_klass))
7951 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
7952 if (is_valid_family_access (access_klass, member_klass, context_klass))
7954 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7955 case FIELD_ATTRIBUTE_PUBLIC:
7962 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
7964 /* FIXME: check all overlapping fields */
7965 int can = can_access_member (method->klass, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7967 MonoClass *nested = method->klass->nested_in;
7969 can = can_access_member (nested, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7972 nested = nested->nested_in;
7979 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
7981 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7983 MonoClass *nested = method->klass->nested_in;
7985 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7988 nested = nested->nested_in;
7993 * with generics calls to explicit interface implementations can be expressed
7994 * directly: the method is private, but we must allow it. This may be opening
7995 * a hole or the generics code should handle this differently.
7996 * Maybe just ensure the interface type is public.
7998 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
8004 * mono_method_can_access_method_full:
8005 * @method: The caller method
8006 * @called: The called method
8007 * @context_klass: The static type on stack of the owner @called object used
8009 * This function must be used with instance calls, as they have more strict family accessibility.
8010 * It can be used with static methods, but context_klass should be NULL.
8012 * Returns: TRUE if caller have proper visibility and acessibility to @called
8015 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
8017 MonoClass *access_class = method->klass;
8018 MonoClass *member_class = called->klass;
8019 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8021 MonoClass *nested = access_class->nested_in;
8023 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8026 nested = nested->nested_in;
8033 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8036 if (called->is_inflated) {
8037 MonoMethodInflated * infl = (MonoMethodInflated*)called;
8038 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
8047 * mono_method_can_access_field_full:
8048 * @method: The caller method
8049 * @field: The accessed field
8050 * @context_klass: The static type on stack of the owner @field object used
8052 * This function must be used with instance fields, as they have more strict family accessibility.
8053 * It can be used with static fields, but context_klass should be NULL.
8055 * Returns: TRUE if caller have proper visibility and acessibility to @field
8058 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
8060 MonoClass *access_class = method->klass;
8061 MonoClass *member_class = field->parent;
8062 /* FIXME: check all overlapping fields */
8063 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8065 MonoClass *nested = access_class->nested_in;
8067 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8070 nested = nested->nested_in;
8077 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8083 * mono_type_is_valid_enum_basetype:
8084 * @type: The MonoType to check
8086 * Returns: TRUE if the type can be used as the basetype of an enum
8088 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
8089 switch (type->type) {
8092 case MONO_TYPE_BOOLEAN:
8095 case MONO_TYPE_CHAR:
8108 * mono_class_is_valid_enum:
8109 * @klass: An enum class to be validated
8111 * This method verify the required properties an enum should have.
8113 * Returns: TRUE if the informed enum class is valid
8115 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
8116 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
8117 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
8119 gboolean mono_class_is_valid_enum (MonoClass *klass) {
8120 MonoClassField * field;
8121 gpointer iter = NULL;
8122 gboolean found_base_field = FALSE;
8124 g_assert (klass->enumtype);
8125 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
8126 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
8130 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
8133 while ((field = mono_class_get_fields (klass, &iter))) {
8134 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
8135 if (found_base_field)
8137 found_base_field = TRUE;
8138 if (!mono_type_is_valid_enum_basetype (field->type))
8143 if (!found_base_field)
8146 if (klass->method.count > 0)
8153 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
8155 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
8158 static gboolean gshared_supported;
8161 mono_set_generic_sharing_supported (gboolean supported)
8163 gshared_supported = supported;
8167 * mono_class_generic_sharing_enabled:
8170 * Returns whether generic sharing is enabled for class.
8172 * This is a stop-gap measure to slowly introduce generic sharing
8173 * until we have all the issues sorted out, at which time this
8174 * function will disappear and generic sharing will always be enabled.
8177 mono_class_generic_sharing_enabled (MonoClass *class)
8179 static int generic_sharing = MONO_GENERIC_SHARING_NONE;
8180 static gboolean inited = FALSE;
8185 if (gshared_supported)
8186 generic_sharing = MONO_GENERIC_SHARING_ALL;
8188 generic_sharing = MONO_GENERIC_SHARING_NONE;
8190 if ((option = g_getenv ("MONO_GENERIC_SHARING"))) {
8191 if (strcmp (option, "corlib") == 0)
8192 generic_sharing = MONO_GENERIC_SHARING_CORLIB;
8193 else if (strcmp (option, "collections") == 0)
8194 generic_sharing = MONO_GENERIC_SHARING_COLLECTIONS;
8195 else if (strcmp (option, "all") == 0)
8196 generic_sharing = MONO_GENERIC_SHARING_ALL;
8197 else if (strcmp (option, "none") == 0)
8198 generic_sharing = MONO_GENERIC_SHARING_NONE;
8200 g_warning ("Unknown generic sharing option `%s'.", option);
8203 if (!gshared_supported)
8204 generic_sharing = MONO_GENERIC_SHARING_NONE;
8209 switch (generic_sharing) {
8210 case MONO_GENERIC_SHARING_NONE:
8212 case MONO_GENERIC_SHARING_ALL:
8214 case MONO_GENERIC_SHARING_CORLIB :
8215 return class->image == mono_defaults.corlib;
8216 case MONO_GENERIC_SHARING_COLLECTIONS:
8217 if (class->image != mono_defaults.corlib)
8219 while (class->nested_in)
8220 class = class->nested_in;
8221 return g_str_has_prefix (class->name_space, "System.Collections.Generic");
8223 g_assert_not_reached ();
8228 * mono_class_setup_interface_id:
8230 * Initializes MonoClass::interface_id if required.
8232 * LOCKING: Acquires the loader lock.
8235 mono_class_setup_interface_id (MonoClass *class)
8237 mono_loader_lock ();
8238 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
8239 class->interface_id = mono_get_unique_iid (class);
8240 mono_loader_unlock ();
8244 * mono_class_alloc_ext:
8246 * Allocate klass->ext if not already done.
8247 * LOCKING: Assumes the loader lock is held.
8250 mono_class_alloc_ext (MonoClass *klass)
8253 if (klass->generic_class) {
8254 klass->ext = g_new0 (MonoClassExt, 1);
8256 klass->ext = mono_image_alloc0 (klass->image, sizeof (MonoClassExt));
8258 class_ext_size += sizeof (MonoClassExt);
8263 * mono_class_setup_interfaces:
8265 * Initialize class->interfaces/interfaces_count.
8266 * LOCKING: Acquires the loader lock.
8269 mono_class_setup_interfaces (MonoClass *klass)
8273 if (klass->interfaces_inited)
8276 mono_loader_lock ();
8278 if (klass->interfaces_inited) {
8279 mono_loader_unlock ();
8283 if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
8286 /* generic IList, ICollection, IEnumerable */
8287 klass->interface_count = 1;
8288 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
8290 args [0] = &klass->element_class->byval_arg;
8291 klass->interfaces [0] = mono_class_bind_generic_parameters (
8292 mono_defaults.generic_ilist_class, 1, args, FALSE);
8293 } else if (klass->generic_class) {
8294 MonoClass *gklass = klass->generic_class->container_class;
8296 klass->interface_count = gklass->interface_count;
8297 klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
8298 for (i = 0; i < klass->interface_count; i++)
8299 klass->interfaces [i] = mono_class_inflate_generic_class (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class));
8302 mono_memory_barrier ();
8304 klass->interfaces_inited = TRUE;
8306 mono_loader_unlock ();