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 class->instance_size += class->parent->instance_size;
1158 class->min_align = class->parent->min_align;
1159 /* we use |= since it may have been set already */
1160 class->has_references |= class->parent->has_references;
1161 blittable = class->parent->blittable;
1163 class->instance_size = sizeof (MonoObject);
1164 class->min_align = 1;
1167 /* We can't really enable 16 bytes alignment until the GC supports it.
1168 The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
1169 boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
1170 Bug #506144 is an example of this issue.
1172 if (class->simd_type)
1173 class->min_align = 16;
1175 /* Get the real size */
1176 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1178 if (explicit_size) {
1179 g_assert ((packing_size & 0xfffffff0) == 0);
1180 class->packing_size = packing_size;
1181 real_size += class->instance_size;
1185 if (explicit_size && real_size) {
1186 class->instance_size = MAX (real_size, class->instance_size);
1188 class->size_inited = 1;
1189 class->blittable = blittable;
1193 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1196 /* Prevent infinite loops if the class references itself */
1197 class->size_inited = 1;
1199 class->fields = mono_image_alloc0 (class->image, sizeof (MonoClassField) * top);
1201 if (class->generic_container) {
1202 container = class->generic_container;
1204 container = gtd->generic_container;
1205 g_assert (container);
1209 * Fetch all the field information.
1211 for (i = 0; i < top; i++){
1212 int idx = class->field.first + i;
1213 field = &class->fields [i];
1215 field->parent = class;
1218 MonoClassField *gfield = >d->fields [i];
1220 field->name = mono_field_get_name (gfield);
1221 /*This memory must come from the image mempool as we don't have a chance to free it.*/
1222 field->type = mono_class_inflate_generic_type_no_copy (class->image, gfield->type, mono_class_get_context (class));
1223 g_assert (field->type->attrs == gfield->type->attrs);
1224 if (mono_field_is_deleted (field))
1226 field->offset = gfield->offset;
1229 guint32 cols [MONO_FIELD_SIZE];
1231 /* class->field.first and idx points into the fieldptr table */
1232 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1233 /* The name is needed for fieldrefs */
1234 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
1235 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL)) {
1236 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1239 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1240 mono_metadata_decode_value (sig, &sig);
1241 /* FIELD signature == 0x06 */
1242 g_assert (*sig == 0x06);
1243 field->type = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1245 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1248 if (mono_field_is_deleted (field))
1250 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1252 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1253 field->offset = offset;
1254 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1255 g_warning ("%s not initialized correctly (missing field layout info for %s)",
1256 class->name, mono_field_get_name (field));
1260 /* Only do these checks if we still think this type is blittable */
1261 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1262 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1265 MonoClass *field_class = mono_class_from_mono_type (field->type);
1267 mono_class_setup_fields (field_class);
1268 if (!field_class || !field_class->blittable)
1273 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1274 class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1275 blittable = class->element_class->blittable;
1278 /* The def_value of fields is compute lazily during vtable creation */
1281 if (class == mono_defaults.string_class)
1284 class->blittable = blittable;
1286 if (class->enumtype && !mono_class_enum_basetype (class)) {
1287 if (!((strcmp (class->name, "Enum") == 0) && (strcmp (class->name_space, "System") == 0)))
1290 if (explicit_size && real_size) {
1291 class->instance_size = MAX (real_size, class->instance_size);
1294 if (class->exception_type)
1296 mono_class_layout_fields (class);
1300 * mono_class_setup_fields_locking:
1301 * @class: The class to initialize
1303 * Initializes the class->fields array of fields.
1304 * Aquires the loader lock.
1307 mono_class_setup_fields_locking (MonoClass *class)
1309 mono_loader_lock ();
1310 mono_class_setup_fields (class);
1311 mono_loader_unlock ();
1315 * mono_class_has_references:
1317 * Returns whenever @klass->has_references is set, initializing it if needed.
1318 * Aquires the loader lock.
1321 mono_class_has_references (MonoClass *klass)
1323 if (klass->init_pending) {
1324 /* Be conservative */
1327 mono_class_init (klass);
1329 return klass->has_references;
1333 /* useful until we keep track of gc-references in corlib etc. */
1335 #define IS_GC_REFERENCE(t) FALSE
1337 #define IS_GC_REFERENCE(t) ((t)->type == MONO_TYPE_U && class->image == mono_defaults.corlib)
1341 * mono_type_get_basic_type_from_generic:
1344 * Returns a closed type corresponding to the possibly open type
1348 mono_type_get_basic_type_from_generic (MonoType *type)
1350 /* When we do generic sharing we let type variables stand for reference types. */
1351 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1352 return &mono_defaults.object_class->byval_arg;
1357 * mono_class_layout_fields:
1360 * Compute the placement of fields inside an object or struct, according to
1361 * the layout rules and set the following fields in @class:
1362 * - has_references (if the class contains instance references firled or structs that contain references)
1363 * - has_static_refs (same, but for static fields)
1364 * - instance_size (size of the object in memory)
1365 * - class_size (size needed for the static fields)
1366 * - size_inited (flag set when the instance_size is set)
1368 * LOCKING: this is supposed to be called with the loader lock held.
1371 mono_class_layout_fields (MonoClass *class)
1374 const int top = class->field.count;
1375 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1376 guint32 pass, passes, real_size;
1377 gboolean gc_aware_layout = FALSE;
1378 MonoClassField *field;
1381 * When we do generic sharing we need to have layout
1382 * information for open generic classes (either with a generic
1383 * context containing type variables or with a generic
1384 * container), so we don't return in that case anymore.
1388 * Enable GC aware auto layout: in this mode, reference
1389 * fields are grouped together inside objects, increasing collector
1391 * Requires that all classes whose layout is known to native code be annotated
1392 * with [StructLayout (LayoutKind.Sequential)]
1393 * Value types have gc_aware_layout disabled by default, as per
1394 * what the default is for other runtimes.
1396 /* corlib is missing [StructLayout] directives in many places */
1397 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1398 if (class->image != mono_defaults.corlib &&
1399 class->byval_arg.type != MONO_TYPE_VALUETYPE)
1400 gc_aware_layout = TRUE;
1401 /* from System.dll, used in metadata/process.h */
1402 if (strcmp (class->name, "ProcessStartInfo") == 0)
1403 gc_aware_layout = FALSE;
1406 /* Compute klass->has_references */
1408 * Process non-static fields first, since static fields might recursively
1409 * refer to the class itself.
1411 for (i = 0; i < top; i++) {
1414 field = &class->fields [i];
1416 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1417 ftype = mono_type_get_underlying_type (field->type);
1418 ftype = mono_type_get_basic_type_from_generic (ftype);
1419 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1420 class->has_references = TRUE;
1424 for (i = 0; i < top; i++) {
1427 field = &class->fields [i];
1429 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1430 ftype = mono_type_get_underlying_type (field->type);
1431 ftype = mono_type_get_basic_type_from_generic (ftype);
1432 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1433 class->has_static_refs = TRUE;
1437 for (i = 0; i < top; i++) {
1440 field = &class->fields [i];
1442 ftype = mono_type_get_underlying_type (field->type);
1443 ftype = mono_type_get_basic_type_from_generic (ftype);
1444 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1445 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1446 class->has_static_refs = TRUE;
1448 class->has_references = TRUE;
1453 * Compute field layout and total size (not considering static fields)
1457 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1458 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1460 if (gc_aware_layout)
1465 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1469 real_size = class->parent->instance_size;
1471 real_size = sizeof (MonoObject);
1473 for (pass = 0; pass < passes; ++pass) {
1474 for (i = 0; i < top; i++){
1479 field = &class->fields [i];
1481 if (mono_field_is_deleted (field))
1483 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1486 ftype = mono_type_get_underlying_type (field->type);
1487 ftype = mono_type_get_basic_type_from_generic (ftype);
1488 if (gc_aware_layout) {
1489 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1498 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1499 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1500 /* This field is a hack inserted by MCS to empty structures */
1504 size = mono_type_size (field->type, &align);
1506 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1507 align = class->packing_size ? MIN (class->packing_size, align): align;
1508 /* if the field has managed references, we need to force-align it
1511 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1512 align = MAX (align, sizeof (gpointer));
1514 class->min_align = MAX (align, class->min_align);
1515 field->offset = real_size;
1516 field->offset += align - 1;
1517 field->offset &= ~(align - 1);
1518 real_size = field->offset + size;
1521 class->instance_size = MAX (real_size, class->instance_size);
1523 if (class->instance_size & (class->min_align - 1)) {
1524 class->instance_size += class->min_align - 1;
1525 class->instance_size &= ~(class->min_align - 1);
1529 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1531 for (i = 0; i < top; i++) {
1536 field = &class->fields [i];
1539 * There must be info about all the fields in a type if it
1540 * uses explicit layout.
1543 if (mono_field_is_deleted (field))
1545 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1548 size = mono_type_size (field->type, &align);
1549 class->min_align = MAX (align, class->min_align);
1552 * When we get here, field->offset is already set by the
1553 * loader (for either runtime fields or fields loaded from metadata).
1554 * The offset is from the start of the object: this works for both
1555 * classes and valuetypes.
1557 field->offset += sizeof (MonoObject);
1558 ftype = mono_type_get_underlying_type (field->type);
1559 ftype = mono_type_get_basic_type_from_generic (ftype);
1560 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1561 if (field->offset % sizeof (gpointer)) {
1562 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1569 real_size = MAX (real_size, size + field->offset);
1571 class->instance_size = MAX (real_size, class->instance_size);
1575 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1577 * For small structs, set min_align to at least the struct size to improve
1578 * performance, and since the JIT memset/memcpy code assumes this and generates
1579 * unaligned accesses otherwise. See #78990 for a testcase.
1581 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1582 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1585 class->size_inited = 1;
1588 * Compute static field layout and size
1590 for (i = 0; i < top; i++){
1594 field = &class->fields [i];
1596 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1598 if (mono_field_is_deleted (field))
1601 size = mono_type_size (field->type, &align);
1602 field->offset = class->sizes.class_size;
1603 field->offset += align - 1;
1604 field->offset &= ~(align - 1);
1605 class->sizes.class_size = field->offset + size;
1610 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1614 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1615 method->klass = class;
1616 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1617 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1618 method->signature = sig;
1619 method->name = name;
1622 if (name [0] == '.') {
1623 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1625 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1631 * mono_class_setup_methods:
1634 * Initializes the 'methods' array in the klass.
1635 * Calling this method should be avoided if possible since it allocates a lot
1636 * of long-living MonoMethod structures.
1637 * Methods belonging to an interface are assigned a sequential slot starting
1641 mono_class_setup_methods (MonoClass *class)
1644 MonoMethod **methods;
1649 mono_loader_lock ();
1651 if (class->methods) {
1652 mono_loader_unlock ();
1656 if (class->generic_class) {
1657 MonoClass *gklass = class->generic_class->container_class;
1659 mono_class_init (gklass);
1660 mono_class_setup_methods (gklass);
1662 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1663 class->method.count = gklass->method.count;
1664 methods = g_new0 (MonoMethod *, class->method.count + 1);
1666 for (i = 0; i < class->method.count; i++) {
1667 methods [i] = mono_class_inflate_generic_method_full (
1668 gklass->methods [i], class, mono_class_get_context (class));
1670 } else if (class->rank) {
1671 MonoMethod *amethod;
1672 MonoMethodSignature *sig;
1673 int count_generic = 0, first_generic = 0;
1676 class->method.count = 3 + (class->rank > 1? 2: 1);
1678 mono_class_setup_interfaces (class);
1680 if (class->interface_count) {
1681 count_generic = generic_array_methods (class);
1682 first_generic = class->method.count;
1683 class->method.count += class->interface_count * count_generic;
1686 methods = mono_image_alloc0 (class->image, sizeof (MonoMethod*) * class->method.count);
1688 sig = mono_metadata_signature_alloc (class->image, class->rank);
1689 sig->ret = &mono_defaults.void_class->byval_arg;
1690 sig->pinvoke = TRUE;
1691 sig->hasthis = TRUE;
1692 for (i = 0; i < class->rank; ++i)
1693 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1695 amethod = create_array_method (class, ".ctor", sig);
1696 methods [method_num++] = amethod;
1697 if (class->rank > 1) {
1698 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1699 sig->ret = &mono_defaults.void_class->byval_arg;
1700 sig->pinvoke = TRUE;
1701 sig->hasthis = TRUE;
1702 for (i = 0; i < class->rank * 2; ++i)
1703 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1705 amethod = create_array_method (class, ".ctor", sig);
1706 methods [method_num++] = amethod;
1708 /* element Get (idx11, [idx2, ...]) */
1709 sig = mono_metadata_signature_alloc (class->image, class->rank);
1710 sig->ret = &class->element_class->byval_arg;
1711 sig->pinvoke = TRUE;
1712 sig->hasthis = TRUE;
1713 for (i = 0; i < class->rank; ++i)
1714 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1715 amethod = create_array_method (class, "Get", sig);
1716 methods [method_num++] = amethod;
1717 /* element& Address (idx11, [idx2, ...]) */
1718 sig = mono_metadata_signature_alloc (class->image, class->rank);
1719 sig->ret = &class->element_class->this_arg;
1720 sig->pinvoke = TRUE;
1721 sig->hasthis = TRUE;
1722 for (i = 0; i < class->rank; ++i)
1723 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1724 amethod = create_array_method (class, "Address", sig);
1725 methods [method_num++] = amethod;
1726 /* void Set (idx11, [idx2, ...], element) */
1727 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1728 sig->ret = &mono_defaults.void_class->byval_arg;
1729 sig->pinvoke = TRUE;
1730 sig->hasthis = TRUE;
1731 for (i = 0; i < class->rank; ++i)
1732 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1733 sig->params [i] = &class->element_class->byval_arg;
1734 amethod = create_array_method (class, "Set", sig);
1735 methods [method_num++] = amethod;
1737 for (i = 0; i < class->interface_count; i++)
1738 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1740 methods = mono_image_alloc (class->image, sizeof (MonoMethod*) * class->method.count);
1741 for (i = 0; i < class->method.count; ++i) {
1742 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1743 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1747 if (MONO_CLASS_IS_INTERFACE (class)) {
1749 /*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
1750 for (i = 0; i < class->method.count; ++i) {
1751 if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
1752 methods [i]->slot = slot++;
1756 /* Needed because of the double-checking locking pattern */
1757 mono_memory_barrier ();
1759 class->methods = methods;
1761 if (mono_debugger_class_loaded_methods_func)
1762 mono_debugger_class_loaded_methods_func (class);
1764 mono_loader_unlock ();
1768 * mono_class_get_method_by_index:
1770 * Returns class->methods [index], initializing class->methods if neccesary.
1772 * LOCKING: Acquires the loader lock.
1775 mono_class_get_method_by_index (MonoClass *class, int index)
1777 /* Avoid calling setup_methods () if possible */
1778 if (class->generic_class && !class->methods) {
1779 MonoClass *gklass = class->generic_class->container_class;
1782 m = mono_class_inflate_generic_method_full (
1783 gklass->methods [index], class, mono_class_get_context (class));
1785 * If setup_methods () is called later for this class, no duplicates are created,
1786 * since inflate_generic_method guarantees that only one instance of a method
1787 * is created for each context.
1790 mono_class_setup_methods (class);
1791 g_assert (m == class->methods [index]);
1795 mono_class_setup_methods (class);
1796 g_assert (index >= 0 && index < class->method.count);
1797 return class->methods [index];
1802 * mono_class_get_inflated_method:
1804 * Given an inflated class CLASS and a method METHOD which should be a method of
1805 * CLASS's generic definition, return the inflated method corresponding to METHOD.
1808 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
1810 MonoClass *gklass = class->generic_class->container_class;
1813 mono_class_setup_methods (gklass);
1814 for (i = 0; i < gklass->method.count; ++i) {
1815 if (gklass->methods [i] == method) {
1817 return class->methods [i];
1819 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
1827 * mono_class_get_vtable_entry:
1829 * Returns class->vtable [offset], computing it if neccesary.
1830 * LOCKING: Acquires the loader lock.
1833 mono_class_get_vtable_entry (MonoClass *class, int offset)
1837 if (class->rank == 1) {
1839 * szarrays do not overwrite any methods of Array, so we can avoid
1840 * initializing their vtables in some cases.
1842 mono_class_setup_vtable (class->parent);
1843 if (offset < class->parent->vtable_size)
1844 return class->parent->vtable [offset];
1847 if (class->generic_class) {
1848 MonoClass *gklass = class->generic_class->container_class;
1849 mono_class_setup_vtable (gklass);
1850 m = gklass->vtable [offset];
1852 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
1854 mono_class_setup_vtable (class);
1855 m = class->vtable [offset];
1862 * mono_class_get_vtable_size:
1864 * Return the vtable size for KLASS.
1867 mono_class_get_vtable_size (MonoClass *klass)
1869 mono_class_setup_vtable (klass);
1871 return klass->vtable_size;
1875 mono_class_setup_properties (MonoClass *class)
1877 guint startm, endm, i, j;
1878 guint32 cols [MONO_PROPERTY_SIZE];
1879 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1880 MonoProperty *properties;
1883 if (class->ext && class->ext->properties)
1886 mono_loader_lock ();
1888 if (class->ext && class->ext->properties) {
1889 mono_loader_unlock ();
1893 mono_class_alloc_ext (class);
1895 if (class->generic_class) {
1896 MonoClass *gklass = class->generic_class->container_class;
1898 mono_class_init (gklass);
1899 mono_class_setup_properties (gklass);
1901 class->ext->property = gklass->ext->property;
1903 properties = g_new0 (MonoProperty, class->ext->property.count + 1);
1905 for (i = 0; i < class->ext->property.count; i++) {
1906 MonoProperty *prop = &properties [i];
1908 *prop = gklass->ext->properties [i];
1911 prop->get = mono_class_inflate_generic_method_full (
1912 prop->get, class, mono_class_get_context (class));
1914 prop->set = mono_class_inflate_generic_method_full (
1915 prop->set, class, mono_class_get_context (class));
1917 prop->parent = class;
1920 class->ext->property.first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
1921 class->ext->property.count = last - class->ext->property.first;
1923 if (class->ext->property.count)
1924 mono_class_setup_methods (class);
1926 properties = mono_image_alloc0 (class->image, sizeof (MonoProperty) * class->ext->property.count);
1927 for (i = class->ext->property.first; i < last; ++i) {
1928 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
1929 properties [i - class->ext->property.first].parent = class;
1930 properties [i - class->ext->property.first].attrs = cols [MONO_PROPERTY_FLAGS];
1931 properties [i - class->ext->property.first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
1933 startm = mono_metadata_methods_from_property (class->image, i, &endm);
1934 for (j = startm; j < endm; ++j) {
1937 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
1939 if (class->image->uncompressed_metadata)
1940 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
1941 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
1943 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
1945 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1946 case METHOD_SEMANTIC_SETTER:
1947 properties [i - class->ext->property.first].set = method;
1949 case METHOD_SEMANTIC_GETTER:
1950 properties [i - class->ext->property.first].get = method;
1958 /*Flush any pending writes as we do double checked locking on class->properties */
1959 mono_memory_barrier ();
1961 /* Leave this assignment as the last op in the function */
1962 class->ext->properties = properties;
1964 mono_loader_unlock ();
1968 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
1970 MonoMethod **om, **retval;
1973 for (om = methods, count = 0; *om; ++om, ++count)
1976 retval = g_new0 (MonoMethod*, count + 1);
1978 for (om = methods, count = 0; *om; ++om, ++count)
1979 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
1985 mono_class_setup_events (MonoClass *class)
1987 guint startm, endm, i, j;
1988 guint32 cols [MONO_EVENT_SIZE];
1989 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
1993 if (class->ext && class->ext->events)
1996 mono_loader_lock ();
1998 if (class->ext && class->ext->events) {
1999 mono_loader_unlock ();
2003 mono_class_alloc_ext (class);
2005 if (class->generic_class) {
2006 MonoClass *gklass = class->generic_class->container_class;
2007 MonoGenericContext *context;
2009 mono_class_setup_events (gklass);
2010 class->ext->event = gklass->ext->event;
2012 class->ext->events = g_new0 (MonoEvent, class->ext->event.count);
2014 if (class->ext->event.count)
2015 context = mono_class_get_context (class);
2017 for (i = 0; i < class->ext->event.count; i++) {
2018 MonoEvent *event = &class->ext->events [i];
2019 MonoEvent *gevent = &gklass->ext->events [i];
2021 event->parent = class;
2022 event->name = gevent->name;
2023 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
2024 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
2025 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
2026 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
2027 event->attrs = gevent->attrs;
2030 mono_loader_unlock ();
2034 class->ext->event.first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2035 class->ext->event.count = last - class->ext->event.first;
2037 if (class->ext->event.count)
2038 mono_class_setup_methods (class);
2040 events = mono_image_alloc0 (class->image, sizeof (MonoEvent) * class->ext->event.count);
2041 for (i = class->ext->event.first; i < last; ++i) {
2042 MonoEvent *event = &events [i - class->ext->event.first];
2044 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
2045 event->parent = class;
2046 event->attrs = cols [MONO_EVENT_FLAGS];
2047 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
2049 startm = mono_metadata_methods_from_event (class->image, i, &endm);
2050 for (j = startm; j < endm; ++j) {
2053 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2055 if (class->image->uncompressed_metadata)
2056 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2057 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2059 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2061 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2062 case METHOD_SEMANTIC_ADD_ON:
2063 event->add = method;
2065 case METHOD_SEMANTIC_REMOVE_ON:
2066 event->remove = method;
2068 case METHOD_SEMANTIC_FIRE:
2069 event->raise = method;
2071 case METHOD_SEMANTIC_OTHER: {
2074 if (event->other == NULL) {
2075 event->other = g_new0 (MonoMethod*, 2);
2077 while (event->other [n])
2079 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
2081 event->other [n] = method;
2082 /* NULL terminated */
2083 event->other [n + 1] = NULL;
2091 /*Flush any pending writes as we do double checked locking on class->properties */
2092 mono_memory_barrier ();
2094 /* Leave this assignment as the last op in the function */
2095 class->ext->events = events;
2097 mono_loader_unlock ();
2101 * Global pool of interface IDs, represented as a bitset.
2102 * LOCKING: this is supposed to be accessed with the loader lock held.
2104 static MonoBitSet *global_interface_bitset = NULL;
2107 * mono_unload_interface_ids:
2108 * @bitset: bit set of interface IDs
2110 * When an image is unloaded, the interface IDs associated with
2111 * the image are put back in the global pool of IDs so the numbers
2115 mono_unload_interface_ids (MonoBitSet *bitset)
2117 mono_loader_lock ();
2118 mono_bitset_sub (global_interface_bitset, bitset);
2119 mono_loader_unlock ();
2123 * mono_get_unique_iid:
2126 * Assign a unique integer ID to the interface represented by @class.
2127 * The ID will positive and as small as possible.
2128 * LOCKING: this is supposed to be called with the loader lock held.
2129 * Returns: the new ID.
2132 mono_get_unique_iid (MonoClass *class)
2136 g_assert (MONO_CLASS_IS_INTERFACE (class));
2138 if (!global_interface_bitset) {
2139 global_interface_bitset = mono_bitset_new (128, 0);
2142 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2144 int old_size = mono_bitset_size (global_interface_bitset);
2145 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2146 mono_bitset_free (global_interface_bitset);
2147 global_interface_bitset = new_set;
2150 mono_bitset_set (global_interface_bitset, iid);
2151 /* set the bit also in the per-image set */
2152 if (class->image->interface_bitset) {
2153 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2154 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2155 mono_bitset_free (class->image->interface_bitset);
2156 class->image->interface_bitset = new_set;
2159 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2161 mono_bitset_set (class->image->interface_bitset, iid);
2163 if (mono_print_vtable) {
2165 char *type_name = mono_type_full_name (&class->byval_arg);
2166 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2167 generic_id = class->generic_class->context.class_inst->id;
2168 g_assert (generic_id != 0);
2172 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2176 g_assert (iid <= 65535);
2181 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res)
2186 mono_class_setup_interfaces (klass);
2188 for (i = 0; i < klass->interface_count; i++) {
2189 ic = klass->interfaces [i];
2192 *res = g_ptr_array_new ();
2193 g_ptr_array_add (*res, ic);
2194 mono_class_init (ic);
2196 collect_implemented_interfaces_aux (ic, res);
2201 mono_class_get_implemented_interfaces (MonoClass *klass)
2203 GPtrArray *res = NULL;
2205 collect_implemented_interfaces_aux (klass, &res);
2210 compare_interface_ids (const void *p_key, const void *p_element) {
2211 const MonoClass *key = p_key;
2212 const MonoClass *element = *(MonoClass**) p_element;
2214 return (key->interface_id - element->interface_id);
2218 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2219 MonoClass **result = bsearch (
2221 klass->interfaces_packed,
2222 klass->interface_offsets_count,
2223 sizeof (MonoClass *),
2224 compare_interface_ids);
2226 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2233 print_implemented_interfaces (MonoClass *klass) {
2234 GPtrArray *ifaces = NULL;
2236 int ancestor_level = 0;
2238 printf ("Packed interface table for class %s has size %d\n", klass->name, klass->interface_offsets_count);
2239 for (i = 0; i < klass->interface_offsets_count; i++)
2240 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2241 klass->interfaces_packed [i]->interface_id,
2242 klass->interface_offsets_packed [i],
2243 klass->interfaces_packed [i]->method.count,
2244 klass->interfaces_packed [i]->name_space,
2245 klass->interfaces_packed [i]->name );
2246 printf ("Interface flags: ");
2247 for (i = 0; i <= klass->max_interface_id; i++)
2248 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2249 printf ("(%d,T)", i);
2251 printf ("(%d,F)", i);
2253 printf ("Dump interface flags:");
2254 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2255 printf (" %02X", klass->interface_bitmap [i]);
2257 while (klass != NULL) {
2258 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2259 ifaces = mono_class_get_implemented_interfaces (klass);
2261 for (i = 0; i < ifaces->len; i++) {
2262 MonoClass *ic = g_ptr_array_index (ifaces, i);
2263 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2264 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2266 mono_class_interface_offset (klass, ic),
2271 g_ptr_array_free (ifaces, TRUE);
2274 klass = klass->parent;
2279 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2282 args [0] = &arg0->byval_arg;
2284 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2288 array_class_get_if_rank (MonoClass *class, guint rank)
2290 return rank ? mono_array_class_get (class, rank) : class;
2294 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2296 valuetype_types [0] = eclass;
2297 if (eclass == mono_defaults.int16_class)
2298 valuetype_types [1] = mono_defaults.uint16_class;
2299 else if (eclass == mono_defaults.uint16_class)
2300 valuetype_types [1] = mono_defaults.int16_class;
2301 else if (eclass == mono_defaults.int32_class)
2302 valuetype_types [1] = mono_defaults.uint32_class;
2303 else if (eclass == mono_defaults.uint32_class)
2304 valuetype_types [1] = mono_defaults.int32_class;
2305 else if (eclass == mono_defaults.int64_class)
2306 valuetype_types [1] = mono_defaults.uint64_class;
2307 else if (eclass == mono_defaults.uint64_class)
2308 valuetype_types [1] = mono_defaults.int64_class;
2309 else if (eclass == mono_defaults.byte_class)
2310 valuetype_types [1] = mono_defaults.sbyte_class;
2311 else if (eclass == mono_defaults.sbyte_class)
2312 valuetype_types [1] = mono_defaults.byte_class;
2313 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2314 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2317 /* this won't be needed once bug #325495 is completely fixed
2318 * though we'll need something similar to know which interfaces to allow
2319 * in arrays when they'll be lazyly created
2321 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2322 * MS returns diferrent types based on which instance is called. For example:
2323 * object obj = new byte[10][];
2324 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2325 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2328 * Fixing this should kill quite some code, save some bits and improve compatibility.
2331 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2333 MonoClass *eclass = class->element_class;
2334 static MonoClass* generic_icollection_class = NULL;
2335 static MonoClass* generic_ienumerable_class = NULL;
2336 static MonoClass* generic_ienumerator_class = NULL;
2337 MonoClass *valuetype_types[2] = { NULL, NULL };
2338 MonoClass **interfaces = NULL;
2339 int i, interface_count, real_count, original_rank;
2341 gboolean internal_enumerator;
2342 gboolean eclass_is_valuetype;
2344 if (!mono_defaults.generic_ilist_class) {
2348 internal_enumerator = FALSE;
2349 eclass_is_valuetype = FALSE;
2350 original_rank = eclass->rank;
2351 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2352 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2354 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2356 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2357 original_rank = eclass->rank;
2358 eclass = eclass->element_class;
2359 internal_enumerator = TRUE;
2360 *is_enumerator = TRUE;
2368 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2369 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2371 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2373 if (!generic_icollection_class) {
2374 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2375 "System.Collections.Generic", "ICollection`1");
2376 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2377 "System.Collections.Generic", "IEnumerable`1");
2378 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2379 "System.Collections.Generic", "IEnumerator`1");
2382 mono_class_init (eclass);
2385 * Arrays in 2.0 need to implement a number of generic interfaces
2386 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2387 * on the element class). We collect the types needed to build the
2388 * instantiations in interfaces at intervals of 3, because 3 are
2389 * the generic interfaces needed to implement.
2391 if (eclass->valuetype) {
2392 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2394 /* IList, ICollection, IEnumerable */
2395 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2396 if (internal_enumerator) {
2398 if (valuetype_types [1])
2402 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2403 interfaces [0] = valuetype_types [0];
2404 if (valuetype_types [1])
2405 interfaces [3] = valuetype_types [1];
2407 eclass_is_valuetype = TRUE;
2410 int idepth = eclass->idepth;
2411 if (!internal_enumerator)
2413 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2414 /* we add object for interfaces and the supertypes for the other
2415 * types. The last of the supertypes is the element class itself which we
2416 * already created the explicit interfaces for (so we include it for IEnumerator
2417 * and exclude it for arrays).
2419 if (MONO_CLASS_IS_INTERFACE (eclass))
2422 interface_count += idepth;
2423 if (eclass->rank && eclass->element_class->valuetype) {
2424 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2425 if (valuetype_types [1])
2428 /* IList, ICollection, IEnumerable */
2429 interface_count *= 3;
2430 real_count = interface_count;
2431 if (internal_enumerator) {
2432 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2433 if (valuetype_types [1])
2436 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2437 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2438 interfaces [0] = mono_defaults.object_class;
2442 for (i = 0; i < idepth; i++) {
2443 mono_class_init (eclass->supertypes [i]);
2444 interfaces [j] = eclass->supertypes [i];
2448 if (all_interfaces) {
2449 for (i = 0; i < eclass->interface_offsets_count; i++) {
2450 interfaces [j] = eclass->interfaces_packed [i];
2454 for (i = 0; i < eclass->interface_count; i++) {
2455 interfaces [j] = eclass->interfaces [i];
2459 if (valuetype_types [1]) {
2460 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2465 /* instantiate the generic interfaces */
2466 for (i = 0; i < interface_count; i += 3) {
2467 MonoClass *iface = interfaces [i];
2469 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2470 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2471 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2473 if (internal_enumerator) {
2475 /* instantiate IEnumerator<iface> */
2476 for (i = 0; i < interface_count; i++) {
2477 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2479 j = interface_count;
2480 if (!eclass_is_valuetype) {
2481 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2482 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2485 for (i = 0; i < eclass->idepth; i++) {
2486 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2490 for (i = 0; i < eclass->interface_offsets_count; i++) {
2491 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2495 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2497 if (valuetype_types [1])
2498 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2502 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2503 for (i = 0; i < real_count; ++i) {
2504 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2505 g_print ("%s implements %s\n", type_name, name);
2516 find_array_interface (MonoClass *klass, const char *name)
2519 for (i = 0; i < klass->interface_count; ++i) {
2520 if (strcmp (klass->interfaces [i]->name, name) == 0)
2527 * Return the number of virtual methods.
2528 * Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
2529 * FIXME It would be nice if this information could be cached somewhere.
2532 count_virtual_methods (MonoClass *class)
2536 class = mono_class_get_generic_type_definition (class); /*We can find this information by looking at the GTD*/
2538 if (class->methods || !MONO_CLASS_HAS_STATIC_METADATA (class)) {
2539 mono_class_setup_methods (class);
2541 for (i = 0; i < class->method.count; ++i) {
2542 flags = class->methods [i]->flags;
2543 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2547 for (i = 0; i < class->method.count; ++i) {
2548 flags = mono_metadata_decode_table_row_col (class->image, MONO_TABLE_METHOD, class->method.first + i, MONO_METHOD_FLAGS);
2550 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2558 * LOCKING: this is supposed to be called with the loader lock held.
2561 setup_interface_offsets (MonoClass *class, int cur_slot)
2565 MonoClass **interfaces_full;
2566 int *interface_offsets_full;
2568 int interface_offsets_count;
2569 MonoClass **array_interfaces;
2570 int num_array_interfaces;
2571 int is_enumerator = FALSE;
2574 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
2575 * implicit interfaces have the property that they are assigned the same slot in the
2576 * vtables for compatible interfaces
2578 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
2580 /* compute maximum number of slots and maximum interface id */
2582 for (k = class; k ; k = k->parent) {
2583 for (i = 0; i < k->interface_count; i++) {
2584 ic = k->interfaces [i];
2587 mono_class_init (ic);
2589 if (max_iid < ic->interface_id)
2590 max_iid = ic->interface_id;
2592 ifaces = mono_class_get_implemented_interfaces (k);
2594 for (i = 0; i < ifaces->len; ++i) {
2595 ic = g_ptr_array_index (ifaces, i);
2596 if (max_iid < ic->interface_id)
2597 max_iid = ic->interface_id;
2599 g_ptr_array_free (ifaces, TRUE);
2602 for (i = 0; i < num_array_interfaces; ++i) {
2603 ic = array_interfaces [i];
2604 mono_class_init (ic);
2605 if (max_iid < ic->interface_id)
2606 max_iid = ic->interface_id;
2609 if (MONO_CLASS_IS_INTERFACE (class)) {
2610 if (max_iid < class->interface_id)
2611 max_iid = class->interface_id;
2613 class->max_interface_id = max_iid;
2614 /* compute vtable offset for interfaces */
2615 interfaces_full = g_malloc (sizeof (MonoClass*) * (max_iid + 1));
2616 interface_offsets_full = g_malloc (sizeof (int) * (max_iid + 1));
2618 for (i = 0; i <= max_iid; i++) {
2619 interfaces_full [i] = NULL;
2620 interface_offsets_full [i] = -1;
2623 for (k = class->parent; k ; k = k->parent) {
2624 ifaces = mono_class_get_implemented_interfaces (k);
2626 for (i = 0; i < ifaces->len; ++i) {
2628 ic = g_ptr_array_index (ifaces, i);
2630 /*Force the sharing of interface offsets between parent and subtypes.*/
2631 io = mono_class_interface_offset (k, ic);
2633 interfaces_full [ic->interface_id] = ic;
2634 interface_offsets_full [ic->interface_id] = io;
2636 g_ptr_array_free (ifaces, TRUE);
2641 ifaces = mono_class_get_implemented_interfaces (class);
2643 for (i = 0; i < ifaces->len; ++i) {
2644 ic = g_ptr_array_index (ifaces, i);
2645 if (interfaces_full [ic->interface_id] != NULL)
2647 interfaces_full [ic->interface_id] = ic;
2648 interface_offsets_full [ic->interface_id] = cur_slot;
2649 cur_slot += count_virtual_methods (ic);
2651 g_ptr_array_free (ifaces, TRUE);
2654 if (MONO_CLASS_IS_INTERFACE (class)) {
2655 interfaces_full [class->interface_id] = class;
2656 interface_offsets_full [class->interface_id] = cur_slot;
2659 if (num_array_interfaces) {
2660 if (is_enumerator) {
2661 int ienumerator_offset;
2662 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
2663 ienumerator_offset = interface_offsets_full [class->interfaces [ienumerator_idx]->interface_id];
2664 for (i = 0; i < num_array_interfaces; ++i) {
2665 ic = array_interfaces [i];
2666 interfaces_full [ic->interface_id] = ic;
2667 if (strcmp (ic->name, "IEnumerator`1") == 0)
2668 interface_offsets_full [ic->interface_id] = ienumerator_offset;
2670 g_assert_not_reached ();
2671 /*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);*/
2674 int ilist_offset, icollection_offset, ienumerable_offset;
2675 int ilist_iface_idx = find_array_interface (class, "IList`1");
2676 int icollection_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "ICollection`1");
2677 int ienumerable_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "IEnumerable`1");
2678 ilist_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interface_id];
2679 icollection_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [icollection_iface_idx]->interface_id];
2680 ienumerable_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [ienumerable_iface_idx]->interface_id];
2681 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
2682 for (i = 0; i < num_array_interfaces; ++i) {
2683 ic = array_interfaces [i];
2684 interfaces_full [ic->interface_id] = ic;
2685 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
2686 interface_offsets_full [ic->interface_id] = ilist_offset;
2687 else if (strcmp (ic->name, "ICollection`1") == 0)
2688 interface_offsets_full [ic->interface_id] = icollection_offset;
2689 else if (strcmp (ic->name, "IEnumerable`1") == 0)
2690 interface_offsets_full [ic->interface_id] = ienumerable_offset;
2692 g_assert_not_reached ();
2693 /*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);*/
2698 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2699 if (interface_offsets_full [i] != -1) {
2700 interface_offsets_count ++;
2705 * We might get called twice: once from mono_class_init () then once from
2706 * mono_class_setup_vtable ().
2708 if (class->interfaces_packed) {
2709 g_assert (class->interface_offsets_count == interface_offsets_count);
2711 class->interface_offsets_count = interface_offsets_count;
2712 class->interfaces_packed = mono_image_alloc (class->image, sizeof (MonoClass*) * interface_offsets_count);
2713 class->interface_offsets_packed = mono_image_alloc (class->image, sizeof (guint16) * interface_offsets_count);
2714 class->interface_bitmap = mono_image_alloc0 (class->image, (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0));
2715 for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
2716 if (interface_offsets_full [i] != -1) {
2717 class->interface_bitmap [i >> 3] |= (1 << (i & 7));
2718 class->interfaces_packed [interface_offsets_count] = interfaces_full [i];
2719 class->interface_offsets_packed [interface_offsets_count] = interface_offsets_full [i];
2720 /*if (num_array_interfaces)
2721 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]);*/
2722 interface_offsets_count ++;
2727 g_free (interfaces_full);
2728 g_free (interface_offsets_full);
2729 g_free (array_interfaces);
2731 //printf ("JUST DONE: ");
2732 //print_implemented_interfaces (class);
2738 * Setup interface offsets for interfaces.
2740 * - class->max_interface_id
2741 * - class->interface_offsets_count
2742 * - class->interfaces_packed
2743 * - class->interface_offsets_packed
2744 * - class->interface_bitmap
2747 mono_class_setup_interface_offsets (MonoClass *class)
2749 mono_loader_lock ();
2751 setup_interface_offsets (class, 0);
2753 mono_loader_unlock ();
2757 * mono_class_setup_vtable:
2759 * Creates the generic vtable of CLASS.
2760 * Initializes the following fields in MonoClass:
2763 * Plus all the fields initialized by setup_interface_offsets ().
2764 * If there is an error during vtable construction, class->exception_type is set.
2766 * LOCKING: Acquires the loader lock.
2769 mono_class_setup_vtable (MonoClass *class)
2771 MonoMethod **overrides;
2772 MonoGenericContext *context;
2781 if (mono_debug_using_mono_debugger ())
2782 /* The debugger currently depends on this */
2783 mono_class_setup_methods (class);
2785 if (MONO_CLASS_IS_INTERFACE (class)) {
2786 /* This sets method->slot for all methods if this is an interface */
2787 mono_class_setup_methods (class);
2791 mono_loader_lock ();
2793 if (class->vtable) {
2794 mono_loader_unlock ();
2798 mono_stats.generic_vtable_count ++;
2800 if (class->generic_class) {
2801 context = mono_class_get_context (class);
2802 type_token = class->generic_class->container_class->type_token;
2804 context = (MonoGenericContext *) class->generic_container;
2805 type_token = class->type_token;
2808 if (class->image->dynamic) {
2809 if (class->generic_class) {
2810 MonoClass *gklass = class->generic_class->container_class;
2812 mono_reflection_get_dynamic_overrides (gklass, &overrides, &onum);
2813 for (i = 0; i < onum; ++i) {
2814 MonoMethod *override = overrides [(i * 2) + 1];
2815 MonoMethod *inflated = NULL;
2818 for (j = 0; j < class->method.count; ++j) {
2819 if (gklass->methods [j] == override) {
2820 inflated = class->methods [j];
2824 g_assert (inflated);
2826 overrides [(i * 2) + 1] = inflated;
2829 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
2832 /* The following call fails if there are missing methods in the type */
2833 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
2837 mono_class_setup_vtable_general (class, overrides, onum);
2841 mono_loader_unlock ();
2846 #define DEBUG_INTERFACE_VTABLE_CODE 0
2847 #define TRACE_INTERFACE_VTABLE_CODE 0
2848 #define VERIFY_INTERFACE_VTABLE_CODE 0
2849 #define VTABLE_SELECTOR (1)
2851 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2852 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
2853 if (!(VTABLE_SELECTOR)) break; \
2857 #define DEBUG_INTERFACE_VTABLE(stmt)
2860 #if TRACE_INTERFACE_VTABLE_CODE
2861 #define TRACE_INTERFACE_VTABLE(stmt) do {\
2862 if (!(VTABLE_SELECTOR)) break; \
2866 #define TRACE_INTERFACE_VTABLE(stmt)
2869 #if VERIFY_INTERFACE_VTABLE_CODE
2870 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
2871 if (!(VTABLE_SELECTOR)) break; \
2875 #define VERIFY_INTERFACE_VTABLE(stmt)
2879 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
2881 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
2885 GString *res = g_string_new ("");
2887 g_string_append_c (res, '(');
2888 for (i = 0; i < sig->param_count; ++i) {
2890 g_string_append_c (res, ',');
2891 mono_type_get_desc (res, sig->params [i], include_namespace);
2893 g_string_append (res, ")=>");
2894 if (sig->ret != NULL) {
2895 mono_type_get_desc (res, sig->ret, include_namespace);
2897 g_string_append (res, "NULL");
2900 g_string_free (res, FALSE);
2904 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
2905 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
2906 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
2907 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
2915 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) {
2916 if (strcmp (im->name, cm->name) == 0) {
2917 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
2918 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
2921 if (! slot_is_empty) {
2922 if (require_newslot) {
2923 if (! interface_is_explicitly_implemented_by_class) {
2924 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
2927 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
2928 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
2932 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
2935 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2936 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
2937 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2938 TRACE_INTERFACE_VTABLE (printf ("]"));
2941 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
2942 /* CAS - SecurityAction.InheritanceDemand on interface */
2943 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
2944 mono_secman_inheritancedemand_method (cm, im);
2947 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
2948 mono_security_core_clr_check_override (class, cm, im);
2949 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
2952 MonoClass *ic = im->klass;
2953 const char *ic_name_space = ic->name_space;
2954 const char *ic_name = ic->name;
2957 if (! require_newslot) {
2958 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
2961 if (cm->klass->rank == 0) {
2962 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
2965 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
2966 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
2967 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
2968 TRACE_INTERFACE_VTABLE (printf ("]"));
2971 if (mono_class_get_image (ic) != mono_defaults.corlib) {
2972 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
2975 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
2976 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
2979 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
2980 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
2984 subname = strstr (cm->name, ic_name_space);
2985 if (subname != cm->name) {
2986 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
2989 subname += strlen (ic_name_space);
2990 if (subname [0] != '.') {
2991 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
2995 if (strstr (subname, ic_name) != subname) {
2996 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
2999 subname += strlen (ic_name);
3000 if (subname [0] != '.') {
3001 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
3005 if (strcmp (subname, im->name) != 0) {
3006 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
3010 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
3011 /* CAS - SecurityAction.InheritanceDemand on interface */
3012 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3013 mono_secman_inheritancedemand_method (cm, im);
3016 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3017 mono_security_core_clr_check_override (class, cm, im);
3019 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
3024 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3026 foreach_override (gpointer key, gpointer value, gpointer user_data) {
3027 MonoMethod *method = key;
3028 MonoMethod *override = value;
3029 MonoClass *method_class = mono_method_get_class (method);
3030 MonoClass *override_class = mono_method_get_class (override);
3032 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
3033 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
3034 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
3037 print_overrides (GHashTable *override_map, const char *message) {
3039 printf ("Override map \"%s\" START:\n", message);
3040 g_hash_table_foreach (override_map, foreach_override, NULL);
3041 printf ("Override map \"%s\" END.\n", message);
3043 printf ("Override map \"%s\" EMPTY.\n", message);
3047 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
3048 char *full_name = mono_type_full_name (&class->byval_arg);
3052 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
3054 if (print_interfaces) {
3055 print_implemented_interfaces (class);
3056 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
3059 if (class->parent) {
3060 parent_size = class->parent->vtable_size;
3064 for (i = 0; i < size; ++i) {
3065 MonoMethod *cm = vtable [i];
3067 char *cm_name = mono_method_full_name (cm, TRUE);
3068 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
3069 printf (" [%c][%03d][INDEX %03d] %s\n", newness, i, cm->slot, cm_name);
3078 #if VERIFY_INTERFACE_VTABLE_CODE
3080 mono_method_try_get_vtable_index (MonoMethod *method)
3082 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3083 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3084 if (imethod->declaring->is_generic)
3085 return imethod->declaring->slot;
3087 return method->slot;
3091 mono_class_verify_vtable (MonoClass *class)
3094 char *full_name = mono_type_full_name (&class->byval_arg);
3096 printf ("*** Verifying VTable of class '%s' \n", full_name);
3100 if (!class->methods)
3103 for (i = 0; i < class->method.count; ++i) {
3104 MonoMethod *cm = class->methods [i];
3107 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
3111 full_name = mono_method_full_name (cm, TRUE);
3113 slot = mono_method_try_get_vtable_index (cm);
3115 if (slot >= class->vtable_size) {
3116 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
3120 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
3121 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3122 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3123 g_free (other_name);
3126 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3133 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3135 char *method_signature;
3138 for (index = 0; index < onum; ++index) {
3139 g_print (" at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
3140 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3142 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3143 type_name = mono_type_full_name (&class->byval_arg);
3144 printf ("no implementation for interface method %s::%s(%s) in class %s\n",
3145 mono_type_get_name (&ic->byval_arg), im->name, method_signature, type_name);
3146 g_free (method_signature);
3148 mono_class_setup_methods (class);
3149 for (index = 0; index < class->method.count; ++index) {
3150 MonoMethod *cm = class->methods [index];
3151 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3153 printf ("METHOD %s(%s)\n", cm->name, method_signature);
3154 g_free (method_signature);
3159 verify_class_overrides (MonoClass *class, MonoMethod **overrides, int onum)
3163 for (i = 0; i < onum; ++i) {
3164 MonoMethod *decl = overrides [i * 2];
3165 MonoMethod *body = overrides [i * 2 + 1];
3167 if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (class)) {
3168 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method belongs to a different class than the declared one"));
3172 if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
3173 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3174 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must not be static to override a base type"));
3176 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must be virtual to override a base type"));
3180 if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
3181 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3182 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a static method in a base type"));
3184 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a non virtual method in a base type"));
3188 if (!mono_class_is_assignable_from_slow (decl->klass, class)) {
3189 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method overrides a class or interface that extended or implemented by this type"));
3196 * LOCKING: this is supposed to be called with the loader lock held.
3199 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
3202 MonoMethod **vtable;
3203 int i, max_vtsize = 0, max_iid, cur_slot = 0;
3204 GPtrArray *ifaces = NULL;
3205 GHashTable *override_map = NULL;
3206 gboolean security_enabled = mono_is_security_manager_active ();
3208 gpointer class_iter;
3209 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3210 int first_non_interface_slot;
3216 if (overrides && !verify_class_overrides (class, overrides, onum))
3219 ifaces = mono_class_get_implemented_interfaces (class);
3222 for (i = 0; i < ifaces->len; i++) {
3223 MonoClass *ic = g_ptr_array_index (ifaces, i);
3224 max_vtsize += ic->method.count;
3226 g_ptr_array_free (ifaces, TRUE);
3230 if (class->parent) {
3231 mono_class_init (class->parent);
3232 mono_class_setup_vtable (class->parent);
3233 max_vtsize += class->parent->vtable_size;
3234 cur_slot = class->parent->vtable_size;
3237 max_vtsize += class->method.count;
3239 vtable = alloca (sizeof (gpointer) * max_vtsize);
3240 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3242 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3244 cur_slot = setup_interface_offsets (class, cur_slot);
3245 max_iid = class->max_interface_id;
3246 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3248 /* Optimized version for generic instances */
3249 if (class->generic_class) {
3250 MonoClass *gklass = class->generic_class->container_class;
3253 mono_class_setup_vtable (gklass);
3254 if (gklass->exception_type != MONO_EXCEPTION_NONE) {
3255 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3259 tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * gklass->vtable_size);
3260 class->vtable_size = gklass->vtable_size;
3261 for (i = 0; i < gklass->vtable_size; ++i)
3262 if (gklass->vtable [i]) {
3263 tmp [i] = mono_class_inflate_generic_method_full (gklass->vtable [i], class, mono_class_get_context (class));
3264 tmp [i]->slot = gklass->vtable [i]->slot;
3266 mono_memory_barrier ();
3267 class->vtable = tmp;
3269 /* Have to set method->slot for abstract virtual methods */
3270 if (class->methods && gklass->methods) {
3271 for (i = 0; i < class->method.count; ++i)
3272 if (class->methods [i]->slot == -1)
3273 class->methods [i]->slot = gklass->methods [i]->slot;
3279 if (class->parent && class->parent->vtable_size) {
3280 MonoClass *parent = class->parent;
3283 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
3285 // Also inherit parent interface vtables, just as a starting point.
3286 // This is needed otherwise bug-77127.exe fails when the property methods
3287 // have different names in the iterface and the class, because for child
3288 // classes the ".override" information is not used anymore.
3289 for (i = 0; i < parent->interface_offsets_count; i++) {
3290 MonoClass *parent_interface = parent->interfaces_packed [i];
3291 int interface_offset = mono_class_interface_offset (class, parent_interface);
3292 /*FIXME this is now dead code as this condition will never hold true.
3293 Since interface offsets are inherited then the offset of an interface implemented
3294 by a parent will never be the out of it's vtable boundary.
3296 if (interface_offset >= parent->vtable_size) {
3297 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
3300 mono_class_setup_methods (parent_interface);
3301 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
3302 for (j = 0; j < parent_interface->method.count; j++) {
3303 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
3304 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
3305 parent_interface_offset + j, parent_interface_offset, j,
3306 interface_offset + j, interface_offset, j));
3313 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
3314 /* override interface methods */
3315 for (i = 0; i < onum; i++) {
3316 MonoMethod *decl = overrides [i*2];
3317 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
3319 dslot = mono_method_get_vtable_slot (decl) + mono_class_interface_offset (class, decl->klass);
3320 vtable [dslot] = overrides [i*2 + 1];
3321 vtable [dslot]->slot = dslot;
3323 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3325 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
3327 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3328 mono_security_core_clr_check_override (class, vtable [dslot], decl);
3331 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
3332 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
3334 // Loop on all implemented interfaces...
3335 for (i = 0; i < class->interface_offsets_count; i++) {
3336 MonoClass *parent = class->parent;
3338 gboolean interface_is_explicitly_implemented_by_class;
3341 ic = class->interfaces_packed [i];
3342 ic_offset = mono_class_interface_offset (class, ic);
3344 mono_class_setup_methods (ic);
3346 // Check if this interface is explicitly implemented (instead of just inherited)
3347 if (parent != NULL) {
3348 int implemented_interfaces_index;
3349 interface_is_explicitly_implemented_by_class = FALSE;
3350 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
3351 if (ic == class->interfaces [implemented_interfaces_index]) {
3352 interface_is_explicitly_implemented_by_class = TRUE;
3357 interface_is_explicitly_implemented_by_class = TRUE;
3360 // Loop on all interface methods...
3361 for (im_index = 0; im_index < ic->method.count; im_index++) {
3362 MonoMethod *im = ic->methods [im_index];
3363 int im_slot = ic_offset + im->slot;
3364 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
3366 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3369 // If there is an explicit implementation, just use it right away,
3370 // otherwise look for a matching method
3371 if (override_im == NULL) {
3376 // First look for a suitable method among the class methods
3378 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
3379 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)));
3380 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
3381 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
3382 vtable [im_slot] = cm;
3383 /* Why do we need this? */
3388 TRACE_INTERFACE_VTABLE (printf ("\n"));
3391 // If the slot is still empty, look in all the inherited virtual methods...
3392 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
3393 MonoClass *parent = class->parent;
3394 // Reverse order, so that last added methods are preferred
3395 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
3396 MonoMethod *cm = parent->vtable [cm_index];
3398 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));
3399 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
3400 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
3401 vtable [im_slot] = cm;
3402 /* Why do we need this? */
3408 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
3412 g_assert (vtable [im_slot] == override_im);
3417 // If the class is not abstract, check that all its interface slots are full.
3418 // The check is done here and not directly at the end of the loop above because
3419 // it can happen (for injected generic array interfaces) that the same slot is
3420 // processed multiple times (those interfaces have overlapping slots), and it
3421 // will not always be the first pass the one that fills the slot.
3422 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3423 for (i = 0; i < class->interface_offsets_count; i++) {
3427 ic = class->interfaces_packed [i];
3428 ic_offset = mono_class_interface_offset (class, ic);
3430 for (im_index = 0; im_index < ic->method.count; im_index++) {
3431 MonoMethod *im = ic->methods [im_index];
3432 int im_slot = ic_offset + im->slot;
3434 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3437 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
3438 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
3439 if (vtable [im_slot] == NULL) {
3440 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
3441 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3443 g_hash_table_destroy (override_map);
3450 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
3452 while ((cm = mono_class_get_virtual_methods (class, &class_iter))) {
3454 * If the method is REUSE_SLOT, we must check in the
3455 * base class for a method to override.
3457 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3459 for (k = class->parent; k ; k = k->parent) {
3464 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
3465 MonoMethodSignature *cmsig, *m1sig;
3467 cmsig = mono_method_signature (cm);
3468 m1sig = mono_method_signature (m1);
3470 if (!cmsig || !m1sig) {
3471 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3475 if (!strcmp(cm->name, m1->name) &&
3476 mono_metadata_signature_equal (cmsig, m1sig)) {
3478 /* CAS - SecurityAction.InheritanceDemand */
3479 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3480 mono_secman_inheritancedemand_method (cm, m1);
3483 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3484 mono_security_core_clr_check_override (class, cm, m1);
3486 slot = mono_method_get_vtable_slot (m1);
3487 g_assert (cm->slot < max_vtsize);
3489 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3490 g_hash_table_insert (override_map, m1, cm);
3501 /*Non final newslot methods must be given a non-interface vtable slot*/
3502 if ((cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && !(cm->flags & METHOD_ATTRIBUTE_FINAL) && cm->slot >= 0)
3506 cm->slot = cur_slot++;
3508 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
3509 vtable [cm->slot] = cm;
3512 /* override non interface methods */
3513 for (i = 0; i < onum; i++) {
3514 MonoMethod *decl = overrides [i*2];
3515 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
3516 g_assert (decl->slot != -1);
3517 vtable [decl->slot] = overrides [i*2 + 1];
3518 overrides [i * 2 + 1]->slot = decl->slot;
3520 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3521 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
3523 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3524 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
3529 * If a method occupies more than one place in the vtable, and it is
3530 * overriden, then change the other occurances too.
3533 for (i = 0; i < max_vtsize; ++i)
3535 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
3540 g_hash_table_destroy (override_map);
3543 /* Ensure that all vtable slots are filled with concrete instance methods */
3544 if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3545 for (i = 0; i < cur_slot; ++i) {
3546 if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
3547 char *type_name = mono_type_get_full_name (class);
3548 char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
3549 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));
3551 g_free (method_name);
3557 if (class->generic_class) {
3558 MonoClass *gklass = class->generic_class->container_class;
3560 mono_class_init (gklass);
3562 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
3564 /* Check that the vtable_size value computed in mono_class_init () is correct */
3565 if (class->vtable_size)
3566 g_assert (cur_slot == class->vtable_size);
3567 class->vtable_size = cur_slot;
3570 /* Try to share the vtable with our parent. */
3571 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
3572 mono_memory_barrier ();
3573 class->vtable = class->parent->vtable;
3575 MonoMethod **tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * class->vtable_size);
3576 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
3577 mono_memory_barrier ();
3578 class->vtable = tmp;
3581 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
3582 if (mono_print_vtable) {
3585 print_implemented_interfaces (class);
3587 for (i = 0; i <= max_iid; i++)
3588 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
3591 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
3592 class->vtable_size, icount);
3594 for (i = 0; i < cur_slot; ++i) {
3599 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
3600 mono_method_full_name (cm, TRUE));
3606 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
3607 class->name, max_iid);
3609 for (i = 0; i < class->interface_count; i++) {
3610 ic = class->interfaces [i];
3611 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
3612 mono_class_interface_offset (class, ic),
3613 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
3616 for (k = class->parent; k ; k = k->parent) {
3617 for (i = 0; i < k->interface_count; i++) {
3618 ic = k->interfaces [i];
3619 printf (" parent slot offset: %03d, method count: %03d, iid: %03d %s\n",
3620 mono_class_interface_offset (class, ic),
3621 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
3627 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
3631 * mono_method_get_vtable_slot:
3633 * Returns method->slot, computing it if neccesary.
3634 * LOCKING: Acquires the loader lock.
3637 mono_method_get_vtable_slot (MonoMethod *method)
3639 if (method->slot == -1) {
3640 mono_class_setup_vtable (method->klass);
3641 g_assert (method->slot != -1);
3643 return method->slot;
3647 * mono_method_get_vtable_index:
3650 * Returns the index into the runtime vtable to access the method or,
3651 * in the case of a virtual generic method, the virtual generic method
3655 mono_method_get_vtable_index (MonoMethod *method)
3657 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3658 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3659 if (imethod->declaring->is_generic)
3660 return mono_method_get_vtable_slot (imethod->declaring);
3662 return mono_method_get_vtable_slot (method);
3665 static MonoMethod *default_ghc = NULL;
3666 static MonoMethod *default_finalize = NULL;
3667 static int finalize_slot = -1;
3668 static int ghc_slot = -1;
3671 initialize_object_slots (MonoClass *class)
3676 if (class == mono_defaults.object_class) {
3677 mono_class_setup_vtable (class);
3678 for (i = 0; i < class->vtable_size; ++i) {
3679 MonoMethod *cm = class->vtable [i];
3681 if (!strcmp (cm->name, "GetHashCode"))
3683 else if (!strcmp (cm->name, "Finalize"))
3687 g_assert (ghc_slot > 0);
3688 default_ghc = class->vtable [ghc_slot];
3690 g_assert (finalize_slot > 0);
3691 default_finalize = class->vtable [finalize_slot];
3696 MonoMethod *array_method;
3698 } GenericArrayMethodInfo;
3700 static int generic_array_method_num = 0;
3701 static GenericArrayMethodInfo *generic_array_method_info = NULL;
3704 generic_array_methods (MonoClass *class)
3706 int i, count_generic = 0;
3707 GList *list = NULL, *tmp;
3708 if (generic_array_method_num)
3709 return generic_array_method_num;
3710 mono_class_setup_methods (class->parent);
3711 for (i = 0; i < class->parent->method.count; i++) {
3712 MonoMethod *m = class->parent->methods [i];
3713 if (!strncmp (m->name, "InternalArray__", 15)) {
3715 list = g_list_prepend (list, m);
3718 list = g_list_reverse (list);
3719 generic_array_method_info = g_malloc (sizeof (GenericArrayMethodInfo) * count_generic);
3721 for (tmp = list; tmp; tmp = tmp->next) {
3722 const char *mname, *iname;
3724 MonoMethod *m = tmp->data;
3725 generic_array_method_info [i].array_method = m;
3726 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
3727 iname = "System.Collections.Generic.ICollection`1.";
3728 mname = m->name + 27;
3729 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
3730 iname = "System.Collections.Generic.IEnumerable`1.";
3731 mname = m->name + 27;
3732 } else if (!strncmp (m->name, "InternalArray__", 15)) {
3733 iname = "System.Collections.Generic.IList`1.";
3734 mname = m->name + 15;
3736 g_assert_not_reached ();
3739 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
3740 strcpy (name, iname);
3741 strcpy (name + strlen (iname), mname);
3742 generic_array_method_info [i].name = name;
3745 /*g_print ("array generic methods: %d\n", count_generic);*/
3747 generic_array_method_num = count_generic;
3749 return generic_array_method_num;
3753 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
3755 MonoGenericContext tmp_context;
3758 tmp_context.class_inst = NULL;
3759 tmp_context.method_inst = iface->generic_class->context.class_inst;
3760 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
3762 for (i = 0; i < generic_array_method_num; i++) {
3763 MonoMethod *m = generic_array_method_info [i].array_method;
3764 MonoMethod *inflated;
3766 inflated = mono_class_inflate_generic_method (m, &tmp_context);
3767 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
3772 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
3774 int len = strlen (s1) + strlen (s2) + 2;
3775 char *s = mono_image_alloc (image, len);
3778 result = g_snprintf (s, len, "%s%c%s", s1, '\0', s2);
3779 g_assert (result == len - 1);
3785 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
3787 gpointer exception_data = NULL;
3789 switch (error->exception_type) {
3790 case MONO_EXCEPTION_TYPE_LOAD:
3791 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
3794 case MONO_EXCEPTION_MISSING_METHOD:
3795 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
3798 case MONO_EXCEPTION_MISSING_FIELD: {
3799 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
3800 const char *class_name;
3803 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
3805 class_name = error->klass->name;
3807 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
3810 g_free ((void*)class_name);
3814 case MONO_EXCEPTION_FILE_NOT_FOUND: {
3817 if (error->ref_only)
3818 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.";
3820 msg = "Could not load file or assembly '%s' or one of its dependencies.";
3822 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
3826 case MONO_EXCEPTION_BAD_IMAGE:
3827 exception_data = error->msg;
3831 g_assert_not_reached ();
3834 mono_class_set_failure (class, error->exception_type, exception_data);
3839 * @class: the class to initialize
3841 * Compute the instance_size, class_size and other infos that cannot be
3842 * computed at mono_class_get() time. Also compute vtable_size if possible.
3843 * Returns TRUE on success or FALSE if there was a problem in loading
3844 * the type (incorrect assemblies, missing assemblies, methods, etc).
3846 * LOCKING: Acquires the loader lock.
3849 mono_class_init (MonoClass *class)
3852 MonoCachedClassInfo cached_info;
3853 gboolean has_cached_info;
3854 int class_init_ok = TRUE;
3858 /* Double-checking locking pattern */
3860 return class->exception_type == MONO_EXCEPTION_NONE;
3862 /*g_print ("Init class %s\n", class->name);*/
3864 /* We do everything inside the lock to prevent races */
3865 mono_loader_lock ();
3867 if (class->inited) {
3868 mono_loader_unlock ();
3869 /* Somebody might have gotten in before us */
3870 return class->exception_type == MONO_EXCEPTION_NONE;
3873 if (class->init_pending) {
3874 mono_loader_unlock ();
3875 /* this indicates a cyclic dependency */
3876 g_error ("pending init %s.%s\n", class->name_space, class->name);
3879 class->init_pending = 1;
3881 if (class->byval_arg.type == MONO_TYPE_ARRAY || class->byval_arg.type == MONO_TYPE_SZARRAY) {
3882 MonoClass *element_class = class->element_class;
3883 if (!element_class->inited)
3884 mono_class_init (element_class);
3885 if (element_class->exception_type != MONO_EXCEPTION_NONE) {
3886 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3891 /* CAS - SecurityAction.InheritanceDemand */
3892 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
3893 mono_secman_inheritancedemand_class (class, class->parent);
3896 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3897 mono_security_core_clr_check_inheritance (class);
3899 mono_stats.initialized_class_count++;
3901 if (class->generic_class && !class->generic_class->is_dynamic) {
3902 MonoClass *gklass = class->generic_class->container_class;
3904 mono_stats.generic_class_count++;
3906 class->method = gklass->method;
3907 class->field = gklass->field;
3909 mono_class_init (gklass);
3910 // FIXME: Why is this needed ?
3911 mono_class_setup_methods (gklass);
3913 if (MONO_CLASS_IS_INTERFACE (class))
3914 class->interface_id = mono_get_unique_iid (class);
3917 if (class->parent && !class->parent->inited)
3918 mono_class_init (class->parent);
3920 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
3922 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
3923 class->nested_classes_inited = TRUE;
3926 * Computes the size used by the fields, and their locations
3928 if (has_cached_info) {
3929 class->instance_size = cached_info.instance_size;
3930 class->sizes.class_size = cached_info.class_size;
3931 class->packing_size = cached_info.packing_size;
3932 class->min_align = cached_info.min_align;
3933 class->blittable = cached_info.blittable;
3934 class->has_references = cached_info.has_references;
3935 class->has_static_refs = cached_info.has_static_refs;
3936 class->no_special_static_fields = cached_info.no_special_static_fields;
3939 if (!class->size_inited){
3940 mono_class_setup_fields (class);
3941 if (class->exception_type || mono_loader_get_last_error ()){
3942 class_init_ok = FALSE;
3947 /* Initialize arrays */
3949 class->method.count = 3 + (class->rank > 1? 2: 1);
3951 if (class->interface_count) {
3952 int count_generic = generic_array_methods (class);
3953 class->method.count += class->interface_count * count_generic;
3957 mono_class_setup_supertypes (class);
3960 initialize_object_slots (class);
3963 * Initialize the rest of the data without creating a generic vtable if possible.
3964 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
3965 * also avoid computing a generic vtable.
3967 if (has_cached_info) {
3969 class->vtable_size = cached_info.vtable_size;
3970 class->has_finalize = cached_info.has_finalize;
3971 class->ghcimpl = cached_info.ghcimpl;
3972 class->has_cctor = cached_info.has_cctor;
3973 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
3974 static int szarray_vtable_size = 0;
3977 if (!szarray_vtable_size) {
3978 mono_class_setup_vtable (class);
3979 szarray_vtable_size = class->vtable_size;
3981 class->vtable_size = szarray_vtable_size;
3983 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
3984 MonoClass *gklass = class->generic_class->container_class;
3986 /* Generic instance case */
3987 class->ghcimpl = gklass->ghcimpl;
3988 class->has_finalize = gklass->has_finalize;
3989 class->has_cctor = gklass->has_cctor;
3991 mono_class_setup_vtable (gklass);
3992 if (gklass->exception_type) {
3993 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3997 class->vtable_size = gklass->vtable_size;
4001 /* ghcimpl is not currently used
4003 if (class->parent) {
4004 MonoMethod *cmethod = class->vtable [ghc_slot];
4005 if (cmethod->is_inflated)
4006 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4007 if (cmethod == default_ghc) {
4013 /* Interfaces and valuetypes are not supposed to have finalizers */
4014 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
4015 MonoMethod *cmethod = NULL;
4017 if (class->parent && class->parent->has_finalize) {
4018 class->has_finalize = 1;
4020 if (class->type_token) {
4021 cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
4022 } else if (class->parent) {
4023 /* FIXME: Optimize this */
4024 mono_class_setup_vtable (class);
4025 if (class->exception_type || mono_loader_get_last_error ())
4027 cmethod = class->vtable [finalize_slot];
4031 /* Check that this is really the finalizer method */
4032 mono_class_setup_vtable (class);
4033 if (class->exception_type || mono_loader_get_last_error ())
4036 class->has_finalize = 0;
4037 if (class->parent) {
4038 cmethod = class->vtable [finalize_slot];
4039 if (cmethod->is_inflated)
4040 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4041 if (cmethod != default_finalize) {
4042 class->has_finalize = 1;
4049 /* C# doesn't allow interfaces to have cctors */
4050 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
4051 MonoMethod *cmethod = NULL;
4053 if (class->type_token) {
4054 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
4055 /* The find_method function ignores the 'flags' argument */
4056 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
4057 class->has_cctor = 1;
4059 mono_class_setup_methods (class);
4061 for (i = 0; i < class->method.count; ++i) {
4062 MonoMethod *method = class->methods [i];
4063 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4064 (strcmp (".cctor", method->name) == 0)) {
4065 class->has_cctor = 1;
4073 if (!mono_setup_vtable_in_class_init) {
4075 * This is an embedding API break, since the caller might assume that
4076 * mono_class_init () constructs a generic vtable, so vtable construction errors
4077 * are visible right after the mono_class_init (), and not after
4078 * mono_class_vtable ().
4080 if (class->parent) {
4081 /* This will compute class->parent->vtable_size for some classes */
4082 mono_class_init (class->parent);
4083 if (class->parent->exception_type) {
4084 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4087 if (mono_loader_get_last_error ())
4089 if (!class->parent->vtable_size) {
4090 /* FIXME: Get rid of this somehow */
4091 mono_class_setup_vtable (class->parent);
4092 if (class->parent->exception_type) {
4093 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4096 if (mono_loader_get_last_error ())
4099 setup_interface_offsets (class, class->parent->vtable_size);
4101 setup_interface_offsets (class, 0);
4104 mono_class_setup_vtable (class);
4106 if (MONO_CLASS_IS_INTERFACE (class))
4107 setup_interface_offsets (class, 0);
4110 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
4111 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
4112 class_init_ok = FALSE;
4118 class_init_ok = FALSE;
4121 /* Because of the double-checking locking pattern */
4122 mono_memory_barrier ();
4124 class->init_pending = 0;
4126 if (mono_loader_get_last_error ()) {
4127 if (class->exception_type == MONO_EXCEPTION_NONE)
4128 set_failure_from_loader_error (class, mono_loader_get_last_error ());
4130 mono_loader_clear_error ();
4133 mono_loader_unlock ();
4135 if (mono_debugger_class_init_func)
4136 mono_debugger_class_init_func (class);
4138 return class_init_ok;
4142 is_corlib_image (MonoImage *image)
4144 /* FIXME: allow the dynamic case for our compilers and with full trust */
4146 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
4148 return image == mono_defaults.corlib;
4152 * LOCKING: this assumes the loader lock is held
4155 mono_class_setup_mono_type (MonoClass *class)
4157 const char *name = class->name;
4158 const char *nspace = class->name_space;
4159 gboolean is_corlib = is_corlib_image (class->image);
4161 class->this_arg.byref = 1;
4162 class->this_arg.data.klass = class;
4163 class->this_arg.type = MONO_TYPE_CLASS;
4164 class->byval_arg.data.klass = class;
4165 class->byval_arg.type = MONO_TYPE_CLASS;
4167 if (is_corlib && !strcmp (nspace, "System")) {
4168 if (!strcmp (name, "ValueType")) {
4170 * do not set the valuetype bit for System.ValueType.
4171 * class->valuetype = 1;
4173 class->blittable = TRUE;
4174 } else if (!strcmp (name, "Enum")) {
4176 * do not set the valuetype bit for System.Enum.
4177 * class->valuetype = 1;
4179 class->valuetype = 0;
4180 class->enumtype = 0;
4181 } else if (!strcmp (name, "Object")) {
4182 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
4183 } else if (!strcmp (name, "String")) {
4184 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
4185 } else if (!strcmp (name, "TypedReference")) {
4186 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
4190 if (class->valuetype) {
4191 int t = MONO_TYPE_VALUETYPE;
4193 if (is_corlib && !strcmp (nspace, "System")) {
4196 if (!strcmp (name, "Boolean")) {
4197 t = MONO_TYPE_BOOLEAN;
4198 } else if (!strcmp(name, "Byte")) {
4200 class->blittable = TRUE;
4204 if (!strcmp (name, "Char")) {
4209 if (!strcmp (name, "Double")) {
4211 class->blittable = TRUE;
4215 if (!strcmp (name, "Int32")) {
4217 class->blittable = TRUE;
4218 } else if (!strcmp(name, "Int16")) {
4220 class->blittable = TRUE;
4221 } else if (!strcmp(name, "Int64")) {
4223 class->blittable = TRUE;
4224 } else if (!strcmp(name, "IntPtr")) {
4226 class->blittable = TRUE;
4230 if (!strcmp (name, "Single")) {
4232 class->blittable = TRUE;
4233 } else if (!strcmp(name, "SByte")) {
4235 class->blittable = TRUE;
4239 if (!strcmp (name, "UInt32")) {
4241 class->blittable = TRUE;
4242 } else if (!strcmp(name, "UInt16")) {
4244 class->blittable = TRUE;
4245 } else if (!strcmp(name, "UInt64")) {
4247 class->blittable = TRUE;
4248 } else if (!strcmp(name, "UIntPtr")) {
4250 class->blittable = TRUE;
4254 if (!strcmp (name, "TypedReference")) {
4255 t = MONO_TYPE_TYPEDBYREF;
4256 class->blittable = TRUE;
4260 if (!strcmp (name, "Void")) {
4268 class->this_arg.type = class->byval_arg.type = t;
4271 if (MONO_CLASS_IS_INTERFACE (class))
4272 class->interface_id = mono_get_unique_iid (class);
4277 * LOCKING: this assumes the loader lock is held
4280 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
4282 gboolean system_namespace;
4283 gboolean is_corlib = is_corlib_image (class->image);
4285 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
4287 /* if root of the hierarchy */
4288 if (system_namespace && !strcmp (class->name, "Object")) {
4289 class->parent = NULL;
4290 class->instance_size = sizeof (MonoObject);
4293 if (!strcmp (class->name, "<Module>")) {
4294 class->parent = NULL;
4295 class->instance_size = 0;
4299 if (!MONO_CLASS_IS_INTERFACE (class)) {
4300 /* Imported COM Objects always derive from __ComObject. */
4301 if (MONO_CLASS_IS_IMPORT (class)) {
4302 mono_init_com_types ();
4303 if (parent == mono_defaults.object_class)
4304 parent = mono_defaults.com_object_class;
4307 /* set the parent to something useful and safe, but mark the type as broken */
4308 parent = mono_defaults.object_class;
4309 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4312 class->parent = parent;
4314 if (parent->generic_class && !parent->name) {
4316 * If the parent is a generic instance, we may get
4317 * called before it is fully initialized, especially
4318 * before it has its name.
4323 class->marshalbyref = parent->marshalbyref;
4324 class->contextbound = parent->contextbound;
4325 class->delegate = parent->delegate;
4326 if (MONO_CLASS_IS_IMPORT (class))
4327 class->is_com_object = 1;
4329 class->is_com_object = parent->is_com_object;
4331 if (system_namespace) {
4332 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
4333 class->marshalbyref = 1;
4335 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
4336 class->contextbound = 1;
4338 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
4339 class->delegate = 1;
4342 if (class->parent->enumtype || (is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
4343 (strcmp (class->parent->name_space, "System") == 0)))
4344 class->valuetype = 1;
4345 if (is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
4346 class->valuetype = class->enumtype = 1;
4348 /*class->enumtype = class->parent->enumtype; */
4349 mono_class_setup_supertypes (class);
4351 /* initialize com types if COM interfaces are present */
4352 if (MONO_CLASS_IS_IMPORT (class))
4353 mono_init_com_types ();
4354 class->parent = NULL;
4360 * mono_class_setup_supertypes:
4363 * Build the data structure needed to make fast type checks work.
4364 * This currently sets two fields in @class:
4365 * - idepth: distance between @class and System.Object in the type
4367 * - supertypes: array of classes: each element has a class in the hierarchy
4368 * starting from @class up to System.Object
4370 * LOCKING: this assumes the loader lock is held
4373 mono_class_setup_supertypes (MonoClass *class)
4377 if (class->supertypes)
4380 if (class->parent && !class->parent->supertypes)
4381 mono_class_setup_supertypes (class->parent);
4383 class->idepth = class->parent->idepth + 1;
4387 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
4388 class->supertypes = mono_image_alloc0 (class->image, sizeof (MonoClass *) * ms);
4390 if (class->parent) {
4391 class->supertypes [class->idepth - 1] = class;
4392 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
4394 class->supertypes [0] = class;
4399 * mono_class_create_from_typedef:
4400 * @image: image where the token is valid
4401 * @type_token: typedef token
4403 * Create the MonoClass* representing the specified type token.
4404 * @type_token must be a TypeDef token.
4407 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
4409 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
4410 MonoClass *class, *parent = NULL;
4411 guint32 cols [MONO_TYPEDEF_SIZE];
4412 guint32 cols_next [MONO_TYPEDEF_SIZE];
4413 guint tidx = mono_metadata_token_index (type_token);
4414 MonoGenericContext *context = NULL;
4415 const char *name, *nspace;
4417 MonoClass **interfaces;
4418 guint32 field_last, method_last;
4419 guint32 nesting_tokeen;
4421 mono_loader_lock ();
4423 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
4424 mono_loader_unlock ();
4428 g_assert (mono_metadata_token_table (type_token) == MONO_TABLE_TYPEDEF);
4430 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
4432 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
4433 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
4435 class = mono_image_alloc0 (image, sizeof (MonoClass));
4438 class->name_space = nspace;
4440 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
4442 class->image = image;
4443 class->type_token = type_token;
4444 class->flags = cols [MONO_TYPEDEF_FLAGS];
4446 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
4448 classes_size += sizeof (MonoClass);
4451 * Check whether we're a generic type definition.
4453 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
4454 if (class->generic_container) {
4455 class->is_generic = 1;
4456 class->generic_container->owner.klass = class;
4457 context = &class->generic_container->context;
4460 if (cols [MONO_TYPEDEF_EXTENDS]) {
4461 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
4463 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
4464 /*WARNING: this must satisfy mono_metadata_type_hash*/
4465 class->this_arg.byref = 1;
4466 class->this_arg.data.klass = class;
4467 class->this_arg.type = MONO_TYPE_CLASS;
4468 class->byval_arg.data.klass = class;
4469 class->byval_arg.type = MONO_TYPE_CLASS;
4471 parent = mono_class_get_full (image, parent_token, context);
4473 if (parent == NULL){
4474 mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
4475 mono_loader_unlock ();
4476 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4481 /* do this early so it's available for interfaces in setup_mono_type () */
4482 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token)))
4483 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
4485 mono_class_setup_parent (class, parent);
4487 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
4488 mono_class_setup_mono_type (class);
4490 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
4493 #ifdef PLATFORM_WIN32
4494 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
4498 class->cast_class = class->element_class = class;
4500 if (!class->enumtype) {
4501 if (!mono_metadata_interfaces_from_typedef_full (
4502 image, type_token, &interfaces, &icount, FALSE, context)){
4503 mono_loader_unlock ();
4504 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4508 class->interfaces = interfaces;
4509 class->interface_count = icount;
4510 class->interfaces_inited = 1;
4513 /*g_print ("Load class %s\n", name);*/
4516 * Compute the field and method lists
4518 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
4519 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
4521 if (tt->rows > tidx){
4522 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
4523 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
4524 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
4526 field_last = image->tables [MONO_TABLE_FIELD].rows;
4527 method_last = image->tables [MONO_TABLE_METHOD].rows;
4530 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
4531 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
4532 class->field.count = field_last - class->field.first;
4534 class->field.count = 0;
4536 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
4537 class->method.count = method_last - class->method.first;
4539 class->method.count = 0;
4541 /* reserve space to store vector pointer in arrays */
4542 if (is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
4543 class->instance_size += 2 * sizeof (gpointer);
4544 g_assert (class->field.count == 0);
4547 if (class->enumtype) {
4548 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
4549 if (!enum_basetype) {
4550 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4551 mono_loader_unlock ();
4552 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4555 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
4559 * If we're a generic type definition, load the constraints.
4560 * We must do this after the class has been constructed to make certain recursive scenarios
4563 if (class->generic_container && !mono_metadata_load_generic_param_constraints_full (image, type_token, class->generic_container)){
4564 char *class_name = g_strdup_printf("%s.%s", class->name_space, class->name);
4565 char *error = concat_two_strings_with_zero (class->image, class_name, class->image->assembly_name);
4566 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, error);
4567 g_free (class_name);
4568 mono_loader_unlock ();
4569 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
4573 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
4574 if (!strncmp (name, "Vector", 6))
4575 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");
4578 mono_loader_unlock ();
4580 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
4585 /** is klass Nullable<T>? */
4587 mono_class_is_nullable (MonoClass *klass)
4589 return klass->generic_class != NULL &&
4590 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
4594 /** if klass is T? return T */
4596 mono_class_get_nullable_param (MonoClass *klass)
4598 g_assert (mono_class_is_nullable (klass));
4599 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4603 * Create the `MonoClass' for an instantiation of a generic type.
4604 * We only do this if we actually need it.
4607 mono_generic_class_get_class (MonoGenericClass *gclass)
4609 MonoClass *klass, *gklass;
4611 mono_loader_lock ();
4612 if (gclass->cached_class) {
4613 mono_loader_unlock ();
4614 return gclass->cached_class;
4617 gclass->cached_class = g_malloc0 (sizeof (MonoClass));
4618 klass = gclass->cached_class;
4620 gklass = gclass->container_class;
4622 if (gklass->nested_in) {
4624 * FIXME: the nested type context should include everything the
4625 * nesting context should have, but it may also have additional
4626 * generic parameters...
4628 klass->nested_in = mono_class_inflate_generic_class (gklass->nested_in,
4629 mono_generic_class_get_context (gclass));
4632 klass->name = gklass->name;
4633 klass->name_space = gklass->name_space;
4635 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4637 klass->image = gklass->image;
4638 klass->flags = gklass->flags;
4639 klass->type_token = gklass->type_token;
4640 klass->field.count = gklass->field.count;
4642 klass->is_inflated = 1;
4643 klass->generic_class = gclass;
4645 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
4646 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
4647 klass->this_arg.byref = TRUE;
4648 klass->enumtype = gklass->enumtype;
4649 klass->valuetype = gklass->valuetype;
4651 klass->cast_class = klass->element_class = klass;
4653 if (mono_class_is_nullable (klass))
4654 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
4657 * We're not interested in the nested classes of a generic instance.
4658 * We use the generic type definition to look for nested classes.
4661 if (gklass->parent) {
4662 klass->parent = mono_class_inflate_generic_class (gklass->parent, mono_generic_class_get_context (gclass));
4666 mono_class_setup_parent (klass, klass->parent);
4668 if (klass->enumtype) {
4669 klass->cast_class = gklass->cast_class;
4670 klass->element_class = gklass->element_class;
4673 if (gclass->is_dynamic) {
4676 mono_class_setup_supertypes (klass);
4678 if (klass->enumtype) {
4680 * For enums, gklass->fields might not been set, but instance_size etc. is
4681 * already set in mono_reflection_create_internal_class (). For non-enums,
4682 * these will be computed normally in mono_class_layout_fields ().
4684 klass->instance_size = gklass->instance_size;
4685 klass->sizes.class_size = gklass->sizes.class_size;
4686 klass->size_inited = 1;
4690 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4692 inflated_classes ++;
4693 inflated_classes_size += sizeof (MonoClass);
4695 mono_loader_unlock ();
4701 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
4703 MonoClass *klass, **ptr;
4708 image = mono_defaults.corlib;
4710 klass = mono_image_alloc0 (image, sizeof (MonoClass));
4711 classes_size += sizeof (MonoClass);
4714 klass->name = pinfo->name;
4716 int n = mono_generic_param_num (param);
4717 klass->name = mono_image_alloc0 (image, 16);
4718 sprintf ((char*)klass->name, "%d", n);
4721 klass->name_space = "";
4722 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
4726 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
4730 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
4731 klass->parent = pinfo->constraints [0];
4733 } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
4734 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
4736 klass->parent = mono_defaults.object_class;
4739 if (count - pos > 0) {
4740 klass->interface_count = count - pos;
4741 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
4742 for (i = pos; i < count; i++)
4743 klass->interfaces [i - pos] = pinfo->constraints [i];
4746 klass->image = image;
4748 klass->inited = TRUE;
4749 klass->cast_class = klass->element_class = klass;
4750 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
4752 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
4753 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
4754 klass->this_arg.byref = TRUE;
4756 /* FIXME: shouldn't this be ->type_token? */
4757 klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
4759 mono_class_setup_supertypes (klass);
4764 #define FAST_CACHE_SIZE 1024
4765 static MonoClass *var_cache_fast [FAST_CACHE_SIZE];
4766 static MonoClass *mvar_cache_fast [FAST_CACHE_SIZE];
4767 static GHashTable *var_cache_slow;
4768 static GHashTable *mvar_cache_slow;
4771 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
4773 int n = mono_generic_param_num (param);
4776 if (n < FAST_CACHE_SIZE)
4777 return (is_mvar ? mvar_cache_fast : var_cache_fast) [n];
4778 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4779 return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
4783 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
4785 int n = mono_generic_param_num (param);
4788 if (n < FAST_CACHE_SIZE) {
4789 (is_mvar ? mvar_cache_fast : var_cache_fast) [n] = klass;
4792 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
4794 ht = g_hash_table_new (NULL, NULL);
4796 mvar_cache_slow = ht;
4798 var_cache_slow = ht;
4801 g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
4805 * LOCKING: Acquires the loader lock.
4808 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
4810 MonoGenericContainer *container = mono_generic_param_owner (param);
4811 MonoGenericParamInfo *pinfo;
4814 mono_loader_lock ();
4817 pinfo = mono_generic_param_info (param);
4818 if (pinfo->pklass) {
4819 mono_loader_unlock ();
4820 return pinfo->pklass;
4826 klass = get_anon_gparam_class (param, is_mvar);
4828 mono_loader_unlock ();
4833 if (!image && container) {
4835 MonoMethod *method = container->owner.method;
4836 image = (method && method->klass) ? method->klass->image : NULL;
4838 MonoClass *klass = container->owner.klass;
4839 // FIXME: 'klass' should not be null
4840 // But, monodis creates GenericContainers without associating a owner to it
4841 image = klass ? klass->image : NULL;
4845 klass = make_generic_param_class (param, image, is_mvar, pinfo);
4847 mono_memory_barrier ();
4850 pinfo->pklass = klass;
4852 set_anon_gparam_class (param, is_mvar, klass);
4854 mono_loader_unlock ();
4856 /* FIXME: Should this go inside 'make_generic_param_klass'? */
4857 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
4863 mono_ptr_class_get (MonoType *type)
4866 MonoClass *el_class;
4870 el_class = mono_class_from_mono_type (type);
4871 image = el_class->image;
4873 mono_loader_lock ();
4875 if (!image->ptr_cache)
4876 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
4878 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
4879 mono_loader_unlock ();
4882 result = mono_image_alloc0 (image, sizeof (MonoClass));
4884 classes_size += sizeof (MonoClass);
4886 result->parent = NULL; /* no parent for PTR types */
4887 result->name_space = el_class->name_space;
4888 name = g_strdup_printf ("%s*", el_class->name);
4889 result->name = mono_image_strdup (image, name);
4892 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4894 result->image = el_class->image;
4895 result->inited = TRUE;
4896 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
4897 /* Can pointers get boxed? */
4898 result->instance_size = sizeof (gpointer);
4899 result->cast_class = result->element_class = el_class;
4900 result->blittable = TRUE;
4902 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
4903 result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
4904 result->this_arg.byref = TRUE;
4906 mono_class_setup_supertypes (result);
4908 g_hash_table_insert (image->ptr_cache, el_class, result);
4910 mono_loader_unlock ();
4912 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4918 mono_fnptr_class_get (MonoMethodSignature *sig)
4921 static GHashTable *ptr_hash = NULL;
4923 /* FIXME: These should be allocate from a mempool as well, but which one ? */
4925 mono_loader_lock ();
4928 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
4930 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
4931 mono_loader_unlock ();
4934 result = g_new0 (MonoClass, 1);
4936 result->parent = NULL; /* no parent for PTR types */
4937 result->name_space = "System";
4938 result->name = "MonoFNPtrFakeClass";
4940 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
4942 result->image = mono_defaults.corlib; /* need to fix... */
4943 result->inited = TRUE;
4944 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
4945 /* Can pointers get boxed? */
4946 result->instance_size = sizeof (gpointer);
4947 result->cast_class = result->element_class = result;
4948 result->blittable = TRUE;
4950 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
4951 result->this_arg.data.method = result->byval_arg.data.method = sig;
4952 result->this_arg.byref = TRUE;
4953 result->blittable = TRUE;
4955 mono_class_setup_supertypes (result);
4957 g_hash_table_insert (ptr_hash, sig, result);
4959 mono_loader_unlock ();
4961 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
4967 mono_class_from_mono_type (MonoType *type)
4969 switch (type->type) {
4970 case MONO_TYPE_OBJECT:
4971 return type->data.klass? type->data.klass: mono_defaults.object_class;
4972 case MONO_TYPE_VOID:
4973 return type->data.klass? type->data.klass: mono_defaults.void_class;
4974 case MONO_TYPE_BOOLEAN:
4975 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
4976 case MONO_TYPE_CHAR:
4977 return type->data.klass? type->data.klass: mono_defaults.char_class;
4979 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
4981 return type->data.klass? type->data.klass: mono_defaults.byte_class;
4983 return type->data.klass? type->data.klass: mono_defaults.int16_class;
4985 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
4987 return type->data.klass? type->data.klass: mono_defaults.int32_class;
4989 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
4991 return type->data.klass? type->data.klass: mono_defaults.int_class;
4993 return type->data.klass? type->data.klass: mono_defaults.uint_class;
4995 return type->data.klass? type->data.klass: mono_defaults.int64_class;
4997 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
4999 return type->data.klass? type->data.klass: mono_defaults.single_class;
5001 return type->data.klass? type->data.klass: mono_defaults.double_class;
5002 case MONO_TYPE_STRING:
5003 return type->data.klass? type->data.klass: mono_defaults.string_class;
5004 case MONO_TYPE_TYPEDBYREF:
5005 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
5006 case MONO_TYPE_ARRAY:
5007 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
5009 return mono_ptr_class_get (type->data.type);
5010 case MONO_TYPE_FNPTR:
5011 return mono_fnptr_class_get (type->data.method);
5012 case MONO_TYPE_SZARRAY:
5013 return mono_array_class_get (type->data.klass, 1);
5014 case MONO_TYPE_CLASS:
5015 case MONO_TYPE_VALUETYPE:
5016 return type->data.klass;
5017 case MONO_TYPE_GENERICINST:
5018 return mono_generic_class_get_class (type->data.generic_class);
5020 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
5021 case MONO_TYPE_MVAR:
5022 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
5024 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
5025 g_assert_not_reached ();
5032 * mono_type_retrieve_from_typespec
5033 * @image: context where the image is created
5034 * @type_spec: typespec token
5035 * @context: the generic context used to evaluate generic instantiations in
5038 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate)
5041 MonoType *t = mono_type_create_from_typespec (image, type_spec);
5044 if (context && (context->class_inst || context->method_inst)) {
5045 MonoType *inflated = inflate_generic_type (NULL, t, context, &error);
5046 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
5050 *did_inflate = TRUE;
5057 * mono_class_create_from_typespec
5058 * @image: context where the image is created
5059 * @type_spec: typespec token
5060 * @context: the generic context used to evaluate generic instantiations in
5063 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context)
5066 gboolean inflated = FALSE;
5067 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated);
5070 ret = mono_class_from_mono_type (t);
5072 mono_metadata_free_type (t);
5077 * mono_bounded_array_class_get:
5078 * @element_class: element class
5079 * @rank: the dimension of the array class
5080 * @bounded: whenever the array has non-zero bounds
5082 * Returns: a class object describing the array with element type @element_type and
5086 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
5090 MonoClass *parent = NULL;
5091 GSList *list, *rootlist = NULL;
5094 gboolean corlib_type = FALSE;
5096 g_assert (rank <= 255);
5099 /* bounded only matters for one-dimensional arrays */
5102 image = eclass->image;
5104 if (rank == 1 && !bounded) {
5106 * This case is very frequent not just during compilation because of calls
5107 * from mono_class_from_mono_type (), mono_array_new (),
5108 * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
5110 EnterCriticalSection (&image->szarray_cache_lock);
5111 if (!image->szarray_cache)
5112 image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5113 class = g_hash_table_lookup (image->szarray_cache, eclass);
5114 LeaveCriticalSection (&image->szarray_cache_lock);
5118 mono_loader_lock ();
5120 mono_loader_lock ();
5122 if (!image->array_cache)
5123 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5125 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
5126 for (; list; list = list->next) {
5128 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
5129 mono_loader_unlock ();
5136 /* for the building corlib use System.Array from it */
5137 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
5138 parent = mono_class_from_name (image, "System", "Array");
5141 parent = mono_defaults.array_class;
5142 if (!parent->inited)
5143 mono_class_init (parent);
5146 class = mono_image_alloc0 (image, sizeof (MonoClass));
5148 class->image = image;
5149 class->name_space = eclass->name_space;
5150 nsize = strlen (eclass->name);
5151 name = g_malloc (nsize + 2 + rank + 1);
5152 memcpy (name, eclass->name, nsize);
5155 memset (name + nsize + 1, ',', rank - 1);
5157 name [nsize + rank] = '*';
5158 name [nsize + rank + bounded] = ']';
5159 name [nsize + rank + bounded + 1] = 0;
5160 class->name = mono_image_strdup (image, name);
5163 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
5165 classes_size += sizeof (MonoClass);
5167 class->type_token = 0;
5168 /* all arrays are marked serializable and sealed, bug #42779 */
5169 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED |
5170 (eclass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5171 class->parent = parent;
5172 class->instance_size = mono_class_instance_size (class->parent);
5174 if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
5175 if (!eclass->reflection_info || eclass->wastypebuilder) {
5176 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
5177 g_assert (eclass->reflection_info && !eclass->wastypebuilder);
5179 /* element_size -1 is ok as this is not an instantitable type*/
5180 class->sizes.element_size = -1;
5182 class->sizes.element_size = mono_class_array_element_size (eclass);
5184 mono_class_setup_supertypes (class);
5186 if (eclass->generic_class)
5187 mono_class_init (eclass);
5188 if (!eclass->size_inited)
5189 mono_class_setup_fields (eclass);
5190 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
5194 if (eclass->enumtype)
5195 class->cast_class = eclass->element_class;
5197 class->cast_class = eclass;
5199 class->element_class = eclass;
5201 if ((rank > 1) || bounded) {
5202 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
5203 class->byval_arg.type = MONO_TYPE_ARRAY;
5204 class->byval_arg.data.array = at;
5205 at->eklass = eclass;
5207 /* FIXME: complete.... */
5209 class->byval_arg.type = MONO_TYPE_SZARRAY;
5210 class->byval_arg.data.klass = eclass;
5212 class->this_arg = class->byval_arg;
5213 class->this_arg.byref = 1;
5218 class->generic_container = eclass->generic_container;
5220 if (rank == 1 && !bounded) {
5221 MonoClass *prev_class;
5223 EnterCriticalSection (&image->szarray_cache_lock);
5224 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
5226 /* Someone got in before us */
5229 g_hash_table_insert (image->szarray_cache, eclass, class);
5230 LeaveCriticalSection (&image->szarray_cache_lock);
5232 list = g_slist_append (rootlist, class);
5233 g_hash_table_insert (image->array_cache, eclass, list);
5236 mono_loader_unlock ();
5238 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5244 * mono_array_class_get:
5245 * @element_class: element class
5246 * @rank: the dimension of the array class
5248 * Returns: a class object describing the array with element type @element_type and
5252 mono_array_class_get (MonoClass *eclass, guint32 rank)
5254 return mono_bounded_array_class_get (eclass, rank, FALSE);
5258 * mono_class_instance_size:
5261 * Returns: the size of an object instance
5264 mono_class_instance_size (MonoClass *klass)
5266 if (!klass->size_inited)
5267 mono_class_init (klass);
5269 return klass->instance_size;
5273 * mono_class_min_align:
5276 * Returns: minimm alignment requirements
5279 mono_class_min_align (MonoClass *klass)
5281 if (!klass->size_inited)
5282 mono_class_init (klass);
5284 return klass->min_align;
5288 * mono_class_value_size:
5291 * This function is used for value types, and return the
5292 * space and the alignment to store that kind of value object.
5294 * Returns: the size of a value of kind @klass
5297 mono_class_value_size (MonoClass *klass, guint32 *align)
5301 /* fixme: check disable, because we still have external revereces to
5302 * mscorlib and Dummy Objects
5304 /*g_assert (klass->valuetype);*/
5306 size = mono_class_instance_size (klass) - sizeof (MonoObject);
5309 *align = klass->min_align;
5315 * mono_class_data_size:
5318 * Returns: the size of the static class data
5321 mono_class_data_size (MonoClass *klass)
5324 mono_class_init (klass);
5326 /* in arrays, sizes.class_size is unioned with element_size
5327 * and arrays have no static fields
5331 return klass->sizes.class_size;
5335 * Auxiliary routine to mono_class_get_field
5337 * Takes a field index instead of a field token.
5339 static MonoClassField *
5340 mono_class_get_field_idx (MonoClass *class, int idx)
5342 mono_class_setup_fields_locking (class);
5345 if (class->image->uncompressed_metadata) {
5347 * class->field.first points to the FieldPtr table, while idx points into the
5348 * Field table, so we have to do a search.
5350 /*FIXME this is broken for types with multiple fields with the same name.*/
5351 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
5354 for (i = 0; i < class->field.count; ++i)
5355 if (mono_field_get_name (&class->fields [i]) == name)
5356 return &class->fields [i];
5357 g_assert_not_reached ();
5359 if (class->field.count) {
5360 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
5361 return &class->fields [idx - class->field.first];
5365 class = class->parent;
5371 * mono_class_get_field:
5372 * @class: the class to lookup the field.
5373 * @field_token: the field token
5375 * Returns: A MonoClassField representing the type and offset of
5376 * the field, or a NULL value if the field does not belong to this
5380 mono_class_get_field (MonoClass *class, guint32 field_token)
5382 int idx = mono_metadata_token_index (field_token);
5384 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
5386 return mono_class_get_field_idx (class, idx - 1);
5390 * mono_class_get_field_from_name:
5391 * @klass: the class to lookup the field.
5392 * @name: the field name
5394 * Search the class @klass and it's parents for a field with the name @name.
5396 * Returns: the MonoClassField pointer of the named field or NULL
5399 mono_class_get_field_from_name (MonoClass *klass, const char *name)
5401 return mono_class_get_field_from_name_full (klass, name, NULL);
5405 * mono_class_get_field_from_name_full:
5406 * @klass: the class to lookup the field.
5407 * @name: the field name
5408 * @type: the type of the fields. This optional.
5410 * Search the class @klass and it's parents for a field with the name @name and type @type.
5412 * If @klass is an inflated generic type, the type comparison is done with the equivalent field
5413 * of its generic type definition.
5415 * Returns: the MonoClassField pointer of the named field or NULL
5418 mono_class_get_field_from_name_full (MonoClass *klass, const char *name, MonoType *type)
5422 mono_class_setup_fields_locking (klass);
5424 for (i = 0; i < klass->field.count; ++i) {
5425 MonoClassField *field = &klass->fields [i];
5427 if (strcmp (name, mono_field_get_name (field)) != 0)
5431 MonoType *field_type = mono_metadata_get_corresponding_field_from_generic_type_definition (field)->type;
5432 if (!mono_metadata_type_equal_full (type, field_type, TRUE))
5437 klass = klass->parent;
5443 * mono_class_get_field_token:
5444 * @field: the field we need the token of
5446 * Get the token of a field. Note that the tokesn is only valid for the image
5447 * the field was loaded from. Don't use this function for fields in dynamic types.
5449 * Returns: the token representing the field in the image it was loaded from.
5452 mono_class_get_field_token (MonoClassField *field)
5454 MonoClass *klass = field->parent;
5457 mono_class_setup_fields_locking (klass);
5459 for (i = 0; i < klass->field.count; ++i) {
5460 if (&klass->fields [i] == field) {
5461 int idx = klass->field.first + i + 1;
5463 if (klass->image->uncompressed_metadata)
5464 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
5465 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
5468 klass = klass->parent;
5471 g_assert_not_reached ();
5476 mono_field_get_index (MonoClassField *field)
5478 int index = field - field->parent->fields;
5480 g_assert (index >= 0 && index < field->parent->field.count);
5486 * mono_class_get_field_default_value:
5488 * Return the default value of the field as a pointer into the metadata blob.
5491 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
5494 guint32 constant_cols [MONO_CONSTANT_SIZE];
5496 MonoClass *klass = field->parent;
5498 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
5500 if (!klass->ext || !klass->ext->field_def_values) {
5501 mono_loader_lock ();
5502 mono_class_alloc_ext (klass);
5503 if (!klass->ext->field_def_values)
5504 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
5505 mono_loader_unlock ();
5508 field_index = mono_field_get_index (field);
5510 if (!klass->ext->field_def_values [field_index].data) {
5511 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
5513 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
5515 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
5516 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
5517 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
5520 *def_type = klass->ext->field_def_values [field_index].def_type;
5521 return klass->ext->field_def_values [field_index].data;
5525 mono_class_get_event_token (MonoEvent *event)
5527 MonoClass *klass = event->parent;
5532 for (i = 0; i < klass->ext->event.count; ++i) {
5533 if (&klass->ext->events [i] == event)
5534 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
5537 klass = klass->parent;
5540 g_assert_not_reached ();
5545 mono_class_get_property_from_name (MonoClass *klass, const char *name)
5549 gpointer iter = NULL;
5550 while ((p = mono_class_get_properties (klass, &iter))) {
5551 if (! strcmp (name, p->name))
5554 klass = klass->parent;
5560 mono_class_get_property_token (MonoProperty *prop)
5562 MonoClass *klass = prop->parent;
5566 gpointer iter = NULL;
5567 while ((p = mono_class_get_properties (klass, &iter))) {
5568 if (&klass->ext->properties [i] == prop)
5569 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
5573 klass = klass->parent;
5576 g_assert_not_reached ();
5581 mono_class_name_from_token (MonoImage *image, guint32 type_token)
5583 const char *name, *nspace;
5585 return g_strdup_printf ("DynamicType 0x%08x", type_token);
5587 switch (type_token & 0xff000000){
5588 case MONO_TOKEN_TYPE_DEF: {
5589 guint32 cols [MONO_TYPEDEF_SIZE];
5590 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5591 guint tidx = mono_metadata_token_index (type_token);
5593 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5594 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5595 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5596 if (strlen (nspace) == 0)
5597 return g_strdup_printf ("%s", name);
5599 return g_strdup_printf ("%s.%s", nspace, name);
5602 case MONO_TOKEN_TYPE_REF: {
5603 guint32 cols [MONO_TYPEREF_SIZE];
5604 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5606 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5607 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
5608 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
5609 if (strlen (nspace) == 0)
5610 return g_strdup_printf ("%s", name);
5612 return g_strdup_printf ("%s.%s", nspace, name);
5615 case MONO_TOKEN_TYPE_SPEC:
5616 return g_strdup_printf ("Typespec 0x%08x", type_token);
5618 g_assert_not_reached ();
5625 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
5628 return g_strdup_printf ("DynamicAssembly %s", image->name);
5630 switch (type_token & 0xff000000){
5631 case MONO_TOKEN_TYPE_DEF:
5632 return mono_stringify_assembly_name (&image->assembly->aname);
5634 case MONO_TOKEN_TYPE_REF: {
5635 MonoAssemblyName aname;
5636 guint32 cols [MONO_TYPEREF_SIZE];
5637 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
5640 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
5642 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
5643 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
5644 case MONO_RESOLTION_SCOPE_MODULE:
5646 return g_strdup ("");
5647 case MONO_RESOLTION_SCOPE_MODULEREF:
5649 return g_strdup ("");
5650 case MONO_RESOLTION_SCOPE_TYPEREF:
5652 return g_strdup ("");
5653 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
5654 mono_assembly_get_assemblyref (image, idx - 1, &aname);
5655 return mono_stringify_assembly_name (&aname);
5657 g_assert_not_reached ();
5661 case MONO_TOKEN_TYPE_SPEC:
5663 return g_strdup ("");
5665 g_assert_not_reached ();
5672 * mono_class_get_full:
5673 * @image: the image where the class resides
5674 * @type_token: the token for the class
5675 * @context: the generic context used to evaluate generic instantiations in
5677 * Returns: the MonoClass that represents @type_token in @image
5680 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5682 MonoClass *class = NULL;
5684 if (image->dynamic) {
5685 int table = mono_metadata_token_table (type_token);
5687 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
5688 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
5691 return mono_lookup_dynamic_token (image, type_token, context);
5694 switch (type_token & 0xff000000){
5695 case MONO_TOKEN_TYPE_DEF:
5696 class = mono_class_create_from_typedef (image, type_token);
5698 case MONO_TOKEN_TYPE_REF:
5699 class = mono_class_from_typeref (image, type_token);
5701 case MONO_TOKEN_TYPE_SPEC:
5702 class = mono_class_create_from_typespec (image, type_token, context);
5705 g_warning ("unknown token type %x", type_token & 0xff000000);
5706 g_assert_not_reached ();
5710 char *name = mono_class_name_from_token (image, type_token);
5711 char *assembly = mono_assembly_name_from_token (image, type_token);
5712 mono_loader_set_error_type_load (name, assembly);
5720 * mono_type_get_full:
5721 * @image: the image where the type resides
5722 * @type_token: the token for the type
5723 * @context: the generic context used to evaluate generic instantiations in
5725 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
5727 * Returns: the MonoType that represents @type_token in @image
5730 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
5732 MonoType *type = NULL;
5733 gboolean inflated = FALSE;
5735 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
5737 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
5739 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
5740 MonoClass *class = mono_class_get_full (image, type_token, context);
5741 return class ? mono_class_get_type (class) : NULL;
5744 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated);
5747 char *name = mono_class_name_from_token (image, type_token);
5748 char *assembly = mono_assembly_name_from_token (image, type_token);
5749 mono_loader_set_error_type_load (name, assembly);
5754 MonoType *tmp = type;
5755 type = mono_class_get_type (mono_class_from_mono_type (type));
5756 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
5757 * A MonoClass::byval_arg of a generic type definion has type CLASS.
5758 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
5760 * The long term solution is to chaise this places and make then set MonoType::type correctly.
5762 if (type->type != tmp->type)
5765 mono_metadata_free_type (tmp);
5772 mono_class_get (MonoImage *image, guint32 type_token)
5774 return mono_class_get_full (image, type_token, NULL);
5778 * mono_image_init_name_cache:
5780 * Initializes the class name cache stored in image->name_cache.
5782 * LOCKING: Acquires the corresponding image lock.
5785 mono_image_init_name_cache (MonoImage *image)
5787 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5788 guint32 cols [MONO_TYPEDEF_SIZE];
5791 guint32 i, visib, nspace_index;
5792 GHashTable *name_cache2, *nspace_table;
5794 mono_image_lock (image);
5796 if (image->name_cache) {
5797 mono_image_unlock (image);
5801 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
5803 if (image->dynamic) {
5804 mono_image_unlock (image);
5808 /* Temporary hash table to avoid lookups in the nspace_table */
5809 name_cache2 = g_hash_table_new (NULL, NULL);
5811 for (i = 1; i <= t->rows; ++i) {
5812 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5813 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5815 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5816 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5818 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5820 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5821 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5823 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
5824 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5825 if (!nspace_table) {
5826 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5827 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5828 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5831 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
5834 /* Load type names from EXPORTEDTYPES table */
5836 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
5837 guint32 cols [MONO_EXP_TYPE_SIZE];
5840 for (i = 0; i < t->rows; ++i) {
5841 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
5842 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
5843 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
5845 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
5846 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
5847 if (!nspace_table) {
5848 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5849 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
5850 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
5853 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
5857 g_hash_table_destroy (name_cache2);
5858 mono_image_unlock (image);
5861 /*FIXME Only dynamic assemblies should allow this operation.*/
5863 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
5864 const char *name, guint32 index)
5866 GHashTable *nspace_table;
5867 GHashTable *name_cache;
5869 mono_image_lock (image);
5871 if (!image->name_cache)
5872 mono_image_init_name_cache (image);
5874 name_cache = image->name_cache;
5875 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
5876 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
5877 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
5879 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
5881 mono_image_unlock (image);
5890 find_nocase (gpointer key, gpointer value, gpointer user_data)
5892 char *name = (char*)key;
5893 FindUserData *data = (FindUserData*)user_data;
5895 if (!data->value && (mono_utf8_strcasecmp (name, (char*)data->key) == 0))
5896 data->value = value;
5900 * mono_class_from_name_case:
5901 * @image: The MonoImage where the type is looked up in
5902 * @name_space: the type namespace
5903 * @name: the type short name.
5905 * Obtains a MonoClass with a given namespace and a given name which
5906 * is located in the given MonoImage. The namespace and name
5907 * lookups are case insensitive.
5910 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
5912 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
5913 guint32 cols [MONO_TYPEDEF_SIZE];
5918 if (image->dynamic) {
5920 FindUserData user_data;
5922 mono_image_lock (image);
5924 if (!image->name_cache)
5925 mono_image_init_name_cache (image);
5927 user_data.key = name_space;
5928 user_data.value = NULL;
5929 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
5931 if (user_data.value) {
5932 GHashTable *nspace_table = (GHashTable*)user_data.value;
5934 user_data.key = name;
5935 user_data.value = NULL;
5937 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
5939 if (user_data.value)
5940 token = GPOINTER_TO_UINT (user_data.value);
5943 mono_image_unlock (image);
5946 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
5952 /* add a cache if needed */
5953 for (i = 1; i <= t->rows; ++i) {
5954 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
5955 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5957 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
5958 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
5960 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
5962 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5963 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5964 if (mono_utf8_strcasecmp (n, name) == 0 && mono_utf8_strcasecmp (nspace, name_space) == 0)
5965 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
5971 return_nested_in (MonoClass *class, char *nested)
5974 char *s = strchr (nested, '/');
5975 gpointer iter = NULL;
5982 while ((found = mono_class_get_nested_types (class, &iter))) {
5983 if (strcmp (found->name, nested) == 0) {
5985 return return_nested_in (found, s);
5993 search_modules (MonoImage *image, const char *name_space, const char *name)
5995 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
5996 MonoImage *file_image;
6001 * The EXPORTEDTYPES table only contains public types, so have to search the
6003 * Note: image->modules contains the contents of the MODULEREF table, while
6004 * the real module list is in the FILE table.
6006 for (i = 0; i < file_table->rows; i++) {
6007 guint32 cols [MONO_FILE_SIZE];
6008 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
6009 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
6012 file_image = mono_image_load_file_for_image (image, i + 1);
6014 class = mono_class_from_name (file_image, name_space, name);
6024 * mono_class_from_name:
6025 * @image: The MonoImage where the type is looked up in
6026 * @name_space: the type namespace
6027 * @name: the type short name.
6029 * Obtains a MonoClass with a given namespace and a given name which
6030 * is located in the given MonoImage.
6033 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
6035 GHashTable *nspace_table;
6036 MonoImage *loaded_image;
6043 if ((nested = strchr (name, '/'))) {
6044 int pos = nested - name;
6045 int len = strlen (name);
6048 memcpy (buf, name, len + 1);
6050 nested = buf + pos + 1;
6054 if (get_class_from_name) {
6055 gboolean res = get_class_from_name (image, name_space, name, &class);
6058 class = search_modules (image, name_space, name);
6060 return class ? return_nested_in (class, nested) : NULL;
6066 mono_image_lock (image);
6068 if (!image->name_cache)
6069 mono_image_init_name_cache (image);
6071 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
6074 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
6076 mono_image_unlock (image);
6078 if (!token && image->dynamic && image->modules) {
6079 /* Search modules as well */
6080 for (i = 0; i < image->module_count; ++i) {
6081 MonoImage *module = image->modules [i];
6083 class = mono_class_from_name (module, name_space, name);
6090 class = search_modules (image, name_space, name);
6098 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
6099 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6100 guint32 cols [MONO_EXP_TYPE_SIZE];
6103 idx = mono_metadata_token_index (token);
6105 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
6107 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
6108 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
6109 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
6112 class = mono_class_from_name (loaded_image, name_space, name);
6114 return return_nested_in (class, nested);
6116 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
6117 guint32 assembly_idx;
6119 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
6121 mono_assembly_load_reference (image, assembly_idx - 1);
6122 g_assert (image->references [assembly_idx - 1]);
6123 if (image->references [assembly_idx - 1] == (gpointer)-1)
6126 /* FIXME: Cycle detection */
6127 return mono_class_from_name (image->references [assembly_idx - 1]->image, name_space, name);
6129 g_error ("not yet implemented");
6133 token = MONO_TOKEN_TYPE_DEF | token;
6135 class = mono_class_get (image, token);
6137 return return_nested_in (class, nested);
6142 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
6143 gboolean check_interfaces)
6145 g_assert (klassc->idepth > 0);
6146 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
6147 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
6149 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
6152 for (i = 0; i < klass->interface_count; i ++) {
6153 MonoClass *ic = klass->interfaces [i];
6158 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
6163 * MS.NET thinks interfaces are a subclass of Object, so we think it as
6166 if (klassc == mono_defaults.object_class)
6173 mono_class_has_variant_generic_params (MonoClass *klass)
6176 MonoGenericContainer *container;
6178 if (!klass->generic_class)
6181 container = klass->generic_class->container_class->generic_container;
6183 for (i = 0; i < container->type_argc; ++i)
6184 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
6191 * mono_class_is_assignable_from:
6192 * @klass: the class to be assigned to
6193 * @oklass: the source class
6195 * Return: true if an instance of object oklass can be assigned to an
6196 * instance of object @klass
6199 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
6202 mono_class_init (klass);
6204 if (!oklass->inited)
6205 mono_class_init (oklass);
6207 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
6208 return klass == oklass;
6210 if (MONO_CLASS_IS_INTERFACE (klass)) {
6211 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
6214 /* interface_offsets might not be set for dynamic classes */
6215 if (oklass->reflection_info && !oklass->interface_bitmap)
6217 * oklass might be a generic type parameter but they have
6218 * interface_offsets set.
6220 return mono_reflection_call_is_assignable_to (oklass, klass);
6221 if (!oklass->interface_bitmap)
6222 /* Happens with generic instances of not-yet created dynamic types */
6224 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
6227 if (mono_class_has_variant_generic_params (klass)) {
6228 if (oklass->generic_class) {
6230 gboolean match = FALSE;
6231 MonoClass *container_class1 = klass->generic_class->container_class;
6232 MonoClass *container_class2 = oklass->generic_class->container_class;
6235 * Check whenever the generic definition of oklass implements the
6236 * generic definition of klass. The IMPLEMENTS_INTERFACE stuff is not usable
6237 * here since the relevant tables are not set up.
6239 for (i = 0; i < container_class2->interface_offsets_count; ++i)
6240 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)))
6244 MonoGenericContainer *container;
6246 container = klass->generic_class->container_class->generic_container;
6249 for (i = 0; i < container->type_argc; ++i) {
6250 MonoClass *param1_class = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [i]);
6251 MonoClass *param2_class = mono_class_from_mono_type (oklass->generic_class->context.class_inst->type_argv [i]);
6253 if (param1_class->valuetype != param2_class->valuetype) {
6258 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
6259 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
6261 if (param1_class != param2_class) {
6262 if ((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_VARIANT) && mono_class_is_assignable_from (param1_class, param2_class))
6264 else if (((mono_generic_container_get_param_info (container, i)->flags & MONO_GEN_PARAM_COVARIANT) && mono_class_is_assignable_from (param2_class, param1_class)))
6278 } else if (klass->rank) {
6279 MonoClass *eclass, *eoclass;
6281 if (oklass->rank != klass->rank)
6284 /* vectors vs. one dimensional arrays */
6285 if (oklass->byval_arg.type != klass->byval_arg.type)
6288 eclass = klass->cast_class;
6289 eoclass = oklass->cast_class;
6292 * a is b does not imply a[] is b[] when a is a valuetype, and
6293 * b is a reference type.
6296 if (eoclass->valuetype) {
6297 if ((eclass == mono_defaults.enum_class) ||
6298 (eclass == mono_defaults.enum_class->parent) ||
6299 (eclass == mono_defaults.object_class))
6303 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6304 } else if (mono_class_is_nullable (klass)) {
6305 if (mono_class_is_nullable (oklass))
6306 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6308 return mono_class_is_assignable_from (klass->cast_class, oklass);
6309 } else if (klass == mono_defaults.object_class)
6312 return mono_class_has_parent (oklass, klass);
6315 /*Check if @candidate implements the interface @target*/
6317 mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
6322 if (candidate == target)
6325 /*A TypeBuilder can have more interfaces on tb->interfaces than on candidate->interfaces*/
6326 if (candidate->image->dynamic && !candidate->wastypebuilder) {
6327 MonoReflectionTypeBuilder *tb = candidate->reflection_info;
6329 if (tb->interfaces) {
6330 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
6331 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
6332 MonoClass *iface_class = mono_class_from_mono_type (iface->type);
6333 if (iface_class == target || mono_class_implement_interface_slow (target, iface_class))
6338 /*setup_interfaces don't mono_class_init anything*/
6339 mono_class_setup_interfaces (candidate);
6340 for (i = 0; i < candidate->interface_count; ++i) {
6341 if (candidate->interfaces [i] == target || mono_class_implement_interface_slow (target, candidate->interfaces [i]))
6345 candidate = candidate->parent;
6346 } while (candidate);
6352 * Check if @oklass can be assigned to @klass.
6353 * This function does the same as mono_class_is_assignable_from but is safe to be used from mono_class_init context.
6356 mono_class_is_assignable_from_slow (MonoClass *target, MonoClass *candidate)
6358 if (candidate == target)
6360 if (target == mono_defaults.object_class)
6363 /*setup_supertypes don't mono_class_init anything */
6364 mono_class_setup_supertypes (candidate);
6365 mono_class_setup_supertypes (target);
6367 if (mono_class_has_parent (candidate, target))
6370 /*If target is not an interface there is no need to check them.*/
6371 if (!MONO_CLASS_IS_INTERFACE (target))
6373 return mono_class_implement_interface_slow (target, candidate);
6377 * mono_class_get_cctor:
6378 * @klass: A MonoClass pointer
6380 * Returns: the static constructor of @klass if it exists, NULL otherwise.
6383 mono_class_get_cctor (MonoClass *klass)
6385 MonoCachedClassInfo cached_info;
6387 if (!klass->has_cctor)
6390 if (mono_class_get_cached_class_info (klass, &cached_info))
6391 return mono_get_method (klass->image, cached_info.cctor_token, klass);
6393 if (klass->generic_class && !klass->methods)
6394 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
6396 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
6400 * mono_class_get_finalizer:
6401 * @klass: The MonoClass pointer
6403 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
6406 mono_class_get_finalizer (MonoClass *klass)
6408 MonoCachedClassInfo cached_info;
6411 mono_class_init (klass);
6412 if (!klass->has_finalize)
6415 if (mono_class_get_cached_class_info (klass, &cached_info))
6416 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
6418 mono_class_setup_vtable (klass);
6419 return klass->vtable [finalize_slot];
6424 * mono_class_needs_cctor_run:
6425 * @klass: the MonoClass pointer
6426 * @caller: a MonoMethod describing the caller
6428 * Determines whenever the class has a static constructor and whenever it
6429 * needs to be called when executing CALLER.
6432 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
6436 method = mono_class_get_cctor (klass);
6438 return (method == caller) ? FALSE : TRUE;
6444 * mono_class_array_element_size:
6447 * Returns: the number of bytes an element of type @klass
6448 * uses when stored into an array.
6451 mono_class_array_element_size (MonoClass *klass)
6453 MonoType *type = &klass->byval_arg;
6456 switch (type->type) {
6459 case MONO_TYPE_BOOLEAN:
6463 case MONO_TYPE_CHAR:
6472 case MONO_TYPE_CLASS:
6473 case MONO_TYPE_STRING:
6474 case MONO_TYPE_OBJECT:
6475 case MONO_TYPE_SZARRAY:
6476 case MONO_TYPE_ARRAY:
6478 case MONO_TYPE_MVAR:
6479 return sizeof (gpointer);
6484 case MONO_TYPE_VALUETYPE:
6485 if (type->data.klass->enumtype) {
6486 type = mono_class_enum_basetype (type->data.klass);
6487 klass = klass->element_class;
6490 return mono_class_instance_size (klass) - sizeof (MonoObject);
6491 case MONO_TYPE_GENERICINST:
6492 type = &type->data.generic_class->container_class->byval_arg;
6495 case MONO_TYPE_VOID:
6499 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
6505 * mono_array_element_size:
6506 * @ac: pointer to a #MonoArrayClass
6508 * Returns: the size of single array element.
6511 mono_array_element_size (MonoClass *ac)
6513 g_assert (ac->rank);
6514 return ac->sizes.element_size;
6518 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
6519 MonoGenericContext *context)
6521 if (image->dynamic) {
6522 MonoClass *tmp_handle_class;
6523 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
6525 g_assert (tmp_handle_class);
6527 *handle_class = tmp_handle_class;
6529 if (tmp_handle_class == mono_defaults.typehandle_class)
6530 return &((MonoClass*)obj)->byval_arg;
6535 switch (token & 0xff000000) {
6536 case MONO_TOKEN_TYPE_DEF:
6537 case MONO_TOKEN_TYPE_REF:
6538 case MONO_TOKEN_TYPE_SPEC: {
6541 *handle_class = mono_defaults.typehandle_class;
6542 type = mono_type_get_full (image, token, context);
6545 mono_class_init (mono_class_from_mono_type (type));
6546 /* We return a MonoType* as handle */
6549 case MONO_TOKEN_FIELD_DEF: {
6551 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
6553 *handle_class = mono_defaults.fieldhandle_class;
6554 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
6557 mono_class_init (class);
6558 return mono_class_get_field (class, token);
6560 case MONO_TOKEN_METHOD_DEF:
6561 case MONO_TOKEN_METHOD_SPEC: {
6563 meth = mono_get_method_full (image, token, NULL, context);
6565 *handle_class = mono_defaults.methodhandle_class;
6568 case MONO_TOKEN_MEMBER_REF: {
6569 guint32 cols [MONO_MEMBERREF_SIZE];
6571 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
6572 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6573 mono_metadata_decode_blob_size (sig, &sig);
6574 if (*sig == 0x6) { /* it's a field */
6576 MonoClassField *field;
6577 field = mono_field_from_token (image, token, &klass, context);
6579 *handle_class = mono_defaults.fieldhandle_class;
6583 meth = mono_get_method_full (image, token, NULL, context);
6585 *handle_class = mono_defaults.methodhandle_class;
6590 g_warning ("Unknown token 0x%08x in ldtoken", token);
6597 * This function might need to call runtime functions so it can't be part
6598 * of the metadata library.
6600 static MonoLookupDynamicToken lookup_dynamic = NULL;
6603 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
6605 lookup_dynamic = func;
6609 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
6611 MonoClass *handle_class;
6613 return lookup_dynamic (image, token, TRUE, &handle_class, context);
6617 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
6619 return lookup_dynamic (image, token, valid_token, handle_class, context);
6622 static MonoGetCachedClassInfo get_cached_class_info = NULL;
6625 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
6627 get_cached_class_info = func;
6631 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
6633 if (!get_cached_class_info)
6636 return get_cached_class_info (klass, res);
6640 mono_install_get_class_from_name (MonoGetClassFromName func)
6642 get_class_from_name = func;
6646 mono_class_get_image (MonoClass *klass)
6648 return klass->image;
6652 * mono_class_get_element_class:
6653 * @klass: the MonoClass to act on
6655 * Returns: the element class of an array or an enumeration.
6658 mono_class_get_element_class (MonoClass *klass)
6660 return klass->element_class;
6664 * mono_class_is_valuetype:
6665 * @klass: the MonoClass to act on
6667 * Returns: true if the MonoClass represents a ValueType.
6670 mono_class_is_valuetype (MonoClass *klass)
6672 return klass->valuetype;
6676 * mono_class_is_enum:
6677 * @klass: the MonoClass to act on
6679 * Returns: true if the MonoClass represents an enumeration.
6682 mono_class_is_enum (MonoClass *klass)
6684 return klass->enumtype;
6688 * mono_class_enum_basetype:
6689 * @klass: the MonoClass to act on
6691 * Returns: the underlying type representation for an enumeration.
6694 mono_class_enum_basetype (MonoClass *klass)
6696 if (klass->element_class == klass)
6700 return &klass->element_class->byval_arg;
6704 * mono_class_get_parent
6705 * @klass: the MonoClass to act on
6707 * Returns: the parent class for this class.
6710 mono_class_get_parent (MonoClass *klass)
6712 return klass->parent;
6716 * mono_class_get_nesting_type;
6717 * @klass: the MonoClass to act on
6719 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
6722 mono_class_get_nesting_type (MonoClass *klass)
6724 return klass->nested_in;
6728 * mono_class_get_rank:
6729 * @klass: the MonoClass to act on
6731 * Returns: the rank for the array (the number of dimensions).
6734 mono_class_get_rank (MonoClass *klass)
6740 * mono_class_get_flags:
6741 * @klass: the MonoClass to act on
6743 * The type flags from the TypeDef table from the metadata.
6744 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
6747 * Returns: the flags from the TypeDef table.
6750 mono_class_get_flags (MonoClass *klass)
6752 return klass->flags;
6756 * mono_class_get_name
6757 * @klass: the MonoClass to act on
6759 * Returns: the name of the class.
6762 mono_class_get_name (MonoClass *klass)
6768 * mono_class_get_namespace:
6769 * @klass: the MonoClass to act on
6771 * Returns: the namespace of the class.
6774 mono_class_get_namespace (MonoClass *klass)
6776 return klass->name_space;
6780 * mono_class_get_type:
6781 * @klass: the MonoClass to act on
6783 * This method returns the internal Type representation for the class.
6785 * Returns: the MonoType from the class.
6788 mono_class_get_type (MonoClass *klass)
6790 return &klass->byval_arg;
6794 * mono_class_get_type_token
6795 * @klass: the MonoClass to act on
6797 * This method returns type token for the class.
6799 * Returns: the type token for the class.
6802 mono_class_get_type_token (MonoClass *klass)
6804 return klass->type_token;
6808 * mono_class_get_byref_type:
6809 * @klass: the MonoClass to act on
6814 mono_class_get_byref_type (MonoClass *klass)
6816 return &klass->this_arg;
6820 * mono_class_num_fields:
6821 * @klass: the MonoClass to act on
6823 * Returns: the number of static and instance fields in the class.
6826 mono_class_num_fields (MonoClass *klass)
6828 return klass->field.count;
6832 * mono_class_num_methods:
6833 * @klass: the MonoClass to act on
6835 * Returns: the number of methods in the class.
6838 mono_class_num_methods (MonoClass *klass)
6840 return klass->method.count;
6844 * mono_class_num_properties
6845 * @klass: the MonoClass to act on
6847 * Returns: the number of properties in the class.
6850 mono_class_num_properties (MonoClass *klass)
6852 mono_class_setup_properties (klass);
6854 return klass->ext->property.count;
6858 * mono_class_num_events:
6859 * @klass: the MonoClass to act on
6861 * Returns: the number of events in the class.
6864 mono_class_num_events (MonoClass *klass)
6866 mono_class_setup_events (klass);
6868 return klass->ext->event.count;
6872 * mono_class_get_fields:
6873 * @klass: the MonoClass to act on
6875 * This routine is an iterator routine for retrieving the fields in a class.
6877 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6878 * iterate over all of the elements. When no more values are
6879 * available, the return value is NULL.
6881 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
6884 mono_class_get_fields (MonoClass* klass, gpointer *iter)
6886 MonoClassField* field;
6890 mono_class_setup_fields_locking (klass);
6891 if (klass->exception_type)
6893 /* start from the first */
6894 if (klass->field.count) {
6895 return *iter = &klass->fields [0];
6903 if (field < &klass->fields [klass->field.count]) {
6904 return *iter = field;
6910 * mono_class_get_methods
6911 * @klass: the MonoClass to act on
6913 * This routine is an iterator routine for retrieving the fields in a class.
6915 * You must pass a gpointer that points to zero and is treated as an opaque handle to
6916 * iterate over all of the elements. When no more values are
6917 * available, the return value is NULL.
6919 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
6922 mono_class_get_methods (MonoClass* klass, gpointer *iter)
6924 MonoMethod** method;
6928 mono_class_init (klass);
6930 mono_class_setup_methods (klass);
6931 /* start from the first */
6932 if (klass->method.count) {
6933 *iter = &klass->methods [0];
6934 return klass->methods [0];
6942 if (method < &klass->methods [klass->method.count]) {
6950 * mono_class_get_virtual_methods:
6952 * Iterate over the virtual methods of KLASS.
6954 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
6957 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
6959 MonoMethod** method;
6962 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
6964 mono_class_setup_methods (klass);
6965 /* start from the first */
6966 method = &klass->methods [0];
6971 while (method < &klass->methods [klass->method.count]) {
6972 if (((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
6976 if (method < &klass->methods [klass->method.count]) {
6983 /* Search directly in metadata to avoid calling setup_methods () */
6984 MonoMethod *res = NULL;
6990 start_index = GPOINTER_TO_UINT (*iter);
6993 for (i = start_index; i < klass->method.count; ++i) {
6994 guint32 cols [MONO_METHOD_SIZE];
6996 /* class->method.first points into the methodptr table */
6997 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
6999 if (cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_VIRTUAL)
7003 if (i < klass->method.count) {
7004 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7005 /* Add 1 here so the if (*iter) check fails */
7006 *iter = GUINT_TO_POINTER (i + 1);
7015 * mono_class_get_properties:
7016 * @klass: the MonoClass to act on
7018 * This routine is an iterator routine for retrieving the properties in a class.
7020 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7021 * iterate over all of the elements. When no more values are
7022 * available, the return value is NULL.
7024 * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
7027 mono_class_get_properties (MonoClass* klass, gpointer *iter)
7029 MonoProperty* property;
7033 mono_class_init (klass);
7035 mono_class_setup_properties (klass);
7036 /* start from the first */
7037 if (klass->ext->property.count) {
7038 return *iter = &klass->ext->properties [0];
7046 if (property < &klass->ext->properties [klass->ext->property.count]) {
7047 return *iter = property;
7053 * mono_class_get_events:
7054 * @klass: the MonoClass to act on
7056 * This routine is an iterator routine for retrieving the properties in a class.
7058 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7059 * iterate over all of the elements. When no more values are
7060 * available, the return value is NULL.
7062 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
7065 mono_class_get_events (MonoClass* klass, gpointer *iter)
7071 mono_class_init (klass);
7073 mono_class_setup_events (klass);
7074 /* start from the first */
7075 if (klass->ext->event.count) {
7076 return *iter = &klass->ext->events [0];
7084 if (event < &klass->ext->events [klass->ext->event.count]) {
7085 return *iter = event;
7091 * mono_class_get_interfaces
7092 * @klass: the MonoClass to act on
7094 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
7096 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7097 * iterate over all of the elements. When no more values are
7098 * available, the return value is NULL.
7100 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7103 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
7110 mono_class_init (klass);
7111 if (!klass->interfaces_inited)
7112 mono_class_setup_interfaces (klass);
7113 /* start from the first */
7114 if (klass->interface_count) {
7115 *iter = &klass->interfaces [0];
7116 return klass->interfaces [0];
7124 if (iface < &klass->interfaces [klass->interface_count]) {
7132 * mono_class_get_nested_types
7133 * @klass: the MonoClass to act on
7135 * This routine is an iterator routine for retrieving the nested types of a class.
7136 * This works only if @klass is non-generic, or a generic type definition.
7138 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7139 * iterate over all of the elements. When no more values are
7140 * available, the return value is NULL.
7142 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7145 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
7153 mono_class_init (klass);
7154 if (!klass->nested_classes_inited) {
7155 if (!klass->type_token)
7156 klass->nested_classes_inited = TRUE;
7157 mono_loader_lock ();
7158 if (!klass->nested_classes_inited) {
7159 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
7162 guint32 cols [MONO_NESTED_CLASS_SIZE];
7163 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
7164 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
7165 mono_class_alloc_ext (klass);
7166 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
7168 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
7171 mono_memory_barrier ();
7172 klass->nested_classes_inited = TRUE;
7173 mono_loader_unlock ();
7177 /* start from the first */
7178 if (klass->ext && klass->ext->nested_classes) {
7179 *iter = klass->ext->nested_classes;
7180 return klass->ext->nested_classes->data;
7182 /* no nested types */
7196 * mono_field_get_name:
7197 * @field: the MonoClassField to act on
7199 * Returns: the name of the field.
7202 mono_field_get_name (MonoClassField *field)
7208 * mono_field_get_type:
7209 * @field: the MonoClassField to act on
7211 * Returns: MonoType of the field.
7214 mono_field_get_type (MonoClassField *field)
7220 * mono_field_get_parent:
7221 * @field: the MonoClassField to act on
7223 * Returns: MonoClass where the field was defined.
7226 mono_field_get_parent (MonoClassField *field)
7228 return field->parent;
7232 * mono_field_get_flags;
7233 * @field: the MonoClassField to act on
7235 * The metadata flags for a field are encoded using the
7236 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
7238 * Returns: the flags for the field.
7241 mono_field_get_flags (MonoClassField *field)
7243 return field->type->attrs;
7247 * mono_field_get_offset;
7248 * @field: the MonoClassField to act on
7250 * Returns: the field offset.
7253 mono_field_get_offset (MonoClassField *field)
7255 return field->offset;
7259 mono_field_get_rva (MonoClassField *field)
7263 MonoClass *klass = field->parent;
7265 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
7267 if (!klass->ext || !klass->ext->field_def_values) {
7268 mono_loader_lock ();
7269 mono_class_alloc_ext (klass);
7270 if (!klass->ext->field_def_values)
7271 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
7272 mono_loader_unlock ();
7275 field_index = mono_field_get_index (field);
7277 if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
7278 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
7280 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
7281 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
7284 return klass->ext->field_def_values [field_index].data;
7288 * mono_field_get_data;
7289 * @field: the MonoClassField to act on
7291 * Returns: pointer to the metadata constant value or to the field
7292 * data if it has an RVA flag.
7295 mono_field_get_data (MonoClassField *field)
7297 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
7298 MonoTypeEnum def_type;
7300 return mono_class_get_field_default_value (field, &def_type);
7301 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
7302 return mono_field_get_rva (field);
7309 * mono_property_get_name:
7310 * @prop: the MonoProperty to act on
7312 * Returns: the name of the property
7315 mono_property_get_name (MonoProperty *prop)
7321 * mono_property_get_set_method
7322 * @prop: the MonoProperty to act on.
7324 * Returns: the setter method of the property (A MonoMethod)
7327 mono_property_get_set_method (MonoProperty *prop)
7333 * mono_property_get_get_method
7334 * @prop: the MonoProperty to act on.
7336 * Returns: the setter method of the property (A MonoMethod)
7339 mono_property_get_get_method (MonoProperty *prop)
7345 * mono_property_get_parent:
7346 * @prop: the MonoProperty to act on.
7348 * Returns: the MonoClass where the property was defined.
7351 mono_property_get_parent (MonoProperty *prop)
7353 return prop->parent;
7357 * mono_property_get_flags:
7358 * @prop: the MonoProperty to act on.
7360 * The metadata flags for a property are encoded using the
7361 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
7363 * Returns: the flags for the property.
7366 mono_property_get_flags (MonoProperty *prop)
7372 * mono_event_get_name:
7373 * @event: the MonoEvent to act on
7375 * Returns: the name of the event.
7378 mono_event_get_name (MonoEvent *event)
7384 * mono_event_get_add_method:
7385 * @event: The MonoEvent to act on.
7387 * Returns: the @add' method for the event (a MonoMethod).
7390 mono_event_get_add_method (MonoEvent *event)
7396 * mono_event_get_remove_method:
7397 * @event: The MonoEvent to act on.
7399 * Returns: the @remove method for the event (a MonoMethod).
7402 mono_event_get_remove_method (MonoEvent *event)
7404 return event->remove;
7408 * mono_event_get_raise_method:
7409 * @event: The MonoEvent to act on.
7411 * Returns: the @raise method for the event (a MonoMethod).
7414 mono_event_get_raise_method (MonoEvent *event)
7416 return event->raise;
7420 * mono_event_get_parent:
7421 * @event: the MonoEvent to act on.
7423 * Returns: the MonoClass where the event is defined.
7426 mono_event_get_parent (MonoEvent *event)
7428 return event->parent;
7432 * mono_event_get_flags
7433 * @event: the MonoEvent to act on.
7435 * The metadata flags for an event are encoded using the
7436 * EVENT_* constants. See the tabledefs.h file for details.
7438 * Returns: the flags for the event.
7441 mono_event_get_flags (MonoEvent *event)
7443 return event->attrs;
7447 * mono_class_get_method_from_name:
7448 * @klass: where to look for the method
7449 * @name_space: name of the method
7450 * @param_count: number of parameters. -1 for any number.
7452 * Obtains a MonoMethod with a given name and number of parameters.
7453 * It only works if there are no multiple signatures for any given method name.
7456 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
7458 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
7462 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
7464 MonoMethod *res = NULL;
7467 /* Search directly in the metadata to avoid calling setup_methods () */
7468 for (i = 0; i < klass->method.count; ++i) {
7469 guint32 cols [MONO_METHOD_SIZE];
7472 /* class->method.first points into the methodptr table */
7473 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
7475 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
7476 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7477 if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
7488 * mono_class_get_method_from_name_flags:
7489 * @klass: where to look for the method
7490 * @name_space: name of the method
7491 * @param_count: number of parameters. -1 for any number.
7492 * @flags: flags which must be set in the method
7494 * Obtains a MonoMethod with a given name and number of parameters.
7495 * It only works if there are no multiple signatures for any given method name.
7498 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
7500 MonoMethod *res = NULL;
7503 mono_class_init (klass);
7505 if (klass->generic_class && !klass->methods) {
7506 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
7508 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
7512 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
7513 mono_class_setup_methods (klass);
7514 for (i = 0; i < klass->method.count; ++i) {
7515 MonoMethod *method = klass->methods [i];
7517 if (method->name[0] == name [0] &&
7518 !strcmp (name, method->name) &&
7519 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
7520 ((method->flags & flags) == flags)) {
7527 res = find_method_in_metadata (klass, name, param_count, flags);
7534 * mono_class_set_failure:
7535 * @klass: class in which the failure was detected
7536 * @ex_type: the kind of exception/error to be thrown (later)
7537 * @ex_data: exception data (specific to each type of exception/error)
7539 * Keep a detected failure informations in the class for later processing.
7540 * Note that only the first failure is kept.
7542 * LOCKING: Acquires the loader lock.
7545 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
7547 if (klass->exception_type)
7550 mono_loader_lock ();
7551 klass->exception_type = ex_type;
7553 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
7554 mono_loader_unlock ();
7560 * mono_class_get_exception_data:
7562 * Return the exception_data property of KLASS.
7564 * LOCKING: Acquires the loader lock.
7567 mono_class_get_exception_data (MonoClass *klass)
7569 return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
7573 * mono_classes_init:
7575 * Initialize the resources used by this module.
7578 mono_classes_init (void)
7580 mono_counters_register ("Inflated methods size",
7581 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
7582 mono_counters_register ("Inflated classes",
7583 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
7584 mono_counters_register ("Inflated classes size",
7585 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
7586 mono_counters_register ("MonoClass size",
7587 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
7588 mono_counters_register ("MonoClassExt size",
7589 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
7593 * mono_classes_cleanup:
7595 * Free the resources used by this module.
7598 mono_classes_cleanup (void)
7600 if (global_interface_bitset)
7601 mono_bitset_free (global_interface_bitset);
7605 * mono_class_get_exception_for_failure:
7606 * @klass: class in which the failure was detected
7608 * Return a constructed MonoException than the caller can then throw
7609 * using mono_raise_exception - or NULL if no failure is present (or
7610 * doesn't result in an exception).
7613 mono_class_get_exception_for_failure (MonoClass *klass)
7615 gpointer exception_data = mono_class_get_exception_data (klass);
7617 switch (klass->exception_type) {
7618 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
7619 MonoDomain *domain = mono_domain_get ();
7620 MonoSecurityManager* secman = mono_security_manager_get_methods ();
7621 MonoMethod *method = exception_data;
7622 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
7623 MonoObject *exc = NULL;
7627 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
7628 args [2] = mono_type_get_object (domain, &klass->byval_arg);
7629 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
7631 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
7632 return (MonoException*) exc;
7634 case MONO_EXCEPTION_TYPE_LOAD: {
7637 char *str = mono_type_get_full_name (klass);
7638 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
7639 name = mono_string_new (mono_domain_get (), str);
7641 ex = mono_get_exception_type_load (name, astr);
7645 case MONO_EXCEPTION_MISSING_METHOD: {
7646 char *class_name = exception_data;
7647 char *assembly_name = class_name + strlen (class_name) + 1;
7649 return mono_get_exception_missing_method (class_name, assembly_name);
7651 case MONO_EXCEPTION_MISSING_FIELD: {
7652 char *class_name = exception_data;
7653 char *member_name = class_name + strlen (class_name) + 1;
7655 return mono_get_exception_missing_field (class_name, member_name);
7657 case MONO_EXCEPTION_FILE_NOT_FOUND: {
7658 char *msg_format = exception_data;
7659 char *assembly_name = msg_format + strlen (msg_format) + 1;
7660 char *msg = g_strdup_printf (msg_format, assembly_name);
7663 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
7669 case MONO_EXCEPTION_BAD_IMAGE: {
7670 return mono_get_exception_bad_image_format (exception_data);
7673 MonoLoaderError *error;
7676 error = mono_loader_get_last_error ();
7678 ex = mono_loader_error_prepare_exception (error);
7682 /* TODO - handle other class related failures */
7689 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
7691 outer_klass = mono_class_get_generic_type_definition (outer_klass);
7692 inner_klass = mono_class_get_generic_type_definition (inner_klass);
7694 if (outer_klass == inner_klass)
7696 inner_klass = inner_klass->nested_in;
7697 } while (inner_klass);
7702 mono_class_get_generic_type_definition (MonoClass *klass)
7704 return klass->generic_class ? klass->generic_class->container_class : klass;
7708 * Check if @klass is a subtype of @parent ignoring generic instantiations.
7710 * Generic instantiations are ignored for all super types of @klass.
7712 * Visibility checks ignoring generic instantiations.
7715 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
7718 klass = mono_class_get_generic_type_definition (klass);
7719 parent = mono_class_get_generic_type_definition (parent);
7721 for (i = 0; i < klass->idepth; ++i) {
7722 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
7728 * Subtype can only access parent members with family protection if the site object
7729 * is subclass of Subtype. For example:
7730 * class A { protected int x; }
7732 * void valid_access () {
7736 * void invalid_access () {
7743 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
7745 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
7748 if (context_klass == NULL)
7750 /*if access_klass is not member_klass context_klass must be type compat*/
7751 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
7757 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
7760 if (accessing == accessed)
7762 if (!accessed || !accessing)
7764 mono_assembly_load_friends (accessed);
7765 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
7766 MonoAssemblyName *friend = tmp->data;
7767 /* Be conservative with checks */
7770 if (strcmp (accessing->aname.name, friend->name))
7772 if (friend->public_key_token [0]) {
7773 if (!accessing->aname.public_key_token [0])
7775 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
7784 * If klass is a generic type or if it is derived from a generic type, return the
7785 * MonoClass of the generic definition
7786 * Returns NULL if not found
7789 get_generic_definition_class (MonoClass *klass)
7792 if (klass->generic_class && klass->generic_class->container_class)
7793 return klass->generic_class->container_class;
7794 klass = klass->parent;
7800 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
7803 for (i = 0; i < ginst->type_argc; ++i) {
7804 MonoType *type = ginst->type_argv[i];
7805 switch (type->type) {
7806 case MONO_TYPE_SZARRAY:
7807 if (!can_access_type (access_klass, type->data.klass))
7810 case MONO_TYPE_ARRAY:
7811 if (!can_access_type (access_klass, type->data.array->eklass))
7815 if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
7818 case MONO_TYPE_CLASS:
7819 case MONO_TYPE_VALUETYPE:
7820 case MONO_TYPE_GENERICINST:
7821 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
7829 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
7833 if (access_klass->element_class && !access_klass->enumtype)
7834 access_klass = access_klass->element_class;
7836 if (member_klass->element_class && !member_klass->enumtype)
7837 member_klass = member_klass->element_class;
7839 access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
7841 if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
7844 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
7847 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
7850 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
7853 /*Non nested type with nested visibility. We just fail it.*/
7854 if (access_level >= TYPE_ATTRIBUTE_NESTED_PRIVATE && access_level <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM && member_klass->nested_in == NULL)
7857 switch (access_level) {
7858 case TYPE_ATTRIBUTE_NOT_PUBLIC:
7859 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7861 case TYPE_ATTRIBUTE_PUBLIC:
7864 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
7867 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
7868 return is_nesting_type (member_klass, access_klass);
7870 case TYPE_ATTRIBUTE_NESTED_FAMILY:
7871 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7873 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
7874 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7876 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
7877 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
7878 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7880 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
7881 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
7882 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
7887 /* FIXME: check visibility of type, too */
7889 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
7891 MonoClass *member_generic_def;
7892 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
7893 access_klass->generic_container) &&
7894 (member_generic_def = get_generic_definition_class (member_klass))) {
7895 MonoClass *access_container;
7897 if (access_klass->generic_container)
7898 access_container = access_klass;
7900 access_container = access_klass->generic_class->container_class;
7902 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
7906 /* Partition I 8.5.3.2 */
7907 /* the access level values are the same for fields and methods */
7908 switch (access_level) {
7909 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
7910 /* same compilation unit */
7911 return access_klass->image == member_klass->image;
7912 case FIELD_ATTRIBUTE_PRIVATE:
7913 return access_klass == member_klass;
7914 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
7915 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
7916 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
7919 case FIELD_ATTRIBUTE_ASSEMBLY:
7920 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7921 case FIELD_ATTRIBUTE_FAMILY:
7922 if (is_valid_family_access (access_klass, member_klass, context_klass))
7925 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
7926 if (is_valid_family_access (access_klass, member_klass, context_klass))
7928 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
7929 case FIELD_ATTRIBUTE_PUBLIC:
7936 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
7938 /* FIXME: check all overlapping fields */
7939 int can = can_access_member (method->klass, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7941 MonoClass *nested = method->klass->nested_in;
7943 can = can_access_member (nested, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
7946 nested = nested->nested_in;
7953 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
7955 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7957 MonoClass *nested = method->klass->nested_in;
7959 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7962 nested = nested->nested_in;
7967 * with generics calls to explicit interface implementations can be expressed
7968 * directly: the method is private, but we must allow it. This may be opening
7969 * a hole or the generics code should handle this differently.
7970 * Maybe just ensure the interface type is public.
7972 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
7978 * mono_method_can_access_method_full:
7979 * @method: The caller method
7980 * @called: The called method
7981 * @context_klass: The static type on stack of the owner @called object used
7983 * This function must be used with instance calls, as they have more strict family accessibility.
7984 * It can be used with static methods, but context_klass should be NULL.
7986 * Returns: TRUE if caller have proper visibility and acessibility to @called
7989 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
7991 MonoClass *access_class = method->klass;
7992 MonoClass *member_class = called->klass;
7993 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
7995 MonoClass *nested = access_class->nested_in;
7997 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8000 nested = nested->nested_in;
8007 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8010 if (called->is_inflated) {
8011 MonoMethodInflated * infl = (MonoMethodInflated*)called;
8012 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
8021 * mono_method_can_access_field_full:
8022 * @method: The caller method
8023 * @field: The accessed field
8024 * @context_klass: The static type on stack of the owner @field object used
8026 * This function must be used with instance fields, as they have more strict family accessibility.
8027 * It can be used with static fields, but context_klass should be NULL.
8029 * Returns: TRUE if caller have proper visibility and acessibility to @field
8032 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
8034 MonoClass *access_class = method->klass;
8035 MonoClass *member_class = field->parent;
8036 /* FIXME: check all overlapping fields */
8037 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8039 MonoClass *nested = access_class->nested_in;
8041 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8044 nested = nested->nested_in;
8051 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8057 * mono_type_is_valid_enum_basetype:
8058 * @type: The MonoType to check
8060 * Returns: TRUE if the type can be used as the basetype of an enum
8062 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
8063 switch (type->type) {
8066 case MONO_TYPE_BOOLEAN:
8069 case MONO_TYPE_CHAR:
8082 * mono_class_is_valid_enum:
8083 * @klass: An enum class to be validated
8085 * This method verify the required properties an enum should have.
8087 * Returns: TRUE if the informed enum class is valid
8089 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
8090 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
8091 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
8093 gboolean mono_class_is_valid_enum (MonoClass *klass) {
8094 MonoClassField * field;
8095 gpointer iter = NULL;
8096 gboolean found_base_field = FALSE;
8098 g_assert (klass->enumtype);
8099 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
8100 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
8104 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
8107 while ((field = mono_class_get_fields (klass, &iter))) {
8108 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
8109 if (found_base_field)
8111 found_base_field = TRUE;
8112 if (!mono_type_is_valid_enum_basetype (field->type))
8117 if (!found_base_field)
8120 if (klass->method.count > 0)
8127 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
8129 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
8132 static gboolean gshared_supported;
8135 mono_set_generic_sharing_supported (gboolean supported)
8137 gshared_supported = supported;
8141 * mono_class_generic_sharing_enabled:
8144 * Returns whether generic sharing is enabled for class.
8146 * This is a stop-gap measure to slowly introduce generic sharing
8147 * until we have all the issues sorted out, at which time this
8148 * function will disappear and generic sharing will always be enabled.
8151 mono_class_generic_sharing_enabled (MonoClass *class)
8153 static int generic_sharing = MONO_GENERIC_SHARING_NONE;
8154 static gboolean inited = FALSE;
8159 if (gshared_supported)
8160 generic_sharing = MONO_GENERIC_SHARING_ALL;
8162 generic_sharing = MONO_GENERIC_SHARING_NONE;
8164 if ((option = g_getenv ("MONO_GENERIC_SHARING"))) {
8165 if (strcmp (option, "corlib") == 0)
8166 generic_sharing = MONO_GENERIC_SHARING_CORLIB;
8167 else if (strcmp (option, "collections") == 0)
8168 generic_sharing = MONO_GENERIC_SHARING_COLLECTIONS;
8169 else if (strcmp (option, "all") == 0)
8170 generic_sharing = MONO_GENERIC_SHARING_ALL;
8171 else if (strcmp (option, "none") == 0)
8172 generic_sharing = MONO_GENERIC_SHARING_NONE;
8174 g_warning ("Unknown generic sharing option `%s'.", option);
8177 if (!gshared_supported)
8178 generic_sharing = MONO_GENERIC_SHARING_NONE;
8183 switch (generic_sharing) {
8184 case MONO_GENERIC_SHARING_NONE:
8186 case MONO_GENERIC_SHARING_ALL:
8188 case MONO_GENERIC_SHARING_CORLIB :
8189 return class->image == mono_defaults.corlib;
8190 case MONO_GENERIC_SHARING_COLLECTIONS:
8191 if (class->image != mono_defaults.corlib)
8193 while (class->nested_in)
8194 class = class->nested_in;
8195 return g_str_has_prefix (class->name_space, "System.Collections.Generic");
8197 g_assert_not_reached ();
8202 * mono_class_setup_interface_id:
8204 * Initializes MonoClass::interface_id if required.
8206 * LOCKING: Acquires the loader lock.
8209 mono_class_setup_interface_id (MonoClass *class)
8211 mono_loader_lock ();
8212 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
8213 class->interface_id = mono_get_unique_iid (class);
8214 mono_loader_unlock ();
8218 * mono_class_alloc_ext:
8220 * Allocate klass->ext if not already done.
8221 * LOCKING: Assumes the loader lock is held.
8224 mono_class_alloc_ext (MonoClass *klass)
8227 if (klass->generic_class) {
8228 klass->ext = g_new0 (MonoClassExt, 1);
8230 klass->ext = mono_image_alloc0 (klass->image, sizeof (MonoClassExt));
8232 class_ext_size += sizeof (MonoClassExt);
8237 * mono_class_setup_interfaces:
8239 * Initialize class->interfaces/interfaces_count.
8240 * LOCKING: Acquires the loader lock.
8243 mono_class_setup_interfaces (MonoClass *klass)
8247 if (klass->interfaces_inited)
8250 mono_loader_lock ();
8252 if (klass->interfaces_inited) {
8253 mono_loader_unlock ();
8257 if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
8260 /* generic IList, ICollection, IEnumerable */
8261 klass->interface_count = 1;
8262 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
8264 args [0] = &klass->element_class->byval_arg;
8265 klass->interfaces [0] = mono_class_bind_generic_parameters (
8266 mono_defaults.generic_ilist_class, 1, args, FALSE);
8267 } else if (klass->generic_class) {
8268 MonoClass *gklass = klass->generic_class->container_class;
8270 klass->interface_count = gklass->interface_count;
8271 klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
8272 for (i = 0; i < klass->interface_count; i++)
8273 klass->interfaces [i] = mono_class_inflate_generic_class (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class));
8276 mono_memory_barrier ();
8278 klass->interfaces_inited = TRUE;
8280 mono_loader_unlock ();