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 guint32 inflated_classes, inflated_classes_size, inflated_methods_size;
51 guint32 classes_size, class_ext_size;
53 /* Function supplied by the runtime to find classes by name using information from the AOT file */
54 static MonoGetClassFromName get_class_from_name = NULL;
56 static MonoClass * mono_class_create_from_typedef (MonoImage *image, guint32 type_token);
57 static gboolean mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res);
58 static gboolean can_access_type (MonoClass *access_klass, MonoClass *member_klass);
59 static MonoMethod* find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags);
60 static int generic_array_methods (MonoClass *class);
61 static void setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos);
63 static MonoMethod* mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter);
64 static char* mono_assembly_name_from_token (MonoImage *image, guint32 type_token);
65 static gboolean mono_class_is_variant_compatible (MonoClass *klass, MonoClass *oklass);
68 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
69 void (*mono_debugger_class_loaded_methods_func) (MonoClass *klass) = NULL;
72 * mono_class_from_typeref:
74 * @type_token: a TypeRef token
76 * Creates the MonoClass* structure representing the type defined by
77 * the typeref token valid inside @image.
78 * Returns: the MonoClass* representing the typeref token, NULL ifcould
82 mono_class_from_typeref (MonoImage *image, guint32 type_token)
84 guint32 cols [MONO_TYPEREF_SIZE];
85 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
87 const char *name, *nspace;
91 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
93 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
94 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
96 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
97 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
98 case MONO_RESOLTION_SCOPE_MODULE:
100 g_error ("null ResolutionScope not yet handled");
101 /* a typedef in disguise */
102 return mono_class_from_name (image, nspace, name);
103 case MONO_RESOLTION_SCOPE_MODULEREF:
104 module = mono_image_load_module (image, idx);
106 return mono_class_from_name (module, nspace, name);
108 char *msg = g_strdup_printf ("%s%s%s", nspace, nspace [0] ? "." : "", name);
111 human_name = mono_stringify_assembly_name (&image->assembly->aname);
112 mono_loader_set_error_type_load (msg, human_name);
118 case MONO_RESOLTION_SCOPE_TYPEREF: {
119 MonoClass *enclosing;
122 if (idx == mono_metadata_token_index (type_token)) {
123 mono_loader_set_error_bad_image (g_strdup_printf ("Image %s with self-referencing typeref token %08x.", image->name, type_token));
127 enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
131 if (enclosing->nested_classes_inited && enclosing->ext) {
132 /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
133 for (tmp = enclosing->ext->nested_classes; tmp; tmp = tmp->next) {
135 if (strcmp (res->name, name) == 0)
139 /* Don't call mono_class_init as we might've been called by it recursively */
140 int i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, 1);
142 guint32 class_nested = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, MONO_NESTED_CLASS_NESTED);
143 guint32 string_offset = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_TYPEDEF], class_nested - 1, MONO_TYPEDEF_NAME);
144 const char *nname = mono_metadata_string_heap (enclosing->image, string_offset);
146 if (strcmp (nname, name) == 0)
147 return mono_class_create_from_typedef (enclosing->image, MONO_TOKEN_TYPE_DEF | class_nested);
149 i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, i + 1);
152 g_warning ("TypeRef ResolutionScope not yet handled (%d) for %s.%s in image %s", idx, nspace, name, image->name);
155 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
159 if (idx > image->tables [MONO_TABLE_ASSEMBLYREF].rows) {
160 mono_loader_set_error_bad_image (g_strdup_printf ("Image %s with invalid assemblyref token %08x.", image->name, idx));
164 if (!image->references || !image->references [idx - 1])
165 mono_assembly_load_reference (image, idx - 1);
166 g_assert (image->references [idx - 1]);
168 /* If the assembly did not load, register this as a type load exception */
169 if (image->references [idx - 1] == REFERENCE_MISSING){
170 MonoAssemblyName aname;
173 mono_assembly_get_assemblyref (image, idx - 1, &aname);
174 human_name = mono_stringify_assembly_name (&aname);
175 mono_loader_set_error_assembly_load (human_name, image->assembly->ref_only);
181 return mono_class_from_name (image->references [idx - 1]->image, nspace, name);
186 mono_image_memdup (MonoImage *image, void *data, guint size)
188 void *res = mono_image_alloc (image, size);
189 memcpy (res, data, size);
193 /* Copy everything mono_metadata_free_array free. */
195 mono_dup_array_type (MonoImage *image, MonoArrayType *a)
198 a = mono_image_memdup (image, a, sizeof (MonoArrayType));
200 a->sizes = mono_image_memdup (image, a->sizes, a->numsizes * sizeof (int));
202 a->lobounds = mono_image_memdup (image, a->lobounds, a->numlobounds * sizeof (int));
204 a = g_memdup (a, sizeof (MonoArrayType));
206 a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
208 a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
213 /* Copy everything mono_metadata_free_method_signature free. */
215 mono_metadata_signature_deep_dup (MonoImage *image, MonoMethodSignature *sig)
219 sig = mono_metadata_signature_dup_full (image, sig);
221 sig->ret = mono_metadata_type_dup (image, sig->ret);
222 for (i = 0; i < sig->param_count; ++i)
223 sig->params [i] = mono_metadata_type_dup (image, sig->params [i]);
229 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
231 MonoAssembly *ta = klass->image->assembly;
233 g_string_append_printf (
234 str, ", %s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
236 ta->aname.major, ta->aname.minor, ta->aname.build, ta->aname.revision,
237 ta->aname.culture && *ta->aname.culture? ta->aname.culture: "neutral",
238 ta->aname.public_key_token [0] ? (char *)ta->aname.public_key_token : "null",
239 (ta->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
243 mono_type_name_check_byref (MonoType *type, GString *str)
246 g_string_append_c (str, '&');
250 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
251 MonoTypeNameFormat format)
255 switch (type->type) {
256 case MONO_TYPE_ARRAY: {
257 int i, rank = type->data.array->rank;
258 MonoTypeNameFormat nested_format;
260 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
261 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
263 mono_type_get_name_recurse (
264 &type->data.array->eklass->byval_arg, str, FALSE, nested_format);
265 g_string_append_c (str, '[');
267 g_string_append_c (str, '*');
268 for (i = 1; i < rank; i++)
269 g_string_append_c (str, ',');
270 g_string_append_c (str, ']');
272 mono_type_name_check_byref (type, str);
274 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
275 _mono_type_get_assembly_name (type->data.array->eklass, str);
278 case MONO_TYPE_SZARRAY: {
279 MonoTypeNameFormat nested_format;
281 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
282 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
284 mono_type_get_name_recurse (
285 &type->data.klass->byval_arg, str, FALSE, nested_format);
286 g_string_append (str, "[]");
288 mono_type_name_check_byref (type, str);
290 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
291 _mono_type_get_assembly_name (type->data.klass, str);
294 case MONO_TYPE_PTR: {
295 MonoTypeNameFormat nested_format;
297 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
298 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
300 mono_type_get_name_recurse (
301 type->data.type, str, FALSE, nested_format);
302 g_string_append_c (str, '*');
304 mono_type_name_check_byref (type, str);
306 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
307 _mono_type_get_assembly_name (mono_class_from_mono_type (type->data.type), str);
312 if (!mono_generic_param_info (type->data.generic_param))
313 g_string_append_printf (str, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", type->data.generic_param->num);
315 g_string_append (str, mono_generic_param_info (type->data.generic_param)->name);
317 mono_type_name_check_byref (type, str);
321 klass = mono_class_from_mono_type (type);
322 if (klass->nested_in) {
323 mono_type_get_name_recurse (
324 &klass->nested_in->byval_arg, str, TRUE, format);
325 if (format == MONO_TYPE_NAME_FORMAT_IL)
326 g_string_append_c (str, '.');
328 g_string_append_c (str, '+');
329 } else if (*klass->name_space) {
330 g_string_append (str, klass->name_space);
331 g_string_append_c (str, '.');
333 if (format == MONO_TYPE_NAME_FORMAT_IL) {
334 char *s = strchr (klass->name, '`');
335 int len = s ? s - klass->name : strlen (klass->name);
337 g_string_append_len (str, klass->name, len);
339 g_string_append (str, klass->name);
342 if (klass->generic_class) {
343 MonoGenericClass *gclass = klass->generic_class;
344 MonoGenericInst *inst = gclass->context.class_inst;
345 MonoTypeNameFormat nested_format;
348 nested_format = format == MONO_TYPE_NAME_FORMAT_FULL_NAME ?
349 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED : format;
351 if (format == MONO_TYPE_NAME_FORMAT_IL)
352 g_string_append_c (str, '<');
354 g_string_append_c (str, '[');
355 for (i = 0; i < inst->type_argc; i++) {
356 MonoType *t = inst->type_argv [i];
359 g_string_append_c (str, ',');
360 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
361 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
362 g_string_append_c (str, '[');
363 mono_type_get_name_recurse (inst->type_argv [i], str, FALSE, nested_format);
364 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
365 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
366 g_string_append_c (str, ']');
368 if (format == MONO_TYPE_NAME_FORMAT_IL)
369 g_string_append_c (str, '>');
371 g_string_append_c (str, ']');
372 } else if (klass->generic_container &&
373 (format != MONO_TYPE_NAME_FORMAT_FULL_NAME) &&
374 (format != MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)) {
377 if (format == MONO_TYPE_NAME_FORMAT_IL)
378 g_string_append_c (str, '<');
380 g_string_append_c (str, '[');
381 for (i = 0; i < klass->generic_container->type_argc; i++) {
383 g_string_append_c (str, ',');
384 g_string_append (str, mono_generic_container_get_param_info (klass->generic_container, i)->name);
386 if (format == MONO_TYPE_NAME_FORMAT_IL)
387 g_string_append_c (str, '>');
389 g_string_append_c (str, ']');
392 mono_type_name_check_byref (type, str);
394 if ((format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
395 (type->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
396 _mono_type_get_assembly_name (klass, str);
402 * mono_type_get_name_full:
404 * @format: the format for the return string.
407 * Returns: the string representation in a number of formats:
409 * if format is MONO_TYPE_NAME_FORMAT_REFLECTION, the return string is
410 * returned in the formatrequired by System.Reflection, this is the
411 * inverse of mono_reflection_parse_type ().
413 * if format is MONO_TYPE_NAME_FORMAT_IL, it returns a syntax that can
414 * be used by the IL assembler.
416 * if format is MONO_TYPE_NAME_FORMAT_FULL_NAME
418 * if format is MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED
421 mono_type_get_name_full (MonoType *type, MonoTypeNameFormat format)
425 result = g_string_new ("");
427 mono_type_get_name_recurse (type, result, FALSE, format);
429 return g_string_free (result, FALSE);
433 * mono_type_get_full_name:
436 * Returns: the string representation for type as required by System.Reflection.
437 * The inverse of mono_reflection_parse_type ().
440 mono_type_get_full_name (MonoClass *class)
442 return mono_type_get_name_full (mono_class_get_type (class), MONO_TYPE_NAME_FORMAT_REFLECTION);
446 * mono_type_get_name:
449 * Returns: the string representation for type as it would be represented in IL code.
452 mono_type_get_name (MonoType *type)
454 return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_IL);
458 * mono_type_get_underlying_type:
461 * Returns: the MonoType for the underlying integer type if @type
462 * is an enum and byref is false, otherwise the type itself.
465 mono_type_get_underlying_type (MonoType *type)
467 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype && !type->byref)
468 return mono_class_enum_basetype (type->data.klass);
469 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype && !type->byref)
470 return mono_class_enum_basetype (type->data.generic_class->container_class);
475 * mono_class_is_open_constructed_type:
478 * Returns TRUE if type represents a generics open constructed type
479 * (not all the type parameters required for the instantiation have
483 mono_class_is_open_constructed_type (MonoType *t)
489 case MONO_TYPE_SZARRAY:
490 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
491 case MONO_TYPE_ARRAY:
492 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
494 return mono_class_is_open_constructed_type (t->data.type);
495 case MONO_TYPE_GENERICINST:
496 return t->data.generic_class->context.class_inst->is_open;
503 inflate_generic_type (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
505 mono_error_init (error);
507 switch (type->type) {
508 case MONO_TYPE_MVAR: {
510 int num = mono_type_get_generic_param_num (type);
511 MonoGenericInst *inst = context->method_inst;
512 if (!inst || !inst->type_argv)
514 if (num >= inst->type_argc) {
515 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
516 mono_error_set_bad_image (error, image, "MVAR %d (%s) cannot be expanded in this context with %d instantiations",
517 num, info ? info->name : "", inst->type_argc);
522 * Note that the VAR/MVAR cases are different from the rest. The other cases duplicate @type,
523 * while the VAR/MVAR duplicates a type from the context. So, we need to ensure that the
524 * ->byref and ->attrs from @type are propagated to the returned type.
526 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
527 nt->byref = type->byref;
528 nt->attrs = type->attrs;
531 case MONO_TYPE_VAR: {
533 int num = mono_type_get_generic_param_num (type);
534 MonoGenericInst *inst = context->class_inst;
537 if (num >= inst->type_argc) {
538 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
539 mono_error_set_bad_image (error, image, "VAR %d (%s) cannot be expanded in this context with %d instantiations",
540 num, info ? info->name : "", inst->type_argc);
543 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
544 nt->byref = type->byref;
545 nt->attrs = type->attrs;
548 case MONO_TYPE_SZARRAY: {
549 MonoClass *eclass = type->data.klass;
550 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
551 if (!inflated || !mono_error_ok (error))
553 nt = mono_metadata_type_dup (image, type);
554 nt->data.klass = mono_class_from_mono_type (inflated);
555 mono_metadata_free_type (inflated);
558 case MONO_TYPE_ARRAY: {
559 MonoClass *eclass = type->data.array->eklass;
560 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
561 if (!inflated || !mono_error_ok (error))
563 nt = mono_metadata_type_dup (image, type);
564 nt->data.array = g_memdup (nt->data.array, sizeof (MonoArrayType));
565 nt->data.array->eklass = mono_class_from_mono_type (inflated);
566 mono_metadata_free_type (inflated);
569 case MONO_TYPE_GENERICINST: {
570 MonoGenericClass *gclass = type->data.generic_class;
571 MonoGenericInst *inst;
573 if (!gclass->context.class_inst->is_open)
576 inst = mono_metadata_inflate_generic_inst (gclass->context.class_inst, context, error);
577 if (!mono_error_ok (error))
579 if (inst != gclass->context.class_inst)
580 gclass = mono_metadata_lookup_generic_class (gclass->container_class, inst, gclass->is_dynamic);
582 if (gclass == type->data.generic_class)
585 nt = mono_metadata_type_dup (image, type);
586 nt->data.generic_class = gclass;
589 case MONO_TYPE_CLASS:
590 case MONO_TYPE_VALUETYPE: {
591 MonoClass *klass = type->data.klass;
592 MonoGenericContainer *container = klass->generic_container;
593 MonoGenericInst *inst;
594 MonoGenericClass *gclass = NULL;
600 /* We can't use context->class_inst directly, since it can have more elements */
601 inst = mono_metadata_inflate_generic_inst (container->context.class_inst, context, error);
602 if (!mono_error_ok (error))
604 if (inst == container->context.class_inst)
607 gclass = mono_metadata_lookup_generic_class (klass, inst, klass->image->dynamic);
609 nt = mono_metadata_type_dup (image, type);
610 nt->type = MONO_TYPE_GENERICINST;
611 nt->data.generic_class = gclass;
621 mono_generic_class_get_context (MonoGenericClass *gclass)
623 return &gclass->context;
627 mono_class_get_context (MonoClass *class)
629 return class->generic_class ? mono_generic_class_get_context (class->generic_class) : NULL;
633 * mono_class_get_generic_container:
635 * Return the generic container of KLASS which should be a generic type definition.
637 MonoGenericContainer*
638 mono_class_get_generic_container (MonoClass *klass)
640 g_assert (klass->is_generic);
642 return klass->generic_container;
646 * mono_class_get_generic_class:
648 * Return the MonoGenericClass of KLASS, which should be a generic instance.
651 mono_class_get_generic_class (MonoClass *klass)
653 g_assert (klass->is_inflated);
655 return klass->generic_class;
659 * mono_class_inflate_generic_type_with_mempool:
660 * @mempool: a mempool
662 * @context: a generics context
663 * @error: error context
665 * The same as mono_class_inflate_generic_type, but allocates the MonoType
666 * from mempool if it is non-NULL. If it is NULL, the MonoType is
667 * allocated on the heap and is owned by the caller.
668 * The returned type can potentially be the same as TYPE, so it should not be
669 * modified by the caller, and it should be freed using mono_metadata_free_type ().
672 mono_class_inflate_generic_type_with_mempool (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
674 MonoType *inflated = NULL;
675 mono_error_init (error);
678 inflated = inflate_generic_type (image, type, context, error);
679 if (!mono_error_ok (error))
683 MonoType *shared = mono_metadata_get_shared_type (type);
688 return mono_metadata_type_dup (image, type);
692 mono_stats.inflated_type_count++;
697 * mono_class_inflate_generic_type:
699 * @context: a generics context
701 * If @type is a generic type and @context is not NULL, instantiate it using the
702 * generics context @context.
704 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
705 * on the heap and is owned by the caller. Returns NULL on error.
707 * @deprecated Please use mono_class_inflate_generic_type_checked instead
710 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
714 result = mono_class_inflate_generic_type_checked (type, context, &error);
716 if (!mono_error_ok (&error)) {
717 mono_error_cleanup (&error);
724 * mono_class_inflate_generic_type:
726 * @context: a generics context
727 * @error: error context to use
729 * If @type is a generic type and @context is not NULL, instantiate it using the
730 * generics context @context.
732 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
733 * on the heap and is owned by the caller.
736 mono_class_inflate_generic_type_checked (MonoType *type, MonoGenericContext *context, MonoError *error)
738 return mono_class_inflate_generic_type_with_mempool (NULL, type, context, error);
742 * mono_class_inflate_generic_type_no_copy:
744 * Same as inflate_generic_type_with_mempool, but return TYPE if no inflation
748 mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context)
751 MonoType *inflated = NULL;
754 inflated = inflate_generic_type (image, type, context, &error);
755 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
761 mono_stats.inflated_type_count++;
766 mono_class_inflate_generic_class_checked (MonoClass *gklass, MonoGenericContext *context, MonoError *error)
771 inflated = mono_class_inflate_generic_type_checked (&gklass->byval_arg, context, error);
772 if (!mono_error_ok (error))
775 res = mono_class_from_mono_type (inflated);
776 mono_metadata_free_type (inflated);
781 * mono_class_inflate_generic_class:
783 * Inflate the class GKLASS with CONTEXT.
786 mono_class_inflate_generic_class (MonoClass *gklass, MonoGenericContext *context)
791 res = mono_class_inflate_generic_class_checked (gklass, context, &error);
792 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
799 static MonoGenericContext
800 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with, MonoError *error)
802 MonoGenericInst *class_inst = NULL;
803 MonoGenericInst *method_inst = NULL;
804 MonoGenericContext res = { NULL, NULL };
806 mono_error_init (error);
808 if (context->class_inst) {
809 class_inst = mono_metadata_inflate_generic_inst (context->class_inst, inflate_with, error);
810 if (!mono_error_ok (error))
814 if (context->method_inst) {
815 method_inst = mono_metadata_inflate_generic_inst (context->method_inst, inflate_with, error);
816 if (!mono_error_ok (error))
820 res.class_inst = class_inst;
821 res.method_inst = method_inst;
827 * mono_class_inflate_generic_method:
828 * @method: a generic method
829 * @context: a generics context
831 * Instantiate the generic method @method using the generics context @context.
833 * Returns: the new instantiated method
836 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
838 return mono_class_inflate_generic_method_full (method, NULL, context);
842 * mono_class_inflate_generic_method_full:
844 * Instantiate method @method with the generic context @context.
845 * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
846 * Use mono_method_signature () and mono_method_get_header () to get the correct values.
849 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
852 MonoMethod *res = mono_class_inflate_generic_method_full_checked (method, klass_hint, context, &error);
853 if (!mono_error_ok (&error))
854 /*FIXME do proper error handling - on this case, kill this function. */
855 g_error ("Could not inflate generic method due to %s", mono_error_get_message (&error));
861 * mono_class_inflate_generic_method_full_checked:
862 * Same as mono_class_inflate_generic_method_full but return failure using @error.
865 mono_class_inflate_generic_method_full_checked (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context, MonoError *error)
868 MonoMethodInflated *iresult, *cached;
869 MonoMethodSignature *sig;
870 MonoGenericContext tmp_context;
871 gboolean is_mb_open = FALSE;
873 mono_error_init (error);
875 /* The `method' has already been instantiated before => we need to peel out the instantiation and create a new context */
876 while (method->is_inflated) {
877 MonoGenericContext *method_context = mono_method_get_context (method);
878 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
880 tmp_context = inflate_generic_context (method_context, context, error);
881 if (!mono_error_ok (error))
883 context = &tmp_context;
885 if (mono_metadata_generic_context_equal (method_context, context))
888 method = imethod->declaring;
891 if (!method->is_generic && !method->klass->generic_container)
895 * The reason for this hack is to fix the behavior of inflating generic methods that come from a MethodBuilder.
896 * What happens is that instantiating a generic MethodBuilder with its own arguments should create a diferent object.
897 * This is opposite to the way non-SRE MethodInfos behave.
899 * This happens, for example, when we want to emit a recursive generic method. Given the following C# code:
901 * void Example<T> () {
905 * In Example, the method token must be encoded as: "void Example<!!0>()"
907 * The reference to the first generic argument, "!!0", must be explicit otherwise it won't be inflated
908 * properly. To get that we need to inflate the MethodBuilder with its own arguments.
910 * On the other hand, inflating a non-SRE generic method with its own arguments should
911 * return itself. For example:
913 * MethodInfo m = ... //m is a generic method definition
914 * MethodInfo res = m.MakeGenericMethod (m.GetGenericArguments ());
917 * To allow such scenarios we must allow inflation of MethodBuilder to happen in a diferent way than
918 * what happens with regular methods.
920 * There is one last touch to this madness, once a TypeBuilder is finished, IOW CreateType() is called,
921 * everything should behave like a regular type or method.
924 is_mb_open = method->is_generic &&
925 method->klass->image->dynamic && !method->klass->wastypebuilder && /* that is a MethodBuilder from an unfinished TypeBuilder */
926 context->method_inst == mono_method_get_generic_container (method)->context.method_inst; /* and it's been instantiated with its own arguments. */
928 iresult = g_new0 (MonoMethodInflated, 1);
929 iresult->context = *context;
930 iresult->declaring = method;
931 iresult->method.method.is_mb_open = is_mb_open;
933 if (!context->method_inst && method->is_generic)
934 iresult->context.method_inst = mono_method_get_generic_container (method)->context.method_inst;
936 if (!context->class_inst) {
937 g_assert (!iresult->declaring->klass->generic_class);
938 if (iresult->declaring->klass->generic_container)
939 iresult->context.class_inst = iresult->declaring->klass->generic_container->context.class_inst;
940 else if (iresult->declaring->klass->generic_class)
941 iresult->context.class_inst = iresult->declaring->klass->generic_class->context.class_inst;
945 cached = mono_method_inflated_lookup (iresult, FALSE);
947 mono_loader_unlock ();
949 return (MonoMethod*)cached;
952 mono_stats.inflated_method_count++;
954 inflated_methods_size += sizeof (MonoMethodInflated);
956 sig = mono_method_signature (method);
958 char *name = mono_type_get_full_name (method->klass);
959 mono_error_set_bad_image (error, method->klass->image, "Could not resolve signature of method %s:%s", name, method->name);
965 memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
967 memcpy (&iresult->method.method, method, sizeof (MonoMethod));
970 result = (MonoMethod *) iresult;
971 result->is_inflated = TRUE;
972 result->is_generic = FALSE;
973 result->sre_method = FALSE;
974 result->signature = NULL;
975 result->is_mb_open = is_mb_open;
977 if (!context->method_inst) {
978 /* Set the generic_container of the result to the generic_container of method */
979 MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
981 if (generic_container) {
982 result->is_generic = 1;
983 mono_method_set_generic_container (result, generic_container);
987 if (!klass_hint || !klass_hint->generic_class ||
988 klass_hint->generic_class->container_class != method->klass ||
989 klass_hint->generic_class->context.class_inst != context->class_inst)
992 if (method->klass->generic_container)
993 result->klass = klass_hint;
995 if (!result->klass) {
996 MonoType *inflated = inflate_generic_type (NULL, &method->klass->byval_arg, context, error);
997 if (!mono_error_ok (error))
1000 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
1002 mono_metadata_free_type (inflated);
1005 mono_method_inflated_lookup (iresult, TRUE);
1006 mono_loader_unlock ();
1010 mono_loader_unlock ();
1016 * mono_get_inflated_method:
1018 * Obsolete. We keep it around since it's mentioned in the public API.
1021 mono_get_inflated_method (MonoMethod *method)
1027 * mono_method_get_context_general:
1029 * @uninflated: handle uninflated methods?
1031 * Returns the generic context of a method or NULL if it doesn't have
1032 * one. For an inflated method that's the context stored in the
1033 * method. Otherwise it's in the method's generic container or in the
1034 * generic container of the method's class.
1037 mono_method_get_context_general (MonoMethod *method, gboolean uninflated)
1039 if (method->is_inflated) {
1040 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1041 return &imethod->context;
1045 if (method->is_generic)
1046 return &(mono_method_get_generic_container (method)->context);
1047 if (method->klass->generic_container)
1048 return &method->klass->generic_container->context;
1053 * mono_method_get_context:
1056 * Returns the generic context for method if it's inflated, otherwise
1060 mono_method_get_context (MonoMethod *method)
1062 return mono_method_get_context_general (method, FALSE);
1066 * mono_method_get_generic_container:
1068 * Returns the generic container of METHOD, which should be a generic method definition.
1069 * Returns NULL if METHOD is not a generic method definition.
1070 * LOCKING: Acquires the loader lock.
1072 MonoGenericContainer*
1073 mono_method_get_generic_container (MonoMethod *method)
1075 MonoGenericContainer *container;
1077 if (!method->is_generic)
1080 container = mono_image_property_lookup (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER);
1081 g_assert (container);
1087 * mono_method_set_generic_container:
1089 * Sets the generic container of METHOD to CONTAINER.
1090 * LOCKING: Acquires the loader lock.
1093 mono_method_set_generic_container (MonoMethod *method, MonoGenericContainer* container)
1095 g_assert (method->is_generic);
1097 mono_image_property_insert (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER, container);
1101 * mono_class_find_enum_basetype:
1102 * @class: The enum class
1104 * Determine the basetype of an enum by iterating through its fields. We do this
1105 * in a separate function since it is cheaper than calling mono_class_setup_fields.
1108 mono_class_find_enum_basetype (MonoClass *class)
1110 MonoGenericContainer *container = NULL;
1111 MonoImage *m = class->image;
1112 const int top = class->field.count;
1115 g_assert (class->enumtype);
1117 if (class->generic_container)
1118 container = class->generic_container;
1119 else if (class->generic_class) {
1120 MonoClass *gklass = class->generic_class->container_class;
1122 container = gklass->generic_container;
1123 g_assert (container);
1127 * Fetch all the field information.
1129 for (i = 0; i < top; i++){
1131 guint32 cols [MONO_FIELD_SIZE];
1132 int idx = class->field.first + i;
1135 /* class->field.first and idx points into the fieldptr table */
1136 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1138 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC) //no need to decode static fields
1141 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL))
1144 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1145 mono_metadata_decode_value (sig, &sig);
1146 /* FIELD signature == 0x06 */
1150 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1153 if (class->generic_class) {
1154 //FIXME do we leak here?
1155 ftype = mono_class_inflate_generic_type (ftype, mono_class_get_context (class));
1156 ftype->attrs = cols [MONO_FIELD_FLAGS];
1166 * Checks for MonoClass::exception_type without resolving all MonoType's into MonoClass'es
1169 mono_type_has_exceptions (MonoType *type)
1171 switch (type->type) {
1172 case MONO_TYPE_CLASS:
1173 case MONO_TYPE_VALUETYPE:
1174 case MONO_TYPE_SZARRAY:
1175 return type->data.klass->exception_type;
1176 case MONO_TYPE_ARRAY:
1177 return type->data.array->eklass->exception_type;
1178 case MONO_TYPE_GENERICINST:
1179 return mono_generic_class_get_class (type->data.generic_class)->exception_type;
1185 * mono_class_setup_fields:
1186 * @class: The class to initialize
1188 * Initializes the class->fields.
1189 * LOCKING: Assumes the loader lock is held.
1192 mono_class_setup_fields (MonoClass *class)
1194 MonoImage *m = class->image;
1195 int top = class->field.count;
1196 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1197 int i, blittable = TRUE;
1198 guint32 real_size = 0;
1199 guint32 packing_size = 0;
1200 gboolean explicit_size;
1201 MonoClassField *field;
1202 MonoGenericContainer *container = NULL;
1203 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1205 if (class->size_inited)
1208 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1210 * This happens when a generic instance of an unfinished generic typebuilder
1211 * is used as an element type for creating an array type. We can't initialize
1212 * the fields of this class using the fields of gklass, since gklass is not
1213 * finished yet, fields could be added to it later.
1219 mono_class_setup_fields (gtd);
1220 if (gtd->exception_type) {
1221 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1225 top = gtd->field.count;
1226 class->field.first = gtd->field.first;
1227 class->field.count = gtd->field.count;
1230 class->instance_size = 0;
1232 class->sizes.class_size = 0;
1234 if (class->parent) {
1235 /* For generic instances, class->parent might not have been initialized */
1236 mono_class_init (class->parent);
1237 if (!class->parent->size_inited) {
1238 mono_class_setup_fields (class->parent);
1239 if (class->parent->exception_type) {
1240 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1244 class->instance_size += class->parent->instance_size;
1245 class->min_align = class->parent->min_align;
1246 /* we use |= since it may have been set already */
1247 class->has_references |= class->parent->has_references;
1248 blittable = class->parent->blittable;
1250 class->instance_size = sizeof (MonoObject);
1251 class->min_align = 1;
1254 /* We can't really enable 16 bytes alignment until the GC supports it.
1255 The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
1256 boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
1257 Bug #506144 is an example of this issue.
1259 if (class->simd_type)
1260 class->min_align = 16;
1262 /* Get the real size */
1263 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1265 if (explicit_size) {
1266 g_assert ((packing_size & 0xfffffff0) == 0);
1267 class->packing_size = packing_size;
1268 real_size += class->instance_size;
1272 if (explicit_size && real_size) {
1273 class->instance_size = MAX (real_size, class->instance_size);
1275 class->size_inited = 1;
1276 class->blittable = blittable;
1280 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1283 /* Prevent infinite loops if the class references itself */
1284 class->size_inited = 1;
1286 class->fields = mono_image_alloc0 (class->image, sizeof (MonoClassField) * top);
1288 if (class->generic_container) {
1289 container = class->generic_container;
1291 container = gtd->generic_container;
1292 g_assert (container);
1296 * Fetch all the field information.
1298 for (i = 0; i < top; i++){
1299 int idx = class->field.first + i;
1300 field = &class->fields [i];
1302 field->parent = class;
1305 MonoClassField *gfield = >d->fields [i];
1307 field->name = mono_field_get_name (gfield);
1308 /*This memory must come from the image mempool as we don't have a chance to free it.*/
1309 field->type = mono_class_inflate_generic_type_no_copy (class->image, gfield->type, mono_class_get_context (class));
1310 g_assert (field->type->attrs == gfield->type->attrs);
1311 if (mono_field_is_deleted (field))
1313 field->offset = gfield->offset;
1316 guint32 cols [MONO_FIELD_SIZE];
1318 /* class->field.first and idx points into the fieldptr table */
1319 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1320 /* The name is needed for fieldrefs */
1321 field->name = mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]);
1322 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL)) {
1323 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1326 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1327 mono_metadata_decode_value (sig, &sig);
1328 /* FIELD signature == 0x06 */
1329 g_assert (*sig == 0x06);
1330 field->type = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1332 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1335 if (mono_field_is_deleted (field))
1337 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1339 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1340 field->offset = offset;
1342 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1343 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Missing field layout info for %s", field->name));
1346 if (field->offset < -1) { /*-1 is used to encode special static fields */
1347 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Invalid negative field offset %d for %s", field->offset, field->name));
1353 /* Only do these checks if we still think this type is blittable */
1354 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1355 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1358 MonoClass *field_class = mono_class_from_mono_type (field->type);
1360 mono_class_setup_fields (field_class);
1361 if (field_class->exception_type) {
1362 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1366 if (!field_class || !field_class->blittable)
1371 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1372 class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1373 blittable = class->element_class->blittable;
1376 if (mono_type_has_exceptions (field->type)) {
1377 char *class_name = mono_type_get_full_name (class);
1378 char *type_name = mono_type_full_name (field->type);
1380 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1381 g_warning ("Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
1382 g_free (class_name);
1386 /* The def_value of fields is compute lazily during vtable creation */
1389 if (class == mono_defaults.string_class)
1392 class->blittable = blittable;
1394 if (class->enumtype && !mono_class_enum_basetype (class)) {
1395 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1398 if (explicit_size && real_size) {
1399 class->instance_size = MAX (real_size, class->instance_size);
1402 if (class->exception_type)
1404 mono_class_layout_fields (class);
1406 /*valuetypes can't be neither bigger than 1Mb or empty. */
1407 if (class->valuetype && (class->instance_size <= 0 || class->instance_size > (0x100000 + sizeof (MonoObject))))
1408 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1412 * mono_class_setup_fields_locking:
1413 * @class: The class to initialize
1415 * Initializes the class->fields array of fields.
1416 * Aquires the loader lock.
1419 mono_class_setup_fields_locking (MonoClass *class)
1421 mono_loader_lock ();
1422 mono_class_setup_fields (class);
1423 mono_loader_unlock ();
1427 * mono_class_has_references:
1429 * Returns whenever @klass->has_references is set, initializing it if needed.
1430 * Aquires the loader lock.
1433 mono_class_has_references (MonoClass *klass)
1435 if (klass->init_pending) {
1436 /* Be conservative */
1439 mono_class_init (klass);
1441 return klass->has_references;
1445 /* useful until we keep track of gc-references in corlib etc. */
1447 #define IS_GC_REFERENCE(t) FALSE
1449 #define IS_GC_REFERENCE(t) ((t)->type == MONO_TYPE_U && class->image == mono_defaults.corlib)
1453 * mono_type_get_basic_type_from_generic:
1456 * Returns a closed type corresponding to the possibly open type
1460 mono_type_get_basic_type_from_generic (MonoType *type)
1462 /* When we do generic sharing we let type variables stand for reference types. */
1463 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1464 return &mono_defaults.object_class->byval_arg;
1469 * mono_class_layout_fields:
1472 * Compute the placement of fields inside an object or struct, according to
1473 * the layout rules and set the following fields in @class:
1474 * - has_references (if the class contains instance references firled or structs that contain references)
1475 * - has_static_refs (same, but for static fields)
1476 * - instance_size (size of the object in memory)
1477 * - class_size (size needed for the static fields)
1478 * - size_inited (flag set when the instance_size is set)
1480 * LOCKING: this is supposed to be called with the loader lock held.
1483 mono_class_layout_fields (MonoClass *class)
1486 const int top = class->field.count;
1487 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1488 guint32 pass, passes, real_size;
1489 gboolean gc_aware_layout = FALSE;
1490 MonoClassField *field;
1493 * When we do generic sharing we need to have layout
1494 * information for open generic classes (either with a generic
1495 * context containing type variables or with a generic
1496 * container), so we don't return in that case anymore.
1500 * Enable GC aware auto layout: in this mode, reference
1501 * fields are grouped together inside objects, increasing collector
1503 * Requires that all classes whose layout is known to native code be annotated
1504 * with [StructLayout (LayoutKind.Sequential)]
1505 * Value types have gc_aware_layout disabled by default, as per
1506 * what the default is for other runtimes.
1508 /* corlib is missing [StructLayout] directives in many places */
1509 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1510 if (class->image != mono_defaults.corlib &&
1511 class->byval_arg.type != MONO_TYPE_VALUETYPE)
1512 gc_aware_layout = TRUE;
1513 /* from System.dll, used in metadata/process.h */
1514 if (strcmp (class->name, "ProcessStartInfo") == 0)
1515 gc_aware_layout = FALSE;
1518 /* Compute klass->has_references */
1520 * Process non-static fields first, since static fields might recursively
1521 * refer to the class itself.
1523 for (i = 0; i < top; i++) {
1526 field = &class->fields [i];
1528 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1529 ftype = mono_type_get_underlying_type (field->type);
1530 ftype = mono_type_get_basic_type_from_generic (ftype);
1531 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1532 class->has_references = TRUE;
1536 for (i = 0; i < top; i++) {
1539 field = &class->fields [i];
1541 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1542 ftype = mono_type_get_underlying_type (field->type);
1543 ftype = mono_type_get_basic_type_from_generic (ftype);
1544 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1545 class->has_static_refs = TRUE;
1549 for (i = 0; i < top; i++) {
1552 field = &class->fields [i];
1554 ftype = mono_type_get_underlying_type (field->type);
1555 ftype = mono_type_get_basic_type_from_generic (ftype);
1556 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1557 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1558 class->has_static_refs = TRUE;
1560 class->has_references = TRUE;
1565 * Compute field layout and total size (not considering static fields)
1569 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1570 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1572 if (gc_aware_layout)
1577 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1581 real_size = class->parent->instance_size;
1583 real_size = sizeof (MonoObject);
1585 for (pass = 0; pass < passes; ++pass) {
1586 for (i = 0; i < top; i++){
1591 field = &class->fields [i];
1593 if (mono_field_is_deleted (field))
1595 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1598 ftype = mono_type_get_underlying_type (field->type);
1599 ftype = mono_type_get_basic_type_from_generic (ftype);
1600 if (gc_aware_layout) {
1601 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1610 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1611 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1612 /* This field is a hack inserted by MCS to empty structures */
1616 size = mono_type_size (field->type, &align);
1618 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1619 align = class->packing_size ? MIN (class->packing_size, align): align;
1620 /* if the field has managed references, we need to force-align it
1623 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1624 align = MAX (align, sizeof (gpointer));
1626 class->min_align = MAX (align, class->min_align);
1627 field->offset = real_size;
1628 field->offset += align - 1;
1629 field->offset &= ~(align - 1);
1630 real_size = field->offset + size;
1633 class->instance_size = MAX (real_size, class->instance_size);
1635 if (class->instance_size & (class->min_align - 1)) {
1636 class->instance_size += class->min_align - 1;
1637 class->instance_size &= ~(class->min_align - 1);
1641 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1643 for (i = 0; i < top; i++) {
1648 field = &class->fields [i];
1651 * There must be info about all the fields in a type if it
1652 * uses explicit layout.
1655 if (mono_field_is_deleted (field))
1657 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1660 size = mono_type_size (field->type, &align);
1661 class->min_align = MAX (align, class->min_align);
1664 * When we get here, field->offset is already set by the
1665 * loader (for either runtime fields or fields loaded from metadata).
1666 * The offset is from the start of the object: this works for both
1667 * classes and valuetypes.
1669 field->offset += sizeof (MonoObject);
1670 ftype = mono_type_get_underlying_type (field->type);
1671 ftype = mono_type_get_basic_type_from_generic (ftype);
1672 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1673 if (field->offset % sizeof (gpointer)) {
1674 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1681 real_size = MAX (real_size, size + field->offset);
1683 class->instance_size = MAX (real_size, class->instance_size);
1687 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1689 * For small structs, set min_align to at least the struct size to improve
1690 * performance, and since the JIT memset/memcpy code assumes this and generates
1691 * unaligned accesses otherwise. See #78990 for a testcase.
1693 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1694 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1697 class->size_inited = 1;
1700 * Compute static field layout and size
1702 for (i = 0; i < top; i++){
1706 field = &class->fields [i];
1708 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1710 if (mono_field_is_deleted (field))
1713 if (mono_type_has_exceptions (field->type)) {
1714 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1718 size = mono_type_size (field->type, &align);
1719 field->offset = class->sizes.class_size;
1720 field->offset += align - 1;
1721 field->offset &= ~(align - 1);
1722 class->sizes.class_size = field->offset + size;
1727 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1731 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1732 method->klass = class;
1733 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1734 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1735 method->signature = sig;
1736 method->name = name;
1739 if (name [0] == '.') {
1740 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1742 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1748 * mono_class_setup_methods:
1751 * Initializes the 'methods' array in the klass.
1752 * Calling this method should be avoided if possible since it allocates a lot
1753 * of long-living MonoMethod structures.
1754 * Methods belonging to an interface are assigned a sequential slot starting
1757 * On failure this function sets class->exception_type
1760 mono_class_setup_methods (MonoClass *class)
1763 MonoMethod **methods;
1768 mono_loader_lock ();
1770 if (class->methods) {
1771 mono_loader_unlock ();
1775 if (class->generic_class) {
1777 MonoClass *gklass = class->generic_class->container_class;
1779 mono_class_init (gklass);
1780 if (!gklass->exception_type)
1781 mono_class_setup_methods (gklass);
1782 if (gklass->exception_type) {
1783 /*FIXME make exception_data less opaque so it's possible to dup it here*/
1784 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
1785 mono_loader_unlock ();
1789 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1790 class->method.count = gklass->method.count;
1791 methods = g_new0 (MonoMethod *, class->method.count + 1);
1793 for (i = 0; i < class->method.count; i++) {
1794 methods [i] = mono_class_inflate_generic_method_full_checked (
1795 gklass->methods [i], class, mono_class_get_context (class), &error);
1796 if (!mono_error_ok (&error)) {
1797 char *method = mono_method_full_name (gklass->methods [i], TRUE);
1798 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Could not inflate method %s due to %s", method, mono_error_get_message (&error)));
1801 mono_error_cleanup (&error);
1802 mono_loader_unlock ();
1806 } else if (class->rank) {
1808 MonoMethod *amethod;
1809 MonoMethodSignature *sig;
1810 int count_generic = 0, first_generic = 0;
1813 class->method.count = 3 + (class->rank > 1? 2: 1);
1815 mono_class_setup_interfaces (class, &error);
1816 g_assert (mono_error_ok (&error)); /*FIXME can this fail for array types?*/
1818 if (class->interface_count) {
1819 count_generic = generic_array_methods (class);
1820 first_generic = class->method.count;
1821 class->method.count += class->interface_count * count_generic;
1824 methods = mono_image_alloc0 (class->image, sizeof (MonoMethod*) * class->method.count);
1826 sig = mono_metadata_signature_alloc (class->image, class->rank);
1827 sig->ret = &mono_defaults.void_class->byval_arg;
1828 sig->pinvoke = TRUE;
1829 sig->hasthis = TRUE;
1830 for (i = 0; i < class->rank; ++i)
1831 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1833 amethod = create_array_method (class, ".ctor", sig);
1834 methods [method_num++] = amethod;
1835 if (class->rank > 1) {
1836 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1837 sig->ret = &mono_defaults.void_class->byval_arg;
1838 sig->pinvoke = TRUE;
1839 sig->hasthis = TRUE;
1840 for (i = 0; i < class->rank * 2; ++i)
1841 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1843 amethod = create_array_method (class, ".ctor", sig);
1844 methods [method_num++] = amethod;
1846 /* element Get (idx11, [idx2, ...]) */
1847 sig = mono_metadata_signature_alloc (class->image, class->rank);
1848 sig->ret = &class->element_class->byval_arg;
1849 sig->pinvoke = TRUE;
1850 sig->hasthis = TRUE;
1851 for (i = 0; i < class->rank; ++i)
1852 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1853 amethod = create_array_method (class, "Get", sig);
1854 methods [method_num++] = amethod;
1855 /* element& Address (idx11, [idx2, ...]) */
1856 sig = mono_metadata_signature_alloc (class->image, class->rank);
1857 sig->ret = &class->element_class->this_arg;
1858 sig->pinvoke = TRUE;
1859 sig->hasthis = TRUE;
1860 for (i = 0; i < class->rank; ++i)
1861 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1862 amethod = create_array_method (class, "Address", sig);
1863 methods [method_num++] = amethod;
1864 /* void Set (idx11, [idx2, ...], element) */
1865 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1866 sig->ret = &mono_defaults.void_class->byval_arg;
1867 sig->pinvoke = TRUE;
1868 sig->hasthis = TRUE;
1869 for (i = 0; i < class->rank; ++i)
1870 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1871 sig->params [i] = &class->element_class->byval_arg;
1872 amethod = create_array_method (class, "Set", sig);
1873 methods [method_num++] = amethod;
1875 for (i = 0; i < class->interface_count; i++)
1876 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1878 methods = mono_image_alloc (class->image, sizeof (MonoMethod*) * class->method.count);
1879 for (i = 0; i < class->method.count; ++i) {
1880 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1881 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1885 if (MONO_CLASS_IS_INTERFACE (class)) {
1887 /*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
1888 for (i = 0; i < class->method.count; ++i) {
1889 if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
1890 methods [i]->slot = slot++;
1894 /* Needed because of the double-checking locking pattern */
1895 mono_memory_barrier ();
1897 class->methods = methods;
1899 if (mono_debugger_class_loaded_methods_func)
1900 mono_debugger_class_loaded_methods_func (class);
1902 mono_loader_unlock ();
1906 * mono_class_get_method_by_index:
1908 * Returns class->methods [index], initializing class->methods if neccesary.
1910 * LOCKING: Acquires the loader lock.
1913 mono_class_get_method_by_index (MonoClass *class, int index)
1915 /* Avoid calling setup_methods () if possible */
1916 if (class->generic_class && !class->methods) {
1917 MonoClass *gklass = class->generic_class->container_class;
1920 m = mono_class_inflate_generic_method_full (
1921 gklass->methods [index], class, mono_class_get_context (class));
1923 * If setup_methods () is called later for this class, no duplicates are created,
1924 * since inflate_generic_method guarantees that only one instance of a method
1925 * is created for each context.
1928 mono_class_setup_methods (class);
1929 g_assert (m == class->methods [index]);
1933 mono_class_setup_methods (class);
1934 g_assert (!class->exception_type); /*FIXME do proper error handling*/
1935 g_assert (index >= 0 && index < class->method.count);
1936 return class->methods [index];
1941 * mono_class_get_inflated_method:
1943 * Given an inflated class CLASS and a method METHOD which should be a method of
1944 * CLASS's generic definition, return the inflated method corresponding to METHOD.
1947 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
1949 MonoClass *gklass = class->generic_class->container_class;
1952 g_assert (method->klass == gklass);
1954 mono_class_setup_methods (gklass);
1955 g_assert (!gklass->exception_type); /*FIXME do proper error handling*/
1957 for (i = 0; i < gklass->method.count; ++i) {
1958 if (gklass->methods [i] == method) {
1960 return class->methods [i];
1962 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
1970 * mono_class_get_vtable_entry:
1972 * Returns class->vtable [offset], computing it if neccesary.
1973 * LOCKING: Acquires the loader lock.
1976 mono_class_get_vtable_entry (MonoClass *class, int offset)
1980 if (class->rank == 1) {
1982 * szarrays do not overwrite any methods of Array, so we can avoid
1983 * initializing their vtables in some cases.
1985 mono_class_setup_vtable (class->parent);
1986 if (offset < class->parent->vtable_size)
1987 return class->parent->vtable [offset];
1990 if (class->generic_class) {
1991 MonoClass *gklass = class->generic_class->container_class;
1992 mono_class_setup_vtable (gklass);
1993 m = gklass->vtable [offset];
1995 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
1997 mono_class_setup_vtable (class);
1998 m = class->vtable [offset];
2005 * mono_class_get_vtable_size:
2007 * Return the vtable size for KLASS.
2010 mono_class_get_vtable_size (MonoClass *klass)
2012 mono_class_setup_vtable (klass);
2014 return klass->vtable_size;
2017 /*This method can fail the class.*/
2019 mono_class_setup_properties (MonoClass *class)
2021 guint startm, endm, i, j;
2022 guint32 cols [MONO_PROPERTY_SIZE];
2023 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2024 MonoProperty *properties;
2027 if (class->ext && class->ext->properties)
2030 mono_loader_lock ();
2032 if (class->ext && class->ext->properties) {
2033 mono_loader_unlock ();
2037 mono_class_alloc_ext (class);
2039 if (class->generic_class) {
2040 MonoClass *gklass = class->generic_class->container_class;
2042 mono_class_init (gklass);
2043 mono_class_setup_properties (gklass);
2044 if (gklass->exception_type) {
2045 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2046 mono_loader_unlock ();
2050 class->ext->property = gklass->ext->property;
2052 properties = g_new0 (MonoProperty, class->ext->property.count + 1);
2054 for (i = 0; i < class->ext->property.count; i++) {
2055 MonoProperty *prop = &properties [i];
2057 *prop = gklass->ext->properties [i];
2060 prop->get = mono_class_inflate_generic_method_full (
2061 prop->get, class, mono_class_get_context (class));
2063 prop->set = mono_class_inflate_generic_method_full (
2064 prop->set, class, mono_class_get_context (class));
2066 prop->parent = class;
2069 int first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2070 int count = last - first;
2073 mono_class_setup_methods (class);
2074 if (class->exception_type) {
2075 mono_loader_unlock ();
2080 class->ext->property.first = first;
2081 class->ext->property.count = count;
2082 properties = mono_image_alloc0 (class->image, sizeof (MonoProperty) * count);
2083 for (i = first; i < last; ++i) {
2084 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
2085 properties [i - first].parent = class;
2086 properties [i - first].attrs = cols [MONO_PROPERTY_FLAGS];
2087 properties [i - first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
2089 startm = mono_metadata_methods_from_property (class->image, i, &endm);
2090 for (j = startm; j < endm; ++j) {
2093 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2095 if (class->image->uncompressed_metadata)
2096 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2097 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2099 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2101 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2102 case METHOD_SEMANTIC_SETTER:
2103 properties [i - first].set = method;
2105 case METHOD_SEMANTIC_GETTER:
2106 properties [i - first].get = method;
2114 /*Flush any pending writes as we do double checked locking on class->properties */
2115 mono_memory_barrier ();
2117 /* Leave this assignment as the last op in the function */
2118 class->ext->properties = properties;
2120 mono_loader_unlock ();
2124 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
2126 MonoMethod **om, **retval;
2129 for (om = methods, count = 0; *om; ++om, ++count)
2132 retval = g_new0 (MonoMethod*, count + 1);
2134 for (om = methods, count = 0; *om; ++om, ++count)
2135 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
2140 /*This method can fail the class.*/
2142 mono_class_setup_events (MonoClass *class)
2145 guint startm, endm, i, j;
2146 guint32 cols [MONO_EVENT_SIZE];
2147 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2151 if (class->ext && class->ext->events)
2154 mono_loader_lock ();
2156 if (class->ext && class->ext->events) {
2157 mono_loader_unlock ();
2161 mono_class_alloc_ext (class);
2163 if (class->generic_class) {
2164 MonoClass *gklass = class->generic_class->container_class;
2165 MonoGenericContext *context;
2167 mono_class_setup_events (gklass);
2168 if (gklass->exception_type) {
2169 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2170 mono_loader_unlock ();
2174 class->ext->event = gklass->ext->event;
2175 class->ext->events = g_new0 (MonoEvent, class->ext->event.count);
2177 if (class->ext->event.count)
2178 context = mono_class_get_context (class);
2180 for (i = 0; i < class->ext->event.count; i++) {
2181 MonoEvent *event = &class->ext->events [i];
2182 MonoEvent *gevent = &gklass->ext->events [i];
2184 event->parent = class;
2185 event->name = gevent->name;
2186 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
2187 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
2188 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
2189 #ifndef MONO_SMALL_CONFIG
2190 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
2192 event->attrs = gevent->attrs;
2195 mono_loader_unlock ();
2199 first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2200 count = last - first;
2203 mono_class_setup_methods (class);
2204 if (class->exception_type) {
2205 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2206 mono_loader_unlock ();
2210 class->ext->event.first = first;
2211 class->ext->event.count = count;
2212 events = mono_image_alloc0 (class->image, sizeof (MonoEvent) * class->ext->event.count);
2213 for (i = first; i < last; ++i) {
2214 MonoEvent *event = &events [i - first];
2216 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
2217 event->parent = class;
2218 event->attrs = cols [MONO_EVENT_FLAGS];
2219 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
2221 startm = mono_metadata_methods_from_event (class->image, i, &endm);
2222 for (j = startm; j < endm; ++j) {
2225 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2227 if (class->image->uncompressed_metadata)
2228 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2229 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2231 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2233 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2234 case METHOD_SEMANTIC_ADD_ON:
2235 event->add = method;
2237 case METHOD_SEMANTIC_REMOVE_ON:
2238 event->remove = method;
2240 case METHOD_SEMANTIC_FIRE:
2241 event->raise = method;
2243 case METHOD_SEMANTIC_OTHER: {
2244 #ifndef MONO_SMALL_CONFIG
2247 if (event->other == NULL) {
2248 event->other = g_new0 (MonoMethod*, 2);
2250 while (event->other [n])
2252 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
2254 event->other [n] = method;
2255 /* NULL terminated */
2256 event->other [n + 1] = NULL;
2265 /*Flush any pending writes as we do double checked locking on class->properties */
2266 mono_memory_barrier ();
2268 /* Leave this assignment as the last op in the function */
2269 class->ext->events = events;
2271 mono_loader_unlock ();
2275 * Global pool of interface IDs, represented as a bitset.
2276 * LOCKING: this is supposed to be accessed with the loader lock held.
2278 static MonoBitSet *global_interface_bitset = NULL;
2281 * mono_unload_interface_ids:
2282 * @bitset: bit set of interface IDs
2284 * When an image is unloaded, the interface IDs associated with
2285 * the image are put back in the global pool of IDs so the numbers
2289 mono_unload_interface_ids (MonoBitSet *bitset)
2291 mono_loader_lock ();
2292 mono_bitset_sub (global_interface_bitset, bitset);
2293 mono_loader_unlock ();
2297 * mono_get_unique_iid:
2300 * Assign a unique integer ID to the interface represented by @class.
2301 * The ID will positive and as small as possible.
2302 * LOCKING: this is supposed to be called with the loader lock held.
2303 * Returns: the new ID.
2306 mono_get_unique_iid (MonoClass *class)
2310 g_assert (MONO_CLASS_IS_INTERFACE (class));
2312 if (!global_interface_bitset) {
2313 global_interface_bitset = mono_bitset_new (128, 0);
2316 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2318 int old_size = mono_bitset_size (global_interface_bitset);
2319 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2320 mono_bitset_free (global_interface_bitset);
2321 global_interface_bitset = new_set;
2324 mono_bitset_set (global_interface_bitset, iid);
2325 /* set the bit also in the per-image set */
2326 if (class->image->interface_bitset) {
2327 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2328 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2329 mono_bitset_free (class->image->interface_bitset);
2330 class->image->interface_bitset = new_set;
2333 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2335 mono_bitset_set (class->image->interface_bitset, iid);
2337 #ifndef MONO_SMALL_CONFIG
2338 if (mono_print_vtable) {
2340 char *type_name = mono_type_full_name (&class->byval_arg);
2341 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2342 generic_id = class->generic_class->context.class_inst->id;
2343 g_assert (generic_id != 0);
2347 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2352 g_assert (iid <= 65535);
2357 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res, MonoError *error)
2362 mono_class_setup_interfaces (klass, error);
2363 if (!mono_error_ok (error))
2366 for (i = 0; i < klass->interface_count; i++) {
2367 ic = klass->interfaces [i];
2370 *res = g_ptr_array_new ();
2371 g_ptr_array_add (*res, ic);
2372 mono_class_init (ic);
2374 collect_implemented_interfaces_aux (ic, res, error);
2375 if (!mono_error_ok (error))
2381 mono_class_get_implemented_interfaces (MonoClass *klass, MonoError *error)
2383 GPtrArray *res = NULL;
2385 collect_implemented_interfaces_aux (klass, &res, error);
2386 if (!mono_error_ok (error)) {
2388 g_ptr_array_free (res, TRUE);
2395 compare_interface_ids (const void *p_key, const void *p_element) {
2396 const MonoClass *key = p_key;
2397 const MonoClass *element = *(MonoClass**) p_element;
2399 return (key->interface_id - element->interface_id);
2402 /*FIXME verify all callers if they should switch to mono_class_interface_offset_with_variance*/
2404 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2405 MonoClass **result = bsearch (
2407 klass->interfaces_packed,
2408 klass->interface_offsets_count,
2409 sizeof (MonoClass *),
2410 compare_interface_ids);
2412 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2419 * mono_class_interface_offset_with_variance:
2421 * Return the interface offset of @itf in @klass. Sets @non_exact_match to TRUE if the match required variance check
2422 * If @itf is an interface with generic variant arguments, try to find the compatible one.
2424 * Note that this function is responsible for resolving ambiguities. Right now we use whatever ordering interfaces_packed gives us.
2426 * FIXME figure out MS disambiguation rules and fix this function.
2429 mono_class_interface_offset_with_variance (MonoClass *klass, MonoClass *itf, gboolean *non_exact_match) {
2430 int i = mono_class_interface_offset (klass, itf);
2431 *non_exact_match = FALSE;
2435 if (!mono_class_has_variant_generic_params (itf))
2438 for (i = 0; i < klass->interface_offsets_count; i++) {
2439 if (mono_class_is_variant_compatible (itf, klass->interfaces_packed [i])) {
2440 *non_exact_match = TRUE;
2441 return klass->interface_offsets_packed [i];
2449 print_implemented_interfaces (MonoClass *klass) {
2451 GPtrArray *ifaces = NULL;
2453 int ancestor_level = 0;
2455 printf ("Packed interface table for class %s has size %d\n", klass->name, klass->interface_offsets_count);
2456 for (i = 0; i < klass->interface_offsets_count; i++)
2457 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2458 klass->interfaces_packed [i]->interface_id,
2459 klass->interface_offsets_packed [i],
2460 klass->interfaces_packed [i]->method.count,
2461 klass->interfaces_packed [i]->name_space,
2462 klass->interfaces_packed [i]->name );
2463 printf ("Interface flags: ");
2464 for (i = 0; i <= klass->max_interface_id; i++)
2465 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2466 printf ("(%d,T)", i);
2468 printf ("(%d,F)", i);
2470 printf ("Dump interface flags:");
2471 #ifdef COMPRESSED_INTERFACE_BITMAP
2473 const uint8_t* p = klass->interface_bitmap;
2474 i = klass->max_interface_id;
2476 printf (" %d x 00 %02X", p [0], p [1]);
2482 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2483 printf (" %02X", klass->interface_bitmap [i]);
2486 while (klass != NULL) {
2487 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2488 ifaces = mono_class_get_implemented_interfaces (klass, &error);
2489 if (!mono_error_ok (&error)) {
2490 printf (" Type failed due to %s\n", mono_error_get_message (&error));
2491 mono_error_cleanup (&error);
2492 } else if (ifaces) {
2493 for (i = 0; i < ifaces->len; i++) {
2494 MonoClass *ic = g_ptr_array_index (ifaces, i);
2495 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2496 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2498 mono_class_interface_offset (klass, ic),
2503 g_ptr_array_free (ifaces, TRUE);
2506 klass = klass->parent;
2511 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2514 args [0] = &arg0->byval_arg;
2516 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2520 array_class_get_if_rank (MonoClass *class, guint rank)
2522 return rank ? mono_array_class_get (class, rank) : class;
2526 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2528 valuetype_types [0] = eclass;
2529 if (eclass == mono_defaults.int16_class)
2530 valuetype_types [1] = mono_defaults.uint16_class;
2531 else if (eclass == mono_defaults.uint16_class)
2532 valuetype_types [1] = mono_defaults.int16_class;
2533 else if (eclass == mono_defaults.int32_class)
2534 valuetype_types [1] = mono_defaults.uint32_class;
2535 else if (eclass == mono_defaults.uint32_class)
2536 valuetype_types [1] = mono_defaults.int32_class;
2537 else if (eclass == mono_defaults.int64_class)
2538 valuetype_types [1] = mono_defaults.uint64_class;
2539 else if (eclass == mono_defaults.uint64_class)
2540 valuetype_types [1] = mono_defaults.int64_class;
2541 else if (eclass == mono_defaults.byte_class)
2542 valuetype_types [1] = mono_defaults.sbyte_class;
2543 else if (eclass == mono_defaults.sbyte_class)
2544 valuetype_types [1] = mono_defaults.byte_class;
2545 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2546 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2549 /* this won't be needed once bug #325495 is completely fixed
2550 * though we'll need something similar to know which interfaces to allow
2551 * in arrays when they'll be lazyly created
2553 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2554 * MS returns diferrent types based on which instance is called. For example:
2555 * object obj = new byte[10][];
2556 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2557 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2560 * Fixing this should kill quite some code, save some bits and improve compatibility.
2563 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2565 MonoClass *eclass = class->element_class;
2566 static MonoClass* generic_icollection_class = NULL;
2567 static MonoClass* generic_ienumerable_class = NULL;
2568 static MonoClass* generic_ienumerator_class = NULL;
2569 MonoClass *valuetype_types[2] = { NULL, NULL };
2570 MonoClass **interfaces = NULL;
2571 int i, interface_count, real_count, original_rank;
2573 gboolean internal_enumerator;
2574 gboolean eclass_is_valuetype;
2576 if (!mono_defaults.generic_ilist_class) {
2580 internal_enumerator = FALSE;
2581 eclass_is_valuetype = FALSE;
2582 original_rank = eclass->rank;
2583 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2584 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2586 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2588 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2589 original_rank = eclass->rank;
2590 eclass = eclass->element_class;
2591 internal_enumerator = TRUE;
2592 *is_enumerator = TRUE;
2600 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2601 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2603 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2605 if (!generic_icollection_class) {
2606 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2607 "System.Collections.Generic", "ICollection`1");
2608 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2609 "System.Collections.Generic", "IEnumerable`1");
2610 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2611 "System.Collections.Generic", "IEnumerator`1");
2614 mono_class_init (eclass);
2617 * Arrays in 2.0 need to implement a number of generic interfaces
2618 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2619 * on the element class). We collect the types needed to build the
2620 * instantiations in interfaces at intervals of 3, because 3 are
2621 * the generic interfaces needed to implement.
2623 if (eclass->valuetype) {
2624 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2626 /* IList, ICollection, IEnumerable */
2627 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2628 if (internal_enumerator) {
2630 if (valuetype_types [1])
2634 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2635 interfaces [0] = valuetype_types [0];
2636 if (valuetype_types [1])
2637 interfaces [3] = valuetype_types [1];
2639 eclass_is_valuetype = TRUE;
2642 int idepth = eclass->idepth;
2643 if (!internal_enumerator)
2646 // FIXME: This doesn't seem to work/required for generic params
2647 if (!(eclass->this_arg.type == MONO_TYPE_VAR || eclass->this_arg.type == MONO_TYPE_MVAR || (eclass->image->dynamic && !eclass->wastypebuilder)))
2648 mono_class_setup_interface_offsets (eclass);
2650 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2651 /* we add object for interfaces and the supertypes for the other
2652 * types. The last of the supertypes is the element class itself which we
2653 * already created the explicit interfaces for (so we include it for IEnumerator
2654 * and exclude it for arrays).
2656 if (MONO_CLASS_IS_INTERFACE (eclass))
2659 interface_count += idepth;
2660 if (eclass->rank && eclass->element_class->valuetype) {
2661 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2662 if (valuetype_types [1])
2665 /* IList, ICollection, IEnumerable */
2666 interface_count *= 3;
2667 real_count = interface_count;
2668 if (internal_enumerator) {
2669 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2670 if (valuetype_types [1])
2673 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2674 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2675 interfaces [0] = mono_defaults.object_class;
2679 for (i = 0; i < idepth; i++) {
2680 mono_class_init (eclass->supertypes [i]);
2681 interfaces [j] = eclass->supertypes [i];
2685 if (all_interfaces) {
2686 for (i = 0; i < eclass->interface_offsets_count; i++) {
2687 interfaces [j] = eclass->interfaces_packed [i];
2691 for (i = 0; i < eclass->interface_count; i++) {
2692 interfaces [j] = eclass->interfaces [i];
2696 if (valuetype_types [1]) {
2697 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2702 /* instantiate the generic interfaces */
2703 for (i = 0; i < interface_count; i += 3) {
2704 MonoClass *iface = interfaces [i];
2706 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2707 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2708 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2710 if (internal_enumerator) {
2712 /* instantiate IEnumerator<iface> */
2713 for (i = 0; i < interface_count; i++) {
2714 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2716 j = interface_count;
2717 if (!eclass_is_valuetype) {
2718 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2719 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2722 for (i = 0; i < eclass->idepth; i++) {
2723 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2727 for (i = 0; i < eclass->interface_offsets_count; i++) {
2728 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2732 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2734 if (valuetype_types [1])
2735 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2739 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2740 for (i = 0; i < real_count; ++i) {
2741 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2742 g_print ("%s implements %s\n", type_name, name);
2753 find_array_interface (MonoClass *klass, const char *name)
2756 for (i = 0; i < klass->interface_count; ++i) {
2757 if (strcmp (klass->interfaces [i]->name, name) == 0)
2764 * Return the number of virtual methods.
2765 * Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
2766 * Return -1 on failure.
2767 * FIXME It would be nice if this information could be cached somewhere.
2770 count_virtual_methods (MonoClass *class)
2774 class = mono_class_get_generic_type_definition (class); /*We can find this information by looking at the GTD*/
2776 if (class->methods || !MONO_CLASS_HAS_STATIC_METADATA (class)) {
2777 mono_class_setup_methods (class);
2778 if (class->exception_type)
2781 for (i = 0; i < class->method.count; ++i) {
2782 flags = class->methods [i]->flags;
2783 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2787 for (i = 0; i < class->method.count; ++i) {
2788 flags = mono_metadata_decode_table_row_col (class->image, MONO_TABLE_METHOD, class->method.first + i, MONO_METHOD_FLAGS);
2790 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2798 find_interface (int num_ifaces, MonoClass **interfaces_full, MonoClass *ic)
2806 m = (l + num_ifaces) / 2;
2807 if (interfaces_full [m] == ic)
2809 if (l == num_ifaces)
2811 if (!interfaces_full [m] || interfaces_full [m]->interface_id > ic->interface_id) {
2820 find_interface_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic)
2822 int i = find_interface (num_ifaces, interfaces_full, ic);
2824 return interface_offsets_full [i];
2829 set_interface_and_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic, int offset, mono_bool force_set)
2831 int i = find_interface (num_ifaces, interfaces_full, ic);
2835 interface_offsets_full [i] = offset;
2838 for (i = 0; i < num_ifaces; ++i) {
2839 if (interfaces_full [i]) {
2841 if (interfaces_full [i]->interface_id < ic->interface_id)
2844 while (end < num_ifaces && interfaces_full [end]) end++;
2845 memmove (interfaces_full + i + 1, interfaces_full + i, sizeof (MonoClass*) * (end - i));
2846 memmove (interface_offsets_full + i + 1, interface_offsets_full + i, sizeof (int) * (end - i));
2848 interfaces_full [i] = ic;
2849 interface_offsets_full [i] = offset;
2855 #ifdef COMPRESSED_INTERFACE_BITMAP
2858 * Compressed interface bitmap design.
2860 * Interface bitmaps take a large amount of memory, because their size is
2861 * linear with the maximum interface id assigned in the process (each interface
2862 * is assigned a unique id as it is loaded). The number of interface classes
2863 * is high because of the many implicit interfaces implemented by arrays (we'll
2864 * need to lazy-load them in the future).
2865 * Most classes implement a very small number of interfaces, so the bitmap is
2866 * sparse. This bitmap needs to be checked by interface casts, so access to the
2867 * needed bit must be fast and doable with few jit instructions.
2869 * The current compression format is as follows:
2870 * *) it is a sequence of one or more two-byte elements
2871 * *) the first byte in the element is the count of empty bitmap bytes
2872 * at the current bitmap position
2873 * *) the second byte in the element is an actual bitmap byte at the current
2876 * As an example, the following compressed bitmap bytes:
2877 * 0x07 0x01 0x00 0x7
2878 * correspond to the following bitmap:
2879 * 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x07
2881 * Each two-byte element can represent up to 2048 bitmap bits, but as few as a single
2882 * bitmap byte for non-sparse sequences. In practice the interface bitmaps created
2883 * during a gmcs bootstrap are reduced to less tha 5% of the original size.
2887 * mono_compress_bitmap:
2888 * @dest: destination buffer
2889 * @bitmap: bitmap buffer
2890 * @size: size of @bitmap in bytes
2892 * This is a mono internal function.
2893 * The @bitmap data is compressed into a format that is small but
2894 * still searchable in few instructions by the JIT and runtime.
2895 * The compressed data is stored in the buffer pointed to by the
2896 * @dest array. Passing a #NULL value for @dest allows to just compute
2897 * the size of the buffer.
2898 * This compression algorithm assumes the bits set in the bitmap are
2899 * few and far between, like in interface bitmaps.
2900 * Returns: the size of the compressed bitmap in bytes.
2903 mono_compress_bitmap (uint8_t *dest, const uint8_t *bitmap, int size)
2907 const uint8_t *end = bitmap + size;
2908 while (bitmap < end) {
2909 if (*bitmap || numz == 255) {
2933 * mono_class_interface_match:
2934 * @bitmap: a compressed bitmap buffer
2935 * @id: the index to check in the bitmap
2937 * This is a mono internal function.
2938 * Checks if a bit is set in a compressed interface bitmap. @id must
2939 * be already checked for being smaller than the maximum id encoded in the
2942 * Returns: a non-zero value if bit @id is set in the bitmap @bitmap,
2946 mono_class_interface_match (const uint8_t *bitmap, int id)
2949 id -= bitmap [0] * 8;
2953 return bitmap [1] & (1 << id);
2962 * LOCKING: this is supposed to be called with the loader lock held.
2963 * Return -1 on failure and set exception_type
2966 setup_interface_offsets (MonoClass *class, int cur_slot)
2970 int i, j, max_iid, num_ifaces;
2971 MonoClass **interfaces_full = NULL;
2972 int *interface_offsets_full = NULL;
2974 GPtrArray **ifaces_array = NULL;
2975 int interface_offsets_count;
2976 MonoClass **array_interfaces = NULL;
2977 int num_array_interfaces;
2978 int is_enumerator = FALSE;
2980 mono_class_setup_supertypes (class);
2982 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
2983 * implicit interfaces have the property that they are assigned the same slot in the
2984 * vtables for compatible interfaces
2986 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
2988 /* compute maximum number of slots and maximum interface id */
2990 num_ifaces = num_array_interfaces; /* this can include duplicated ones */
2991 ifaces_array = g_new0 (GPtrArray *, class->idepth);
2992 for (j = 0; j < class->idepth; j++) {
2993 k = class->supertypes [j];
2994 num_ifaces += k->interface_count;
2995 for (i = 0; i < k->interface_count; i++) {
2996 ic = k->interfaces [i];
2999 mono_class_init (ic);
3001 if (max_iid < ic->interface_id)
3002 max_iid = ic->interface_id;
3004 ifaces = mono_class_get_implemented_interfaces (k, &error);
3005 if (!mono_error_ok (&error)) {
3006 char *name = mono_type_get_full_name (k);
3007 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Error getting the interfaces of %s due to %s", name, mono_error_get_message (&error)));
3009 mono_error_cleanup (&error);
3014 num_ifaces += ifaces->len;
3015 for (i = 0; i < ifaces->len; ++i) {
3016 ic = g_ptr_array_index (ifaces, i);
3017 if (max_iid < ic->interface_id)
3018 max_iid = ic->interface_id;
3020 ifaces_array [j] = ifaces;
3024 for (i = 0; i < num_array_interfaces; ++i) {
3025 ic = array_interfaces [i];
3026 mono_class_init (ic);
3027 if (max_iid < ic->interface_id)
3028 max_iid = ic->interface_id;
3031 if (MONO_CLASS_IS_INTERFACE (class)) {
3033 if (max_iid < class->interface_id)
3034 max_iid = class->interface_id;
3036 class->max_interface_id = max_iid;
3037 /* compute vtable offset for interfaces */
3038 interfaces_full = g_malloc0 (sizeof (MonoClass*) * num_ifaces);
3039 interface_offsets_full = g_malloc (sizeof (int) * num_ifaces);
3041 for (i = 0; i < num_ifaces; i++) {
3042 interface_offsets_full [i] = -1;
3045 /* skip the current class */
3046 for (j = 0; j < class->idepth - 1; j++) {
3047 k = class->supertypes [j];
3048 ifaces = ifaces_array [j];
3051 for (i = 0; i < ifaces->len; ++i) {
3053 ic = g_ptr_array_index (ifaces, i);
3055 /*Force the sharing of interface offsets between parent and subtypes.*/
3056 io = mono_class_interface_offset (k, ic);
3058 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, io, TRUE);
3063 g_assert (class == class->supertypes [class->idepth - 1]);
3064 ifaces = ifaces_array [class->idepth - 1];
3066 for (i = 0; i < ifaces->len; ++i) {
3068 ic = g_ptr_array_index (ifaces, i);
3069 if (set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, cur_slot, FALSE))
3071 count = count_virtual_methods (ic);
3073 char *name = mono_type_get_full_name (ic);
3074 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Error calculating interface offset of %s", name));
3083 if (MONO_CLASS_IS_INTERFACE (class))
3084 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, class, cur_slot, TRUE);
3086 if (num_array_interfaces) {
3087 if (is_enumerator) {
3088 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
3089 int ienumerator_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ienumerator_idx]);
3090 g_assert (ienumerator_offset >= 0);
3091 for (i = 0; i < num_array_interfaces; ++i) {
3092 ic = array_interfaces [i];
3093 if (strcmp (ic->name, "IEnumerator`1") == 0)
3094 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, ienumerator_offset, TRUE);
3096 g_assert_not_reached ();
3097 /*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);*/
3100 int ilist_offset, icollection_offset, ienumerable_offset;
3101 int ilist_iface_idx = find_array_interface (class, "IList`1");
3102 MonoClass* ilist_class = class->interfaces [ilist_iface_idx];
3103 int icollection_iface_idx = find_array_interface (ilist_class, "ICollection`1");
3104 int ienumerable_iface_idx = find_array_interface (ilist_class, "IEnumerable`1");
3105 ilist_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ilist_iface_idx]);
3106 icollection_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [icollection_iface_idx]);
3107 ienumerable_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [ienumerable_iface_idx]);
3108 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
3109 for (i = 0; i < num_array_interfaces; ++i) {
3111 ic = array_interfaces [i];
3112 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
3113 offset = ilist_offset;
3114 else if (strcmp (ic->name, "ICollection`1") == 0)
3115 offset = icollection_offset;
3116 else if (strcmp (ic->name, "IEnumerable`1") == 0)
3117 offset = ienumerable_offset;
3119 g_assert_not_reached ();
3120 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, offset, TRUE);
3121 /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, offset, class->interfaces [0]->name);*/
3126 for (interface_offsets_count = 0, i = 0; i < num_ifaces; i++) {
3127 if (interface_offsets_full [i] != -1) {
3128 interface_offsets_count ++;
3133 * We might get called twice: once from mono_class_init () then once from
3134 * mono_class_setup_vtable ().
3136 if (class->interfaces_packed) {
3137 g_assert (class->interface_offsets_count == interface_offsets_count);
3141 class->interface_offsets_count = interface_offsets_count;
3142 class->interfaces_packed = mono_image_alloc (class->image, sizeof (MonoClass*) * interface_offsets_count);
3143 class->interface_offsets_packed = mono_image_alloc (class->image, sizeof (guint16) * interface_offsets_count);
3144 bsize = (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0);
3145 #ifdef COMPRESSED_INTERFACE_BITMAP
3146 bitmap = g_malloc0 (bsize);
3148 bitmap = mono_image_alloc0 (class->image, bsize);
3150 for (i = 0; i < interface_offsets_count; i++) {
3151 int id = interfaces_full [i]->interface_id;
3152 bitmap [id >> 3] |= (1 << (id & 7));
3153 class->interfaces_packed [i] = interfaces_full [i];
3154 class->interface_offsets_packed [i] = interface_offsets_full [i];
3155 /*if (num_array_interfaces)
3156 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]);*/
3158 #ifdef COMPRESSED_INTERFACE_BITMAP
3159 i = mono_compress_bitmap (NULL, bitmap, bsize);
3160 class->interface_bitmap = mono_image_alloc0 (class->image, i);
3161 mono_compress_bitmap (class->interface_bitmap, bitmap, bsize);
3164 class->interface_bitmap = bitmap;
3169 g_free (interfaces_full);
3170 g_free (interface_offsets_full);
3171 g_free (array_interfaces);
3172 for (i = 0; i < class->idepth; i++) {
3173 ifaces = ifaces_array [i];
3175 g_ptr_array_free (ifaces, TRUE);
3177 g_free (ifaces_array);
3179 //printf ("JUST DONE: ");
3180 //print_implemented_interfaces (class);
3186 * Setup interface offsets for interfaces.
3188 * - class->max_interface_id
3189 * - class->interface_offsets_count
3190 * - class->interfaces_packed
3191 * - class->interface_offsets_packed
3192 * - class->interface_bitmap
3194 * This function can fail @class.
3197 mono_class_setup_interface_offsets (MonoClass *class)
3199 mono_loader_lock ();
3201 setup_interface_offsets (class, 0);
3203 mono_loader_unlock ();
3207 * mono_class_setup_vtable:
3209 * Creates the generic vtable of CLASS.
3210 * Initializes the following fields in MonoClass:
3213 * Plus all the fields initialized by setup_interface_offsets ().
3214 * If there is an error during vtable construction, class->exception_type is set.
3216 * LOCKING: Acquires the loader lock.
3219 mono_class_setup_vtable (MonoClass *class)
3221 MonoMethod **overrides;
3222 MonoGenericContext *context;
3231 if (mono_debug_using_mono_debugger ())
3232 /* The debugger currently depends on this */
3233 mono_class_setup_methods (class);
3235 if (MONO_CLASS_IS_INTERFACE (class)) {
3236 /* This sets method->slot for all methods if this is an interface */
3237 mono_class_setup_methods (class);
3241 if (class->exception_type)
3244 mono_loader_lock ();
3246 if (class->vtable) {
3247 mono_loader_unlock ();
3251 mono_stats.generic_vtable_count ++;
3253 if (class->generic_class) {
3254 context = mono_class_get_context (class);
3255 type_token = class->generic_class->container_class->type_token;
3257 context = (MonoGenericContext *) class->generic_container;
3258 type_token = class->type_token;
3261 if (class->image->dynamic) {
3262 if (class->generic_class) {
3263 MonoClass *gklass = class->generic_class->container_class;
3265 mono_reflection_get_dynamic_overrides (gklass, &overrides, &onum);
3266 for (i = 0; i < onum; ++i) {
3267 MonoMethod *override = overrides [(i * 2) + 1];
3268 MonoMethod *inflated = NULL;
3271 for (j = 0; j < class->method.count; ++j) {
3272 if (gklass->methods [j] == override) {
3273 inflated = class->methods [j];
3277 g_assert (inflated);
3279 overrides [(i * 2) + 1] = inflated;
3282 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
3285 /* The following call fails if there are missing methods in the type */
3286 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
3290 mono_class_setup_vtable_general (class, overrides, onum);
3294 mono_loader_unlock ();
3299 #define DEBUG_INTERFACE_VTABLE_CODE 0
3300 #define TRACE_INTERFACE_VTABLE_CODE 0
3301 #define VERIFY_INTERFACE_VTABLE_CODE 0
3302 #define VTABLE_SELECTOR (1)
3304 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3305 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
3306 if (!(VTABLE_SELECTOR)) break; \
3310 #define DEBUG_INTERFACE_VTABLE(stmt)
3313 #if TRACE_INTERFACE_VTABLE_CODE
3314 #define TRACE_INTERFACE_VTABLE(stmt) do {\
3315 if (!(VTABLE_SELECTOR)) break; \
3319 #define TRACE_INTERFACE_VTABLE(stmt)
3322 #if VERIFY_INTERFACE_VTABLE_CODE
3323 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
3324 if (!(VTABLE_SELECTOR)) break; \
3328 #define VERIFY_INTERFACE_VTABLE(stmt)
3332 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3334 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
3338 GString *res = g_string_new ("");
3340 g_string_append_c (res, '(');
3341 for (i = 0; i < sig->param_count; ++i) {
3343 g_string_append_c (res, ',');
3344 mono_type_get_desc (res, sig->params [i], include_namespace);
3346 g_string_append (res, ")=>");
3347 if (sig->ret != NULL) {
3348 mono_type_get_desc (res, sig->ret, include_namespace);
3350 g_string_append (res, "NULL");
3353 g_string_free (res, FALSE);
3357 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
3358 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
3359 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
3360 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
3368 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) {
3369 MonoMethodSignature *cmsig, *imsig;
3370 if (strcmp (im->name, cm->name) == 0) {
3371 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
3372 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
3375 if (! slot_is_empty) {
3376 if (require_newslot) {
3377 if (! interface_is_explicitly_implemented_by_class) {
3378 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
3381 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3382 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
3386 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
3389 cmsig = mono_method_signature (cm);
3390 imsig = mono_method_signature (im);
3391 if (!cmsig || !imsig) {
3392 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not resolve the signature of a virtual method"));
3396 if (! mono_metadata_signature_equal (cmsig, imsig)) {
3397 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
3398 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3399 TRACE_INTERFACE_VTABLE (printf ("]"));
3402 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
3403 /* CAS - SecurityAction.InheritanceDemand on interface */
3404 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3405 mono_secman_inheritancedemand_method (cm, im);
3408 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3409 mono_security_core_clr_check_override (class, cm, im);
3410 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
3413 MonoClass *ic = im->klass;
3414 const char *ic_name_space = ic->name_space;
3415 const char *ic_name = ic->name;
3418 if (! require_newslot) {
3419 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
3422 if (cm->klass->rank == 0) {
3423 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
3426 if (! mono_metadata_signature_equal (mono_method_signature (cm), mono_method_signature (im))) {
3427 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
3428 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3429 TRACE_INTERFACE_VTABLE (printf ("]"));
3432 if (mono_class_get_image (ic) != mono_defaults.corlib) {
3433 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
3436 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
3437 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
3440 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
3441 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
3445 subname = strstr (cm->name, ic_name_space);
3446 if (subname != cm->name) {
3447 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
3450 subname += strlen (ic_name_space);
3451 if (subname [0] != '.') {
3452 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
3456 if (strstr (subname, ic_name) != subname) {
3457 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
3460 subname += strlen (ic_name);
3461 if (subname [0] != '.') {
3462 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
3466 if (strcmp (subname, im->name) != 0) {
3467 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
3471 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
3472 /* CAS - SecurityAction.InheritanceDemand on interface */
3473 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3474 mono_secman_inheritancedemand_method (cm, im);
3477 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3478 mono_security_core_clr_check_override (class, cm, im);
3480 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
3485 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3487 foreach_override (gpointer key, gpointer value, gpointer user_data) {
3488 MonoMethod *method = key;
3489 MonoMethod *override = value;
3490 MonoClass *method_class = mono_method_get_class (method);
3491 MonoClass *override_class = mono_method_get_class (override);
3493 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
3494 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
3495 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
3498 print_overrides (GHashTable *override_map, const char *message) {
3500 printf ("Override map \"%s\" START:\n", message);
3501 g_hash_table_foreach (override_map, foreach_override, NULL);
3502 printf ("Override map \"%s\" END.\n", message);
3504 printf ("Override map \"%s\" EMPTY.\n", message);
3508 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
3509 char *full_name = mono_type_full_name (&class->byval_arg);
3513 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
3515 if (print_interfaces) {
3516 print_implemented_interfaces (class);
3517 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
3520 if (class->parent) {
3521 parent_size = class->parent->vtable_size;
3525 for (i = 0; i < size; ++i) {
3526 MonoMethod *cm = vtable [i];
3528 char *cm_name = mono_method_full_name (cm, TRUE);
3529 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
3530 printf (" [%c][%03d][INDEX %03d] %s\n", newness, i, cm->slot, cm_name);
3539 #if VERIFY_INTERFACE_VTABLE_CODE
3541 mono_method_try_get_vtable_index (MonoMethod *method)
3543 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3544 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3545 if (imethod->declaring->is_generic)
3546 return imethod->declaring->slot;
3548 return method->slot;
3552 mono_class_verify_vtable (MonoClass *class)
3555 char *full_name = mono_type_full_name (&class->byval_arg);
3557 printf ("*** Verifying VTable of class '%s' \n", full_name);
3561 if (!class->methods)
3564 for (i = 0; i < class->method.count; ++i) {
3565 MonoMethod *cm = class->methods [i];
3568 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
3572 full_name = mono_method_full_name (cm, TRUE);
3574 slot = mono_method_try_get_vtable_index (cm);
3576 if (slot >= class->vtable_size) {
3577 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
3581 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
3582 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3583 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3584 g_free (other_name);
3587 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3594 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3596 char *method_signature;
3599 for (index = 0; index < onum; ++index) {
3600 g_print (" at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
3601 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3603 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3604 type_name = mono_type_full_name (&class->byval_arg);
3605 printf ("no implementation for interface method %s::%s(%s) in class %s\n",
3606 mono_type_get_name (&ic->byval_arg), im->name, method_signature, type_name);
3607 g_free (method_signature);
3609 mono_class_setup_methods (class);
3610 if (class->exception_type) {
3611 char *name = mono_type_get_full_name (class);
3612 printf ("CLASS %s failed to resolve methods\n", name);
3616 for (index = 0; index < class->method.count; ++index) {
3617 MonoMethod *cm = class->methods [index];
3618 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3620 printf ("METHOD %s(%s)\n", cm->name, method_signature);
3621 g_free (method_signature);
3626 verify_class_overrides (MonoClass *class, MonoMethod **overrides, int onum)
3630 for (i = 0; i < onum; ++i) {
3631 MonoMethod *decl = overrides [i * 2];
3632 MonoMethod *body = overrides [i * 2 + 1];
3634 if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (class)) {
3635 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method belongs to a different class than the declared one"));
3639 if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
3640 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3641 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must not be static to override a base type"));
3643 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must be virtual to override a base type"));
3647 if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
3648 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3649 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a static method in a base type"));
3651 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a non virtual method in a base type"));
3655 if (!mono_class_is_assignable_from_slow (decl->klass, class)) {
3656 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method overrides a class or interface that extended or implemented by this type"));
3663 * LOCKING: this is supposed to be called with the loader lock held.
3666 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum)
3670 MonoMethod **vtable;
3671 int i, max_vtsize = 0, max_iid, cur_slot = 0;
3672 GPtrArray *ifaces = NULL;
3673 GHashTable *override_map = NULL;
3674 gboolean security_enabled = mono_is_security_manager_active ();
3676 gpointer class_iter;
3677 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3678 int first_non_interface_slot;
3680 GSList *virt_methods = NULL, *l;
3685 if (overrides && !verify_class_overrides (class, overrides, onum))
3688 ifaces = mono_class_get_implemented_interfaces (class, &error);
3689 if (!mono_error_ok (&error)) {
3690 char *name = mono_type_get_full_name (class);
3691 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Could not resolve %s interfaces due to %s", name, mono_error_get_message (&error)));
3693 mono_error_cleanup (&error);
3695 } else if (ifaces) {
3696 for (i = 0; i < ifaces->len; i++) {
3697 MonoClass *ic = g_ptr_array_index (ifaces, i);
3698 max_vtsize += ic->method.count;
3700 g_ptr_array_free (ifaces, TRUE);
3704 if (class->parent) {
3705 mono_class_init (class->parent);
3706 mono_class_setup_vtable (class->parent);
3708 if (class->parent->exception_type) {
3709 char *name = mono_type_get_full_name (class->parent);
3710 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Parent %s failed to load", name));
3715 max_vtsize += class->parent->vtable_size;
3716 cur_slot = class->parent->vtable_size;
3719 max_vtsize += class->method.count;
3721 vtable = alloca (sizeof (gpointer) * max_vtsize);
3722 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3724 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3726 cur_slot = setup_interface_offsets (class, cur_slot);
3727 if (cur_slot == -1) /*setup_interface_offsets fails the type.*/
3730 max_iid = class->max_interface_id;
3731 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3733 /* Optimized version for generic instances */
3734 if (class->generic_class) {
3735 MonoClass *gklass = class->generic_class->container_class;
3738 mono_class_setup_vtable (gklass);
3739 if (gklass->exception_type != MONO_EXCEPTION_NONE) {
3740 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3744 tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * gklass->vtable_size);
3745 class->vtable_size = gklass->vtable_size;
3746 for (i = 0; i < gklass->vtable_size; ++i)
3747 if (gklass->vtable [i]) {
3748 tmp [i] = mono_class_inflate_generic_method_full (gklass->vtable [i], class, mono_class_get_context (class));
3749 tmp [i]->slot = gklass->vtable [i]->slot;
3751 mono_memory_barrier ();
3752 class->vtable = tmp;
3754 /* Have to set method->slot for abstract virtual methods */
3755 if (class->methods && gklass->methods) {
3756 for (i = 0; i < class->method.count; ++i)
3757 if (class->methods [i]->slot == -1)
3758 class->methods [i]->slot = gklass->methods [i]->slot;
3764 if (class->parent && class->parent->vtable_size) {
3765 MonoClass *parent = class->parent;
3768 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
3770 // Also inherit parent interface vtables, just as a starting point.
3771 // This is needed otherwise bug-77127.exe fails when the property methods
3772 // have different names in the iterface and the class, because for child
3773 // classes the ".override" information is not used anymore.
3774 for (i = 0; i < parent->interface_offsets_count; i++) {
3775 MonoClass *parent_interface = parent->interfaces_packed [i];
3776 int interface_offset = mono_class_interface_offset (class, parent_interface);
3777 /*FIXME this is now dead code as this condition will never hold true.
3778 Since interface offsets are inherited then the offset of an interface implemented
3779 by a parent will never be the out of it's vtable boundary.
3781 if (interface_offset >= parent->vtable_size) {
3782 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
3785 mono_class_setup_methods (parent_interface); /*FIXME Just kill this whole chunk of dead code*/
3786 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
3787 for (j = 0; j < parent_interface->method.count && !class->exception_type; j++) {
3788 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
3789 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
3790 parent_interface_offset + j, parent_interface_offset, j,
3791 interface_offset + j, interface_offset, j));
3798 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
3799 /* override interface methods */
3800 for (i = 0; i < onum; i++) {
3801 MonoMethod *decl = overrides [i*2];
3802 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
3804 dslot = mono_method_get_vtable_slot (decl);
3806 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3810 dslot += mono_class_interface_offset (class, decl->klass);
3811 vtable [dslot] = overrides [i*2 + 1];
3812 vtable [dslot]->slot = dslot;
3814 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
3816 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
3818 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3819 mono_security_core_clr_check_override (class, vtable [dslot], decl);
3822 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
3823 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
3826 * Create a list of virtual methods to avoid calling
3827 * mono_class_get_virtual_methods () which is slow because of the metadata
3831 gpointer iter = NULL;
3834 virt_methods = NULL;
3835 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
3836 virt_methods = g_slist_prepend (virt_methods, cm);
3838 if (class->exception_type)
3842 // Loop on all implemented interfaces...
3843 for (i = 0; i < class->interface_offsets_count; i++) {
3844 MonoClass *parent = class->parent;
3846 gboolean interface_is_explicitly_implemented_by_class;
3849 ic = class->interfaces_packed [i];
3850 ic_offset = mono_class_interface_offset (class, ic);
3852 mono_class_setup_methods (ic);
3853 if (ic->exception_type)
3856 // Check if this interface is explicitly implemented (instead of just inherited)
3857 if (parent != NULL) {
3858 int implemented_interfaces_index;
3859 interface_is_explicitly_implemented_by_class = FALSE;
3860 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
3861 if (ic == class->interfaces [implemented_interfaces_index]) {
3862 interface_is_explicitly_implemented_by_class = TRUE;
3867 interface_is_explicitly_implemented_by_class = TRUE;
3870 // Loop on all interface methods...
3871 for (im_index = 0; im_index < ic->method.count; im_index++) {
3872 MonoMethod *im = ic->methods [im_index];
3873 int im_slot = ic_offset + im->slot;
3874 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
3876 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3879 // If there is an explicit implementation, just use it right away,
3880 // otherwise look for a matching method
3881 if (override_im == NULL) {
3886 // First look for a suitable method among the class methods
3888 for (l = virt_methods; l; l = l->next) {
3890 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)));
3891 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
3892 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
3893 vtable [im_slot] = cm;
3894 /* Why do we need this? */
3899 TRACE_INTERFACE_VTABLE (printf ("\n"));
3900 if (class->exception_type) /*Might be set by check_interface_method_override*/
3904 // If the slot is still empty, look in all the inherited virtual methods...
3905 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
3906 MonoClass *parent = class->parent;
3907 // Reverse order, so that last added methods are preferred
3908 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
3909 MonoMethod *cm = parent->vtable [cm_index];
3911 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));
3912 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
3913 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
3914 vtable [im_slot] = cm;
3915 /* Why do we need this? */
3921 if (class->exception_type) /*Might be set by check_interface_method_override*/
3923 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
3927 g_assert (vtable [im_slot] == override_im);
3932 // If the class is not abstract, check that all its interface slots are full.
3933 // The check is done here and not directly at the end of the loop above because
3934 // it can happen (for injected generic array interfaces) that the same slot is
3935 // processed multiple times (those interfaces have overlapping slots), and it
3936 // will not always be the first pass the one that fills the slot.
3937 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
3938 for (i = 0; i < class->interface_offsets_count; i++) {
3942 ic = class->interfaces_packed [i];
3943 ic_offset = mono_class_interface_offset (class, ic);
3945 for (im_index = 0; im_index < ic->method.count; im_index++) {
3946 MonoMethod *im = ic->methods [im_index];
3947 int im_slot = ic_offset + im->slot;
3949 if (im->flags & METHOD_ATTRIBUTE_STATIC)
3952 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
3953 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
3954 if (vtable [im_slot] == NULL) {
3955 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
3962 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
3964 for (l = virt_methods; l; l = l->next) {
3967 * If the method is REUSE_SLOT, we must check in the
3968 * base class for a method to override.
3970 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3972 for (k = class->parent; k ; k = k->parent) {
3977 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
3978 MonoMethodSignature *cmsig, *m1sig;
3980 cmsig = mono_method_signature (cm);
3981 m1sig = mono_method_signature (m1);
3983 if (!cmsig || !m1sig) {
3984 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3988 if (!strcmp(cm->name, m1->name) &&
3989 mono_metadata_signature_equal (cmsig, m1sig)) {
3991 /* CAS - SecurityAction.InheritanceDemand */
3992 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3993 mono_secman_inheritancedemand_method (cm, m1);
3996 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3997 mono_security_core_clr_check_override (class, cm, m1);
3999 slot = mono_method_get_vtable_slot (m1);
4003 g_assert (cm->slot < max_vtsize);
4005 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4006 g_hash_table_insert (override_map, m1, cm);
4010 if (k->exception_type)
4020 /*Non final newslot methods must be given a non-interface vtable slot*/
4021 if ((cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && !(cm->flags & METHOD_ATTRIBUTE_FINAL) && cm->slot >= 0)
4025 cm->slot = cur_slot++;
4027 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
4028 vtable [cm->slot] = cm;
4031 /* override non interface methods */
4032 for (i = 0; i < onum; i++) {
4033 MonoMethod *decl = overrides [i*2];
4034 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
4035 g_assert (decl->slot != -1);
4036 vtable [decl->slot] = overrides [i*2 + 1];
4037 overrides [i * 2 + 1]->slot = decl->slot;
4039 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4040 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
4042 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4043 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
4048 * If a method occupies more than one place in the vtable, and it is
4049 * overriden, then change the other occurances too.
4052 for (i = 0; i < max_vtsize; ++i)
4054 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
4059 g_hash_table_destroy (override_map);
4060 override_map = NULL;
4063 g_slist_free (virt_methods);
4064 virt_methods = NULL;
4066 /* Ensure that all vtable slots are filled with concrete instance methods */
4067 if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
4068 for (i = 0; i < cur_slot; ++i) {
4069 if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
4070 char *type_name = mono_type_get_full_name (class);
4071 char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
4072 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));
4074 g_free (method_name);
4080 if (class->generic_class) {
4081 MonoClass *gklass = class->generic_class->container_class;
4083 mono_class_init (gklass);
4085 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
4087 /* Check that the vtable_size value computed in mono_class_init () is correct */
4088 if (class->vtable_size)
4089 g_assert (cur_slot == class->vtable_size);
4090 class->vtable_size = cur_slot;
4093 /* Try to share the vtable with our parent. */
4094 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
4095 mono_memory_barrier ();
4096 class->vtable = class->parent->vtable;
4098 MonoMethod **tmp = mono_image_alloc0 (class->image, sizeof (gpointer) * class->vtable_size);
4099 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
4100 mono_memory_barrier ();
4101 class->vtable = tmp;
4104 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
4105 if (mono_print_vtable) {
4108 print_implemented_interfaces (class);
4110 for (i = 0; i <= max_iid; i++)
4111 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
4114 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
4115 class->vtable_size, icount);
4117 for (i = 0; i < cur_slot; ++i) {
4122 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
4123 mono_method_full_name (cm, TRUE));
4129 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
4130 class->name, max_iid);
4132 for (i = 0; i < class->interface_count; i++) {
4133 ic = class->interfaces [i];
4134 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
4135 mono_class_interface_offset (class, ic),
4136 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
4139 for (k = class->parent; k ; k = k->parent) {
4140 for (i = 0; i < k->interface_count; i++) {
4141 ic = k->interfaces [i];
4142 printf (" parent slot offset: %03d, method count: %03d, iid: %03d %s\n",
4143 mono_class_interface_offset (class, ic),
4144 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
4150 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
4155 char *name = mono_type_get_full_name (class);
4156 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("VTable setup of type %s failed", name));
4159 g_hash_table_destroy (override_map);
4161 g_slist_free (virt_methods);
4166 * mono_method_get_vtable_slot:
4168 * Returns method->slot, computing it if neccesary. Return -1 on failure.
4169 * LOCKING: Acquires the loader lock.
4171 * FIXME Use proper MonoError machinery here.
4174 mono_method_get_vtable_slot (MonoMethod *method)
4176 if (method->slot == -1) {
4177 mono_class_setup_vtable (method->klass);
4178 if (method->klass->exception_type)
4180 g_assert (method->slot != -1);
4182 return method->slot;
4186 * mono_method_get_vtable_index:
4189 * Returns the index into the runtime vtable to access the method or,
4190 * in the case of a virtual generic method, the virtual generic method
4191 * thunk. Returns -1 on failure.
4193 * FIXME Use proper MonoError machinery here.
4196 mono_method_get_vtable_index (MonoMethod *method)
4198 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4199 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4200 if (imethod->declaring->is_generic)
4201 return mono_method_get_vtable_slot (imethod->declaring);
4203 return mono_method_get_vtable_slot (method);
4206 static MonoMethod *default_ghc = NULL;
4207 static MonoMethod *default_finalize = NULL;
4208 static int finalize_slot = -1;
4209 static int ghc_slot = -1;
4212 initialize_object_slots (MonoClass *class)
4217 if (class == mono_defaults.object_class) {
4218 mono_class_setup_vtable (class);
4219 for (i = 0; i < class->vtable_size; ++i) {
4220 MonoMethod *cm = class->vtable [i];
4222 if (!strcmp (cm->name, "GetHashCode"))
4224 else if (!strcmp (cm->name, "Finalize"))
4228 g_assert (ghc_slot > 0);
4229 default_ghc = class->vtable [ghc_slot];
4231 g_assert (finalize_slot > 0);
4232 default_finalize = class->vtable [finalize_slot];
4237 MonoMethod *array_method;
4239 } GenericArrayMethodInfo;
4241 static int generic_array_method_num = 0;
4242 static GenericArrayMethodInfo *generic_array_method_info = NULL;
4245 generic_array_methods (MonoClass *class)
4247 int i, count_generic = 0;
4248 GList *list = NULL, *tmp;
4249 if (generic_array_method_num)
4250 return generic_array_method_num;
4251 mono_class_setup_methods (class->parent); /*This is setting up System.Array*/
4252 g_assert (!class->parent->exception_type); /*So hitting this assert is a huge problem*/
4253 for (i = 0; i < class->parent->method.count; i++) {
4254 MonoMethod *m = class->parent->methods [i];
4255 if (!strncmp (m->name, "InternalArray__", 15)) {
4257 list = g_list_prepend (list, m);
4260 list = g_list_reverse (list);
4261 generic_array_method_info = g_malloc (sizeof (GenericArrayMethodInfo) * count_generic);
4263 for (tmp = list; tmp; tmp = tmp->next) {
4264 const char *mname, *iname;
4266 MonoMethod *m = tmp->data;
4267 generic_array_method_info [i].array_method = m;
4268 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
4269 iname = "System.Collections.Generic.ICollection`1.";
4270 mname = m->name + 27;
4271 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
4272 iname = "System.Collections.Generic.IEnumerable`1.";
4273 mname = m->name + 27;
4274 } else if (!strncmp (m->name, "InternalArray__", 15)) {
4275 iname = "System.Collections.Generic.IList`1.";
4276 mname = m->name + 15;
4278 g_assert_not_reached ();
4281 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
4282 strcpy (name, iname);
4283 strcpy (name + strlen (iname), mname);
4284 generic_array_method_info [i].name = name;
4287 /*g_print ("array generic methods: %d\n", count_generic);*/
4289 generic_array_method_num = count_generic;
4291 return generic_array_method_num;
4295 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
4297 MonoGenericContext tmp_context;
4300 tmp_context.class_inst = NULL;
4301 tmp_context.method_inst = iface->generic_class->context.class_inst;
4302 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
4304 for (i = 0; i < generic_array_method_num; i++) {
4305 MonoMethod *m = generic_array_method_info [i].array_method;
4306 MonoMethod *inflated;
4308 inflated = mono_class_inflate_generic_method (m, &tmp_context);
4309 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
4314 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
4316 int len = strlen (s1) + strlen (s2) + 2;
4317 char *s = mono_image_alloc (image, len);
4320 result = g_snprintf (s, len, "%s%c%s", s1, '\0', s2);
4321 g_assert (result == len - 1);
4327 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
4329 gpointer exception_data = NULL;
4331 switch (error->exception_type) {
4332 case MONO_EXCEPTION_TYPE_LOAD:
4333 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
4336 case MONO_EXCEPTION_MISSING_METHOD:
4337 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
4340 case MONO_EXCEPTION_MISSING_FIELD: {
4341 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
4342 const char *class_name;
4345 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
4347 class_name = error->klass->name;
4349 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
4352 g_free ((void*)class_name);
4356 case MONO_EXCEPTION_FILE_NOT_FOUND: {
4359 if (error->ref_only)
4360 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.";
4362 msg = "Could not load file or assembly '%s' or one of its dependencies.";
4364 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
4368 case MONO_EXCEPTION_BAD_IMAGE:
4369 exception_data = error->msg;
4373 g_assert_not_reached ();
4376 mono_class_set_failure (class, error->exception_type, exception_data);
4381 * @class: the class to initialize
4383 * Compute the instance_size, class_size and other infos that cannot be
4384 * computed at mono_class_get() time. Also compute vtable_size if possible.
4385 * Returns TRUE on success or FALSE if there was a problem in loading
4386 * the type (incorrect assemblies, missing assemblies, methods, etc).
4388 * LOCKING: Acquires the loader lock.
4391 mono_class_init (MonoClass *class)
4394 MonoCachedClassInfo cached_info;
4395 gboolean has_cached_info;
4399 /* Double-checking locking pattern */
4401 return class->exception_type == MONO_EXCEPTION_NONE;
4403 /*g_print ("Init class %s\n", class->name);*/
4405 /* We do everything inside the lock to prevent races */
4406 mono_loader_lock ();
4408 if (class->inited) {
4409 mono_loader_unlock ();
4410 /* Somebody might have gotten in before us */
4411 return class->exception_type == MONO_EXCEPTION_NONE;
4414 if (class->init_pending) {
4415 mono_loader_unlock ();
4416 /* this indicates a cyclic dependency */
4417 g_error ("pending init %s.%s\n", class->name_space, class->name);
4420 class->init_pending = 1;
4422 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
4423 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
4428 if (class->byval_arg.type == MONO_TYPE_ARRAY || class->byval_arg.type == MONO_TYPE_SZARRAY) {
4429 MonoClass *element_class = class->element_class;
4430 if (!element_class->inited)
4431 mono_class_init (element_class);
4432 if (element_class->exception_type != MONO_EXCEPTION_NONE) {
4433 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4438 /* CAS - SecurityAction.InheritanceDemand */
4439 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
4440 mono_secman_inheritancedemand_class (class, class->parent);
4443 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4444 mono_security_core_clr_check_inheritance (class);
4446 mono_stats.initialized_class_count++;
4448 if (class->generic_class && !class->generic_class->is_dynamic) {
4449 MonoClass *gklass = class->generic_class->container_class;
4451 mono_stats.generic_class_count++;
4453 class->method = gklass->method;
4454 class->field = gklass->field;
4456 mono_class_init (gklass);
4457 // FIXME: Why is this needed ?
4458 if (!gklass->exception_type)
4459 mono_class_setup_methods (gklass);
4460 if (gklass->exception_type) {
4461 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Generic Type Defintion failed to init"));
4465 if (MONO_CLASS_IS_INTERFACE (class))
4466 class->interface_id = mono_get_unique_iid (class);
4469 if (class->parent && !class->parent->inited)
4470 mono_class_init (class->parent);
4472 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
4474 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
4475 class->nested_classes_inited = TRUE;
4478 * Computes the size used by the fields, and their locations
4480 if (has_cached_info) {
4481 class->instance_size = cached_info.instance_size;
4482 class->sizes.class_size = cached_info.class_size;
4483 class->packing_size = cached_info.packing_size;
4484 class->min_align = cached_info.min_align;
4485 class->blittable = cached_info.blittable;
4486 class->has_references = cached_info.has_references;
4487 class->has_static_refs = cached_info.has_static_refs;
4488 class->no_special_static_fields = cached_info.no_special_static_fields;
4491 if (!class->size_inited){
4492 mono_class_setup_fields (class);
4493 if (class->exception_type || mono_loader_get_last_error ())
4497 /* Initialize arrays */
4499 class->method.count = 3 + (class->rank > 1? 2: 1);
4501 if (class->interface_count) {
4502 int count_generic = generic_array_methods (class);
4503 class->method.count += class->interface_count * count_generic;
4507 mono_class_setup_supertypes (class);
4510 initialize_object_slots (class);
4513 * Initialize the rest of the data without creating a generic vtable if possible.
4514 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
4515 * also avoid computing a generic vtable.
4517 if (has_cached_info) {
4519 class->vtable_size = cached_info.vtable_size;
4520 class->has_finalize = cached_info.has_finalize;
4521 class->ghcimpl = cached_info.ghcimpl;
4522 class->has_cctor = cached_info.has_cctor;
4523 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
4524 static int szarray_vtable_size = 0;
4527 if (!szarray_vtable_size) {
4528 mono_class_setup_vtable (class);
4529 szarray_vtable_size = class->vtable_size;
4531 class->vtable_size = szarray_vtable_size;
4533 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
4534 MonoClass *gklass = class->generic_class->container_class;
4536 /* Generic instance case */
4537 class->ghcimpl = gklass->ghcimpl;
4538 class->has_finalize = gklass->has_finalize;
4539 class->has_cctor = gklass->has_cctor;
4541 mono_class_setup_vtable (gklass);
4542 if (gklass->exception_type) {
4543 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4547 class->vtable_size = gklass->vtable_size;
4551 /* ghcimpl is not currently used
4553 if (class->parent) {
4554 MonoMethod *cmethod = class->vtable [ghc_slot];
4555 if (cmethod->is_inflated)
4556 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4557 if (cmethod == default_ghc) {
4563 /* Interfaces and valuetypes are not supposed to have finalizers */
4564 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
4565 MonoMethod *cmethod = NULL;
4567 if (class->parent && class->parent->has_finalize) {
4568 class->has_finalize = 1;
4570 if (class->type_token) {
4571 cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
4572 } else if (class->parent) {
4573 /* FIXME: Optimize this */
4574 mono_class_setup_vtable (class);
4575 if (class->exception_type || mono_loader_get_last_error ())
4577 cmethod = class->vtable [finalize_slot];
4581 /* Check that this is really the finalizer method */
4582 mono_class_setup_vtable (class);
4583 if (class->exception_type || mono_loader_get_last_error ())
4586 g_assert (class->vtable_size > finalize_slot);
4588 class->has_finalize = 0;
4589 if (class->parent) {
4590 cmethod = class->vtable [finalize_slot];
4592 if (cmethod->is_inflated)
4593 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4594 if (cmethod != default_finalize) {
4595 class->has_finalize = 1;
4602 /* C# doesn't allow interfaces to have cctors */
4603 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
4604 MonoMethod *cmethod = NULL;
4606 if (class->type_token) {
4607 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
4608 /* The find_method function ignores the 'flags' argument */
4609 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
4610 class->has_cctor = 1;
4612 mono_class_setup_methods (class);
4613 if (class->exception_type)
4616 for (i = 0; i < class->method.count; ++i) {
4617 MonoMethod *method = class->methods [i];
4618 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4619 (strcmp (".cctor", method->name) == 0)) {
4620 class->has_cctor = 1;
4628 if (class->parent) {
4629 /* This will compute class->parent->vtable_size for some classes */
4630 mono_class_init (class->parent);
4631 if (class->parent->exception_type) {
4632 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4635 if (mono_loader_get_last_error ())
4637 if (!class->parent->vtable_size) {
4638 /* FIXME: Get rid of this somehow */
4639 mono_class_setup_vtable (class->parent);
4640 if (class->parent->exception_type) {
4641 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4644 if (mono_loader_get_last_error ())
4647 setup_interface_offsets (class, class->parent->vtable_size);
4649 setup_interface_offsets (class, 0);
4655 /* Because of the double-checking locking pattern */
4656 mono_memory_barrier ();
4658 class->init_pending = 0;
4660 if (mono_loader_get_last_error ()) {
4661 if (class->exception_type == MONO_EXCEPTION_NONE) {
4662 set_failure_from_loader_error (class, mono_loader_get_last_error ());
4664 mono_loader_clear_error ();
4667 mono_loader_unlock ();
4669 if (mono_debugger_class_init_func)
4670 mono_debugger_class_init_func (class);
4672 return class->exception_type == MONO_EXCEPTION_NONE;
4676 is_corlib_image (MonoImage *image)
4678 /* FIXME: allow the dynamic case for our compilers and with full trust */
4680 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
4682 return image == mono_defaults.corlib;
4686 * LOCKING: this assumes the loader lock is held
4689 mono_class_setup_mono_type (MonoClass *class)
4691 const char *name = class->name;
4692 const char *nspace = class->name_space;
4693 gboolean is_corlib = is_corlib_image (class->image);
4695 class->this_arg.byref = 1;
4696 class->this_arg.data.klass = class;
4697 class->this_arg.type = MONO_TYPE_CLASS;
4698 class->byval_arg.data.klass = class;
4699 class->byval_arg.type = MONO_TYPE_CLASS;
4701 if (is_corlib && !strcmp (nspace, "System")) {
4702 if (!strcmp (name, "ValueType")) {
4704 * do not set the valuetype bit for System.ValueType.
4705 * class->valuetype = 1;
4707 class->blittable = TRUE;
4708 } else if (!strcmp (name, "Enum")) {
4710 * do not set the valuetype bit for System.Enum.
4711 * class->valuetype = 1;
4713 class->valuetype = 0;
4714 class->enumtype = 0;
4715 } else if (!strcmp (name, "Object")) {
4716 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
4717 } else if (!strcmp (name, "String")) {
4718 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
4719 } else if (!strcmp (name, "TypedReference")) {
4720 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
4724 if (class->valuetype) {
4725 int t = MONO_TYPE_VALUETYPE;
4727 if (is_corlib && !strcmp (nspace, "System")) {
4730 if (!strcmp (name, "Boolean")) {
4731 t = MONO_TYPE_BOOLEAN;
4732 } else if (!strcmp(name, "Byte")) {
4734 class->blittable = TRUE;
4738 if (!strcmp (name, "Char")) {
4743 if (!strcmp (name, "Double")) {
4745 class->blittable = TRUE;
4749 if (!strcmp (name, "Int32")) {
4751 class->blittable = TRUE;
4752 } else if (!strcmp(name, "Int16")) {
4754 class->blittable = TRUE;
4755 } else if (!strcmp(name, "Int64")) {
4757 class->blittable = TRUE;
4758 } else if (!strcmp(name, "IntPtr")) {
4760 class->blittable = TRUE;
4764 if (!strcmp (name, "Single")) {
4766 class->blittable = TRUE;
4767 } else if (!strcmp(name, "SByte")) {
4769 class->blittable = TRUE;
4773 if (!strcmp (name, "UInt32")) {
4775 class->blittable = TRUE;
4776 } else if (!strcmp(name, "UInt16")) {
4778 class->blittable = TRUE;
4779 } else if (!strcmp(name, "UInt64")) {
4781 class->blittable = TRUE;
4782 } else if (!strcmp(name, "UIntPtr")) {
4784 class->blittable = TRUE;
4788 if (!strcmp (name, "TypedReference")) {
4789 t = MONO_TYPE_TYPEDBYREF;
4790 class->blittable = TRUE;
4794 if (!strcmp (name, "Void")) {
4802 class->this_arg.type = class->byval_arg.type = t;
4805 if (MONO_CLASS_IS_INTERFACE (class))
4806 class->interface_id = mono_get_unique_iid (class);
4811 * COM initialization (using mono_init_com_types) is delayed until needed.
4812 * However when a [ComImport] attribute is present on a type it will trigger
4813 * the initialization. This is not a problem unless the BCL being executed
4814 * lacks the types that COM depends on (e.g. Variant on Silverlight).
4817 init_com_from_comimport (MonoClass *class)
4819 /* we don't always allow COM initialization under the CoreCLR (e.g. Moonlight does not require it) */
4820 if ((mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)) {
4821 /* but some other CoreCLR user could requires it for their platform (i.e. trusted) code */
4822 if (!mono_security_core_clr_determine_platform_image (class->image)) {
4823 /* but it can not be made available for application (i.e. user code) since all COM calls
4824 * are considered native calls. In this case we fail with a TypeLoadException (just like
4825 * Silverlight 2 does */
4826 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4830 /* FIXME : we should add an extra checks to ensure COM can be initialized properly before continuing */
4831 mono_init_com_types ();
4835 * LOCKING: this assumes the loader lock is held
4838 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
4840 gboolean system_namespace;
4841 gboolean is_corlib = is_corlib_image (class->image);
4843 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
4845 /* if root of the hierarchy */
4846 if (system_namespace && !strcmp (class->name, "Object")) {
4847 class->parent = NULL;
4848 class->instance_size = sizeof (MonoObject);
4851 if (!strcmp (class->name, "<Module>")) {
4852 class->parent = NULL;
4853 class->instance_size = 0;
4857 if (!MONO_CLASS_IS_INTERFACE (class)) {
4858 /* Imported COM Objects always derive from __ComObject. */
4859 if (MONO_CLASS_IS_IMPORT (class)) {
4860 init_com_from_comimport (class);
4861 if (parent == mono_defaults.object_class)
4862 parent = mono_defaults.com_object_class;
4865 /* set the parent to something useful and safe, but mark the type as broken */
4866 parent = mono_defaults.object_class;
4867 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4870 class->parent = parent;
4872 if (parent->generic_class && !parent->name) {
4874 * If the parent is a generic instance, we may get
4875 * called before it is fully initialized, especially
4876 * before it has its name.
4881 class->marshalbyref = parent->marshalbyref;
4882 class->contextbound = parent->contextbound;
4883 class->delegate = parent->delegate;
4884 if (MONO_CLASS_IS_IMPORT (class))
4885 class->is_com_object = 1;
4887 class->is_com_object = parent->is_com_object;
4889 if (system_namespace) {
4890 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
4891 class->marshalbyref = 1;
4893 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
4894 class->contextbound = 1;
4896 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
4897 class->delegate = 1;
4900 if (class->parent->enumtype || (is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
4901 (strcmp (class->parent->name_space, "System") == 0)))
4902 class->valuetype = 1;
4903 if (is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
4904 class->valuetype = class->enumtype = 1;
4906 /*class->enumtype = class->parent->enumtype; */
4907 mono_class_setup_supertypes (class);
4909 /* initialize com types if COM interfaces are present */
4910 if (MONO_CLASS_IS_IMPORT (class))
4911 init_com_from_comimport (class);
4912 class->parent = NULL;
4918 * mono_class_setup_supertypes:
4921 * Build the data structure needed to make fast type checks work.
4922 * This currently sets two fields in @class:
4923 * - idepth: distance between @class and System.Object in the type
4925 * - supertypes: array of classes: each element has a class in the hierarchy
4926 * starting from @class up to System.Object
4928 * LOCKING: this assumes the loader lock is held
4931 mono_class_setup_supertypes (MonoClass *class)
4935 if (class->supertypes)
4938 if (class->parent && !class->parent->supertypes)
4939 mono_class_setup_supertypes (class->parent);
4941 class->idepth = class->parent->idepth + 1;
4945 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
4946 class->supertypes = mono_image_alloc0 (class->image, sizeof (MonoClass *) * ms);
4948 if (class->parent) {
4949 class->supertypes [class->idepth - 1] = class;
4950 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
4952 class->supertypes [0] = class;
4957 * mono_class_create_from_typedef:
4958 * @image: image where the token is valid
4959 * @type_token: typedef token
4961 * Create the MonoClass* representing the specified type token.
4962 * @type_token must be a TypeDef token.
4965 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
4967 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
4968 MonoClass *class, *parent = NULL;
4969 guint32 cols [MONO_TYPEDEF_SIZE];
4970 guint32 cols_next [MONO_TYPEDEF_SIZE];
4971 guint tidx = mono_metadata_token_index (type_token);
4972 MonoGenericContext *context = NULL;
4973 const char *name, *nspace;
4975 MonoClass **interfaces;
4976 guint32 field_last, method_last;
4977 guint32 nesting_tokeen;
4979 if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || tidx > tt->rows)
4982 mono_loader_lock ();
4984 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
4985 mono_loader_unlock ();
4989 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
4991 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
4992 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
4994 class = mono_image_alloc0 (image, sizeof (MonoClass));
4997 class->name_space = nspace;
4999 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
5001 class->image = image;
5002 class->type_token = type_token;
5003 class->flags = cols [MONO_TYPEDEF_FLAGS];
5005 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
5007 classes_size += sizeof (MonoClass);
5010 * Check whether we're a generic type definition.
5012 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
5013 if (class->generic_container) {
5014 class->is_generic = 1;
5015 class->generic_container->owner.klass = class;
5016 context = &class->generic_container->context;
5019 if (cols [MONO_TYPEDEF_EXTENDS]) {
5020 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
5022 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
5023 /*WARNING: this must satisfy mono_metadata_type_hash*/
5024 class->this_arg.byref = 1;
5025 class->this_arg.data.klass = class;
5026 class->this_arg.type = MONO_TYPE_CLASS;
5027 class->byval_arg.data.klass = class;
5028 class->byval_arg.type = MONO_TYPE_CLASS;
5030 parent = mono_class_get_full (image, parent_token, context);
5032 if (parent == NULL){
5033 mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
5034 mono_loader_unlock ();
5035 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5040 /* do this early so it's available for interfaces in setup_mono_type () */
5041 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token))) {
5042 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
5043 if (!class->nested_in) {
5044 mono_internal_hash_table_remove (&image->class_cache, GUINT_TO_POINTER (type_token));
5045 mono_loader_unlock ();
5046 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5051 mono_class_setup_parent (class, parent);
5053 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
5054 mono_class_setup_mono_type (class);
5056 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
5060 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
5064 class->cast_class = class->element_class = class;
5066 if (!class->enumtype) {
5067 if (!mono_metadata_interfaces_from_typedef_full (
5068 image, type_token, &interfaces, &icount, FALSE, context)){
5069 mono_loader_unlock ();
5070 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5074 class->interfaces = interfaces;
5075 class->interface_count = icount;
5076 class->interfaces_inited = 1;
5079 /*g_print ("Load class %s\n", name);*/
5082 * Compute the field and method lists
5084 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
5085 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
5087 if (tt->rows > tidx){
5088 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
5089 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
5090 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
5092 field_last = image->tables [MONO_TABLE_FIELD].rows;
5093 method_last = image->tables [MONO_TABLE_METHOD].rows;
5096 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
5097 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
5098 class->field.count = field_last - class->field.first;
5100 class->field.count = 0;
5102 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
5103 class->method.count = method_last - class->method.first;
5105 class->method.count = 0;
5107 /* reserve space to store vector pointer in arrays */
5108 if (is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
5109 class->instance_size += 2 * sizeof (gpointer);
5110 g_assert (class->field.count == 0);
5113 if (class->enumtype) {
5114 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
5115 if (!enum_basetype) {
5116 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5117 mono_loader_unlock ();
5118 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5121 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
5125 * If we're a generic type definition, load the constraints.
5126 * We must do this after the class has been constructed to make certain recursive scenarios
5129 if (class->generic_container && !mono_metadata_load_generic_param_constraints_full (image, type_token, class->generic_container)){
5130 char *class_name = g_strdup_printf("%s.%s", class->name_space, class->name);
5131 char *error = concat_two_strings_with_zero (class->image, class_name, class->image->assembly_name);
5132 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, error);
5133 g_free (class_name);
5134 mono_loader_unlock ();
5135 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5139 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
5140 if (!strncmp (name, "Vector", 6))
5141 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");
5144 mono_loader_unlock ();
5146 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5151 /** is klass Nullable<T>? */
5153 mono_class_is_nullable (MonoClass *klass)
5155 return klass->generic_class != NULL &&
5156 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
5160 /** if klass is T? return T */
5162 mono_class_get_nullable_param (MonoClass *klass)
5164 g_assert (mono_class_is_nullable (klass));
5165 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
5169 * Create the `MonoClass' for an instantiation of a generic type.
5170 * We only do this if we actually need it.
5173 mono_generic_class_get_class (MonoGenericClass *gclass)
5175 MonoClass *klass, *gklass;
5177 mono_loader_lock ();
5178 if (gclass->cached_class) {
5179 mono_loader_unlock ();
5180 return gclass->cached_class;
5183 gclass->cached_class = g_malloc0 (sizeof (MonoClass));
5184 klass = gclass->cached_class;
5186 gklass = gclass->container_class;
5188 if (gklass->nested_in) {
5190 * FIXME: the nested type context should include everything the
5191 * nesting context should have, but it may also have additional
5192 * generic parameters...
5194 klass->nested_in = mono_class_inflate_generic_class (gklass->nested_in,
5195 mono_generic_class_get_context (gclass));
5198 klass->name = gklass->name;
5199 klass->name_space = gklass->name_space;
5201 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
5203 klass->image = gklass->image;
5204 klass->flags = gklass->flags;
5205 klass->type_token = gklass->type_token;
5206 klass->field.count = gklass->field.count;
5208 klass->is_inflated = 1;
5209 klass->generic_class = gclass;
5211 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
5212 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
5213 klass->this_arg.byref = TRUE;
5214 klass->enumtype = gklass->enumtype;
5215 klass->valuetype = gklass->valuetype;
5217 klass->cast_class = klass->element_class = klass;
5219 if (mono_class_is_nullable (klass))
5220 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
5223 * We're not interested in the nested classes of a generic instance.
5224 * We use the generic type definition to look for nested classes.
5227 if (gklass->parent) {
5228 klass->parent = mono_class_inflate_generic_class (gklass->parent, mono_generic_class_get_context (gclass));
5232 mono_class_setup_parent (klass, klass->parent);
5234 if (klass->enumtype) {
5235 klass->cast_class = gklass->cast_class;
5236 klass->element_class = gklass->element_class;
5239 if (gclass->is_dynamic) {
5242 mono_class_setup_supertypes (klass);
5244 if (klass->enumtype) {
5246 * For enums, gklass->fields might not been set, but instance_size etc. is
5247 * already set in mono_reflection_create_internal_class (). For non-enums,
5248 * these will be computed normally in mono_class_layout_fields ().
5250 klass->instance_size = gklass->instance_size;
5251 klass->sizes.class_size = gklass->sizes.class_size;
5252 klass->size_inited = 1;
5256 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
5258 inflated_classes ++;
5259 inflated_classes_size += sizeof (MonoClass);
5261 mono_loader_unlock ();
5267 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
5269 MonoClass *klass, **ptr;
5271 MonoGenericContainer *container = mono_generic_param_owner (param);
5275 image = mono_defaults.corlib;
5277 klass = mono_image_alloc0 (image, sizeof (MonoClass));
5278 classes_size += sizeof (MonoClass);
5281 klass->name = pinfo->name;
5283 int n = mono_generic_param_num (param);
5284 klass->name = mono_image_alloc0 (image, 16);
5285 sprintf ((char*)klass->name, "%d", n);
5290 MonoMethod *omethod = container->owner.method;
5291 klass->name_space = (omethod && omethod->klass) ? omethod->klass->name_space : "";
5293 MonoClass *oklass = container->owner.klass;
5294 klass->name_space = oklass ? oklass->name_space : "";
5297 klass->name_space = "";
5300 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
5304 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
5308 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
5309 klass->parent = pinfo->constraints [0];
5311 } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
5312 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
5314 klass->parent = mono_defaults.object_class;
5317 if (count - pos > 0) {
5318 klass->interface_count = count - pos;
5319 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
5320 klass->interfaces_inited = TRUE;
5321 for (i = pos; i < count; i++)
5322 klass->interfaces [i - pos] = pinfo->constraints [i];
5325 klass->image = image;
5327 klass->inited = TRUE;
5328 klass->cast_class = klass->element_class = klass;
5329 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
5331 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
5332 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
5333 klass->this_arg.byref = TRUE;
5335 /* FIXME: shouldn't this be ->type_token? */
5336 klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
5338 mono_class_setup_supertypes (klass);
5340 if (count - pos > 0) {
5341 mono_class_setup_vtable (klass->parent);
5342 g_assert (!klass->parent->exception_type);
5343 setup_interface_offsets (klass, klass->parent->vtable_size);
5349 #define FAST_CACHE_SIZE 16
5350 static MonoClass *var_cache_fast [FAST_CACHE_SIZE];
5351 static MonoClass *mvar_cache_fast [FAST_CACHE_SIZE];
5352 static GHashTable *var_cache_slow;
5353 static GHashTable *mvar_cache_slow;
5356 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
5358 int n = mono_generic_param_num (param);
5361 if (n < FAST_CACHE_SIZE)
5362 return (is_mvar ? mvar_cache_fast : var_cache_fast) [n];
5363 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
5364 return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
5368 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
5370 int n = mono_generic_param_num (param);
5373 if (n < FAST_CACHE_SIZE) {
5374 (is_mvar ? mvar_cache_fast : var_cache_fast) [n] = klass;
5377 ht = is_mvar ? mvar_cache_slow : var_cache_slow;
5379 ht = g_hash_table_new (NULL, NULL);
5381 mvar_cache_slow = ht;
5383 var_cache_slow = ht;
5386 g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
5390 * LOCKING: Acquires the loader lock.
5393 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
5395 MonoGenericContainer *container = mono_generic_param_owner (param);
5396 MonoGenericParamInfo *pinfo;
5399 mono_loader_lock ();
5402 pinfo = mono_generic_param_info (param);
5403 if (pinfo->pklass) {
5404 mono_loader_unlock ();
5405 return pinfo->pklass;
5411 klass = get_anon_gparam_class (param, is_mvar);
5413 mono_loader_unlock ();
5418 if (!image && container) {
5420 MonoMethod *method = container->owner.method;
5421 image = (method && method->klass) ? method->klass->image : NULL;
5423 MonoClass *klass = container->owner.klass;
5424 // FIXME: 'klass' should not be null
5425 // But, monodis creates GenericContainers without associating a owner to it
5426 image = klass ? klass->image : NULL;
5430 klass = make_generic_param_class (param, image, is_mvar, pinfo);
5432 mono_memory_barrier ();
5435 pinfo->pklass = klass;
5437 set_anon_gparam_class (param, is_mvar, klass);
5439 mono_loader_unlock ();
5441 /* FIXME: Should this go inside 'make_generic_param_klass'? */
5442 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
5448 mono_ptr_class_get (MonoType *type)
5451 MonoClass *el_class;
5455 el_class = mono_class_from_mono_type (type);
5456 image = el_class->image;
5458 mono_loader_lock ();
5460 if (!image->ptr_cache)
5461 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5463 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
5464 mono_loader_unlock ();
5467 result = mono_image_alloc0 (image, sizeof (MonoClass));
5469 classes_size += sizeof (MonoClass);
5471 result->parent = NULL; /* no parent for PTR types */
5472 result->name_space = el_class->name_space;
5473 name = g_strdup_printf ("%s*", el_class->name);
5474 result->name = mono_image_strdup (image, name);
5477 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5479 result->image = el_class->image;
5480 result->inited = TRUE;
5481 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5482 /* Can pointers get boxed? */
5483 result->instance_size = sizeof (gpointer);
5484 result->cast_class = result->element_class = el_class;
5485 result->blittable = TRUE;
5487 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
5488 result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
5489 result->this_arg.byref = TRUE;
5491 mono_class_setup_supertypes (result);
5493 g_hash_table_insert (image->ptr_cache, el_class, result);
5495 mono_loader_unlock ();
5497 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5503 mono_fnptr_class_get (MonoMethodSignature *sig)
5506 static GHashTable *ptr_hash = NULL;
5508 /* FIXME: These should be allocate from a mempool as well, but which one ? */
5510 mono_loader_lock ();
5513 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5515 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
5516 mono_loader_unlock ();
5519 result = g_new0 (MonoClass, 1);
5521 result->parent = NULL; /* no parent for PTR types */
5522 result->name_space = "System";
5523 result->name = "MonoFNPtrFakeClass";
5525 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5527 result->image = mono_defaults.corlib; /* need to fix... */
5528 result->inited = TRUE;
5529 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
5530 /* Can pointers get boxed? */
5531 result->instance_size = sizeof (gpointer);
5532 result->cast_class = result->element_class = result;
5533 result->blittable = TRUE;
5535 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
5536 result->this_arg.data.method = result->byval_arg.data.method = sig;
5537 result->this_arg.byref = TRUE;
5538 result->blittable = TRUE;
5540 mono_class_setup_supertypes (result);
5542 g_hash_table_insert (ptr_hash, sig, result);
5544 mono_loader_unlock ();
5546 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5552 mono_class_from_mono_type (MonoType *type)
5554 switch (type->type) {
5555 case MONO_TYPE_OBJECT:
5556 return type->data.klass? type->data.klass: mono_defaults.object_class;
5557 case MONO_TYPE_VOID:
5558 return type->data.klass? type->data.klass: mono_defaults.void_class;
5559 case MONO_TYPE_BOOLEAN:
5560 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
5561 case MONO_TYPE_CHAR:
5562 return type->data.klass? type->data.klass: mono_defaults.char_class;
5564 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
5566 return type->data.klass? type->data.klass: mono_defaults.byte_class;
5568 return type->data.klass? type->data.klass: mono_defaults.int16_class;
5570 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
5572 return type->data.klass? type->data.klass: mono_defaults.int32_class;
5574 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
5576 return type->data.klass? type->data.klass: mono_defaults.int_class;
5578 return type->data.klass? type->data.klass: mono_defaults.uint_class;
5580 return type->data.klass? type->data.klass: mono_defaults.int64_class;
5582 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
5584 return type->data.klass? type->data.klass: mono_defaults.single_class;
5586 return type->data.klass? type->data.klass: mono_defaults.double_class;
5587 case MONO_TYPE_STRING:
5588 return type->data.klass? type->data.klass: mono_defaults.string_class;
5589 case MONO_TYPE_TYPEDBYREF:
5590 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
5591 case MONO_TYPE_ARRAY:
5592 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
5594 return mono_ptr_class_get (type->data.type);
5595 case MONO_TYPE_FNPTR:
5596 return mono_fnptr_class_get (type->data.method);
5597 case MONO_TYPE_SZARRAY:
5598 return mono_array_class_get (type->data.klass, 1);
5599 case MONO_TYPE_CLASS:
5600 case MONO_TYPE_VALUETYPE:
5601 return type->data.klass;
5602 case MONO_TYPE_GENERICINST:
5603 return mono_generic_class_get_class (type->data.generic_class);
5605 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
5606 case MONO_TYPE_MVAR:
5607 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
5609 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
5610 g_assert_not_reached ();
5617 * mono_type_retrieve_from_typespec
5618 * @image: context where the image is created
5619 * @type_spec: typespec token
5620 * @context: the generic context used to evaluate generic instantiations in
5623 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate, MonoError *error)
5625 MonoType *t = mono_type_create_from_typespec (image, type_spec);
5627 mono_error_init (error);
5628 *did_inflate = FALSE;
5631 char *name = mono_class_name_from_token (image, type_spec);
5632 char *assembly = mono_assembly_name_from_token (image, type_spec);
5633 mono_error_set_type_load_name (error, name, assembly, "Could not resolve typespec token %08x", type_spec);
5637 if (context && (context->class_inst || context->method_inst)) {
5638 MonoType *inflated = inflate_generic_type (NULL, t, context, error);
5640 if (!mono_error_ok (error))
5645 *did_inflate = TRUE;
5652 * mono_class_create_from_typespec
5653 * @image: context where the image is created
5654 * @type_spec: typespec token
5655 * @context: the generic context used to evaluate generic instantiations in
5658 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, MonoError *error)
5661 gboolean inflated = FALSE;
5662 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated, error);
5663 if (!mono_error_ok (error))
5665 ret = mono_class_from_mono_type (t);
5667 mono_metadata_free_type (t);
5672 * mono_bounded_array_class_get:
5673 * @element_class: element class
5674 * @rank: the dimension of the array class
5675 * @bounded: whenever the array has non-zero bounds
5677 * Returns: a class object describing the array with element type @element_type and
5681 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
5685 MonoClass *parent = NULL;
5686 GSList *list, *rootlist = NULL;
5689 gboolean corlib_type = FALSE;
5691 g_assert (rank <= 255);
5694 /* bounded only matters for one-dimensional arrays */
5697 image = eclass->image;
5699 if (rank == 1 && !bounded) {
5701 * This case is very frequent not just during compilation because of calls
5702 * from mono_class_from_mono_type (), mono_array_new (),
5703 * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
5705 EnterCriticalSection (&image->szarray_cache_lock);
5706 if (!image->szarray_cache)
5707 image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5708 class = g_hash_table_lookup (image->szarray_cache, eclass);
5709 LeaveCriticalSection (&image->szarray_cache_lock);
5713 mono_loader_lock ();
5715 mono_loader_lock ();
5717 if (!image->array_cache)
5718 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5720 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
5721 for (; list; list = list->next) {
5723 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
5724 mono_loader_unlock ();
5731 /* for the building corlib use System.Array from it */
5732 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
5733 parent = mono_class_from_name (image, "System", "Array");
5736 parent = mono_defaults.array_class;
5737 if (!parent->inited)
5738 mono_class_init (parent);
5741 class = mono_image_alloc0 (image, sizeof (MonoClass));
5743 class->image = image;
5744 class->name_space = eclass->name_space;
5745 nsize = strlen (eclass->name);
5746 name = g_malloc (nsize + 2 + rank + 1);
5747 memcpy (name, eclass->name, nsize);
5750 memset (name + nsize + 1, ',', rank - 1);
5752 name [nsize + rank] = '*';
5753 name [nsize + rank + bounded] = ']';
5754 name [nsize + rank + bounded + 1] = 0;
5755 class->name = mono_image_strdup (image, name);
5758 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
5760 classes_size += sizeof (MonoClass);
5762 class->type_token = 0;
5763 /* all arrays are marked serializable and sealed, bug #42779 */
5764 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED | TYPE_ATTRIBUTE_PUBLIC;
5765 class->parent = parent;
5766 class->instance_size = mono_class_instance_size (class->parent);
5768 if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
5769 if (!eclass->ref_info_handle || eclass->wastypebuilder) {
5770 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
5771 g_assert (eclass->ref_info_handle && !eclass->wastypebuilder);
5773 /* element_size -1 is ok as this is not an instantitable type*/
5774 class->sizes.element_size = -1;
5776 class->sizes.element_size = mono_class_array_element_size (eclass);
5778 mono_class_setup_supertypes (class);
5780 if (eclass->generic_class)
5781 mono_class_init (eclass);
5782 if (!eclass->size_inited)
5783 mono_class_setup_fields (eclass);
5784 if (eclass->exception_type) /*FIXME we fail the array type, but we have to let other fields be set.*/
5785 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5787 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
5791 if (eclass->enumtype)
5792 class->cast_class = eclass->element_class;
5794 class->cast_class = eclass;
5796 class->element_class = eclass;
5798 if ((rank > 1) || bounded) {
5799 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
5800 class->byval_arg.type = MONO_TYPE_ARRAY;
5801 class->byval_arg.data.array = at;
5802 at->eklass = eclass;
5804 /* FIXME: complete.... */
5806 class->byval_arg.type = MONO_TYPE_SZARRAY;
5807 class->byval_arg.data.klass = eclass;
5809 class->this_arg = class->byval_arg;
5810 class->this_arg.byref = 1;
5815 class->generic_container = eclass->generic_container;
5817 if (rank == 1 && !bounded) {
5818 MonoClass *prev_class;
5820 EnterCriticalSection (&image->szarray_cache_lock);
5821 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
5823 /* Someone got in before us */
5826 g_hash_table_insert (image->szarray_cache, eclass, class);
5827 LeaveCriticalSection (&image->szarray_cache_lock);
5829 list = g_slist_append (rootlist, class);
5830 g_hash_table_insert (image->array_cache, eclass, list);
5833 mono_loader_unlock ();
5835 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5841 * mono_array_class_get:
5842 * @element_class: element class
5843 * @rank: the dimension of the array class
5845 * Returns: a class object describing the array with element type @element_type and
5849 mono_array_class_get (MonoClass *eclass, guint32 rank)
5851 return mono_bounded_array_class_get (eclass, rank, FALSE);
5855 * mono_class_instance_size:
5858 * Returns: the size of an object instance
5861 mono_class_instance_size (MonoClass *klass)
5863 if (!klass->size_inited)
5864 mono_class_init (klass);
5866 return klass->instance_size;
5870 * mono_class_min_align:
5873 * Returns: minimm alignment requirements
5876 mono_class_min_align (MonoClass *klass)
5878 if (!klass->size_inited)
5879 mono_class_init (klass);
5881 return klass->min_align;
5885 * mono_class_value_size:
5888 * This function is used for value types, and return the
5889 * space and the alignment to store that kind of value object.
5891 * Returns: the size of a value of kind @klass
5894 mono_class_value_size (MonoClass *klass, guint32 *align)
5898 /* fixme: check disable, because we still have external revereces to
5899 * mscorlib and Dummy Objects
5901 /*g_assert (klass->valuetype);*/
5903 size = mono_class_instance_size (klass) - sizeof (MonoObject);
5906 *align = klass->min_align;
5912 * mono_class_data_size:
5915 * Returns: the size of the static class data
5918 mono_class_data_size (MonoClass *klass)
5921 mono_class_init (klass);
5923 /* in arrays, sizes.class_size is unioned with element_size
5924 * and arrays have no static fields
5928 return klass->sizes.class_size;
5932 * Auxiliary routine to mono_class_get_field
5934 * Takes a field index instead of a field token.
5936 static MonoClassField *
5937 mono_class_get_field_idx (MonoClass *class, int idx)
5939 mono_class_setup_fields_locking (class);
5940 if (class->exception_type)
5944 if (class->image->uncompressed_metadata) {
5946 * class->field.first points to the FieldPtr table, while idx points into the
5947 * Field table, so we have to do a search.
5949 /*FIXME this is broken for types with multiple fields with the same name.*/
5950 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
5953 for (i = 0; i < class->field.count; ++i)
5954 if (mono_field_get_name (&class->fields [i]) == name)
5955 return &class->fields [i];
5956 g_assert_not_reached ();
5958 if (class->field.count) {
5959 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
5960 return &class->fields [idx - class->field.first];
5964 class = class->parent;
5970 * mono_class_get_field:
5971 * @class: the class to lookup the field.
5972 * @field_token: the field token
5974 * Returns: A MonoClassField representing the type and offset of
5975 * the field, or a NULL value if the field does not belong to this
5979 mono_class_get_field (MonoClass *class, guint32 field_token)
5981 int idx = mono_metadata_token_index (field_token);
5983 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
5985 return mono_class_get_field_idx (class, idx - 1);
5989 * mono_class_get_field_from_name:
5990 * @klass: the class to lookup the field.
5991 * @name: the field name
5993 * Search the class @klass and it's parents for a field with the name @name.
5995 * Returns: the MonoClassField pointer of the named field or NULL
5998 mono_class_get_field_from_name (MonoClass *klass, const char *name)
6000 return mono_class_get_field_from_name_full (klass, name, NULL);
6004 * mono_class_get_field_from_name_full:
6005 * @klass: the class to lookup the field.
6006 * @name: the field name
6007 * @type: the type of the fields. This optional.
6009 * Search the class @klass and it's parents for a field with the name @name and type @type.
6011 * If @klass is an inflated generic type, the type comparison is done with the equivalent field
6012 * of its generic type definition.
6014 * Returns: the MonoClassField pointer of the named field or NULL
6017 mono_class_get_field_from_name_full (MonoClass *klass, const char *name, MonoType *type)
6021 mono_class_setup_fields_locking (klass);
6022 if (klass->exception_type)
6026 for (i = 0; i < klass->field.count; ++i) {
6027 MonoClassField *field = &klass->fields [i];
6029 if (strcmp (name, mono_field_get_name (field)) != 0)
6033 MonoType *field_type = mono_metadata_get_corresponding_field_from_generic_type_definition (field)->type;
6034 if (!mono_metadata_type_equal_full (type, field_type, TRUE))
6039 klass = klass->parent;
6045 * mono_class_get_field_token:
6046 * @field: the field we need the token of
6048 * Get the token of a field. Note that the tokesn is only valid for the image
6049 * the field was loaded from. Don't use this function for fields in dynamic types.
6051 * Returns: the token representing the field in the image it was loaded from.
6054 mono_class_get_field_token (MonoClassField *field)
6056 MonoClass *klass = field->parent;
6059 mono_class_setup_fields_locking (klass);
6060 if (klass->exception_type)
6064 for (i = 0; i < klass->field.count; ++i) {
6065 if (&klass->fields [i] == field) {
6066 int idx = klass->field.first + i + 1;
6068 if (klass->image->uncompressed_metadata)
6069 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
6070 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
6073 klass = klass->parent;
6076 g_assert_not_reached ();
6081 mono_field_get_index (MonoClassField *field)
6083 int index = field - field->parent->fields;
6085 g_assert (index >= 0 && index < field->parent->field.count);
6091 * mono_class_get_field_default_value:
6093 * Return the default value of the field as a pointer into the metadata blob.
6096 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
6099 guint32 constant_cols [MONO_CONSTANT_SIZE];
6101 MonoClass *klass = field->parent;
6103 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
6105 if (!klass->ext || !klass->ext->field_def_values) {
6106 mono_loader_lock ();
6107 mono_class_alloc_ext (klass);
6108 if (!klass->ext->field_def_values)
6109 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
6110 mono_loader_unlock ();
6113 field_index = mono_field_get_index (field);
6115 if (!klass->ext->field_def_values [field_index].data) {
6116 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
6118 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
6120 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
6121 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
6122 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
6125 *def_type = klass->ext->field_def_values [field_index].def_type;
6126 return klass->ext->field_def_values [field_index].data;
6130 * mono_class_get_property_default_value:
6132 * Return the default value of the field as a pointer into the metadata blob.
6135 mono_class_get_property_default_value (MonoProperty *property, MonoTypeEnum *def_type)
6138 guint32 constant_cols [MONO_CONSTANT_SIZE];
6139 MonoClass *klass = property->parent;
6141 g_assert (property->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT);
6142 /*We don't cache here because it is not used by C# so it's quite rare.*/
6144 cindex = mono_metadata_get_constant_index (klass->image, mono_class_get_property_token (property), 0);
6148 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
6149 *def_type = constant_cols [MONO_CONSTANT_TYPE];
6150 return (gpointer)mono_metadata_blob_heap (klass->image, constant_cols [MONO_CONSTANT_VALUE]);
6154 mono_class_get_event_token (MonoEvent *event)
6156 MonoClass *klass = event->parent;
6161 for (i = 0; i < klass->ext->event.count; ++i) {
6162 if (&klass->ext->events [i] == event)
6163 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
6166 klass = klass->parent;
6169 g_assert_not_reached ();
6174 mono_class_get_property_from_name (MonoClass *klass, const char *name)
6178 gpointer iter = NULL;
6179 while ((p = mono_class_get_properties (klass, &iter))) {
6180 if (! strcmp (name, p->name))
6183 klass = klass->parent;
6189 mono_class_get_property_token (MonoProperty *prop)
6191 MonoClass *klass = prop->parent;
6195 gpointer iter = NULL;
6196 while ((p = mono_class_get_properties (klass, &iter))) {
6197 if (&klass->ext->properties [i] == prop)
6198 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
6202 klass = klass->parent;
6205 g_assert_not_reached ();
6210 mono_class_name_from_token (MonoImage *image, guint32 type_token)
6212 const char *name, *nspace;
6214 return g_strdup_printf ("DynamicType 0x%08x", type_token);
6216 switch (type_token & 0xff000000){
6217 case MONO_TOKEN_TYPE_DEF: {
6218 guint32 cols [MONO_TYPEDEF_SIZE];
6219 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
6220 guint tidx = mono_metadata_token_index (type_token);
6222 if (tidx > tt->rows)
6223 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6225 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
6226 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6227 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6228 if (strlen (nspace) == 0)
6229 return g_strdup_printf ("%s", name);
6231 return g_strdup_printf ("%s.%s", nspace, name);
6234 case MONO_TOKEN_TYPE_REF: {
6235 guint32 cols [MONO_TYPEREF_SIZE];
6236 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
6237 guint tidx = mono_metadata_token_index (type_token);
6240 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6241 mono_metadata_decode_row (t, tidx-1, cols, MONO_TYPEREF_SIZE);
6242 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
6243 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
6244 if (strlen (nspace) == 0)
6245 return g_strdup_printf ("%s", name);
6247 return g_strdup_printf ("%s.%s", nspace, name);
6250 case MONO_TOKEN_TYPE_SPEC:
6251 return g_strdup_printf ("Typespec 0x%08x", type_token);
6253 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6258 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
6261 return g_strdup_printf ("DynamicAssembly %s", image->name);
6263 switch (type_token & 0xff000000){
6264 case MONO_TOKEN_TYPE_DEF:
6265 return mono_stringify_assembly_name (&image->assembly->aname);
6267 case MONO_TOKEN_TYPE_REF: {
6268 MonoAssemblyName aname;
6269 guint32 cols [MONO_TYPEREF_SIZE];
6270 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
6271 guint32 idx = mono_metadata_token_index (type_token);
6274 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6276 mono_metadata_decode_row (t, idx-1, cols, MONO_TYPEREF_SIZE);
6278 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
6279 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
6280 case MONO_RESOLTION_SCOPE_MODULE:
6282 return g_strdup ("");
6283 case MONO_RESOLTION_SCOPE_MODULEREF:
6285 return g_strdup ("");
6286 case MONO_RESOLTION_SCOPE_TYPEREF:
6288 return g_strdup ("");
6289 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
6290 mono_assembly_get_assemblyref (image, idx - 1, &aname);
6291 return mono_stringify_assembly_name (&aname);
6293 g_assert_not_reached ();
6297 case MONO_TOKEN_TYPE_SPEC:
6299 return g_strdup ("");
6301 g_assert_not_reached ();
6308 * mono_class_get_full:
6309 * @image: the image where the class resides
6310 * @type_token: the token for the class
6311 * @context: the generic context used to evaluate generic instantiations in
6313 * Returns: the MonoClass that represents @type_token in @image
6316 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
6319 MonoClass *class = NULL;
6321 if (image->dynamic) {
6322 int table = mono_metadata_token_table (type_token);
6324 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
6325 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
6328 return mono_lookup_dynamic_token (image, type_token, context);
6331 switch (type_token & 0xff000000){
6332 case MONO_TOKEN_TYPE_DEF:
6333 class = mono_class_create_from_typedef (image, type_token);
6335 case MONO_TOKEN_TYPE_REF:
6336 class = mono_class_from_typeref (image, type_token);
6338 case MONO_TOKEN_TYPE_SPEC:
6339 class = mono_class_create_from_typespec (image, type_token, context, &error);
6340 if (!mono_error_ok (&error)) {
6341 /*FIXME don't swallow the error message*/
6342 mono_error_cleanup (&error);
6346 g_warning ("unknown token type %x", type_token & 0xff000000);
6347 g_assert_not_reached ();
6351 char *name = mono_class_name_from_token (image, type_token);
6352 char *assembly = mono_assembly_name_from_token (image, type_token);
6353 mono_loader_set_error_type_load (name, assembly);
6361 * mono_type_get_full:
6362 * @image: the image where the type resides
6363 * @type_token: the token for the type
6364 * @context: the generic context used to evaluate generic instantiations in
6366 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
6368 * Returns: the MonoType that represents @type_token in @image
6371 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
6374 MonoType *type = NULL;
6375 gboolean inflated = FALSE;
6377 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
6379 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
6381 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
6382 MonoClass *class = mono_class_get_full (image, type_token, context);
6383 return class ? mono_class_get_type (class) : NULL;
6386 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated, &error);
6388 if (!mono_error_ok (&error)) {
6389 /*FIXME don't swalloc the error message.*/
6390 char *name = mono_class_name_from_token (image, type_token);
6391 char *assembly = mono_assembly_name_from_token (image, type_token);
6393 g_warning ("Error loading type %s from %s due to %s", name, assembly, mono_error_get_message (&error));
6395 mono_error_cleanup (&error);
6396 mono_loader_set_error_type_load (name, assembly);
6401 MonoType *tmp = type;
6402 type = mono_class_get_type (mono_class_from_mono_type (type));
6403 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
6404 * A MonoClass::byval_arg of a generic type definion has type CLASS.
6405 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
6407 * The long term solution is to chaise this places and make then set MonoType::type correctly.
6409 if (type->type != tmp->type)
6412 mono_metadata_free_type (tmp);
6419 mono_class_get (MonoImage *image, guint32 type_token)
6421 return mono_class_get_full (image, type_token, NULL);
6425 * mono_image_init_name_cache:
6427 * Initializes the class name cache stored in image->name_cache.
6429 * LOCKING: Acquires the corresponding image lock.
6432 mono_image_init_name_cache (MonoImage *image)
6434 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
6435 guint32 cols [MONO_TYPEDEF_SIZE];
6438 guint32 i, visib, nspace_index;
6439 GHashTable *name_cache2, *nspace_table;
6441 mono_image_lock (image);
6443 if (image->name_cache) {
6444 mono_image_unlock (image);
6448 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
6450 if (image->dynamic) {
6451 mono_image_unlock (image);
6455 /* Temporary hash table to avoid lookups in the nspace_table */
6456 name_cache2 = g_hash_table_new (NULL, NULL);
6458 for (i = 1; i <= t->rows; ++i) {
6459 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
6460 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
6462 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
6463 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
6465 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
6467 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6468 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6470 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
6471 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6472 if (!nspace_table) {
6473 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6474 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6475 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6478 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
6481 /* Load type names from EXPORTEDTYPES table */
6483 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6484 guint32 cols [MONO_EXP_TYPE_SIZE];
6487 for (i = 0; i < t->rows; ++i) {
6488 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
6489 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
6490 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
6492 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
6493 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6494 if (!nspace_table) {
6495 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6496 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6497 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6500 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
6504 g_hash_table_destroy (name_cache2);
6505 mono_image_unlock (image);
6508 /*FIXME Only dynamic assemblies should allow this operation.*/
6510 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
6511 const char *name, guint32 index)
6513 GHashTable *nspace_table;
6514 GHashTable *name_cache;
6517 mono_image_lock (image);
6519 if (!image->name_cache)
6520 mono_image_init_name_cache (image);
6522 name_cache = image->name_cache;
6523 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
6524 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6525 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
6528 if ((old_index = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, (char*) name))))
6529 g_error ("overrwritting old token %x on image %s for type %s::%s", old_index, image->name, nspace, name);
6531 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
6533 mono_image_unlock (image);
6542 find_nocase (gpointer key, gpointer value, gpointer user_data)
6544 char *name = (char*)key;
6545 FindUserData *data = (FindUserData*)user_data;
6547 if (!data->value && (mono_utf8_strcasecmp (name, (char*)data->key) == 0))
6548 data->value = value;
6552 * mono_class_from_name_case:
6553 * @image: The MonoImage where the type is looked up in
6554 * @name_space: the type namespace
6555 * @name: the type short name.
6557 * Obtains a MonoClass with a given namespace and a given name which
6558 * is located in the given MonoImage. The namespace and name
6559 * lookups are case insensitive.
6562 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
6564 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
6565 guint32 cols [MONO_TYPEDEF_SIZE];
6570 if (image->dynamic) {
6572 FindUserData user_data;
6574 mono_image_lock (image);
6576 if (!image->name_cache)
6577 mono_image_init_name_cache (image);
6579 user_data.key = name_space;
6580 user_data.value = NULL;
6581 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
6583 if (user_data.value) {
6584 GHashTable *nspace_table = (GHashTable*)user_data.value;
6586 user_data.key = name;
6587 user_data.value = NULL;
6589 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
6591 if (user_data.value)
6592 token = GPOINTER_TO_UINT (user_data.value);
6595 mono_image_unlock (image);
6598 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
6604 /* add a cache if needed */
6605 for (i = 1; i <= t->rows; ++i) {
6606 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
6607 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
6609 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
6610 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
6612 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
6614 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6615 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6616 if (mono_utf8_strcasecmp (n, name) == 0 && mono_utf8_strcasecmp (nspace, name_space) == 0)
6617 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
6623 return_nested_in (MonoClass *class, char *nested)
6626 char *s = strchr (nested, '/');
6627 gpointer iter = NULL;
6634 while ((found = mono_class_get_nested_types (class, &iter))) {
6635 if (strcmp (found->name, nested) == 0) {
6637 return return_nested_in (found, s);
6645 search_modules (MonoImage *image, const char *name_space, const char *name)
6647 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
6648 MonoImage *file_image;
6653 * The EXPORTEDTYPES table only contains public types, so have to search the
6655 * Note: image->modules contains the contents of the MODULEREF table, while
6656 * the real module list is in the FILE table.
6658 for (i = 0; i < file_table->rows; i++) {
6659 guint32 cols [MONO_FILE_SIZE];
6660 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
6661 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
6664 file_image = mono_image_load_file_for_image (image, i + 1);
6666 class = mono_class_from_name (file_image, name_space, name);
6676 * mono_class_from_name:
6677 * @image: The MonoImage where the type is looked up in
6678 * @name_space: the type namespace
6679 * @name: the type short name.
6681 * Obtains a MonoClass with a given namespace and a given name which
6682 * is located in the given MonoImage.
6685 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
6687 GHashTable *nspace_table;
6688 MonoImage *loaded_image;
6695 if ((nested = strchr (name, '/'))) {
6696 int pos = nested - name;
6697 int len = strlen (name);
6700 memcpy (buf, name, len + 1);
6702 nested = buf + pos + 1;
6706 if (get_class_from_name) {
6707 gboolean res = get_class_from_name (image, name_space, name, &class);
6710 class = search_modules (image, name_space, name);
6712 return class ? return_nested_in (class, nested) : NULL;
6718 mono_image_lock (image);
6720 if (!image->name_cache)
6721 mono_image_init_name_cache (image);
6723 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
6726 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
6728 mono_image_unlock (image);
6730 if (!token && image->dynamic && image->modules) {
6731 /* Search modules as well */
6732 for (i = 0; i < image->module_count; ++i) {
6733 MonoImage *module = image->modules [i];
6735 class = mono_class_from_name (module, name_space, name);
6742 class = search_modules (image, name_space, name);
6750 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
6751 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6752 guint32 cols [MONO_EXP_TYPE_SIZE];
6755 idx = mono_metadata_token_index (token);
6757 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
6759 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
6760 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
6761 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
6764 class = mono_class_from_name (loaded_image, name_space, name);
6766 return return_nested_in (class, nested);
6768 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
6769 guint32 assembly_idx;
6771 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
6773 mono_assembly_load_reference (image, assembly_idx - 1);
6774 g_assert (image->references [assembly_idx - 1]);
6775 if (image->references [assembly_idx - 1] == (gpointer)-1)
6778 /* FIXME: Cycle detection */
6779 return mono_class_from_name (image->references [assembly_idx - 1]->image, name_space, name);
6781 g_error ("not yet implemented");
6785 token = MONO_TOKEN_TYPE_DEF | token;
6787 class = mono_class_get (image, token);
6789 return return_nested_in (class, nested);
6793 /*FIXME test for interfaces with variant generic arguments*/
6795 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
6796 gboolean check_interfaces)
6798 g_assert (klassc->idepth > 0);
6799 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
6800 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
6802 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
6805 for (i = 0; i < klass->interface_count; i ++) {
6806 MonoClass *ic = klass->interfaces [i];
6811 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
6816 * MS.NET thinks interfaces are a subclass of Object, so we think it as
6819 if (klassc == mono_defaults.object_class)
6826 mono_class_has_variant_generic_params (MonoClass *klass)
6829 MonoGenericContainer *container;
6831 if (!klass->generic_class)
6834 container = klass->generic_class->container_class->generic_container;
6836 for (i = 0; i < container->type_argc; ++i)
6837 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
6844 * @container the generic container from the GTD
6845 * @klass: the class to be assigned to
6846 * @oklass: the source class
6848 * Both klass and oklass must be instances of the same generic interface.
6849 * Return true if @klass can be assigned to a @klass variable
6852 mono_class_is_variant_compatible (MonoClass *klass, MonoClass *oklass)
6855 MonoType **klass_argv, **oklass_argv;
6856 MonoClass *klass_gtd = mono_class_get_generic_type_definition (klass);
6857 MonoGenericContainer *container = klass_gtd->generic_container;
6859 /*Viable candidates are instances of the same generic interface*/
6860 if (mono_class_get_generic_type_definition (oklass) != klass_gtd)
6863 klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
6864 oklass_argv = &oklass->generic_class->context.class_inst->type_argv [0];
6866 for (j = 0; j < container->type_argc; ++j) {
6867 MonoClass *param1_class = mono_class_from_mono_type (klass_argv [j]);
6868 MonoClass *param2_class = mono_class_from_mono_type (oklass_argv [j]);
6870 if (param1_class->valuetype != param2_class->valuetype)
6874 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
6875 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
6877 if (param1_class != param2_class) {
6878 if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_VARIANT) {
6879 if (!mono_class_is_assignable_from (param1_class, param2_class))
6881 } else if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_COVARIANT) {
6882 if (!mono_class_is_assignable_from (param2_class, param1_class))
6892 * mono_class_is_assignable_from:
6893 * @klass: the class to be assigned to
6894 * @oklass: the source class
6896 * Return: true if an instance of object oklass can be assigned to an
6897 * instance of object @klass
6900 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
6903 mono_class_init (klass);
6905 if (!oklass->inited)
6906 mono_class_init (oklass);
6908 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
6909 return klass == oklass;
6911 if (MONO_CLASS_IS_INTERFACE (klass)) {
6912 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR))
6915 /* interface_offsets might not be set for dynamic classes */
6916 if (oklass->ref_info_handle && !oklass->interface_bitmap)
6918 * oklass might be a generic type parameter but they have
6919 * interface_offsets set.
6921 return mono_reflection_call_is_assignable_to (oklass, klass);
6922 if (!oklass->interface_bitmap)
6923 /* Happens with generic instances of not-yet created dynamic types */
6925 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
6928 if (mono_class_has_variant_generic_params (klass)) {
6931 mono_class_setup_interfaces (oklass, &error);
6932 if (!mono_error_ok (&error)) {
6933 mono_error_cleanup (&error);
6937 /*klass is a generic variant interface, We need to extract from oklass a list of ifaces which are viable candidates.*/
6938 for (i = 0; i < oklass->interface_offsets_count; ++i) {
6939 MonoClass *iface = oklass->interfaces_packed [i];
6941 if (mono_class_is_variant_compatible (klass, iface))
6946 } else if (klass->delegate) {
6947 if (mono_class_has_variant_generic_params (klass) && mono_class_is_variant_compatible (klass, oklass))
6949 }else if (klass->rank) {
6950 MonoClass *eclass, *eoclass;
6952 if (oklass->rank != klass->rank)
6955 /* vectors vs. one dimensional arrays */
6956 if (oklass->byval_arg.type != klass->byval_arg.type)
6959 eclass = klass->cast_class;
6960 eoclass = oklass->cast_class;
6963 * a is b does not imply a[] is b[] when a is a valuetype, and
6964 * b is a reference type.
6967 if (eoclass->valuetype) {
6968 if ((eclass == mono_defaults.enum_class) ||
6969 (eclass == mono_defaults.enum_class->parent) ||
6970 (eclass == mono_defaults.object_class))
6974 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6975 } else if (mono_class_is_nullable (klass)) {
6976 if (mono_class_is_nullable (oklass))
6977 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
6979 return mono_class_is_assignable_from (klass->cast_class, oklass);
6980 } else if (klass == mono_defaults.object_class)
6983 return mono_class_has_parent (oklass, klass);
6986 /*Check if @oklass is variant compatible with @klass.*/
6988 mono_class_is_variant_compatible_slow (MonoClass *klass, MonoClass *oklass)
6991 MonoType **klass_argv, **oklass_argv;
6992 MonoClass *klass_gtd = mono_class_get_generic_type_definition (klass);
6993 MonoGenericContainer *container = klass_gtd->generic_container;
6995 /*Viable candidates are instances of the same generic interface*/
6996 if (mono_class_get_generic_type_definition (oklass) != klass_gtd)
6999 klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
7000 oklass_argv = &oklass->generic_class->context.class_inst->type_argv [0];
7002 for (j = 0; j < container->type_argc; ++j) {
7003 MonoClass *param1_class = mono_class_from_mono_type (klass_argv [j]);
7004 MonoClass *param2_class = mono_class_from_mono_type (oklass_argv [j]);
7006 if (param1_class->valuetype != param2_class->valuetype)
7010 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
7011 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
7013 if (param1_class != param2_class) {
7014 if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_VARIANT) {
7015 if (!mono_class_is_assignable_from_slow (param1_class, param2_class))
7017 } else if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_COVARIANT) {
7018 if (!mono_class_is_assignable_from_slow (param2_class, param1_class))
7026 /*Check if @candidate implements the interface @target*/
7028 mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
7032 gboolean is_variant = mono_class_has_variant_generic_params (target);
7034 if (is_variant && MONO_CLASS_IS_INTERFACE (candidate)) {
7035 if (mono_class_is_variant_compatible_slow (target, candidate))
7040 if (candidate == target)
7043 /*A TypeBuilder can have more interfaces on tb->interfaces than on candidate->interfaces*/
7044 if (candidate->image->dynamic && !candidate->wastypebuilder) {
7045 MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (candidate);
7047 if (tb->interfaces) {
7048 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
7049 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
7050 MonoClass *iface_class = mono_class_from_mono_type (iface->type);
7051 if (iface_class == target)
7053 if (is_variant && mono_class_is_variant_compatible_slow (target, iface_class))
7055 if (mono_class_implement_interface_slow (target, iface_class))
7060 /*setup_interfaces don't mono_class_init anything*/
7061 mono_class_setup_interfaces (candidate, &error);
7062 if (!mono_error_ok (&error)) {
7063 mono_error_cleanup (&error);
7067 for (i = 0; i < candidate->interface_count; ++i) {
7068 if (candidate->interfaces [i] == target)
7071 if (is_variant && mono_class_is_variant_compatible_slow (target, candidate->interfaces [i]))
7074 if (mono_class_implement_interface_slow (target, candidate->interfaces [i]))
7078 candidate = candidate->parent;
7079 } while (candidate);
7085 * Check if @oklass can be assigned to @klass.
7086 * This function does the same as mono_class_is_assignable_from but is safe to be used from mono_class_init context.
7089 mono_class_is_assignable_from_slow (MonoClass *target, MonoClass *candidate)
7091 if (candidate == target)
7093 if (target == mono_defaults.object_class)
7096 /*setup_supertypes don't mono_class_init anything */
7097 mono_class_setup_supertypes (candidate);
7098 mono_class_setup_supertypes (target);
7100 if (mono_class_has_parent (candidate, target))
7103 /*If target is not an interface there is no need to check them.*/
7104 if (MONO_CLASS_IS_INTERFACE (target))
7105 return mono_class_implement_interface_slow (target, candidate);
7107 if (target->delegate && mono_class_has_variant_generic_params (target))
7108 return mono_class_is_variant_compatible (target, candidate);
7110 /*FIXME properly handle nullables and arrays */
7116 * mono_class_get_cctor:
7117 * @klass: A MonoClass pointer
7119 * Returns: the static constructor of @klass if it exists, NULL otherwise.
7122 mono_class_get_cctor (MonoClass *klass)
7124 MonoCachedClassInfo cached_info;
7126 if (klass->image->dynamic) {
7128 * has_cctor is not set for these classes because mono_class_init () is
7131 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
7134 if (!klass->has_cctor)
7137 if (mono_class_get_cached_class_info (klass, &cached_info))
7138 return mono_get_method (klass->image, cached_info.cctor_token, klass);
7140 if (klass->generic_class && !klass->methods)
7141 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
7143 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
7147 * mono_class_get_finalizer:
7148 * @klass: The MonoClass pointer
7150 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
7153 mono_class_get_finalizer (MonoClass *klass)
7155 MonoCachedClassInfo cached_info;
7158 mono_class_init (klass);
7159 if (!klass->has_finalize)
7162 if (mono_class_get_cached_class_info (klass, &cached_info))
7163 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
7165 mono_class_setup_vtable (klass);
7166 return klass->vtable [finalize_slot];
7171 * mono_class_needs_cctor_run:
7172 * @klass: the MonoClass pointer
7173 * @caller: a MonoMethod describing the caller
7175 * Determines whenever the class has a static constructor and whenever it
7176 * needs to be called when executing CALLER.
7179 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
7183 method = mono_class_get_cctor (klass);
7185 return (method == caller) ? FALSE : TRUE;
7191 * mono_class_array_element_size:
7194 * Returns: the number of bytes an element of type @klass
7195 * uses when stored into an array.
7198 mono_class_array_element_size (MonoClass *klass)
7200 MonoType *type = &klass->byval_arg;
7203 switch (type->type) {
7206 case MONO_TYPE_BOOLEAN:
7210 case MONO_TYPE_CHAR:
7219 case MONO_TYPE_CLASS:
7220 case MONO_TYPE_STRING:
7221 case MONO_TYPE_OBJECT:
7222 case MONO_TYPE_SZARRAY:
7223 case MONO_TYPE_ARRAY:
7225 case MONO_TYPE_MVAR:
7226 return sizeof (gpointer);
7231 case MONO_TYPE_VALUETYPE:
7232 if (type->data.klass->enumtype) {
7233 type = mono_class_enum_basetype (type->data.klass);
7234 klass = klass->element_class;
7237 return mono_class_instance_size (klass) - sizeof (MonoObject);
7238 case MONO_TYPE_GENERICINST:
7239 type = &type->data.generic_class->container_class->byval_arg;
7242 case MONO_TYPE_VOID:
7246 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
7252 * mono_array_element_size:
7253 * @ac: pointer to a #MonoArrayClass
7255 * Returns: the size of single array element.
7258 mono_array_element_size (MonoClass *ac)
7260 g_assert (ac->rank);
7261 return ac->sizes.element_size;
7265 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
7266 MonoGenericContext *context)
7268 if (image->dynamic) {
7269 MonoClass *tmp_handle_class;
7270 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
7272 g_assert (tmp_handle_class);
7274 *handle_class = tmp_handle_class;
7276 if (tmp_handle_class == mono_defaults.typehandle_class)
7277 return &((MonoClass*)obj)->byval_arg;
7282 switch (token & 0xff000000) {
7283 case MONO_TOKEN_TYPE_DEF:
7284 case MONO_TOKEN_TYPE_REF:
7285 case MONO_TOKEN_TYPE_SPEC: {
7288 *handle_class = mono_defaults.typehandle_class;
7289 type = mono_type_get_full (image, token, context);
7292 mono_class_init (mono_class_from_mono_type (type));
7293 /* We return a MonoType* as handle */
7296 case MONO_TOKEN_FIELD_DEF: {
7298 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
7302 *handle_class = mono_defaults.fieldhandle_class;
7303 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
7306 mono_class_init (class);
7307 return mono_class_get_field (class, token);
7309 case MONO_TOKEN_METHOD_DEF:
7310 case MONO_TOKEN_METHOD_SPEC: {
7312 meth = mono_get_method_full (image, token, NULL, context);
7314 *handle_class = mono_defaults.methodhandle_class;
7317 case MONO_TOKEN_MEMBER_REF: {
7318 guint32 cols [MONO_MEMBERREF_SIZE];
7320 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
7321 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
7322 mono_metadata_decode_blob_size (sig, &sig);
7323 if (*sig == 0x6) { /* it's a field */
7325 MonoClassField *field;
7326 field = mono_field_from_token (image, token, &klass, context);
7328 *handle_class = mono_defaults.fieldhandle_class;
7332 meth = mono_get_method_full (image, token, NULL, context);
7334 *handle_class = mono_defaults.methodhandle_class;
7339 g_warning ("Unknown token 0x%08x in ldtoken", token);
7346 * This function might need to call runtime functions so it can't be part
7347 * of the metadata library.
7349 static MonoLookupDynamicToken lookup_dynamic = NULL;
7352 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
7354 lookup_dynamic = func;
7358 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
7360 MonoClass *handle_class;
7362 return lookup_dynamic (image, token, TRUE, &handle_class, context);
7366 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
7368 return lookup_dynamic (image, token, valid_token, handle_class, context);
7371 static MonoGetCachedClassInfo get_cached_class_info = NULL;
7374 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
7376 get_cached_class_info = func;
7380 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
7382 if (!get_cached_class_info)
7385 return get_cached_class_info (klass, res);
7389 mono_install_get_class_from_name (MonoGetClassFromName func)
7391 get_class_from_name = func;
7395 mono_class_get_image (MonoClass *klass)
7397 return klass->image;
7401 * mono_class_get_element_class:
7402 * @klass: the MonoClass to act on
7404 * Returns: the element class of an array or an enumeration.
7407 mono_class_get_element_class (MonoClass *klass)
7409 return klass->element_class;
7413 * mono_class_is_valuetype:
7414 * @klass: the MonoClass to act on
7416 * Returns: true if the MonoClass represents a ValueType.
7419 mono_class_is_valuetype (MonoClass *klass)
7421 return klass->valuetype;
7425 * mono_class_is_enum:
7426 * @klass: the MonoClass to act on
7428 * Returns: true if the MonoClass represents an enumeration.
7431 mono_class_is_enum (MonoClass *klass)
7433 return klass->enumtype;
7437 * mono_class_enum_basetype:
7438 * @klass: the MonoClass to act on
7440 * Returns: the underlying type representation for an enumeration.
7443 mono_class_enum_basetype (MonoClass *klass)
7445 if (klass->element_class == klass)
7446 /* SRE or broken types */
7449 return &klass->element_class->byval_arg;
7453 * mono_class_get_parent
7454 * @klass: the MonoClass to act on
7456 * Returns: the parent class for this class.
7459 mono_class_get_parent (MonoClass *klass)
7461 return klass->parent;
7465 * mono_class_get_nesting_type;
7466 * @klass: the MonoClass to act on
7468 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
7471 mono_class_get_nesting_type (MonoClass *klass)
7473 return klass->nested_in;
7477 * mono_class_get_rank:
7478 * @klass: the MonoClass to act on
7480 * Returns: the rank for the array (the number of dimensions).
7483 mono_class_get_rank (MonoClass *klass)
7489 * mono_class_get_flags:
7490 * @klass: the MonoClass to act on
7492 * The type flags from the TypeDef table from the metadata.
7493 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
7496 * Returns: the flags from the TypeDef table.
7499 mono_class_get_flags (MonoClass *klass)
7501 return klass->flags;
7505 * mono_class_get_name
7506 * @klass: the MonoClass to act on
7508 * Returns: the name of the class.
7511 mono_class_get_name (MonoClass *klass)
7517 * mono_class_get_namespace:
7518 * @klass: the MonoClass to act on
7520 * Returns: the namespace of the class.
7523 mono_class_get_namespace (MonoClass *klass)
7525 return klass->name_space;
7529 * mono_class_get_type:
7530 * @klass: the MonoClass to act on
7532 * This method returns the internal Type representation for the class.
7534 * Returns: the MonoType from the class.
7537 mono_class_get_type (MonoClass *klass)
7539 return &klass->byval_arg;
7543 * mono_class_get_type_token
7544 * @klass: the MonoClass to act on
7546 * This method returns type token for the class.
7548 * Returns: the type token for the class.
7551 mono_class_get_type_token (MonoClass *klass)
7553 return klass->type_token;
7557 * mono_class_get_byref_type:
7558 * @klass: the MonoClass to act on
7563 mono_class_get_byref_type (MonoClass *klass)
7565 return &klass->this_arg;
7569 * mono_class_num_fields:
7570 * @klass: the MonoClass to act on
7572 * Returns: the number of static and instance fields in the class.
7575 mono_class_num_fields (MonoClass *klass)
7577 return klass->field.count;
7581 * mono_class_num_methods:
7582 * @klass: the MonoClass to act on
7584 * Returns: the number of methods in the class.
7587 mono_class_num_methods (MonoClass *klass)
7589 return klass->method.count;
7593 * mono_class_num_properties
7594 * @klass: the MonoClass to act on
7596 * Returns: the number of properties in the class.
7599 mono_class_num_properties (MonoClass *klass)
7601 mono_class_setup_properties (klass);
7603 return klass->ext->property.count;
7607 * mono_class_num_events:
7608 * @klass: the MonoClass to act on
7610 * Returns: the number of events in the class.
7613 mono_class_num_events (MonoClass *klass)
7615 mono_class_setup_events (klass);
7617 return klass->ext->event.count;
7621 * mono_class_get_fields:
7622 * @klass: the MonoClass to act on
7624 * This routine is an iterator routine for retrieving the fields in a class.
7626 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7627 * iterate over all of the elements. When no more values are
7628 * available, the return value is NULL.
7630 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
7633 mono_class_get_fields (MonoClass* klass, gpointer *iter)
7635 MonoClassField* field;
7639 mono_class_setup_fields_locking (klass);
7640 if (klass->exception_type)
7642 /* start from the first */
7643 if (klass->field.count) {
7644 return *iter = &klass->fields [0];
7652 if (field < &klass->fields [klass->field.count]) {
7653 return *iter = field;
7659 * mono_class_get_methods
7660 * @klass: the MonoClass to act on
7662 * This routine is an iterator routine for retrieving the fields in a class.
7664 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7665 * iterate over all of the elements. When no more values are
7666 * available, the return value is NULL.
7668 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
7671 mono_class_get_methods (MonoClass* klass, gpointer *iter)
7673 MonoMethod** method;
7677 mono_class_init (klass);
7679 mono_class_setup_methods (klass);
7682 * We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
7683 * FIXME we should better report this error to the caller
7685 if (!klass->methods)
7687 /* start from the first */
7688 if (klass->method.count) {
7689 *iter = &klass->methods [0];
7690 return klass->methods [0];
7698 if (method < &klass->methods [klass->method.count]) {
7706 * mono_class_get_virtual_methods:
7708 * Iterate over the virtual methods of KLASS.
7710 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
7713 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
7715 MonoMethod** method;
7718 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
7720 mono_class_setup_methods (klass);
7722 * We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
7723 * FIXME we should better report this error to the caller
7725 if (!klass->methods)
7727 /* start from the first */
7728 method = &klass->methods [0];
7733 while (method < &klass->methods [klass->method.count]) {
7734 if (((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
7738 if (method < &klass->methods [klass->method.count]) {
7745 /* Search directly in metadata to avoid calling setup_methods () */
7746 MonoMethod *res = NULL;
7752 start_index = GPOINTER_TO_UINT (*iter);
7755 for (i = start_index; i < klass->method.count; ++i) {
7758 /* class->method.first points into the methodptr table */
7759 flags = mono_metadata_decode_table_row_col (klass->image, MONO_TABLE_METHOD, klass->method.first + i, MONO_METHOD_FLAGS);
7761 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
7765 if (i < klass->method.count) {
7766 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
7767 /* Add 1 here so the if (*iter) check fails */
7768 *iter = GUINT_TO_POINTER (i + 1);
7777 * mono_class_get_properties:
7778 * @klass: the MonoClass to act on
7780 * This routine is an iterator routine for retrieving the properties in a class.
7782 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7783 * iterate over all of the elements. When no more values are
7784 * available, the return value is NULL.
7786 * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
7789 mono_class_get_properties (MonoClass* klass, gpointer *iter)
7791 MonoProperty* property;
7795 mono_class_init (klass);
7797 mono_class_setup_properties (klass);
7798 /* start from the first */
7799 if (klass->ext->property.count) {
7800 return *iter = &klass->ext->properties [0];
7808 if (property < &klass->ext->properties [klass->ext->property.count]) {
7809 return *iter = property;
7815 * mono_class_get_events:
7816 * @klass: the MonoClass to act on
7818 * This routine is an iterator routine for retrieving the properties in a class.
7820 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7821 * iterate over all of the elements. When no more values are
7822 * available, the return value is NULL.
7824 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
7827 mono_class_get_events (MonoClass* klass, gpointer *iter)
7833 mono_class_init (klass);
7835 mono_class_setup_events (klass);
7836 /* start from the first */
7837 if (klass->ext->event.count) {
7838 return *iter = &klass->ext->events [0];
7846 if (event < &klass->ext->events [klass->ext->event.count]) {
7847 return *iter = event;
7853 * mono_class_get_interfaces
7854 * @klass: the MonoClass to act on
7856 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
7858 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7859 * iterate over all of the elements. When no more values are
7860 * available, the return value is NULL.
7862 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7865 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
7873 mono_class_init (klass);
7874 if (!klass->interfaces_inited) {
7875 mono_class_setup_interfaces (klass, &error);
7876 if (!mono_error_ok (&error)) {
7877 mono_error_cleanup (&error);
7881 /* start from the first */
7882 if (klass->interface_count) {
7883 *iter = &klass->interfaces [0];
7884 return klass->interfaces [0];
7892 if (iface < &klass->interfaces [klass->interface_count]) {
7900 * mono_class_get_nested_types
7901 * @klass: the MonoClass to act on
7903 * This routine is an iterator routine for retrieving the nested types of a class.
7904 * This works only if @klass is non-generic, or a generic type definition.
7906 * You must pass a gpointer that points to zero and is treated as an opaque handle to
7907 * iterate over all of the elements. When no more values are
7908 * available, the return value is NULL.
7910 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
7913 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
7921 mono_class_init (klass);
7922 if (!klass->nested_classes_inited) {
7923 if (!klass->type_token)
7924 klass->nested_classes_inited = TRUE;
7925 mono_loader_lock ();
7926 if (!klass->nested_classes_inited) {
7927 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
7930 guint32 cols [MONO_NESTED_CLASS_SIZE];
7931 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
7932 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
7935 mono_class_alloc_ext (klass);
7936 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
7938 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
7941 mono_memory_barrier ();
7942 klass->nested_classes_inited = TRUE;
7943 mono_loader_unlock ();
7947 /* start from the first */
7948 if (klass->ext && klass->ext->nested_classes) {
7949 *iter = klass->ext->nested_classes;
7950 return klass->ext->nested_classes->data;
7952 /* no nested types */
7966 * mono_field_get_name:
7967 * @field: the MonoClassField to act on
7969 * Returns: the name of the field.
7972 mono_field_get_name (MonoClassField *field)
7978 * mono_field_get_type:
7979 * @field: the MonoClassField to act on
7981 * Returns: MonoType of the field.
7984 mono_field_get_type (MonoClassField *field)
7990 * mono_field_get_parent:
7991 * @field: the MonoClassField to act on
7993 * Returns: MonoClass where the field was defined.
7996 mono_field_get_parent (MonoClassField *field)
7998 return field->parent;
8002 * mono_field_get_flags;
8003 * @field: the MonoClassField to act on
8005 * The metadata flags for a field are encoded using the
8006 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
8008 * Returns: the flags for the field.
8011 mono_field_get_flags (MonoClassField *field)
8013 return field->type->attrs;
8017 * mono_field_get_offset;
8018 * @field: the MonoClassField to act on
8020 * Returns: the field offset.
8023 mono_field_get_offset (MonoClassField *field)
8025 return field->offset;
8029 mono_field_get_rva (MonoClassField *field)
8033 MonoClass *klass = field->parent;
8035 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
8037 if (!klass->ext || !klass->ext->field_def_values) {
8038 mono_loader_lock ();
8039 mono_class_alloc_ext (klass);
8040 if (!klass->ext->field_def_values)
8041 klass->ext->field_def_values = mono_image_alloc0 (klass->image, sizeof (MonoFieldDefaultValue) * klass->field.count);
8042 mono_loader_unlock ();
8045 field_index = mono_field_get_index (field);
8047 if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
8048 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
8050 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
8051 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
8054 return klass->ext->field_def_values [field_index].data;
8058 * mono_field_get_data;
8059 * @field: the MonoClassField to act on
8061 * Returns: pointer to the metadata constant value or to the field
8062 * data if it has an RVA flag.
8065 mono_field_get_data (MonoClassField *field)
8067 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
8068 MonoTypeEnum def_type;
8070 return mono_class_get_field_default_value (field, &def_type);
8071 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
8072 return mono_field_get_rva (field);
8079 * mono_property_get_name:
8080 * @prop: the MonoProperty to act on
8082 * Returns: the name of the property
8085 mono_property_get_name (MonoProperty *prop)
8091 * mono_property_get_set_method
8092 * @prop: the MonoProperty to act on.
8094 * Returns: the setter method of the property (A MonoMethod)
8097 mono_property_get_set_method (MonoProperty *prop)
8103 * mono_property_get_get_method
8104 * @prop: the MonoProperty to act on.
8106 * Returns: the setter method of the property (A MonoMethod)
8109 mono_property_get_get_method (MonoProperty *prop)
8115 * mono_property_get_parent:
8116 * @prop: the MonoProperty to act on.
8118 * Returns: the MonoClass where the property was defined.
8121 mono_property_get_parent (MonoProperty *prop)
8123 return prop->parent;
8127 * mono_property_get_flags:
8128 * @prop: the MonoProperty to act on.
8130 * The metadata flags for a property are encoded using the
8131 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
8133 * Returns: the flags for the property.
8136 mono_property_get_flags (MonoProperty *prop)
8142 * mono_event_get_name:
8143 * @event: the MonoEvent to act on
8145 * Returns: the name of the event.
8148 mono_event_get_name (MonoEvent *event)
8154 * mono_event_get_add_method:
8155 * @event: The MonoEvent to act on.
8157 * Returns: the @add' method for the event (a MonoMethod).
8160 mono_event_get_add_method (MonoEvent *event)
8166 * mono_event_get_remove_method:
8167 * @event: The MonoEvent to act on.
8169 * Returns: the @remove method for the event (a MonoMethod).
8172 mono_event_get_remove_method (MonoEvent *event)
8174 return event->remove;
8178 * mono_event_get_raise_method:
8179 * @event: The MonoEvent to act on.
8181 * Returns: the @raise method for the event (a MonoMethod).
8184 mono_event_get_raise_method (MonoEvent *event)
8186 return event->raise;
8190 * mono_event_get_parent:
8191 * @event: the MonoEvent to act on.
8193 * Returns: the MonoClass where the event is defined.
8196 mono_event_get_parent (MonoEvent *event)
8198 return event->parent;
8202 * mono_event_get_flags
8203 * @event: the MonoEvent to act on.
8205 * The metadata flags for an event are encoded using the
8206 * EVENT_* constants. See the tabledefs.h file for details.
8208 * Returns: the flags for the event.
8211 mono_event_get_flags (MonoEvent *event)
8213 return event->attrs;
8217 * mono_class_get_method_from_name:
8218 * @klass: where to look for the method
8219 * @name_space: name of the method
8220 * @param_count: number of parameters. -1 for any number.
8222 * Obtains a MonoMethod with a given name and number of parameters.
8223 * It only works if there are no multiple signatures for any given method name.
8226 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
8228 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
8232 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
8234 MonoMethod *res = NULL;
8237 /* Search directly in the metadata to avoid calling setup_methods () */
8238 for (i = 0; i < klass->method.count; ++i) {
8239 guint32 cols [MONO_METHOD_SIZE];
8242 /* class->method.first points into the methodptr table */
8243 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
8245 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
8246 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
8247 if ((param_count == -1) || mono_method_signature (method)->param_count == param_count) {
8258 * mono_class_get_method_from_name_flags:
8259 * @klass: where to look for the method
8260 * @name_space: name of the method
8261 * @param_count: number of parameters. -1 for any number.
8262 * @flags: flags which must be set in the method
8264 * Obtains a MonoMethod with a given name and number of parameters.
8265 * It only works if there are no multiple signatures for any given method name.
8268 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
8270 MonoMethod *res = NULL;
8273 mono_class_init (klass);
8275 if (klass->generic_class && !klass->methods) {
8276 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
8278 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
8282 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
8283 mono_class_setup_methods (klass);
8285 We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8286 See mono/tests/array_load_exception.il
8287 FIXME we should better report this error to the caller
8289 if (!klass->methods)
8291 for (i = 0; i < klass->method.count; ++i) {
8292 MonoMethod *method = klass->methods [i];
8294 if (method->name[0] == name [0] &&
8295 !strcmp (name, method->name) &&
8296 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
8297 ((method->flags & flags) == flags)) {
8304 res = find_method_in_metadata (klass, name, param_count, flags);
8311 * mono_class_set_failure:
8312 * @klass: class in which the failure was detected
8313 * @ex_type: the kind of exception/error to be thrown (later)
8314 * @ex_data: exception data (specific to each type of exception/error)
8316 * Keep a detected failure informations in the class for later processing.
8317 * Note that only the first failure is kept.
8319 * LOCKING: Acquires the loader lock.
8322 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
8324 if (klass->exception_type)
8327 mono_loader_lock ();
8328 klass->exception_type = ex_type;
8330 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
8331 mono_loader_unlock ();
8337 * mono_class_get_exception_data:
8339 * Return the exception_data property of KLASS.
8341 * LOCKING: Acquires the loader lock.
8344 mono_class_get_exception_data (MonoClass *klass)
8346 return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
8350 * mono_classes_init:
8352 * Initialize the resources used by this module.
8355 mono_classes_init (void)
8357 mono_counters_register ("Inflated methods size",
8358 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
8359 mono_counters_register ("Inflated classes",
8360 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
8361 mono_counters_register ("Inflated classes size",
8362 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
8363 mono_counters_register ("MonoClass size",
8364 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
8365 mono_counters_register ("MonoClassExt size",
8366 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
8370 * mono_classes_cleanup:
8372 * Free the resources used by this module.
8375 mono_classes_cleanup (void)
8377 if (global_interface_bitset)
8378 mono_bitset_free (global_interface_bitset);
8382 * mono_class_get_exception_for_failure:
8383 * @klass: class in which the failure was detected
8385 * Return a constructed MonoException than the caller can then throw
8386 * using mono_raise_exception - or NULL if no failure is present (or
8387 * doesn't result in an exception).
8390 mono_class_get_exception_for_failure (MonoClass *klass)
8392 gpointer exception_data = mono_class_get_exception_data (klass);
8394 switch (klass->exception_type) {
8395 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
8396 MonoDomain *domain = mono_domain_get ();
8397 MonoSecurityManager* secman = mono_security_manager_get_methods ();
8398 MonoMethod *method = exception_data;
8399 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
8400 MonoObject *exc = NULL;
8404 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
8405 args [2] = mono_type_get_object (domain, &klass->byval_arg);
8406 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
8408 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
8409 return (MonoException*) exc;
8411 case MONO_EXCEPTION_TYPE_LOAD: {
8414 char *str = mono_type_get_full_name (klass);
8415 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
8416 name = mono_string_new (mono_domain_get (), str);
8418 ex = mono_get_exception_type_load (name, astr);
8422 case MONO_EXCEPTION_MISSING_METHOD: {
8423 char *class_name = exception_data;
8424 char *assembly_name = class_name + strlen (class_name) + 1;
8426 return mono_get_exception_missing_method (class_name, assembly_name);
8428 case MONO_EXCEPTION_MISSING_FIELD: {
8429 char *class_name = exception_data;
8430 char *member_name = class_name + strlen (class_name) + 1;
8432 return mono_get_exception_missing_field (class_name, member_name);
8434 case MONO_EXCEPTION_FILE_NOT_FOUND: {
8435 char *msg_format = exception_data;
8436 char *assembly_name = msg_format + strlen (msg_format) + 1;
8437 char *msg = g_strdup_printf (msg_format, assembly_name);
8440 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
8446 case MONO_EXCEPTION_BAD_IMAGE: {
8447 return mono_get_exception_bad_image_format (exception_data);
8450 MonoLoaderError *error;
8453 error = mono_loader_get_last_error ();
8455 ex = mono_loader_error_prepare_exception (error);
8459 /* TODO - handle other class related failures */
8466 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
8468 outer_klass = mono_class_get_generic_type_definition (outer_klass);
8469 inner_klass = mono_class_get_generic_type_definition (inner_klass);
8471 if (outer_klass == inner_klass)
8473 inner_klass = inner_klass->nested_in;
8474 } while (inner_klass);
8479 mono_class_get_generic_type_definition (MonoClass *klass)
8481 return klass->generic_class ? klass->generic_class->container_class : klass;
8485 * Check if @klass is a subtype of @parent ignoring generic instantiations.
8487 * Generic instantiations are ignored for all super types of @klass.
8489 * Visibility checks ignoring generic instantiations.
8492 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
8495 klass = mono_class_get_generic_type_definition (klass);
8496 parent = mono_class_get_generic_type_definition (parent);
8498 for (i = 0; i < klass->idepth; ++i) {
8499 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
8505 * Subtype can only access parent members with family protection if the site object
8506 * is subclass of Subtype. For example:
8507 * class A { protected int x; }
8509 * void valid_access () {
8513 * void invalid_access () {
8520 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
8522 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
8525 if (context_klass == NULL)
8527 /*if access_klass is not member_klass context_klass must be type compat*/
8528 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
8534 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
8537 if (accessing == accessed)
8539 if (!accessed || !accessing)
8542 /* extra safety under CoreCLR - the runtime does not verify the strongname signatures
8543 * anywhere so untrusted friends are not safe to access platform's code internals */
8544 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8545 if (!mono_security_core_clr_can_access_internals (accessing->image, accessed->image))
8549 mono_assembly_load_friends (accessed);
8550 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
8551 MonoAssemblyName *friend = tmp->data;
8552 /* Be conservative with checks */
8555 if (strcmp (accessing->aname.name, friend->name))
8557 if (friend->public_key_token [0]) {
8558 if (!accessing->aname.public_key_token [0])
8560 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
8569 * If klass is a generic type or if it is derived from a generic type, return the
8570 * MonoClass of the generic definition
8571 * Returns NULL if not found
8574 get_generic_definition_class (MonoClass *klass)
8577 if (klass->generic_class && klass->generic_class->container_class)
8578 return klass->generic_class->container_class;
8579 klass = klass->parent;
8585 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
8588 for (i = 0; i < ginst->type_argc; ++i) {
8589 MonoType *type = ginst->type_argv[i];
8590 switch (type->type) {
8591 case MONO_TYPE_SZARRAY:
8592 if (!can_access_type (access_klass, type->data.klass))
8595 case MONO_TYPE_ARRAY:
8596 if (!can_access_type (access_klass, type->data.array->eklass))
8600 if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
8603 case MONO_TYPE_CLASS:
8604 case MONO_TYPE_VALUETYPE:
8605 case MONO_TYPE_GENERICINST:
8606 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
8614 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
8618 if (access_klass->element_class && !access_klass->enumtype)
8619 access_klass = access_klass->element_class;
8621 if (member_klass->element_class && !member_klass->enumtype)
8622 member_klass = member_klass->element_class;
8624 access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
8626 if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
8629 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
8632 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
8635 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
8638 /*Non nested type with nested visibility. We just fail it.*/
8639 if (access_level >= TYPE_ATTRIBUTE_NESTED_PRIVATE && access_level <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM && member_klass->nested_in == NULL)
8642 switch (access_level) {
8643 case TYPE_ATTRIBUTE_NOT_PUBLIC:
8644 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8646 case TYPE_ATTRIBUTE_PUBLIC:
8649 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
8652 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
8653 return is_nesting_type (member_klass, access_klass);
8655 case TYPE_ATTRIBUTE_NESTED_FAMILY:
8656 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
8658 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
8659 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8661 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
8662 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
8663 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
8665 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
8666 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
8667 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
8672 /* FIXME: check visibility of type, too */
8674 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
8676 MonoClass *member_generic_def;
8677 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
8678 access_klass->generic_container) &&
8679 (member_generic_def = get_generic_definition_class (member_klass))) {
8680 MonoClass *access_container;
8682 if (access_klass->generic_container)
8683 access_container = access_klass;
8685 access_container = access_klass->generic_class->container_class;
8687 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
8691 /* Partition I 8.5.3.2 */
8692 /* the access level values are the same for fields and methods */
8693 switch (access_level) {
8694 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
8695 /* same compilation unit */
8696 return access_klass->image == member_klass->image;
8697 case FIELD_ATTRIBUTE_PRIVATE:
8698 return access_klass == member_klass;
8699 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
8700 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
8701 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
8704 case FIELD_ATTRIBUTE_ASSEMBLY:
8705 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8706 case FIELD_ATTRIBUTE_FAMILY:
8707 if (is_valid_family_access (access_klass, member_klass, context_klass))
8710 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
8711 if (is_valid_family_access (access_klass, member_klass, context_klass))
8713 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
8714 case FIELD_ATTRIBUTE_PUBLIC:
8721 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
8723 /* FIXME: check all overlapping fields */
8724 int can = can_access_member (method->klass, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8726 MonoClass *nested = method->klass->nested_in;
8728 can = can_access_member (nested, field->parent, NULL, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8731 nested = nested->nested_in;
8738 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
8740 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8742 MonoClass *nested = method->klass->nested_in;
8744 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8747 nested = nested->nested_in;
8752 * with generics calls to explicit interface implementations can be expressed
8753 * directly: the method is private, but we must allow it. This may be opening
8754 * a hole or the generics code should handle this differently.
8755 * Maybe just ensure the interface type is public.
8757 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
8763 * mono_method_can_access_method_full:
8764 * @method: The caller method
8765 * @called: The called method
8766 * @context_klass: The static type on stack of the owner @called object used
8768 * This function must be used with instance calls, as they have more strict family accessibility.
8769 * It can be used with static methods, but context_klass should be NULL.
8771 * Returns: TRUE if caller have proper visibility and acessibility to @called
8774 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
8776 MonoClass *access_class = method->klass;
8777 MonoClass *member_class = called->klass;
8778 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8780 MonoClass *nested = access_class->nested_in;
8782 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
8785 nested = nested->nested_in;
8792 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8795 if (called->is_inflated) {
8796 MonoMethodInflated * infl = (MonoMethodInflated*)called;
8797 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
8806 * mono_method_can_access_field_full:
8807 * @method: The caller method
8808 * @field: The accessed field
8809 * @context_klass: The static type on stack of the owner @field object used
8811 * This function must be used with instance fields, as they have more strict family accessibility.
8812 * It can be used with static fields, but context_klass should be NULL.
8814 * Returns: TRUE if caller have proper visibility and acessibility to @field
8817 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
8819 MonoClass *access_class = method->klass;
8820 MonoClass *member_class = field->parent;
8821 /* FIXME: check all overlapping fields */
8822 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8824 MonoClass *nested = access_class->nested_in;
8826 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
8829 nested = nested->nested_in;
8836 if (!can_access_type (access_class, member_class) && (!access_class->nested_in || !can_access_type (access_class->nested_in, member_class)))
8842 * mono_type_is_valid_enum_basetype:
8843 * @type: The MonoType to check
8845 * Returns: TRUE if the type can be used as the basetype of an enum
8847 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
8848 switch (type->type) {
8851 case MONO_TYPE_BOOLEAN:
8854 case MONO_TYPE_CHAR:
8867 * mono_class_is_valid_enum:
8868 * @klass: An enum class to be validated
8870 * This method verify the required properties an enum should have.
8872 * Returns: TRUE if the informed enum class is valid
8874 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
8875 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
8876 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
8878 gboolean mono_class_is_valid_enum (MonoClass *klass) {
8879 MonoClassField * field;
8880 gpointer iter = NULL;
8881 gboolean found_base_field = FALSE;
8883 g_assert (klass->enumtype);
8884 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
8885 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
8889 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
8892 while ((field = mono_class_get_fields (klass, &iter))) {
8893 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
8894 if (found_base_field)
8896 found_base_field = TRUE;
8897 if (!mono_type_is_valid_enum_basetype (field->type))
8902 if (!found_base_field)
8905 if (klass->method.count > 0)
8912 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
8914 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
8918 * mono_class_setup_interface_id:
8920 * Initializes MonoClass::interface_id if required.
8922 * LOCKING: Acquires the loader lock.
8925 mono_class_setup_interface_id (MonoClass *class)
8927 mono_loader_lock ();
8928 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
8929 class->interface_id = mono_get_unique_iid (class);
8930 mono_loader_unlock ();
8934 * mono_class_alloc_ext:
8936 * Allocate klass->ext if not already done.
8937 * LOCKING: Assumes the loader lock is held.
8940 mono_class_alloc_ext (MonoClass *klass)
8943 if (klass->generic_class) {
8944 klass->ext = g_new0 (MonoClassExt, 1);
8946 klass->ext = mono_image_alloc0 (klass->image, sizeof (MonoClassExt));
8948 class_ext_size += sizeof (MonoClassExt);
8953 * mono_class_setup_interfaces:
8955 * Initialize class->interfaces/interfaces_count.
8956 * LOCKING: Acquires the loader lock.
8957 * This function can fail the type.
8960 mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
8964 mono_error_init (error);
8966 if (klass->interfaces_inited)
8969 mono_loader_lock ();
8971 if (klass->interfaces_inited) {
8972 mono_loader_unlock ();
8976 if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
8979 /* generic IList, ICollection, IEnumerable */
8980 klass->interface_count = 1;
8981 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
8983 args [0] = &klass->element_class->byval_arg;
8984 klass->interfaces [0] = mono_class_bind_generic_parameters (
8985 mono_defaults.generic_ilist_class, 1, args, FALSE);
8986 } else if (klass->generic_class) {
8987 MonoClass *gklass = klass->generic_class->container_class;
8989 klass->interface_count = gklass->interface_count;
8990 klass->interfaces = g_new0 (MonoClass *, klass->interface_count);
8991 for (i = 0; i < klass->interface_count; i++) {
8992 klass->interfaces [i] = mono_class_inflate_generic_class_checked (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class), error);
8993 if (!mono_error_ok (error)) {
8994 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not setup the interfaces"));
8995 g_free (klass->interfaces);
8996 klass->interfaces = NULL;
9002 mono_memory_barrier ();
9004 klass->interfaces_inited = TRUE;
9006 mono_loader_unlock ();