Fix variance test involving nullable types.
[mono-project.git] / mono / metadata / class.c
blobe18ce76dcc83523d5318fa4a2559fe965838c42a
1 /*
2 * class.c: Class management for the Mono runtime
4 * Author:
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)
9 */
10 #include <config.h>
11 #ifdef HAVE_ALLOCA_H
12 #include <alloca.h>
13 #endif
14 #include <glib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #if !HOST_WIN32
19 #include <mono/io-layer/atomic.h>
20 #endif
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>
44 #include <mono/utils/mono-logger-internal.h>
45 MonoStats mono_stats;
47 gboolean mono_print_vtable = FALSE;
49 /* Statistics */
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);
66 static void mono_field_resolve_type (MonoClassField *field, MonoError *error);
67 static guint32 mono_field_resolve_flags (MonoClassField *field);
68 static void mono_class_setup_vtable_full (MonoClass *class, GList *in_setup);
71 void (*mono_debugger_class_init_func) (MonoClass *klass) = NULL;
72 void (*mono_debugger_class_loaded_methods_func) (MonoClass *klass) = NULL;
75 * mono_class_from_typeref:
76 * @image: a MonoImage
77 * @type_token: a TypeRef token
79 * Creates the MonoClass* structure representing the type defined by
80 * the typeref token valid inside @image.
81 * Returns: the MonoClass* representing the typeref token, NULL ifcould
82 * not be loaded.
84 MonoClass *
85 mono_class_from_typeref (MonoImage *image, guint32 type_token)
87 MonoError error;
88 guint32 cols [MONO_TYPEREF_SIZE];
89 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
90 guint32 idx;
91 const char *name, *nspace;
92 MonoClass *res;
93 MonoImage *module;
95 if (!mono_verifier_verify_typeref_row (image, (type_token & 0xffffff) - 1, &error)) {
96 mono_trace_warning (MONO_TRACE_TYPE, "Failed to resolve typeref from %s due to '%s'", image->name, mono_error_get_message (&error));
97 return NULL;
100 mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
102 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
103 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
105 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
106 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
107 case MONO_RESOLTION_SCOPE_MODULE:
108 if (!idx)
109 g_error ("null ResolutionScope not yet handled");
110 /* a typedef in disguise */
111 return mono_class_from_name (image, nspace, name);
112 case MONO_RESOLTION_SCOPE_MODULEREF:
113 module = mono_image_load_module (image, idx);
114 if (module)
115 return mono_class_from_name (module, nspace, name);
116 else {
117 char *msg = g_strdup_printf ("%s%s%s", nspace, nspace [0] ? "." : "", name);
118 char *human_name;
120 human_name = mono_stringify_assembly_name (&image->assembly->aname);
121 mono_loader_set_error_type_load (msg, human_name);
122 g_free (msg);
123 g_free (human_name);
125 return NULL;
127 case MONO_RESOLTION_SCOPE_TYPEREF: {
128 MonoClass *enclosing;
129 GList *tmp;
131 if (idx == mono_metadata_token_index (type_token)) {
132 mono_loader_set_error_bad_image (g_strdup_printf ("Image %s with self-referencing typeref token %08x.", image->name, type_token));
133 return NULL;
136 enclosing = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | idx);
137 if (!enclosing)
138 return NULL;
140 if (enclosing->nested_classes_inited && enclosing->ext) {
141 /* Micro-optimization: don't scan the metadata tables if enclosing is already inited */
142 for (tmp = enclosing->ext->nested_classes; tmp; tmp = tmp->next) {
143 res = tmp->data;
144 if (strcmp (res->name, name) == 0)
145 return res;
147 } else {
148 /* Don't call mono_class_init as we might've been called by it recursively */
149 int i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, 1);
150 while (i) {
151 guint32 class_nested = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, MONO_NESTED_CLASS_NESTED);
152 guint32 string_offset = mono_metadata_decode_row_col (&enclosing->image->tables [MONO_TABLE_TYPEDEF], class_nested - 1, MONO_TYPEDEF_NAME);
153 const char *nname = mono_metadata_string_heap (enclosing->image, string_offset);
155 if (strcmp (nname, name) == 0)
156 return mono_class_create_from_typedef (enclosing->image, MONO_TOKEN_TYPE_DEF | class_nested);
158 i = mono_metadata_nesting_typedef (enclosing->image, enclosing->type_token, i + 1);
161 g_warning ("TypeRef ResolutionScope not yet handled (%d) for %s.%s in image %s", idx, nspace, name, image->name);
162 return NULL;
164 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
165 break;
168 if (idx > image->tables [MONO_TABLE_ASSEMBLYREF].rows) {
169 mono_loader_set_error_bad_image (g_strdup_printf ("Image %s with invalid assemblyref token %08x.", image->name, idx));
170 return NULL;
173 if (!image->references || !image->references [idx - 1])
174 mono_assembly_load_reference (image, idx - 1);
175 g_assert (image->references [idx - 1]);
177 /* If the assembly did not load, register this as a type load exception */
178 if (image->references [idx - 1] == REFERENCE_MISSING){
179 MonoAssemblyName aname;
180 char *human_name;
182 mono_assembly_get_assemblyref (image, idx - 1, &aname);
183 human_name = mono_stringify_assembly_name (&aname);
184 mono_loader_set_error_assembly_load (human_name, image->assembly ? image->assembly->ref_only : FALSE);
185 g_free (human_name);
187 return NULL;
190 return mono_class_from_name (image->references [idx - 1]->image, nspace, name);
194 static void *
195 mono_image_memdup (MonoImage *image, void *data, guint size)
197 void *res = mono_image_alloc (image, size);
198 memcpy (res, data, size);
199 return res;
202 /* Copy everything mono_metadata_free_array free. */
203 MonoArrayType *
204 mono_dup_array_type (MonoImage *image, MonoArrayType *a)
206 if (image) {
207 a = mono_image_memdup (image, a, sizeof (MonoArrayType));
208 if (a->sizes)
209 a->sizes = mono_image_memdup (image, a->sizes, a->numsizes * sizeof (int));
210 if (a->lobounds)
211 a->lobounds = mono_image_memdup (image, a->lobounds, a->numlobounds * sizeof (int));
212 } else {
213 a = g_memdup (a, sizeof (MonoArrayType));
214 if (a->sizes)
215 a->sizes = g_memdup (a->sizes, a->numsizes * sizeof (int));
216 if (a->lobounds)
217 a->lobounds = g_memdup (a->lobounds, a->numlobounds * sizeof (int));
219 return a;
222 /* Copy everything mono_metadata_free_method_signature free. */
223 MonoMethodSignature*
224 mono_metadata_signature_deep_dup (MonoImage *image, MonoMethodSignature *sig)
226 int i;
228 sig = mono_metadata_signature_dup_full (image, sig);
230 sig->ret = mono_metadata_type_dup (image, sig->ret);
231 for (i = 0; i < sig->param_count; ++i)
232 sig->params [i] = mono_metadata_type_dup (image, sig->params [i]);
234 return sig;
237 static void
238 _mono_type_get_assembly_name (MonoClass *klass, GString *str)
240 MonoAssembly *ta = klass->image->assembly;
241 char *name;
243 name = mono_stringify_assembly_name (&ta->aname);
244 g_string_append_printf (str, ", %s", name);
245 g_free (name);
248 static inline void
249 mono_type_name_check_byref (MonoType *type, GString *str)
251 if (type->byref)
252 g_string_append_c (str, '&');
255 static void
256 mono_type_get_name_recurse (MonoType *type, GString *str, gboolean is_recursed,
257 MonoTypeNameFormat format)
259 MonoClass *klass;
261 switch (type->type) {
262 case MONO_TYPE_ARRAY: {
263 int i, rank = type->data.array->rank;
264 MonoTypeNameFormat nested_format;
266 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
267 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
269 mono_type_get_name_recurse (
270 &type->data.array->eklass->byval_arg, str, FALSE, nested_format);
271 g_string_append_c (str, '[');
272 if (rank == 1)
273 g_string_append_c (str, '*');
274 for (i = 1; i < rank; i++)
275 g_string_append_c (str, ',');
276 g_string_append_c (str, ']');
278 mono_type_name_check_byref (type, str);
280 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
281 _mono_type_get_assembly_name (type->data.array->eklass, str);
282 break;
284 case MONO_TYPE_SZARRAY: {
285 MonoTypeNameFormat nested_format;
287 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
288 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
290 mono_type_get_name_recurse (
291 &type->data.klass->byval_arg, str, FALSE, nested_format);
292 g_string_append (str, "[]");
294 mono_type_name_check_byref (type, str);
296 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
297 _mono_type_get_assembly_name (type->data.klass, str);
298 break;
300 case MONO_TYPE_PTR: {
301 MonoTypeNameFormat nested_format;
303 nested_format = format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED ?
304 MONO_TYPE_NAME_FORMAT_FULL_NAME : format;
306 mono_type_get_name_recurse (
307 type->data.type, str, FALSE, nested_format);
308 g_string_append_c (str, '*');
310 mono_type_name_check_byref (type, str);
312 if (format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)
313 _mono_type_get_assembly_name (mono_class_from_mono_type (type->data.type), str);
314 break;
316 case MONO_TYPE_VAR:
317 case MONO_TYPE_MVAR:
318 if (!mono_generic_param_info (type->data.generic_param))
319 g_string_append_printf (str, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", type->data.generic_param->num);
320 else
321 g_string_append (str, mono_generic_param_info (type->data.generic_param)->name);
323 mono_type_name_check_byref (type, str);
325 break;
326 default:
327 klass = mono_class_from_mono_type (type);
328 if (klass->nested_in) {
329 mono_type_get_name_recurse (
330 &klass->nested_in->byval_arg, str, TRUE, format);
331 if (format == MONO_TYPE_NAME_FORMAT_IL)
332 g_string_append_c (str, '.');
333 else
334 g_string_append_c (str, '+');
335 } else if (*klass->name_space) {
336 g_string_append (str, klass->name_space);
337 g_string_append_c (str, '.');
339 if (format == MONO_TYPE_NAME_FORMAT_IL) {
340 char *s = strchr (klass->name, '`');
341 int len = s ? s - klass->name : strlen (klass->name);
343 g_string_append_len (str, klass->name, len);
344 } else
345 g_string_append (str, klass->name);
346 if (is_recursed)
347 break;
348 if (klass->generic_class) {
349 MonoGenericClass *gclass = klass->generic_class;
350 MonoGenericInst *inst = gclass->context.class_inst;
351 MonoTypeNameFormat nested_format;
352 int i;
354 nested_format = format == MONO_TYPE_NAME_FORMAT_FULL_NAME ?
355 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED : format;
357 if (format == MONO_TYPE_NAME_FORMAT_IL)
358 g_string_append_c (str, '<');
359 else
360 g_string_append_c (str, '[');
361 for (i = 0; i < inst->type_argc; i++) {
362 MonoType *t = inst->type_argv [i];
364 if (i)
365 g_string_append_c (str, ',');
366 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
367 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
368 g_string_append_c (str, '[');
369 mono_type_get_name_recurse (inst->type_argv [i], str, FALSE, nested_format);
370 if ((nested_format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
371 (t->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
372 g_string_append_c (str, ']');
374 if (format == MONO_TYPE_NAME_FORMAT_IL)
375 g_string_append_c (str, '>');
376 else
377 g_string_append_c (str, ']');
378 } else if (klass->generic_container &&
379 (format != MONO_TYPE_NAME_FORMAT_FULL_NAME) &&
380 (format != MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED)) {
381 int i;
383 if (format == MONO_TYPE_NAME_FORMAT_IL)
384 g_string_append_c (str, '<');
385 else
386 g_string_append_c (str, '[');
387 for (i = 0; i < klass->generic_container->type_argc; i++) {
388 if (i)
389 g_string_append_c (str, ',');
390 g_string_append (str, mono_generic_container_get_param_info (klass->generic_container, i)->name);
392 if (format == MONO_TYPE_NAME_FORMAT_IL)
393 g_string_append_c (str, '>');
394 else
395 g_string_append_c (str, ']');
398 mono_type_name_check_byref (type, str);
400 if ((format == MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED) &&
401 (type->type != MONO_TYPE_VAR) && (type->type != MONO_TYPE_MVAR))
402 _mono_type_get_assembly_name (klass, str);
403 break;
408 * mono_type_get_name_full:
409 * @type: a type
410 * @format: the format for the return string.
413 * Returns: the string representation in a number of formats:
415 * if format is MONO_TYPE_NAME_FORMAT_REFLECTION, the return string is
416 * returned in the formatrequired by System.Reflection, this is the
417 * inverse of mono_reflection_parse_type ().
419 * if format is MONO_TYPE_NAME_FORMAT_IL, it returns a syntax that can
420 * be used by the IL assembler.
422 * if format is MONO_TYPE_NAME_FORMAT_FULL_NAME
424 * if format is MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED
426 char*
427 mono_type_get_name_full (MonoType *type, MonoTypeNameFormat format)
429 GString* result;
431 result = g_string_new ("");
433 mono_type_get_name_recurse (type, result, FALSE, format);
435 return g_string_free (result, FALSE);
439 * mono_type_get_full_name:
440 * @class: a class
442 * Returns: the string representation for type as required by System.Reflection.
443 * The inverse of mono_reflection_parse_type ().
445 char *
446 mono_type_get_full_name (MonoClass *class)
448 return mono_type_get_name_full (mono_class_get_type (class), MONO_TYPE_NAME_FORMAT_REFLECTION);
452 * mono_type_get_name:
453 * @type: a type
455 * Returns: the string representation for type as it would be represented in IL code.
457 char*
458 mono_type_get_name (MonoType *type)
460 return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_IL);
464 * mono_type_get_underlying_type:
465 * @type: a type
467 * Returns: the MonoType for the underlying integer type if @type
468 * is an enum and byref is false, otherwise the type itself.
470 MonoType*
471 mono_type_get_underlying_type (MonoType *type)
473 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype && !type->byref)
474 return mono_class_enum_basetype (type->data.klass);
475 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype && !type->byref)
476 return mono_class_enum_basetype (type->data.generic_class->container_class);
477 return type;
481 * mono_class_is_open_constructed_type:
482 * @type: a type
484 * Returns TRUE if type represents a generics open constructed type.
485 * IOW, not all type parameters required for the instantiation have
486 * been provided or it's a generic type definition.
488 * An open constructed type means it's a non realizable type. Not to
489 * be mixed up with an abstract type - we can't cast or dispatch to
490 * an open type, for example.
492 gboolean
493 mono_class_is_open_constructed_type (MonoType *t)
495 switch (t->type) {
496 case MONO_TYPE_VAR:
497 case MONO_TYPE_MVAR:
498 return TRUE;
499 case MONO_TYPE_SZARRAY:
500 return mono_class_is_open_constructed_type (&t->data.klass->byval_arg);
501 case MONO_TYPE_ARRAY:
502 return mono_class_is_open_constructed_type (&t->data.array->eklass->byval_arg);
503 case MONO_TYPE_PTR:
504 return mono_class_is_open_constructed_type (t->data.type);
505 case MONO_TYPE_GENERICINST:
506 return t->data.generic_class->context.class_inst->is_open;
507 case MONO_TYPE_CLASS:
508 case MONO_TYPE_VALUETYPE:
509 return t->data.klass->generic_container != NULL;
510 default:
511 return FALSE;
515 static MonoType*
516 inflate_generic_type (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
518 mono_error_init (error);
520 switch (type->type) {
521 case MONO_TYPE_MVAR: {
522 MonoType *nt;
523 int num = mono_type_get_generic_param_num (type);
524 MonoGenericInst *inst = context->method_inst;
525 if (!inst || !inst->type_argv)
526 return NULL;
527 if (num >= inst->type_argc) {
528 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
529 mono_error_set_bad_image (error, image, "MVAR %d (%s) cannot be expanded in this context with %d instantiations",
530 num, info ? info->name : "", inst->type_argc);
531 return NULL;
535 * Note that the VAR/MVAR cases are different from the rest. The other cases duplicate @type,
536 * while the VAR/MVAR duplicates a type from the context. So, we need to ensure that the
537 * ->byref and ->attrs from @type are propagated to the returned type.
539 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
540 nt->byref = type->byref;
541 nt->attrs = type->attrs;
542 return nt;
544 case MONO_TYPE_VAR: {
545 MonoType *nt;
546 int num = mono_type_get_generic_param_num (type);
547 MonoGenericInst *inst = context->class_inst;
548 if (!inst)
549 return NULL;
550 if (num >= inst->type_argc) {
551 MonoGenericParamInfo *info = mono_generic_param_info (type->data.generic_param);
552 mono_error_set_bad_image (error, image, "VAR %d (%s) cannot be expanded in this context with %d instantiations",
553 num, info ? info->name : "", inst->type_argc);
554 return NULL;
556 nt = mono_metadata_type_dup (image, inst->type_argv [num]);
557 nt->byref = type->byref;
558 nt->attrs = type->attrs;
559 return nt;
561 case MONO_TYPE_SZARRAY: {
562 MonoClass *eclass = type->data.klass;
563 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
564 if (!inflated || !mono_error_ok (error))
565 return NULL;
566 nt = mono_metadata_type_dup (image, type);
567 nt->data.klass = mono_class_from_mono_type (inflated);
568 mono_metadata_free_type (inflated);
569 return nt;
571 case MONO_TYPE_ARRAY: {
572 MonoClass *eclass = type->data.array->eklass;
573 MonoType *nt, *inflated = inflate_generic_type (NULL, &eclass->byval_arg, context, error);
574 if (!inflated || !mono_error_ok (error))
575 return NULL;
576 nt = mono_metadata_type_dup (image, type);
577 nt->data.array->eklass = mono_class_from_mono_type (inflated);
578 mono_metadata_free_type (inflated);
579 return nt;
581 case MONO_TYPE_GENERICINST: {
582 MonoGenericClass *gclass = type->data.generic_class;
583 MonoGenericInst *inst;
584 MonoType *nt;
585 if (!gclass->context.class_inst->is_open)
586 return NULL;
588 inst = mono_metadata_inflate_generic_inst (gclass->context.class_inst, context, error);
589 if (!mono_error_ok (error))
590 return NULL;
591 if (inst != gclass->context.class_inst)
592 gclass = mono_metadata_lookup_generic_class (gclass->container_class, inst, gclass->is_dynamic);
594 if (gclass == type->data.generic_class)
595 return NULL;
597 nt = mono_metadata_type_dup (image, type);
598 nt->data.generic_class = gclass;
599 return nt;
601 case MONO_TYPE_CLASS:
602 case MONO_TYPE_VALUETYPE: {
603 MonoClass *klass = type->data.klass;
604 MonoGenericContainer *container = klass->generic_container;
605 MonoGenericInst *inst;
606 MonoGenericClass *gclass = NULL;
607 MonoType *nt;
609 if (!container)
610 return NULL;
612 /* We can't use context->class_inst directly, since it can have more elements */
613 inst = mono_metadata_inflate_generic_inst (container->context.class_inst, context, error);
614 if (!mono_error_ok (error))
615 return NULL;
616 if (inst == container->context.class_inst)
617 return NULL;
619 gclass = mono_metadata_lookup_generic_class (klass, inst, klass->image->dynamic);
621 nt = mono_metadata_type_dup (image, type);
622 nt->type = MONO_TYPE_GENERICINST;
623 nt->data.generic_class = gclass;
624 return nt;
626 default:
627 return NULL;
629 return NULL;
632 MonoGenericContext *
633 mono_generic_class_get_context (MonoGenericClass *gclass)
635 return &gclass->context;
638 MonoGenericContext *
639 mono_class_get_context (MonoClass *class)
641 return class->generic_class ? mono_generic_class_get_context (class->generic_class) : NULL;
645 * mono_class_get_generic_container:
647 * Return the generic container of KLASS which should be a generic type definition.
649 MonoGenericContainer*
650 mono_class_get_generic_container (MonoClass *klass)
652 g_assert (klass->is_generic);
654 return klass->generic_container;
658 * mono_class_get_generic_class:
660 * Return the MonoGenericClass of KLASS, which should be a generic instance.
662 MonoGenericClass*
663 mono_class_get_generic_class (MonoClass *klass)
665 g_assert (klass->is_inflated);
667 return klass->generic_class;
671 * mono_class_inflate_generic_type_with_mempool:
672 * @mempool: a mempool
673 * @type: a type
674 * @context: a generics context
675 * @error: error context
677 * The same as mono_class_inflate_generic_type, but allocates the MonoType
678 * from mempool if it is non-NULL. If it is NULL, the MonoType is
679 * allocated on the heap and is owned by the caller.
680 * The returned type can potentially be the same as TYPE, so it should not be
681 * modified by the caller, and it should be freed using mono_metadata_free_type ().
683 MonoType*
684 mono_class_inflate_generic_type_with_mempool (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
686 MonoType *inflated = NULL;
687 mono_error_init (error);
689 if (context)
690 inflated = inflate_generic_type (image, type, context, error);
691 if (!mono_error_ok (error))
692 return NULL;
694 if (!inflated) {
695 MonoType *shared = mono_metadata_get_shared_type (type);
697 if (shared) {
698 return shared;
699 } else {
700 return mono_metadata_type_dup (image, type);
704 mono_stats.inflated_type_count++;
705 return inflated;
709 * mono_class_inflate_generic_type:
710 * @type: a type
711 * @context: a generics context
713 * If @type is a generic type and @context is not NULL, instantiate it using the
714 * generics context @context.
716 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
717 * on the heap and is owned by the caller. Returns NULL on error.
719 * @deprecated Please use mono_class_inflate_generic_type_checked instead
721 MonoType*
722 mono_class_inflate_generic_type (MonoType *type, MonoGenericContext *context)
724 MonoError error;
725 MonoType *result;
726 result = mono_class_inflate_generic_type_checked (type, context, &error);
728 if (!mono_error_ok (&error)) {
729 mono_error_cleanup (&error);
730 return NULL;
732 return result;
736 * mono_class_inflate_generic_type:
737 * @type: a type
738 * @context: a generics context
739 * @error: error context to use
741 * If @type is a generic type and @context is not NULL, instantiate it using the
742 * generics context @context.
744 * Returns: the instantiated type or a copy of @type. The returned MonoType is allocated
745 * on the heap and is owned by the caller.
747 MonoType*
748 mono_class_inflate_generic_type_checked (MonoType *type, MonoGenericContext *context, MonoError *error)
750 return mono_class_inflate_generic_type_with_mempool (NULL, type, context, error);
754 * mono_class_inflate_generic_type_no_copy:
756 * Same as inflate_generic_type_with_mempool, but return TYPE if no inflation
757 * was done.
759 static MonoType*
760 mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
762 MonoType *inflated = NULL;
764 mono_error_init (error);
765 if (context) {
766 inflated = inflate_generic_type (image, type, context, error);
767 if (!mono_error_ok (error))
768 return NULL;
771 if (!inflated)
772 return type;
774 mono_stats.inflated_type_count++;
775 return inflated;
778 static MonoClass*
779 mono_class_inflate_generic_class_checked (MonoClass *gklass, MonoGenericContext *context, MonoError *error)
781 MonoClass *res;
782 MonoType *inflated;
784 inflated = mono_class_inflate_generic_type_checked (&gklass->byval_arg, context, error);
785 if (!mono_error_ok (error))
786 return NULL;
788 res = mono_class_from_mono_type (inflated);
789 mono_metadata_free_type (inflated);
791 return res;
794 * mono_class_inflate_generic_class:
796 * Inflate the class GKLASS with CONTEXT.
798 MonoClass*
799 mono_class_inflate_generic_class (MonoClass *gklass, MonoGenericContext *context)
801 MonoError error;
802 MonoClass *res;
804 res = mono_class_inflate_generic_class_checked (gklass, context, &error);
805 g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
807 return res;
812 static MonoGenericContext
813 inflate_generic_context (MonoGenericContext *context, MonoGenericContext *inflate_with, MonoError *error)
815 MonoGenericInst *class_inst = NULL;
816 MonoGenericInst *method_inst = NULL;
817 MonoGenericContext res = { NULL, NULL };
819 mono_error_init (error);
821 if (context->class_inst) {
822 class_inst = mono_metadata_inflate_generic_inst (context->class_inst, inflate_with, error);
823 if (!mono_error_ok (error))
824 goto fail;
827 if (context->method_inst) {
828 method_inst = mono_metadata_inflate_generic_inst (context->method_inst, inflate_with, error);
829 if (!mono_error_ok (error))
830 goto fail;
833 res.class_inst = class_inst;
834 res.method_inst = method_inst;
835 fail:
836 return res;
840 * mono_class_inflate_generic_method:
841 * @method: a generic method
842 * @context: a generics context
844 * Instantiate the generic method @method using the generics context @context.
846 * Returns: the new instantiated method
848 MonoMethod *
849 mono_class_inflate_generic_method (MonoMethod *method, MonoGenericContext *context)
851 return mono_class_inflate_generic_method_full (method, NULL, context);
855 * mono_class_inflate_generic_method_full:
857 * Instantiate method @method with the generic context @context.
858 * BEWARE: All non-trivial fields are invalid, including klass, signature, and header.
859 * Use mono_method_signature () and mono_method_get_header () to get the correct values.
861 MonoMethod*
862 mono_class_inflate_generic_method_full (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context)
864 MonoError error;
865 MonoMethod *res = mono_class_inflate_generic_method_full_checked (method, klass_hint, context, &error);
866 if (!mono_error_ok (&error))
867 /*FIXME do proper error handling - on this case, kill this function. */
868 g_error ("Could not inflate generic method due to %s", mono_error_get_message (&error));
870 return res;
874 * mono_class_inflate_generic_method_full_checked:
875 * Same as mono_class_inflate_generic_method_full but return failure using @error.
877 MonoMethod*
878 mono_class_inflate_generic_method_full_checked (MonoMethod *method, MonoClass *klass_hint, MonoGenericContext *context, MonoError *error)
880 MonoMethod *result;
881 MonoMethodInflated *iresult, *cached;
882 MonoMethodSignature *sig;
883 MonoGenericContext tmp_context;
884 gboolean is_mb_open = FALSE;
886 mono_error_init (error);
888 /* The `method' has already been instantiated before => we need to peel out the instantiation and create a new context */
889 while (method->is_inflated) {
890 MonoGenericContext *method_context = mono_method_get_context (method);
891 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
893 tmp_context = inflate_generic_context (method_context, context, error);
894 if (!mono_error_ok (error))
895 return NULL;
896 context = &tmp_context;
898 if (mono_metadata_generic_context_equal (method_context, context))
899 return method;
901 method = imethod->declaring;
905 * A method only needs to be inflated if the context has argument for which it is
906 * parametric. Eg:
908 * class Foo<T> { void Bar(); } - doesn't need to be inflated if only mvars' are supplied
909 * class Foo { void Bar<T> (); } - doesn't need to be if only vars' are supplied
912 if (!((method->is_generic && context->method_inst) ||
913 (method->klass->generic_container && context->class_inst)))
914 return method;
917 * The reason for this hack is to fix the behavior of inflating generic methods that come from a MethodBuilder.
918 * What happens is that instantiating a generic MethodBuilder with its own arguments should create a diferent object.
919 * This is opposite to the way non-SRE MethodInfos behave.
921 * This happens, for example, when we want to emit a recursive generic method. Given the following C# code:
923 * void Example<T> () {
924 * Example<T> ();
927 * In Example, the method token must be encoded as: "void Example<!!0>()"
929 * The reference to the first generic argument, "!!0", must be explicit otherwise it won't be inflated
930 * properly. To get that we need to inflate the MethodBuilder with its own arguments.
932 * On the other hand, inflating a non-SRE generic method with its own arguments should
933 * return itself. For example:
935 * MethodInfo m = ... //m is a generic method definition
936 * MethodInfo res = m.MakeGenericMethod (m.GetGenericArguments ());
937 * res == m
939 * To allow such scenarios we must allow inflation of MethodBuilder to happen in a diferent way than
940 * what happens with regular methods.
942 * There is one last touch to this madness, once a TypeBuilder is finished, IOW CreateType() is called,
943 * everything should behave like a regular type or method.
946 is_mb_open = method->is_generic &&
947 method->klass->image->dynamic && !method->klass->wastypebuilder && /* that is a MethodBuilder from an unfinished TypeBuilder */
948 context->method_inst == mono_method_get_generic_container (method)->context.method_inst; /* and it's been instantiated with its own arguments. */
950 iresult = g_new0 (MonoMethodInflated, 1);
951 iresult->context = *context;
952 iresult->declaring = method;
953 iresult->method.method.is_mb_open = is_mb_open;
955 if (!context->method_inst && method->is_generic)
956 iresult->context.method_inst = mono_method_get_generic_container (method)->context.method_inst;
958 if (!context->class_inst) {
959 g_assert (!iresult->declaring->klass->generic_class);
960 if (iresult->declaring->klass->generic_container)
961 iresult->context.class_inst = iresult->declaring->klass->generic_container->context.class_inst;
962 else if (iresult->declaring->klass->generic_class)
963 iresult->context.class_inst = iresult->declaring->klass->generic_class->context.class_inst;
966 mono_loader_lock ();
967 cached = mono_method_inflated_lookup (iresult, FALSE);
968 if (cached) {
969 mono_loader_unlock ();
970 g_free (iresult);
971 return (MonoMethod*)cached;
974 mono_stats.inflated_method_count++;
976 inflated_methods_size += sizeof (MonoMethodInflated);
978 sig = mono_method_signature (method);
979 if (!sig) {
980 char *name = mono_type_get_full_name (method->klass);
981 mono_error_set_bad_image (error, method->klass->image, "Could not resolve signature of method %s:%s", name, method->name);
982 g_free (name);
983 goto fail;
986 if (sig->pinvoke) {
987 memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
988 } else {
989 memcpy (&iresult->method.method, method, sizeof (MonoMethod));
992 result = (MonoMethod *) iresult;
993 result->is_inflated = TRUE;
994 result->is_generic = FALSE;
995 result->sre_method = FALSE;
996 result->signature = NULL;
997 result->is_mb_open = is_mb_open;
999 if (!context->method_inst) {
1000 /* Set the generic_container of the result to the generic_container of method */
1001 MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
1003 if (generic_container) {
1004 result->is_generic = 1;
1005 mono_method_set_generic_container (result, generic_container);
1009 if (!klass_hint || !klass_hint->generic_class ||
1010 klass_hint->generic_class->container_class != method->klass ||
1011 klass_hint->generic_class->context.class_inst != context->class_inst)
1012 klass_hint = NULL;
1014 if (method->klass->generic_container)
1015 result->klass = klass_hint;
1017 if (!result->klass) {
1018 MonoType *inflated = inflate_generic_type (NULL, &method->klass->byval_arg, context, error);
1019 if (!mono_error_ok (error))
1020 goto fail;
1022 result->klass = inflated ? mono_class_from_mono_type (inflated) : method->klass;
1023 if (inflated)
1024 mono_metadata_free_type (inflated);
1028 * FIXME: This should hold, but it doesn't:
1030 * if (result->is_inflated && mono_method_get_context (result)->method_inst &&
1031 * mono_method_get_context (result)->method_inst == mono_method_get_generic_container (((MonoMethodInflated*)result)->declaring)->context.method_inst) {
1032 * g_assert (result->is_generic);
1035 * Fixing this here causes other things to break, hence a very
1036 * ugly hack in mini-trampolines.c - see
1037 * is_generic_method_definition().
1040 mono_method_inflated_lookup (iresult, TRUE);
1041 mono_loader_unlock ();
1042 return result;
1044 fail:
1045 mono_loader_unlock ();
1046 g_free (iresult);
1047 return NULL;
1051 * mono_get_inflated_method:
1053 * Obsolete. We keep it around since it's mentioned in the public API.
1055 MonoMethod*
1056 mono_get_inflated_method (MonoMethod *method)
1058 return method;
1062 * mono_method_get_context_general:
1063 * @method: a method
1064 * @uninflated: handle uninflated methods?
1066 * Returns the generic context of a method or NULL if it doesn't have
1067 * one. For an inflated method that's the context stored in the
1068 * method. Otherwise it's in the method's generic container or in the
1069 * generic container of the method's class.
1071 MonoGenericContext*
1072 mono_method_get_context_general (MonoMethod *method, gboolean uninflated)
1074 if (method->is_inflated) {
1075 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1076 return &imethod->context;
1078 if (!uninflated)
1079 return NULL;
1080 if (method->is_generic)
1081 return &(mono_method_get_generic_container (method)->context);
1082 if (method->klass->generic_container)
1083 return &method->klass->generic_container->context;
1084 return NULL;
1088 * mono_method_get_context:
1089 * @method: a method
1091 * Returns the generic context for method if it's inflated, otherwise
1092 * NULL.
1094 MonoGenericContext*
1095 mono_method_get_context (MonoMethod *method)
1097 return mono_method_get_context_general (method, FALSE);
1101 * mono_method_get_generic_container:
1103 * Returns the generic container of METHOD, which should be a generic method definition.
1104 * Returns NULL if METHOD is not a generic method definition.
1105 * LOCKING: Acquires the loader lock.
1107 MonoGenericContainer*
1108 mono_method_get_generic_container (MonoMethod *method)
1110 MonoGenericContainer *container;
1112 if (!method->is_generic)
1113 return NULL;
1115 container = mono_image_property_lookup (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER);
1116 g_assert (container);
1118 return container;
1122 * mono_method_set_generic_container:
1124 * Sets the generic container of METHOD to CONTAINER.
1125 * LOCKING: Acquires the loader lock.
1127 void
1128 mono_method_set_generic_container (MonoMethod *method, MonoGenericContainer* container)
1130 g_assert (method->is_generic);
1132 mono_image_property_insert (method->klass->image, method, MONO_METHOD_PROP_GENERIC_CONTAINER, container);
1135 /**
1136 * mono_class_find_enum_basetype:
1137 * @class: The enum class
1139 * Determine the basetype of an enum by iterating through its fields. We do this
1140 * in a separate function since it is cheaper than calling mono_class_setup_fields.
1142 static MonoType*
1143 mono_class_find_enum_basetype (MonoClass *class)
1145 MonoGenericContainer *container = NULL;
1146 MonoImage *m = class->image;
1147 const int top = class->field.count;
1148 int i;
1150 g_assert (class->enumtype);
1152 if (class->generic_container)
1153 container = class->generic_container;
1154 else if (class->generic_class) {
1155 MonoClass *gklass = class->generic_class->container_class;
1157 container = gklass->generic_container;
1158 g_assert (container);
1162 * Fetch all the field information.
1164 for (i = 0; i < top; i++){
1165 const char *sig;
1166 guint32 cols [MONO_FIELD_SIZE];
1167 int idx = class->field.first + i;
1168 MonoType *ftype;
1170 /* class->field.first and idx points into the fieldptr table */
1171 mono_metadata_decode_table_row (m, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
1173 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_STATIC) //no need to decode static fields
1174 continue;
1176 if (!mono_verifier_verify_field_signature (class->image, cols [MONO_FIELD_SIGNATURE], NULL))
1177 return NULL;
1179 sig = mono_metadata_blob_heap (m, cols [MONO_FIELD_SIGNATURE]);
1180 mono_metadata_decode_value (sig, &sig);
1181 /* FIELD signature == 0x06 */
1182 if (*sig != 0x06)
1183 return NULL;
1185 ftype = mono_metadata_parse_type_full (m, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
1186 if (!ftype)
1187 return NULL;
1188 if (class->generic_class) {
1189 //FIXME do we leak here?
1190 ftype = mono_class_inflate_generic_type (ftype, mono_class_get_context (class));
1191 ftype->attrs = cols [MONO_FIELD_FLAGS];
1194 return ftype;
1197 return NULL;
1201 * Checks for MonoClass::exception_type without resolving all MonoType's into MonoClass'es
1203 static gboolean
1204 mono_type_has_exceptions (MonoType *type)
1206 switch (type->type) {
1207 case MONO_TYPE_CLASS:
1208 case MONO_TYPE_VALUETYPE:
1209 case MONO_TYPE_SZARRAY:
1210 return type->data.klass->exception_type;
1211 case MONO_TYPE_ARRAY:
1212 return type->data.array->eklass->exception_type;
1213 case MONO_TYPE_GENERICINST:
1214 return mono_generic_class_get_class (type->data.generic_class)->exception_type;
1216 return FALSE;
1220 * mono_class_alloc:
1222 * Allocate memory for some data belonging to CLASS, either from its image's mempool,
1223 * or from the heap.
1225 static gpointer
1226 mono_class_alloc (MonoClass *class, int size)
1228 if (class->generic_class)
1229 return mono_image_set_alloc (class->generic_class->owner, size);
1230 else
1231 return mono_image_alloc (class->image, size);
1234 static gpointer
1235 mono_class_alloc0 (MonoClass *class, int size)
1237 gpointer res;
1239 res = mono_class_alloc (class, size);
1240 memset (res, 0, size);
1241 return res;
1244 #define mono_class_new0(class,struct_type, n_structs) \
1245 ((struct_type *) mono_class_alloc0 ((class), ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
1248 * mono_class_setup_basic_field_info:
1249 * @class: The class to initialize
1251 * Initializes the class->fields.
1252 * LOCKING: Assumes the loader lock is held.
1254 static void
1255 mono_class_setup_basic_field_info (MonoClass *class)
1257 MonoClassField *field;
1258 MonoClass *gtd;
1259 MonoImage *image;
1260 int i, top;
1262 if (class->fields)
1263 return;
1265 gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1266 image = class->image;
1267 top = class->field.count;
1269 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1271 * This happens when a generic instance of an unfinished generic typebuilder
1272 * is used as an element type for creating an array type. We can't initialize
1273 * the fields of this class using the fields of gklass, since gklass is not
1274 * finished yet, fields could be added to it later.
1276 return;
1279 if (gtd) {
1280 mono_class_setup_basic_field_info (gtd);
1282 top = gtd->field.count;
1283 class->field.first = gtd->field.first;
1284 class->field.count = gtd->field.count;
1287 class->fields = mono_class_alloc0 (class, sizeof (MonoClassField) * top);
1290 * Fetch all the field information.
1292 for (i = 0; i < top; i++){
1293 field = &class->fields [i];
1294 field->parent = class;
1296 if (gtd) {
1297 field->name = mono_field_get_name (&gtd->fields [i]);
1298 } else {
1299 int idx = class->field.first + i;
1300 /* class->field.first and idx points into the fieldptr table */
1301 guint32 name_idx = mono_metadata_decode_table_row_col (image, MONO_TABLE_FIELD, idx, MONO_FIELD_NAME);
1302 /* The name is needed for fieldrefs */
1303 field->name = mono_metadata_string_heap (image, name_idx);
1308 /**
1309 * mono_class_setup_fields:
1310 * @class: The class to initialize
1312 * Initializes the class->fields.
1313 * LOCKING: Assumes the loader lock is held.
1315 static void
1316 mono_class_setup_fields (MonoClass *class)
1318 MonoError error;
1319 MonoImage *m = class->image;
1320 int top;
1321 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1322 int i, blittable = TRUE;
1323 guint32 real_size = 0;
1324 guint32 packing_size = 0;
1325 gboolean explicit_size;
1326 MonoClassField *field;
1327 MonoGenericContainer *container = NULL;
1328 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
1330 if (class->size_inited)
1331 return;
1333 if (class->generic_class && class->generic_class->container_class->image->dynamic && !class->generic_class->container_class->wastypebuilder) {
1335 * This happens when a generic instance of an unfinished generic typebuilder
1336 * is used as an element type for creating an array type. We can't initialize
1337 * the fields of this class using the fields of gklass, since gklass is not
1338 * finished yet, fields could be added to it later.
1340 return;
1343 mono_class_setup_basic_field_info (class);
1344 top = class->field.count;
1346 if (gtd) {
1347 mono_class_setup_fields (gtd);
1348 if (gtd->exception_type) {
1349 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1350 return;
1354 class->instance_size = 0;
1355 if (!class->rank)
1356 class->sizes.class_size = 0;
1358 if (class->parent) {
1359 /* For generic instances, class->parent might not have been initialized */
1360 mono_class_init (class->parent);
1361 if (!class->parent->size_inited) {
1362 mono_class_setup_fields (class->parent);
1363 if (class->parent->exception_type) {
1364 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1365 return;
1368 class->instance_size += class->parent->instance_size;
1369 class->min_align = class->parent->min_align;
1370 /* we use |= since it may have been set already */
1371 class->has_references |= class->parent->has_references;
1372 blittable = class->parent->blittable;
1373 } else {
1374 class->instance_size = sizeof (MonoObject);
1375 class->min_align = 1;
1378 /* We can't really enable 16 bytes alignment until the GC supports it.
1379 The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
1380 boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
1381 Bug #506144 is an example of this issue.
1383 if (class->simd_type)
1384 class->min_align = 16;
1386 /* Get the real size */
1387 explicit_size = mono_metadata_packing_from_typedef (class->image, class->type_token, &packing_size, &real_size);
1389 if (explicit_size) {
1390 g_assert ((packing_size & 0xfffffff0) == 0);
1391 class->packing_size = packing_size;
1392 real_size += class->instance_size;
1395 if (!top) {
1396 if (explicit_size && real_size) {
1397 class->instance_size = MAX (real_size, class->instance_size);
1399 class->size_inited = 1;
1400 class->blittable = blittable;
1401 return;
1404 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1405 blittable = FALSE;
1407 /* Prevent infinite loops if the class references itself */
1408 class->size_inited = 1;
1410 if (class->generic_container) {
1411 container = class->generic_container;
1412 } else if (gtd) {
1413 container = gtd->generic_container;
1414 g_assert (container);
1418 * Fetch all the field information.
1420 for (i = 0; i < top; i++){
1421 int idx = class->field.first + i;
1422 field = &class->fields [i];
1424 field->parent = class;
1426 if (!field->type) {
1427 mono_field_resolve_type (field, &error);
1428 if (!mono_error_ok (&error)) {
1429 /*mono_field_resolve_type already failed class*/
1430 mono_error_cleanup (&error);
1431 return;
1433 if (!field->type)
1434 g_error ("could not resolve %s:%s\n", mono_type_get_full_name(class), field->name);
1435 g_assert (field->type);
1438 if (mono_field_is_deleted (field))
1439 continue;
1440 if (gtd) {
1441 MonoClassField *gfield = &gtd->fields [i];
1442 field->offset = gfield->offset;
1443 } else {
1444 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1445 guint32 offset;
1446 mono_metadata_field_info (m, idx, &offset, NULL, NULL);
1447 field->offset = offset;
1449 if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1450 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Missing field layout info for %s", field->name));
1451 break;
1453 if (field->offset < -1) { /*-1 is used to encode special static fields */
1454 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Invalid negative field offset %d for %s", field->offset, field->name));
1455 break;
1460 /* Only do these checks if we still think this type is blittable */
1461 if (blittable && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1462 if (field->type->byref || MONO_TYPE_IS_REFERENCE (field->type)) {
1463 blittable = FALSE;
1464 } else {
1465 MonoClass *field_class = mono_class_from_mono_type (field->type);
1466 if (field_class) {
1467 mono_class_setup_fields (field_class);
1468 if (field_class->exception_type) {
1469 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1470 break;
1473 if (!field_class || !field_class->blittable)
1474 blittable = FALSE;
1478 if (class->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1479 class->cast_class = class->element_class = mono_class_from_mono_type (field->type);
1480 blittable = class->element_class->blittable;
1483 if (mono_type_has_exceptions (field->type)) {
1484 char *class_name = mono_type_get_full_name (class);
1485 char *type_name = mono_type_full_name (field->type);
1487 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1488 g_warning ("Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
1489 g_free (class_name);
1490 g_free (type_name);
1491 break;
1493 /* The def_value of fields is compute lazily during vtable creation */
1496 if (class == mono_defaults.string_class)
1497 blittable = FALSE;
1499 class->blittable = blittable;
1501 if (class->enumtype && !mono_class_enum_basetype (class)) {
1502 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1503 return;
1505 if (explicit_size && real_size) {
1506 class->instance_size = MAX (real_size, class->instance_size);
1509 if (class->exception_type)
1510 return;
1511 mono_class_layout_fields (class);
1513 /*valuetypes can't be neither bigger than 1Mb or empty. */
1514 if (class->valuetype && (class->instance_size <= 0 || class->instance_size > (0x100000 + sizeof (MonoObject))))
1515 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1518 /**
1519 * mono_class_setup_fields_locking:
1520 * @class: The class to initialize
1522 * Initializes the class->fields array of fields.
1523 * Aquires the loader lock.
1525 static void
1526 mono_class_setup_fields_locking (MonoClass *class)
1528 mono_loader_lock ();
1529 mono_class_setup_fields (class);
1530 mono_loader_unlock ();
1534 * mono_class_has_references:
1536 * Returns whenever @klass->has_references is set, initializing it if needed.
1537 * Aquires the loader lock.
1539 static gboolean
1540 mono_class_has_references (MonoClass *klass)
1542 if (klass->init_pending) {
1543 /* Be conservative */
1544 return TRUE;
1545 } else {
1546 mono_class_init (klass);
1548 return klass->has_references;
1553 * mono_type_get_basic_type_from_generic:
1554 * @type: a type
1556 * Returns a closed type corresponding to the possibly open type
1557 * passed to it.
1559 MonoType*
1560 mono_type_get_basic_type_from_generic (MonoType *type)
1562 /* When we do generic sharing we let type variables stand for reference types. */
1563 if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR))
1564 return &mono_defaults.object_class->byval_arg;
1565 return type;
1569 * mono_class_layout_fields:
1570 * @class: a class
1572 * Compute the placement of fields inside an object or struct, according to
1573 * the layout rules and set the following fields in @class:
1574 * - has_references (if the class contains instance references firled or structs that contain references)
1575 * - has_static_refs (same, but for static fields)
1576 * - instance_size (size of the object in memory)
1577 * - class_size (size needed for the static fields)
1578 * - size_inited (flag set when the instance_size is set)
1580 * LOCKING: this is supposed to be called with the loader lock held.
1582 void
1583 mono_class_layout_fields (MonoClass *class)
1585 int i;
1586 const int top = class->field.count;
1587 guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
1588 guint32 pass, passes, real_size;
1589 gboolean gc_aware_layout = FALSE;
1590 MonoClassField *field;
1593 * When we do generic sharing we need to have layout
1594 * information for open generic classes (either with a generic
1595 * context containing type variables or with a generic
1596 * container), so we don't return in that case anymore.
1600 * Enable GC aware auto layout: in this mode, reference
1601 * fields are grouped together inside objects, increasing collector
1602 * performance.
1603 * Requires that all classes whose layout is known to native code be annotated
1604 * with [StructLayout (LayoutKind.Sequential)]
1605 * Value types have gc_aware_layout disabled by default, as per
1606 * what the default is for other runtimes.
1608 /* corlib is missing [StructLayout] directives in many places */
1609 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1610 if (class->image != mono_defaults.corlib &&
1611 class->byval_arg.type != MONO_TYPE_VALUETYPE)
1612 gc_aware_layout = TRUE;
1613 /* from System.dll, used in metadata/process.h */
1614 if (strcmp (class->name, "ProcessStartInfo") == 0)
1615 gc_aware_layout = FALSE;
1618 /* Compute klass->has_references */
1620 * Process non-static fields first, since static fields might recursively
1621 * refer to the class itself.
1623 for (i = 0; i < top; i++) {
1624 MonoType *ftype;
1626 field = &class->fields [i];
1628 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
1629 ftype = mono_type_get_underlying_type (field->type);
1630 ftype = mono_type_get_basic_type_from_generic (ftype);
1631 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1632 class->has_references = TRUE;
1636 for (i = 0; i < top; i++) {
1637 MonoType *ftype;
1639 field = &class->fields [i];
1641 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1642 ftype = mono_type_get_underlying_type (field->type);
1643 ftype = mono_type_get_basic_type_from_generic (ftype);
1644 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1645 class->has_static_refs = TRUE;
1649 for (i = 0; i < top; i++) {
1650 MonoType *ftype;
1652 field = &class->fields [i];
1654 ftype = mono_type_get_underlying_type (field->type);
1655 ftype = mono_type_get_basic_type_from_generic (ftype);
1656 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1657 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1658 class->has_static_refs = TRUE;
1659 else
1660 class->has_references = TRUE;
1665 * Compute field layout and total size (not considering static fields)
1668 switch (layout) {
1669 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
1670 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
1672 if (gc_aware_layout)
1673 passes = 2;
1674 else
1675 passes = 1;
1677 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
1678 passes = 1;
1680 if (class->parent) {
1681 mono_class_setup_fields (class->parent);
1682 if (class->parent->exception_type) {
1683 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1684 return;
1686 real_size = class->parent->instance_size;
1687 } else {
1688 real_size = sizeof (MonoObject);
1691 for (pass = 0; pass < passes; ++pass) {
1692 for (i = 0; i < top; i++){
1693 gint32 align;
1694 guint32 size;
1695 MonoType *ftype;
1697 field = &class->fields [i];
1699 if (mono_field_is_deleted (field))
1700 continue;
1701 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1702 continue;
1704 ftype = mono_type_get_underlying_type (field->type);
1705 ftype = mono_type_get_basic_type_from_generic (ftype);
1706 if (gc_aware_layout) {
1707 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1708 if (pass == 1)
1709 continue;
1710 } else {
1711 if (pass == 0)
1712 continue;
1716 if ((top == 1) && (class->instance_size == sizeof (MonoObject)) &&
1717 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
1718 /* This field is a hack inserted by MCS to empty structures */
1719 continue;
1722 size = mono_type_size (field->type, &align);
1724 /* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
1725 align = class->packing_size ? MIN (class->packing_size, align): align;
1726 /* if the field has managed references, we need to force-align it
1727 * see bug #77788
1729 if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype)))))
1730 align = MAX (align, sizeof (gpointer));
1732 class->min_align = MAX (align, class->min_align);
1733 field->offset = real_size;
1734 if (align) {
1735 field->offset += align - 1;
1736 field->offset &= ~(align - 1);
1738 /*TypeBuilders produce all sort of weird things*/
1739 g_assert (class->image->dynamic || field->offset > 0);
1740 real_size = field->offset + size;
1743 class->instance_size = MAX (real_size, class->instance_size);
1745 if (class->instance_size & (class->min_align - 1)) {
1746 class->instance_size += class->min_align - 1;
1747 class->instance_size &= ~(class->min_align - 1);
1750 break;
1751 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
1752 real_size = 0;
1753 for (i = 0; i < top; i++) {
1754 gint32 align;
1755 guint32 size;
1756 MonoType *ftype;
1758 field = &class->fields [i];
1761 * There must be info about all the fields in a type if it
1762 * uses explicit layout.
1765 if (mono_field_is_deleted (field))
1766 continue;
1767 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1768 continue;
1770 size = mono_type_size (field->type, &align);
1771 class->min_align = MAX (align, class->min_align);
1774 * When we get here, field->offset is already set by the
1775 * loader (for either runtime fields or fields loaded from metadata).
1776 * The offset is from the start of the object: this works for both
1777 * classes and valuetypes.
1779 field->offset += sizeof (MonoObject);
1780 ftype = mono_type_get_underlying_type (field->type);
1781 ftype = mono_type_get_basic_type_from_generic (ftype);
1782 if (MONO_TYPE_IS_REFERENCE (ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && mono_class_has_references (mono_class_from_mono_type (ftype))))) {
1783 if (field->offset % sizeof (gpointer)) {
1784 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1789 * Calc max size.
1791 real_size = MAX (real_size, size + field->offset);
1793 class->instance_size = MAX (real_size, class->instance_size);
1794 break;
1797 if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1799 * For small structs, set min_align to at least the struct size to improve
1800 * performance, and since the JIT memset/memcpy code assumes this and generates
1801 * unaligned accesses otherwise. See #78990 for a testcase.
1803 if (class->instance_size <= sizeof (MonoObject) + sizeof (gpointer))
1804 class->min_align = MAX (class->min_align, class->instance_size - sizeof (MonoObject));
1807 class->size_inited = 1;
1810 * Compute static field layout and size
1812 for (i = 0; i < top; i++){
1813 gint32 align;
1814 guint32 size;
1816 field = &class->fields [i];
1818 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
1819 continue;
1820 if (mono_field_is_deleted (field))
1821 continue;
1823 if (mono_type_has_exceptions (field->type)) {
1824 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
1825 break;
1828 size = mono_type_size (field->type, &align);
1829 field->offset = class->sizes.class_size;
1830 /*align is always non-zero here*/
1831 field->offset += align - 1;
1832 field->offset &= ~(align - 1);
1833 class->sizes.class_size = field->offset + size;
1837 static MonoMethod*
1838 create_array_method (MonoClass *class, const char *name, MonoMethodSignature *sig)
1840 MonoMethod *method;
1842 method = (MonoMethod *) mono_image_alloc0 (class->image, sizeof (MonoMethodPInvoke));
1843 method->klass = class;
1844 method->flags = METHOD_ATTRIBUTE_PUBLIC;
1845 method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
1846 method->signature = sig;
1847 method->name = name;
1848 method->slot = -1;
1849 /* .ctor */
1850 if (name [0] == '.') {
1851 method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
1852 } else {
1853 method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
1855 return method;
1859 * mono_class_setup_methods:
1860 * @class: a class
1862 * Initializes the 'methods' array in the klass.
1863 * Calling this method should be avoided if possible since it allocates a lot
1864 * of long-living MonoMethod structures.
1865 * Methods belonging to an interface are assigned a sequential slot starting
1866 * from 0.
1868 * On failure this function sets class->exception_type
1870 void
1871 mono_class_setup_methods (MonoClass *class)
1873 int i;
1874 MonoMethod **methods;
1876 if (class->methods)
1877 return;
1879 mono_loader_lock ();
1881 if (class->methods) {
1882 mono_loader_unlock ();
1883 return;
1886 if (class->generic_class) {
1887 MonoError error;
1888 MonoClass *gklass = class->generic_class->container_class;
1890 mono_class_init (gklass);
1891 if (!gklass->exception_type)
1892 mono_class_setup_methods (gklass);
1893 if (gklass->exception_type) {
1894 /*FIXME make exception_data less opaque so it's possible to dup it here*/
1895 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
1896 mono_loader_unlock ();
1897 return;
1900 /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
1901 class->method.count = gklass->method.count;
1902 methods = mono_class_alloc0 (class, sizeof (MonoMethod*) * (class->method.count + 1));
1904 for (i = 0; i < class->method.count; i++) {
1905 methods [i] = mono_class_inflate_generic_method_full_checked (
1906 gklass->methods [i], class, mono_class_get_context (class), &error);
1907 if (!mono_error_ok (&error)) {
1908 char *method = mono_method_full_name (gklass->methods [i], TRUE);
1909 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)));
1911 g_free (method);
1912 mono_error_cleanup (&error);
1913 mono_loader_unlock ();
1914 return;
1917 } else if (class->rank) {
1918 MonoError error;
1919 MonoMethod *amethod;
1920 MonoMethodSignature *sig;
1921 int count_generic = 0, first_generic = 0;
1922 int method_num = 0;
1924 class->method.count = 3 + (class->rank > 1? 2: 1);
1926 mono_class_setup_interfaces (class, &error);
1927 g_assert (mono_error_ok (&error)); /*FIXME can this fail for array types?*/
1929 if (class->interface_count) {
1930 count_generic = generic_array_methods (class);
1931 first_generic = class->method.count;
1932 class->method.count += class->interface_count * count_generic;
1935 methods = mono_class_alloc0 (class, sizeof (MonoMethod*) * class->method.count);
1937 sig = mono_metadata_signature_alloc (class->image, class->rank);
1938 sig->ret = &mono_defaults.void_class->byval_arg;
1939 sig->pinvoke = TRUE;
1940 sig->hasthis = TRUE;
1941 for (i = 0; i < class->rank; ++i)
1942 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1944 amethod = create_array_method (class, ".ctor", sig);
1945 methods [method_num++] = amethod;
1946 if (class->rank > 1) {
1947 sig = mono_metadata_signature_alloc (class->image, class->rank * 2);
1948 sig->ret = &mono_defaults.void_class->byval_arg;
1949 sig->pinvoke = TRUE;
1950 sig->hasthis = TRUE;
1951 for (i = 0; i < class->rank * 2; ++i)
1952 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1954 amethod = create_array_method (class, ".ctor", sig);
1955 methods [method_num++] = amethod;
1957 /* element Get (idx11, [idx2, ...]) */
1958 sig = mono_metadata_signature_alloc (class->image, class->rank);
1959 sig->ret = &class->element_class->byval_arg;
1960 sig->pinvoke = TRUE;
1961 sig->hasthis = TRUE;
1962 for (i = 0; i < class->rank; ++i)
1963 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1964 amethod = create_array_method (class, "Get", sig);
1965 methods [method_num++] = amethod;
1966 /* element& Address (idx11, [idx2, ...]) */
1967 sig = mono_metadata_signature_alloc (class->image, class->rank);
1968 sig->ret = &class->element_class->this_arg;
1969 sig->pinvoke = TRUE;
1970 sig->hasthis = TRUE;
1971 for (i = 0; i < class->rank; ++i)
1972 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1973 amethod = create_array_method (class, "Address", sig);
1974 methods [method_num++] = amethod;
1975 /* void Set (idx11, [idx2, ...], element) */
1976 sig = mono_metadata_signature_alloc (class->image, class->rank + 1);
1977 sig->ret = &mono_defaults.void_class->byval_arg;
1978 sig->pinvoke = TRUE;
1979 sig->hasthis = TRUE;
1980 for (i = 0; i < class->rank; ++i)
1981 sig->params [i] = &mono_defaults.int32_class->byval_arg;
1982 sig->params [i] = &class->element_class->byval_arg;
1983 amethod = create_array_method (class, "Set", sig);
1984 methods [method_num++] = amethod;
1986 for (i = 0; i < class->interface_count; i++)
1987 setup_generic_array_ifaces (class, class->interfaces [i], methods, first_generic + i * count_generic);
1988 } else {
1989 methods = mono_class_alloc (class, sizeof (MonoMethod*) * class->method.count);
1990 for (i = 0; i < class->method.count; ++i) {
1991 int idx = mono_metadata_translate_token_index (class->image, MONO_TABLE_METHOD, class->method.first + i + 1);
1992 methods [i] = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | idx, class);
1996 if (MONO_CLASS_IS_INTERFACE (class)) {
1997 int slot = 0;
1998 /*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
1999 for (i = 0; i < class->method.count; ++i) {
2000 if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
2001 methods [i]->slot = slot++;
2005 /* Needed because of the double-checking locking pattern */
2006 mono_memory_barrier ();
2008 class->methods = methods;
2010 if (mono_debugger_class_loaded_methods_func)
2011 mono_debugger_class_loaded_methods_func (class);
2013 mono_loader_unlock ();
2017 * mono_class_get_method_by_index:
2019 * Returns class->methods [index], initializing class->methods if neccesary.
2021 * LOCKING: Acquires the loader lock.
2023 MonoMethod*
2024 mono_class_get_method_by_index (MonoClass *class, int index)
2026 /* Avoid calling setup_methods () if possible */
2027 if (class->generic_class && !class->methods) {
2028 MonoClass *gklass = class->generic_class->container_class;
2029 MonoMethod *m;
2031 m = mono_class_inflate_generic_method_full (
2032 gklass->methods [index], class, mono_class_get_context (class));
2034 * If setup_methods () is called later for this class, no duplicates are created,
2035 * since inflate_generic_method guarantees that only one instance of a method
2036 * is created for each context.
2039 mono_class_setup_methods (class);
2040 g_assert (m == class->methods [index]);
2042 return m;
2043 } else {
2044 mono_class_setup_methods (class);
2045 if (class->exception_type) /*FIXME do proper error handling*/
2046 return NULL;
2047 g_assert (index >= 0 && index < class->method.count);
2048 return class->methods [index];
2053 * mono_class_get_inflated_method:
2055 * Given an inflated class CLASS and a method METHOD which should be a method of
2056 * CLASS's generic definition, return the inflated method corresponding to METHOD.
2058 MonoMethod*
2059 mono_class_get_inflated_method (MonoClass *class, MonoMethod *method)
2061 MonoClass *gklass = class->generic_class->container_class;
2062 int i;
2064 g_assert (method->klass == gklass);
2066 mono_class_setup_methods (gklass);
2067 g_assert (!gklass->exception_type); /*FIXME do proper error handling*/
2069 for (i = 0; i < gklass->method.count; ++i) {
2070 if (gklass->methods [i] == method) {
2071 if (class->methods)
2072 return class->methods [i];
2073 else
2074 return mono_class_inflate_generic_method_full (gklass->methods [i], class, mono_class_get_context (class));
2078 return NULL;
2082 * mono_class_get_vtable_entry:
2084 * Returns class->vtable [offset], computing it if neccesary. Returns NULL on failure.
2085 * LOCKING: Acquires the loader lock.
2087 MonoMethod*
2088 mono_class_get_vtable_entry (MonoClass *class, int offset)
2090 MonoMethod *m;
2092 if (class->rank == 1) {
2094 * szarrays do not overwrite any methods of Array, so we can avoid
2095 * initializing their vtables in some cases.
2097 mono_class_setup_vtable (class->parent);
2098 if (offset < class->parent->vtable_size)
2099 return class->parent->vtable [offset];
2102 if (class->generic_class) {
2103 MonoClass *gklass = class->generic_class->container_class;
2104 mono_class_setup_vtable (gklass);
2105 m = gklass->vtable [offset];
2107 m = mono_class_inflate_generic_method_full (m, class, mono_class_get_context (class));
2108 } else {
2109 mono_class_setup_vtable (class);
2110 if (class->exception_type)
2111 return NULL;
2112 m = class->vtable [offset];
2115 return m;
2119 * mono_class_get_vtable_size:
2121 * Return the vtable size for KLASS.
2124 mono_class_get_vtable_size (MonoClass *klass)
2126 mono_class_setup_vtable (klass);
2128 return klass->vtable_size;
2131 /*This method can fail the class.*/
2132 static void
2133 mono_class_setup_properties (MonoClass *class)
2135 guint startm, endm, i, j;
2136 guint32 cols [MONO_PROPERTY_SIZE];
2137 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2138 MonoProperty *properties;
2139 guint32 last;
2141 if (class->ext && class->ext->properties)
2142 return;
2144 mono_loader_lock ();
2146 if (class->ext && class->ext->properties) {
2147 mono_loader_unlock ();
2148 return;
2151 mono_class_alloc_ext (class);
2153 if (class->generic_class) {
2154 MonoClass *gklass = class->generic_class->container_class;
2156 mono_class_init (gklass);
2157 mono_class_setup_properties (gklass);
2158 if (gklass->exception_type) {
2159 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2160 mono_loader_unlock ();
2161 return;
2164 class->ext->property = gklass->ext->property;
2166 properties = mono_class_new0 (class, MonoProperty, class->ext->property.count + 1);
2168 for (i = 0; i < class->ext->property.count; i++) {
2169 MonoProperty *prop = &properties [i];
2171 *prop = gklass->ext->properties [i];
2173 if (prop->get)
2174 prop->get = mono_class_inflate_generic_method_full (
2175 prop->get, class, mono_class_get_context (class));
2176 if (prop->set)
2177 prop->set = mono_class_inflate_generic_method_full (
2178 prop->set, class, mono_class_get_context (class));
2180 prop->parent = class;
2182 } else {
2183 int first = mono_metadata_properties_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2184 int count = last - first;
2186 if (count) {
2187 mono_class_setup_methods (class);
2188 if (class->exception_type) {
2189 mono_loader_unlock ();
2190 return;
2194 class->ext->property.first = first;
2195 class->ext->property.count = count;
2196 properties = mono_class_alloc0 (class, sizeof (MonoProperty) * count);
2197 for (i = first; i < last; ++i) {
2198 mono_metadata_decode_table_row (class->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
2199 properties [i - first].parent = class;
2200 properties [i - first].attrs = cols [MONO_PROPERTY_FLAGS];
2201 properties [i - first].name = mono_metadata_string_heap (class->image, cols [MONO_PROPERTY_NAME]);
2203 startm = mono_metadata_methods_from_property (class->image, i, &endm);
2204 for (j = startm; j < endm; ++j) {
2205 MonoMethod *method;
2207 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2209 if (class->image->uncompressed_metadata)
2210 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2211 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2212 else
2213 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2215 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2216 case METHOD_SEMANTIC_SETTER:
2217 properties [i - first].set = method;
2218 break;
2219 case METHOD_SEMANTIC_GETTER:
2220 properties [i - first].get = method;
2221 break;
2222 default:
2223 break;
2228 /*Flush any pending writes as we do double checked locking on class->properties */
2229 mono_memory_barrier ();
2231 /* Leave this assignment as the last op in the function */
2232 class->ext->properties = properties;
2234 mono_loader_unlock ();
2237 static MonoMethod**
2238 inflate_method_listz (MonoMethod **methods, MonoClass *class, MonoGenericContext *context)
2240 MonoMethod **om, **retval;
2241 int count;
2243 for (om = methods, count = 0; *om; ++om, ++count)
2246 retval = g_new0 (MonoMethod*, count + 1);
2247 count = 0;
2248 for (om = methods, count = 0; *om; ++om, ++count)
2249 retval [count] = mono_class_inflate_generic_method_full (*om, class, context);
2251 return retval;
2254 /*This method can fail the class.*/
2255 static void
2256 mono_class_setup_events (MonoClass *class)
2258 int first, count;
2259 guint startm, endm, i, j;
2260 guint32 cols [MONO_EVENT_SIZE];
2261 MonoTableInfo *msemt = &class->image->tables [MONO_TABLE_METHODSEMANTICS];
2262 guint32 last;
2263 MonoEvent *events;
2265 if (class->ext && class->ext->events)
2266 return;
2268 mono_loader_lock ();
2270 if (class->ext && class->ext->events) {
2271 mono_loader_unlock ();
2272 return;
2275 mono_class_alloc_ext (class);
2277 if (class->generic_class) {
2278 MonoClass *gklass = class->generic_class->container_class;
2279 MonoGenericContext *context;
2281 mono_class_setup_events (gklass);
2282 if (gklass->exception_type) {
2283 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2284 mono_loader_unlock ();
2285 return;
2288 class->ext->event = gklass->ext->event;
2289 class->ext->events = mono_class_new0 (class, MonoEvent, class->ext->event.count);
2291 if (class->ext->event.count)
2292 context = mono_class_get_context (class);
2294 for (i = 0; i < class->ext->event.count; i++) {
2295 MonoEvent *event = &class->ext->events [i];
2296 MonoEvent *gevent = &gklass->ext->events [i];
2298 event->parent = class;
2299 event->name = gevent->name;
2300 event->add = gevent->add ? mono_class_inflate_generic_method_full (gevent->add, class, context) : NULL;
2301 event->remove = gevent->remove ? mono_class_inflate_generic_method_full (gevent->remove, class, context) : NULL;
2302 event->raise = gevent->raise ? mono_class_inflate_generic_method_full (gevent->raise, class, context) : NULL;
2303 #ifndef MONO_SMALL_CONFIG
2304 event->other = gevent->other ? inflate_method_listz (gevent->other, class, context) : NULL;
2305 #endif
2306 event->attrs = gevent->attrs;
2309 mono_loader_unlock ();
2310 return;
2313 first = mono_metadata_events_from_typedef (class->image, mono_metadata_token_index (class->type_token) - 1, &last);
2314 count = last - first;
2316 if (count) {
2317 mono_class_setup_methods (class);
2318 if (class->exception_type) {
2319 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
2320 mono_loader_unlock ();
2321 return;
2324 class->ext->event.first = first;
2325 class->ext->event.count = count;
2326 events = mono_class_alloc0 (class, sizeof (MonoEvent) * class->ext->event.count);
2327 for (i = first; i < last; ++i) {
2328 MonoEvent *event = &events [i - first];
2330 mono_metadata_decode_table_row (class->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
2331 event->parent = class;
2332 event->attrs = cols [MONO_EVENT_FLAGS];
2333 event->name = mono_metadata_string_heap (class->image, cols [MONO_EVENT_NAME]);
2335 startm = mono_metadata_methods_from_event (class->image, i, &endm);
2336 for (j = startm; j < endm; ++j) {
2337 MonoMethod *method;
2339 mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
2341 if (class->image->uncompressed_metadata)
2342 /* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
2343 method = mono_get_method (class->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], class);
2344 else
2345 method = class->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - class->method.first];
2347 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
2348 case METHOD_SEMANTIC_ADD_ON:
2349 event->add = method;
2350 break;
2351 case METHOD_SEMANTIC_REMOVE_ON:
2352 event->remove = method;
2353 break;
2354 case METHOD_SEMANTIC_FIRE:
2355 event->raise = method;
2356 break;
2357 case METHOD_SEMANTIC_OTHER: {
2358 #ifndef MONO_SMALL_CONFIG
2359 int n = 0;
2361 if (event->other == NULL) {
2362 event->other = g_new0 (MonoMethod*, 2);
2363 } else {
2364 while (event->other [n])
2365 n++;
2366 event->other = g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
2368 event->other [n] = method;
2369 /* NULL terminated */
2370 event->other [n + 1] = NULL;
2371 #endif
2372 break;
2374 default:
2375 break;
2379 /*Flush any pending writes as we do double checked locking on class->properties */
2380 mono_memory_barrier ();
2382 /* Leave this assignment as the last op in the function */
2383 class->ext->events = events;
2385 mono_loader_unlock ();
2389 * Global pool of interface IDs, represented as a bitset.
2390 * LOCKING: this is supposed to be accessed with the loader lock held.
2392 static MonoBitSet *global_interface_bitset = NULL;
2395 * mono_unload_interface_ids:
2396 * @bitset: bit set of interface IDs
2398 * When an image is unloaded, the interface IDs associated with
2399 * the image are put back in the global pool of IDs so the numbers
2400 * can be reused.
2402 void
2403 mono_unload_interface_ids (MonoBitSet *bitset)
2405 mono_loader_lock ();
2406 mono_bitset_sub (global_interface_bitset, bitset);
2407 mono_loader_unlock ();
2410 void
2411 mono_unload_interface_id (MonoClass *class)
2413 if (class->interface_id) {
2414 mono_loader_lock ();
2415 mono_bitset_clear (global_interface_bitset, class->interface_id);
2416 mono_loader_unlock ();
2421 * mono_get_unique_iid:
2422 * @class: interface
2424 * Assign a unique integer ID to the interface represented by @class.
2425 * The ID will positive and as small as possible.
2426 * LOCKING: this is supposed to be called with the loader lock held.
2427 * Returns: the new ID.
2429 static guint
2430 mono_get_unique_iid (MonoClass *class)
2432 int iid;
2434 g_assert (MONO_CLASS_IS_INTERFACE (class));
2436 if (!global_interface_bitset) {
2437 global_interface_bitset = mono_bitset_new (128, 0);
2440 iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
2441 if (iid < 0) {
2442 int old_size = mono_bitset_size (global_interface_bitset);
2443 MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
2444 mono_bitset_free (global_interface_bitset);
2445 global_interface_bitset = new_set;
2446 iid = old_size;
2448 mono_bitset_set (global_interface_bitset, iid);
2449 /* set the bit also in the per-image set */
2450 if (!class->generic_class) {
2451 if (class->image->interface_bitset) {
2452 if (iid >= mono_bitset_size (class->image->interface_bitset)) {
2453 MonoBitSet *new_set = mono_bitset_clone (class->image->interface_bitset, iid + 1);
2454 mono_bitset_free (class->image->interface_bitset);
2455 class->image->interface_bitset = new_set;
2457 } else {
2458 class->image->interface_bitset = mono_bitset_new (iid + 1, 0);
2460 mono_bitset_set (class->image->interface_bitset, iid);
2463 #ifndef MONO_SMALL_CONFIG
2464 if (mono_print_vtable) {
2465 int generic_id;
2466 char *type_name = mono_type_full_name (&class->byval_arg);
2467 if (class->generic_class && !class->generic_class->context.class_inst->is_open) {
2468 generic_id = class->generic_class->context.class_inst->id;
2469 g_assert (generic_id != 0);
2470 } else {
2471 generic_id = 0;
2473 printf ("Interface: assigned id %d to %s|%s|%d\n", iid, class->image->name, type_name, generic_id);
2474 g_free (type_name);
2476 #endif
2478 g_assert (iid <= 65535);
2479 return iid;
2482 static void
2483 collect_implemented_interfaces_aux (MonoClass *klass, GPtrArray **res, MonoError *error)
2485 int i;
2486 MonoClass *ic;
2488 mono_class_setup_interfaces (klass, error);
2489 if (!mono_error_ok (error))
2490 return;
2492 for (i = 0; i < klass->interface_count; i++) {
2493 ic = klass->interfaces [i];
2495 if (*res == NULL)
2496 *res = g_ptr_array_new ();
2497 g_ptr_array_add (*res, ic);
2498 mono_class_init (ic);
2499 if (ic->exception_type) {
2500 mono_error_set_type_load_class (error, ic, "Error Loading class");
2501 return;
2504 collect_implemented_interfaces_aux (ic, res, error);
2505 if (!mono_error_ok (error))
2506 return;
2510 GPtrArray*
2511 mono_class_get_implemented_interfaces (MonoClass *klass, MonoError *error)
2513 GPtrArray *res = NULL;
2515 collect_implemented_interfaces_aux (klass, &res, error);
2516 if (!mono_error_ok (error)) {
2517 if (res)
2518 g_ptr_array_free (res, TRUE);
2519 return NULL;
2521 return res;
2524 static int
2525 compare_interface_ids (const void *p_key, const void *p_element) {
2526 const MonoClass *key = p_key;
2527 const MonoClass *element = *(MonoClass**) p_element;
2529 return (key->interface_id - element->interface_id);
2532 /*FIXME verify all callers if they should switch to mono_class_interface_offset_with_variance*/
2534 mono_class_interface_offset (MonoClass *klass, MonoClass *itf) {
2535 MonoClass **result = bsearch (
2536 itf,
2537 klass->interfaces_packed,
2538 klass->interface_offsets_count,
2539 sizeof (MonoClass *),
2540 compare_interface_ids);
2541 if (result) {
2542 return klass->interface_offsets_packed [result - (klass->interfaces_packed)];
2543 } else {
2544 return -1;
2549 * mono_class_interface_offset_with_variance:
2551 * Return the interface offset of @itf in @klass. Sets @non_exact_match to TRUE if the match required variance check
2552 * If @itf is an interface with generic variant arguments, try to find the compatible one.
2554 * Note that this function is responsible for resolving ambiguities. Right now we use whatever ordering interfaces_packed gives us.
2556 * FIXME figure out MS disambiguation rules and fix this function.
2559 mono_class_interface_offset_with_variance (MonoClass *klass, MonoClass *itf, gboolean *non_exact_match) {
2560 int i = mono_class_interface_offset (klass, itf);
2561 *non_exact_match = FALSE;
2562 if (i >= 0)
2563 return i;
2565 if (!mono_class_has_variant_generic_params (itf))
2566 return -1;
2568 for (i = 0; i < klass->interface_offsets_count; i++) {
2569 if (mono_class_is_variant_compatible (itf, klass->interfaces_packed [i])) {
2570 *non_exact_match = TRUE;
2571 return klass->interface_offsets_packed [i];
2575 return -1;
2578 static void
2579 print_implemented_interfaces (MonoClass *klass) {
2580 char *name;
2581 MonoError error;
2582 GPtrArray *ifaces = NULL;
2583 int i;
2584 int ancestor_level = 0;
2586 name = mono_type_get_full_name (klass);
2587 printf ("Packed interface table for class %s has size %d\n", name, klass->interface_offsets_count);
2588 g_free (name);
2590 for (i = 0; i < klass->interface_offsets_count; i++)
2591 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2592 klass->interfaces_packed [i]->interface_id,
2593 klass->interface_offsets_packed [i],
2594 klass->interfaces_packed [i]->method.count,
2595 klass->interfaces_packed [i]->name_space,
2596 klass->interfaces_packed [i]->name );
2597 printf ("Interface flags: ");
2598 for (i = 0; i <= klass->max_interface_id; i++)
2599 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, i))
2600 printf ("(%d,T)", i);
2601 else
2602 printf ("(%d,F)", i);
2603 printf ("\n");
2604 printf ("Dump interface flags:");
2605 #ifdef COMPRESSED_INTERFACE_BITMAP
2607 const uint8_t* p = klass->interface_bitmap;
2608 i = klass->max_interface_id;
2609 while (i > 0) {
2610 printf (" %d x 00 %02X", p [0], p [1]);
2611 i -= p [0] * 8;
2612 i -= 8;
2615 #else
2616 for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
2617 printf (" %02X", klass->interface_bitmap [i]);
2618 #endif
2619 printf ("\n");
2620 while (klass != NULL) {
2621 printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
2622 ifaces = mono_class_get_implemented_interfaces (klass, &error);
2623 if (!mono_error_ok (&error)) {
2624 printf (" Type failed due to %s\n", mono_error_get_message (&error));
2625 mono_error_cleanup (&error);
2626 } else if (ifaces) {
2627 for (i = 0; i < ifaces->len; i++) {
2628 MonoClass *ic = g_ptr_array_index (ifaces, i);
2629 printf (" [UIID %d] interface %s\n", ic->interface_id, ic->name);
2630 printf (" [%03d][UUID %03d][SLOT %03d][SIZE %03d] interface %s.%s\n", i,
2631 ic->interface_id,
2632 mono_class_interface_offset (klass, ic),
2633 ic->method.count,
2634 ic->name_space,
2635 ic->name );
2637 g_ptr_array_free (ifaces, TRUE);
2639 ancestor_level ++;
2640 klass = klass->parent;
2644 static MonoClass*
2645 inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
2647 MonoType *args [1];
2648 args [0] = &arg0->byval_arg;
2650 return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
2653 static MonoClass*
2654 array_class_get_if_rank (MonoClass *class, guint rank)
2656 return rank ? mono_array_class_get (class, rank) : class;
2659 static void
2660 fill_valuetype_array_derived_types (MonoClass **valuetype_types, MonoClass *eclass, int rank)
2662 valuetype_types [0] = eclass;
2663 if (eclass == mono_defaults.int16_class)
2664 valuetype_types [1] = mono_defaults.uint16_class;
2665 else if (eclass == mono_defaults.uint16_class)
2666 valuetype_types [1] = mono_defaults.int16_class;
2667 else if (eclass == mono_defaults.int32_class)
2668 valuetype_types [1] = mono_defaults.uint32_class;
2669 else if (eclass == mono_defaults.uint32_class)
2670 valuetype_types [1] = mono_defaults.int32_class;
2671 else if (eclass == mono_defaults.int64_class)
2672 valuetype_types [1] = mono_defaults.uint64_class;
2673 else if (eclass == mono_defaults.uint64_class)
2674 valuetype_types [1] = mono_defaults.int64_class;
2675 else if (eclass == mono_defaults.byte_class)
2676 valuetype_types [1] = mono_defaults.sbyte_class;
2677 else if (eclass == mono_defaults.sbyte_class)
2678 valuetype_types [1] = mono_defaults.byte_class;
2679 else if (eclass->enumtype && mono_class_enum_basetype (eclass))
2680 valuetype_types [1] = mono_class_from_mono_type (mono_class_enum_basetype (eclass));
2683 /* this won't be needed once bug #325495 is completely fixed
2684 * though we'll need something similar to know which interfaces to allow
2685 * in arrays when they'll be lazyly created
2687 * FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
2688 * MS returns diferrent types based on which instance is called. For example:
2689 * object obj = new byte[10][];
2690 * Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
2691 * Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
2692 * a != b ==> true
2694 * Fixing this should kill quite some code, save some bits and improve compatibility.
2696 static MonoClass**
2697 get_implicit_generic_array_interfaces (MonoClass *class, int *num, int *is_enumerator)
2699 MonoClass *eclass = class->element_class;
2700 static MonoClass* generic_icollection_class = NULL;
2701 static MonoClass* generic_ienumerable_class = NULL;
2702 static MonoClass* generic_ienumerator_class = NULL;
2703 MonoClass *valuetype_types[2] = { NULL, NULL };
2704 MonoClass **interfaces = NULL;
2705 int i, interface_count, real_count, original_rank;
2706 int all_interfaces;
2707 gboolean internal_enumerator;
2708 gboolean eclass_is_valuetype;
2710 if (!mono_defaults.generic_ilist_class) {
2711 *num = 0;
2712 return NULL;
2714 internal_enumerator = FALSE;
2715 eclass_is_valuetype = FALSE;
2716 original_rank = eclass->rank;
2717 if (class->byval_arg.type != MONO_TYPE_SZARRAY) {
2718 if (class->generic_class && class->nested_in == mono_defaults.array_class && strcmp (class->name, "InternalEnumerator`1") == 0) {
2720 * For a Enumerator<T[]> we need to get the list of interfaces for T.
2722 eclass = mono_class_from_mono_type (class->generic_class->context.class_inst->type_argv [0]);
2723 original_rank = eclass->rank;
2724 eclass = eclass->element_class;
2725 internal_enumerator = TRUE;
2726 *is_enumerator = TRUE;
2727 } else {
2728 *num = 0;
2729 return NULL;
2734 * with this non-lazy impl we can't implement all the interfaces so we do just the minimal stuff
2735 * for deep levels of arrays of arrays (string[][] has all the interfaces, string[][][] doesn't)
2737 all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE;
2739 if (!generic_icollection_class) {
2740 generic_icollection_class = mono_class_from_name (mono_defaults.corlib,
2741 "System.Collections.Generic", "ICollection`1");
2742 generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib,
2743 "System.Collections.Generic", "IEnumerable`1");
2744 generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib,
2745 "System.Collections.Generic", "IEnumerator`1");
2748 mono_class_init (eclass);
2751 * Arrays in 2.0 need to implement a number of generic interfaces
2752 * (IList`1, ICollection`1, IEnumerable`1 for a number of types depending
2753 * on the element class). We collect the types needed to build the
2754 * instantiations in interfaces at intervals of 3, because 3 are
2755 * the generic interfaces needed to implement.
2757 if (eclass->valuetype) {
2758 fill_valuetype_array_derived_types (valuetype_types, eclass, original_rank);
2760 /* IList, ICollection, IEnumerable */
2761 real_count = interface_count = valuetype_types [1] ? 6 : 3;
2762 if (internal_enumerator) {
2763 ++real_count;
2764 if (valuetype_types [1])
2765 ++real_count;
2768 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2769 interfaces [0] = valuetype_types [0];
2770 if (valuetype_types [1])
2771 interfaces [3] = valuetype_types [1];
2773 eclass_is_valuetype = TRUE;
2774 } else {
2775 int j;
2776 int idepth = eclass->idepth;
2777 if (!internal_enumerator)
2778 idepth--;
2780 // FIXME: This doesn't seem to work/required for generic params
2781 if (!(eclass->this_arg.type == MONO_TYPE_VAR || eclass->this_arg.type == MONO_TYPE_MVAR || (eclass->image->dynamic && !eclass->wastypebuilder)))
2782 mono_class_setup_interface_offsets (eclass);
2784 interface_count = all_interfaces? eclass->interface_offsets_count: eclass->interface_count;
2785 /* we add object for interfaces and the supertypes for the other
2786 * types. The last of the supertypes is the element class itself which we
2787 * already created the explicit interfaces for (so we include it for IEnumerator
2788 * and exclude it for arrays).
2790 if (MONO_CLASS_IS_INTERFACE (eclass))
2791 interface_count++;
2792 else
2793 interface_count += idepth;
2794 if (eclass->rank && eclass->element_class->valuetype) {
2795 fill_valuetype_array_derived_types (valuetype_types, eclass->element_class, original_rank);
2796 if (valuetype_types [1])
2797 ++interface_count;
2799 /* IList, ICollection, IEnumerable */
2800 interface_count *= 3;
2801 real_count = interface_count;
2802 if (internal_enumerator) {
2803 real_count += (MONO_CLASS_IS_INTERFACE (eclass) ? 1 : idepth) + eclass->interface_offsets_count;
2804 if (valuetype_types [1])
2805 ++real_count;
2807 interfaces = g_malloc0 (sizeof (MonoClass*) * real_count);
2808 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2809 interfaces [0] = mono_defaults.object_class;
2810 j = 3;
2811 } else {
2812 j = 0;
2813 for (i = 0; i < idepth; i++) {
2814 mono_class_init (eclass->supertypes [i]);
2815 interfaces [j] = eclass->supertypes [i];
2816 j += 3;
2819 if (all_interfaces) {
2820 for (i = 0; i < eclass->interface_offsets_count; i++) {
2821 interfaces [j] = eclass->interfaces_packed [i];
2822 j += 3;
2824 } else {
2825 for (i = 0; i < eclass->interface_count; i++) {
2826 interfaces [j] = eclass->interfaces [i];
2827 j += 3;
2830 if (valuetype_types [1]) {
2831 interfaces [j] = array_class_get_if_rank (valuetype_types [1], original_rank);
2832 j += 3;
2836 /* instantiate the generic interfaces */
2837 for (i = 0; i < interface_count; i += 3) {
2838 MonoClass *iface = interfaces [i];
2840 interfaces [i + 0] = inflate_class_one_arg (mono_defaults.generic_ilist_class, iface);
2841 interfaces [i + 1] = inflate_class_one_arg (generic_icollection_class, iface);
2842 interfaces [i + 2] = inflate_class_one_arg (generic_ienumerable_class, iface);
2844 if (internal_enumerator) {
2845 int j;
2846 /* instantiate IEnumerator<iface> */
2847 for (i = 0; i < interface_count; i++) {
2848 interfaces [i] = inflate_class_one_arg (generic_ienumerator_class, interfaces [i]);
2850 j = interface_count;
2851 if (!eclass_is_valuetype) {
2852 if (MONO_CLASS_IS_INTERFACE (eclass)) {
2853 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, mono_defaults.object_class);
2854 j ++;
2855 } else {
2856 for (i = 0; i < eclass->idepth; i++) {
2857 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->supertypes [i]);
2858 j ++;
2861 for (i = 0; i < eclass->interface_offsets_count; i++) {
2862 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, eclass->interfaces_packed [i]);
2863 j ++;
2865 } else {
2866 interfaces [j++] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [0], original_rank));
2868 if (valuetype_types [1])
2869 interfaces [j] = inflate_class_one_arg (generic_ienumerator_class, array_class_get_if_rank (valuetype_types [1], original_rank));
2871 #if 0
2873 char *type_name = mono_type_get_name_full (&class->byval_arg, 0);
2874 for (i = 0; i < real_count; ++i) {
2875 char *name = mono_type_get_name_full (&interfaces [i]->byval_arg, 0);
2876 g_print ("%s implements %s\n", type_name, name);
2877 g_free (name);
2879 g_free (type_name);
2881 #endif
2882 *num = real_count;
2883 return interfaces;
2886 static int
2887 find_array_interface (MonoClass *klass, const char *name)
2889 int i;
2890 for (i = 0; i < klass->interface_count; ++i) {
2891 if (strcmp (klass->interfaces [i]->name, name) == 0)
2892 return i;
2894 return -1;
2898 * Return the number of virtual methods.
2899 * Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
2900 * Return -1 on failure.
2901 * FIXME It would be nice if this information could be cached somewhere.
2903 static int
2904 count_virtual_methods (MonoClass *class)
2906 int i, count = 0;
2907 guint32 flags;
2908 class = mono_class_get_generic_type_definition (class); /*We can find this information by looking at the GTD*/
2910 if (class->methods || !MONO_CLASS_HAS_STATIC_METADATA (class)) {
2911 mono_class_setup_methods (class);
2912 if (class->exception_type)
2913 return -1;
2915 for (i = 0; i < class->method.count; ++i) {
2916 flags = class->methods [i]->flags;
2917 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2918 ++count;
2920 } else {
2921 for (i = 0; i < class->method.count; ++i) {
2922 flags = mono_metadata_decode_table_row_col (class->image, MONO_TABLE_METHOD, class->method.first + i, MONO_METHOD_FLAGS);
2924 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
2925 ++count;
2928 return count;
2931 static int
2932 find_interface (int num_ifaces, MonoClass **interfaces_full, MonoClass *ic)
2934 int m, l = 0;
2935 if (!num_ifaces)
2936 return -1;
2937 while (1) {
2938 if (l > num_ifaces)
2939 return -1;
2940 m = (l + num_ifaces) / 2;
2941 if (interfaces_full [m] == ic)
2942 return m;
2943 if (l == num_ifaces)
2944 return -1;
2945 if (!interfaces_full [m] || interfaces_full [m]->interface_id > ic->interface_id) {
2946 num_ifaces = m - 1;
2947 } else {
2948 l = m + 1;
2953 static int
2954 find_interface_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic)
2956 int i = find_interface (num_ifaces, interfaces_full, ic);
2957 if (ic >= 0)
2958 return interface_offsets_full [i];
2959 return -1;
2962 static mono_bool
2963 set_interface_and_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic, int offset, mono_bool force_set)
2965 int i = find_interface (num_ifaces, interfaces_full, ic);
2966 if (i >= 0) {
2967 if (!force_set)
2968 return TRUE;
2969 interface_offsets_full [i] = offset;
2970 return FALSE;
2972 for (i = 0; i < num_ifaces; ++i) {
2973 if (interfaces_full [i]) {
2974 int end;
2975 if (interfaces_full [i]->interface_id < ic->interface_id)
2976 continue;
2977 end = i + 1;
2978 while (end < num_ifaces && interfaces_full [end]) end++;
2979 memmove (interfaces_full + i + 1, interfaces_full + i, sizeof (MonoClass*) * (end - i));
2980 memmove (interface_offsets_full + i + 1, interface_offsets_full + i, sizeof (int) * (end - i));
2982 interfaces_full [i] = ic;
2983 interface_offsets_full [i] = offset;
2984 break;
2986 return FALSE;
2989 #ifdef COMPRESSED_INTERFACE_BITMAP
2992 * Compressed interface bitmap design.
2994 * Interface bitmaps take a large amount of memory, because their size is
2995 * linear with the maximum interface id assigned in the process (each interface
2996 * is assigned a unique id as it is loaded). The number of interface classes
2997 * is high because of the many implicit interfaces implemented by arrays (we'll
2998 * need to lazy-load them in the future).
2999 * Most classes implement a very small number of interfaces, so the bitmap is
3000 * sparse. This bitmap needs to be checked by interface casts, so access to the
3001 * needed bit must be fast and doable with few jit instructions.
3003 * The current compression format is as follows:
3004 * *) it is a sequence of one or more two-byte elements
3005 * *) the first byte in the element is the count of empty bitmap bytes
3006 * at the current bitmap position
3007 * *) the second byte in the element is an actual bitmap byte at the current
3008 * bitmap position
3010 * As an example, the following compressed bitmap bytes:
3011 * 0x07 0x01 0x00 0x7
3012 * correspond to the following bitmap:
3013 * 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x07
3015 * Each two-byte element can represent up to 2048 bitmap bits, but as few as a single
3016 * bitmap byte for non-sparse sequences. In practice the interface bitmaps created
3017 * during a gmcs bootstrap are reduced to less tha 5% of the original size.
3021 * mono_compress_bitmap:
3022 * @dest: destination buffer
3023 * @bitmap: bitmap buffer
3024 * @size: size of @bitmap in bytes
3026 * This is a mono internal function.
3027 * The @bitmap data is compressed into a format that is small but
3028 * still searchable in few instructions by the JIT and runtime.
3029 * The compressed data is stored in the buffer pointed to by the
3030 * @dest array. Passing a #NULL value for @dest allows to just compute
3031 * the size of the buffer.
3032 * This compression algorithm assumes the bits set in the bitmap are
3033 * few and far between, like in interface bitmaps.
3034 * Returns: the size of the compressed bitmap in bytes.
3037 mono_compress_bitmap (uint8_t *dest, const uint8_t *bitmap, int size)
3039 int numz = 0;
3040 int res = 0;
3041 const uint8_t *end = bitmap + size;
3042 while (bitmap < end) {
3043 if (*bitmap || numz == 255) {
3044 if (dest) {
3045 *dest++ = numz;
3046 *dest++ = *bitmap;
3048 res += 2;
3049 numz = 0;
3050 bitmap++;
3051 continue;
3053 bitmap++;
3054 numz++;
3056 if (numz) {
3057 res += 2;
3058 if (dest) {
3059 *dest++ = numz;
3060 *dest++ = 0;
3063 return res;
3067 * mono_class_interface_match:
3068 * @bitmap: a compressed bitmap buffer
3069 * @id: the index to check in the bitmap
3071 * This is a mono internal function.
3072 * Checks if a bit is set in a compressed interface bitmap. @id must
3073 * be already checked for being smaller than the maximum id encoded in the
3074 * bitmap.
3076 * Returns: a non-zero value if bit @id is set in the bitmap @bitmap,
3077 * #FALSE otherwise.
3080 mono_class_interface_match (const uint8_t *bitmap, int id)
3082 while (TRUE) {
3083 id -= bitmap [0] * 8;
3084 if (id < 8) {
3085 if (id < 0)
3086 return 0;
3087 return bitmap [1] & (1 << id);
3089 bitmap += 2;
3090 id -= 8;
3093 #endif
3096 * LOCKING: this is supposed to be called with the loader lock held.
3097 * Return -1 on failure and set exception_type
3099 static int
3100 setup_interface_offsets (MonoClass *class, int cur_slot)
3102 MonoError error;
3103 MonoClass *k, *ic;
3104 int i, j, max_iid, num_ifaces;
3105 MonoClass **interfaces_full = NULL;
3106 int *interface_offsets_full = NULL;
3107 GPtrArray *ifaces;
3108 GPtrArray **ifaces_array = NULL;
3109 int interface_offsets_count;
3110 MonoClass **array_interfaces = NULL;
3111 int num_array_interfaces;
3112 int is_enumerator = FALSE;
3114 mono_class_setup_supertypes (class);
3116 * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
3117 * implicit interfaces have the property that they are assigned the same slot in the
3118 * vtables for compatible interfaces
3120 array_interfaces = get_implicit_generic_array_interfaces (class, &num_array_interfaces, &is_enumerator);
3122 /* compute maximum number of slots and maximum interface id */
3123 max_iid = 0;
3124 num_ifaces = num_array_interfaces; /* this can include duplicated ones */
3125 ifaces_array = g_new0 (GPtrArray *, class->idepth);
3126 for (j = 0; j < class->idepth; j++) {
3127 k = class->supertypes [j];
3128 num_ifaces += k->interface_count;
3129 for (i = 0; i < k->interface_count; i++) {
3130 ic = k->interfaces [i];
3132 if (!ic->inited)
3133 mono_class_init (ic);
3135 if (max_iid < ic->interface_id)
3136 max_iid = ic->interface_id;
3138 ifaces = mono_class_get_implemented_interfaces (k, &error);
3139 if (!mono_error_ok (&error)) {
3140 char *name = mono_type_get_full_name (k);
3141 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)));
3142 g_free (name);
3143 mono_error_cleanup (&error);
3144 cur_slot = -1;
3145 goto end;
3147 if (ifaces) {
3148 num_ifaces += ifaces->len;
3149 for (i = 0; i < ifaces->len; ++i) {
3150 ic = g_ptr_array_index (ifaces, i);
3151 if (max_iid < ic->interface_id)
3152 max_iid = ic->interface_id;
3154 ifaces_array [j] = ifaces;
3158 for (i = 0; i < num_array_interfaces; ++i) {
3159 ic = array_interfaces [i];
3160 mono_class_init (ic);
3161 if (max_iid < ic->interface_id)
3162 max_iid = ic->interface_id;
3165 if (MONO_CLASS_IS_INTERFACE (class)) {
3166 num_ifaces++;
3167 if (max_iid < class->interface_id)
3168 max_iid = class->interface_id;
3170 class->max_interface_id = max_iid;
3171 /* compute vtable offset for interfaces */
3172 interfaces_full = g_malloc0 (sizeof (MonoClass*) * num_ifaces);
3173 interface_offsets_full = g_malloc (sizeof (int) * num_ifaces);
3175 for (i = 0; i < num_ifaces; i++) {
3176 interface_offsets_full [i] = -1;
3179 /* skip the current class */
3180 for (j = 0; j < class->idepth - 1; j++) {
3181 k = class->supertypes [j];
3182 ifaces = ifaces_array [j];
3184 if (ifaces) {
3185 for (i = 0; i < ifaces->len; ++i) {
3186 int io;
3187 ic = g_ptr_array_index (ifaces, i);
3189 /*Force the sharing of interface offsets between parent and subtypes.*/
3190 io = mono_class_interface_offset (k, ic);
3191 g_assert (io >= 0);
3192 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, io, TRUE);
3197 g_assert (class == class->supertypes [class->idepth - 1]);
3198 ifaces = ifaces_array [class->idepth - 1];
3199 if (ifaces) {
3200 for (i = 0; i < ifaces->len; ++i) {
3201 int count;
3202 ic = g_ptr_array_index (ifaces, i);
3203 if (set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, cur_slot, FALSE))
3204 continue;
3205 count = count_virtual_methods (ic);
3206 if (count == -1) {
3207 char *name = mono_type_get_full_name (ic);
3208 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Error calculating interface offset of %s", name));
3209 g_free (name);
3210 cur_slot = -1;
3211 goto end;
3213 cur_slot += count;
3217 if (MONO_CLASS_IS_INTERFACE (class))
3218 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, class, cur_slot, TRUE);
3220 if (num_array_interfaces) {
3221 if (is_enumerator) {
3222 int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
3223 int ienumerator_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ienumerator_idx]);
3224 g_assert (ienumerator_offset >= 0);
3225 for (i = 0; i < num_array_interfaces; ++i) {
3226 ic = array_interfaces [i];
3227 if (strcmp (ic->name, "IEnumerator`1") == 0)
3228 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, ienumerator_offset, TRUE);
3229 else
3230 g_assert_not_reached ();
3231 /*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);*/
3233 } else {
3234 int ilist_offset, icollection_offset, ienumerable_offset;
3235 int ilist_iface_idx = find_array_interface (class, "IList`1");
3236 MonoClass* ilist_class = class->interfaces [ilist_iface_idx];
3237 int icollection_iface_idx = find_array_interface (ilist_class, "ICollection`1");
3238 int ienumerable_iface_idx = find_array_interface (ilist_class, "IEnumerable`1");
3239 ilist_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ilist_iface_idx]);
3240 icollection_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [icollection_iface_idx]);
3241 ienumerable_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [ienumerable_iface_idx]);
3242 g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
3243 for (i = 0; i < num_array_interfaces; ++i) {
3244 int offset;
3245 ic = array_interfaces [i];
3246 if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
3247 offset = ilist_offset;
3248 else if (strcmp (ic->name, "ICollection`1") == 0)
3249 offset = icollection_offset;
3250 else if (strcmp (ic->name, "IEnumerable`1") == 0)
3251 offset = ienumerable_offset;
3252 else
3253 g_assert_not_reached ();
3254 set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, offset, TRUE);
3255 /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, offset, class->interfaces [0]->name);*/
3260 for (interface_offsets_count = 0, i = 0; i < num_ifaces; i++) {
3261 if (interface_offsets_full [i] != -1) {
3262 interface_offsets_count ++;
3267 * We might get called twice: once from mono_class_init () then once from
3268 * mono_class_setup_vtable ().
3270 if (class->interfaces_packed) {
3271 g_assert (class->interface_offsets_count == interface_offsets_count);
3272 } else {
3273 uint8_t *bitmap;
3274 int bsize;
3275 class->interface_offsets_count = interface_offsets_count;
3276 class->interfaces_packed = mono_class_alloc (class, sizeof (MonoClass*) * interface_offsets_count);
3277 class->interface_offsets_packed = mono_class_alloc (class, sizeof (guint16) * interface_offsets_count);
3278 bsize = (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0);
3279 #ifdef COMPRESSED_INTERFACE_BITMAP
3280 bitmap = g_malloc0 (bsize);
3281 #else
3282 bitmap = mono_class_alloc0 (class, bsize);
3283 #endif
3284 for (i = 0; i < interface_offsets_count; i++) {
3285 int id = interfaces_full [i]->interface_id;
3286 bitmap [id >> 3] |= (1 << (id & 7));
3287 class->interfaces_packed [i] = interfaces_full [i];
3288 class->interface_offsets_packed [i] = interface_offsets_full [i];
3289 /*if (num_array_interfaces)
3290 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]);*/
3292 #ifdef COMPRESSED_INTERFACE_BITMAP
3293 i = mono_compress_bitmap (NULL, bitmap, bsize);
3294 class->interface_bitmap = mono_class_alloc0 (class, i);
3295 mono_compress_bitmap (class->interface_bitmap, bitmap, bsize);
3296 g_free (bitmap);
3297 #else
3298 class->interface_bitmap = bitmap;
3299 #endif
3302 end:
3303 g_free (interfaces_full);
3304 g_free (interface_offsets_full);
3305 g_free (array_interfaces);
3306 for (i = 0; i < class->idepth; i++) {
3307 ifaces = ifaces_array [i];
3308 if (ifaces)
3309 g_ptr_array_free (ifaces, TRUE);
3311 g_free (ifaces_array);
3313 //printf ("JUST DONE: ");
3314 //print_implemented_interfaces (class);
3316 return cur_slot;
3320 * Setup interface offsets for interfaces.
3321 * Initializes:
3322 * - class->max_interface_id
3323 * - class->interface_offsets_count
3324 * - class->interfaces_packed
3325 * - class->interface_offsets_packed
3326 * - class->interface_bitmap
3328 * This function can fail @class.
3330 void
3331 mono_class_setup_interface_offsets (MonoClass *class)
3333 mono_loader_lock ();
3335 setup_interface_offsets (class, 0);
3337 mono_loader_unlock ();
3340 /*Checks if @klass has @parent as one of it's parents type gtd
3342 * For example:
3343 * Foo<T>
3344 * Bar<T> : Foo<Bar<Bar<T>>>
3347 static gboolean
3348 mono_class_has_gtd_parent (MonoClass *klass, MonoClass *parent)
3350 klass = mono_class_get_generic_type_definition (klass);
3351 parent = mono_class_get_generic_type_definition (parent);
3352 mono_class_setup_supertypes (klass);
3353 mono_class_setup_supertypes (parent);
3355 return klass->idepth >= parent->idepth &&
3356 mono_class_get_generic_type_definition (klass->supertypes [parent->idepth - 1]) == parent;
3359 gboolean
3360 mono_class_check_vtable_constraints (MonoClass *class, GList *in_setup)
3362 MonoGenericInst *ginst;
3363 int i;
3364 if (!class->generic_class) {
3365 mono_class_setup_vtable_full (class, in_setup);
3366 return class->exception_type == 0;
3369 mono_class_setup_vtable_full (mono_class_get_generic_type_definition (class), in_setup);
3370 if (class->generic_class->container_class->exception_type) {
3371 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Failed to load generic definition vtable"));
3372 return FALSE;
3375 ginst = class->generic_class->context.class_inst;
3376 for (i = 0; i < ginst->type_argc; ++i) {
3377 MonoClass *arg;
3378 if (ginst->type_argv [i]->type != MONO_TYPE_GENERICINST)
3379 continue;
3380 arg = mono_class_from_mono_type (ginst->type_argv [i]);
3381 /*Those 2 will be checked by mono_class_setup_vtable itself*/
3382 if (mono_class_has_gtd_parent (class, arg) || mono_class_has_gtd_parent (arg, class))
3383 continue;
3384 if (!mono_class_check_vtable_constraints (arg, in_setup)) {
3385 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Failed to load generic parameter %d", i));
3386 return FALSE;
3389 return TRUE;
3393 * mono_class_setup_vtable:
3395 * Creates the generic vtable of CLASS.
3396 * Initializes the following fields in MonoClass:
3397 * - vtable
3398 * - vtable_size
3399 * Plus all the fields initialized by setup_interface_offsets ().
3400 * If there is an error during vtable construction, class->exception_type is set.
3402 * LOCKING: Acquires the loader lock.
3404 void
3405 mono_class_setup_vtable (MonoClass *class)
3407 mono_class_setup_vtable_full (class, NULL);
3410 static void
3411 mono_class_setup_vtable_full (MonoClass *class, GList *in_setup)
3413 MonoMethod **overrides;
3414 MonoGenericContext *context;
3415 guint32 type_token;
3416 int onum = 0;
3417 gboolean ok = TRUE;
3419 if (class->vtable)
3420 return;
3422 if (mono_debug_using_mono_debugger ())
3423 /* The debugger currently depends on this */
3424 mono_class_setup_methods (class);
3426 if (MONO_CLASS_IS_INTERFACE (class)) {
3427 /* This sets method->slot for all methods if this is an interface */
3428 mono_class_setup_methods (class);
3429 return;
3432 if (class->exception_type)
3433 return;
3435 if (g_list_find (in_setup, class))
3436 return;
3438 mono_loader_lock ();
3440 if (class->vtable) {
3441 mono_loader_unlock ();
3442 return;
3445 mono_stats.generic_vtable_count ++;
3446 in_setup = g_list_prepend (in_setup, class);
3448 if (class->generic_class) {
3449 if (!mono_class_check_vtable_constraints (class, in_setup)) {
3450 mono_loader_unlock ();
3451 g_list_remove (in_setup, class);
3452 return;
3455 context = mono_class_get_context (class);
3456 type_token = class->generic_class->container_class->type_token;
3457 } else {
3458 context = (MonoGenericContext *) class->generic_container;
3459 type_token = class->type_token;
3462 if (class->image->dynamic) {
3463 /* Generic instances can have zero method overrides without causing any harm.
3464 * This is true since we don't do layout all over again for them, we simply inflate
3465 * the layout of the parent.
3467 mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
3468 } else {
3469 /* The following call fails if there are missing methods in the type */
3470 /* FIXME it's probably a good idea to avoid this for generic instances. */
3471 ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
3474 if (ok)
3475 mono_class_setup_vtable_general (class, overrides, onum, in_setup);
3476 else
3477 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load list of method overrides"));
3479 g_free (overrides);
3481 mono_loader_unlock ();
3482 g_list_remove (in_setup, class);
3484 return;
3487 #define DEBUG_INTERFACE_VTABLE_CODE 0
3488 #define TRACE_INTERFACE_VTABLE_CODE 0
3489 #define VERIFY_INTERFACE_VTABLE_CODE 0
3490 #define VTABLE_SELECTOR (1)
3492 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3493 #define DEBUG_INTERFACE_VTABLE(stmt) do {\
3494 if (!(VTABLE_SELECTOR)) break; \
3495 stmt;\
3496 } while (0)
3497 #else
3498 #define DEBUG_INTERFACE_VTABLE(stmt)
3499 #endif
3501 #if TRACE_INTERFACE_VTABLE_CODE
3502 #define TRACE_INTERFACE_VTABLE(stmt) do {\
3503 if (!(VTABLE_SELECTOR)) break; \
3504 stmt;\
3505 } while (0)
3506 #else
3507 #define TRACE_INTERFACE_VTABLE(stmt)
3508 #endif
3510 #if VERIFY_INTERFACE_VTABLE_CODE
3511 #define VERIFY_INTERFACE_VTABLE(stmt) do {\
3512 if (!(VTABLE_SELECTOR)) break; \
3513 stmt;\
3514 } while (0)
3515 #else
3516 #define VERIFY_INTERFACE_VTABLE(stmt)
3517 #endif
3520 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3521 static char*
3522 mono_signature_get_full_desc (MonoMethodSignature *sig, gboolean include_namespace)
3524 int i;
3525 char *result;
3526 GString *res = g_string_new ("");
3528 g_string_append_c (res, '(');
3529 for (i = 0; i < sig->param_count; ++i) {
3530 if (i > 0)
3531 g_string_append_c (res, ',');
3532 mono_type_get_desc (res, sig->params [i], include_namespace);
3534 g_string_append (res, ")=>");
3535 if (sig->ret != NULL) {
3536 mono_type_get_desc (res, sig->ret, include_namespace);
3537 } else {
3538 g_string_append (res, "NULL");
3540 result = res->str;
3541 g_string_free (res, FALSE);
3542 return result;
3544 static void
3545 print_method_signatures (MonoMethod *im, MonoMethod *cm) {
3546 char *im_sig = mono_signature_get_full_desc (mono_method_signature (im), TRUE);
3547 char *cm_sig = mono_signature_get_full_desc (mono_method_signature (cm), TRUE);
3548 printf ("(IM \"%s\", CM \"%s\")", im_sig, cm_sig);
3549 g_free (im_sig);
3550 g_free (cm_sig);
3554 #endif
3555 static gboolean
3556 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) {
3557 MonoMethodSignature *cmsig, *imsig;
3558 if (strcmp (im->name, cm->name) == 0) {
3559 if (! (cm->flags & METHOD_ATTRIBUTE_PUBLIC)) {
3560 TRACE_INTERFACE_VTABLE (printf ("[PUBLIC CHECK FAILED]"));
3561 return FALSE;
3563 if (! slot_is_empty) {
3564 if (require_newslot) {
3565 if (! interface_is_explicitly_implemented_by_class) {
3566 TRACE_INTERFACE_VTABLE (printf ("[NOT EXPLICIT IMPLEMENTATION IN FULL SLOT REFUSED]"));
3567 return FALSE;
3569 if (! (cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
3570 TRACE_INTERFACE_VTABLE (printf ("[NEWSLOT CHECK FAILED]"));
3571 return FALSE;
3573 } else {
3574 TRACE_INTERFACE_VTABLE (printf ("[FULL SLOT REFUSED]"));
3577 cmsig = mono_method_signature (cm);
3578 imsig = mono_method_signature (im);
3579 if (!cmsig || !imsig) {
3580 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not resolve the signature of a virtual method"));
3581 return FALSE;
3584 if (! mono_metadata_signature_equal (cmsig, imsig)) {
3585 TRACE_INTERFACE_VTABLE (printf ("[SIGNATURE CHECK FAILED "));
3586 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3587 TRACE_INTERFACE_VTABLE (printf ("]"));
3588 return FALSE;
3590 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS]"));
3591 /* CAS - SecurityAction.InheritanceDemand on interface */
3592 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3593 mono_secman_inheritancedemand_method (cm, im);
3596 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3597 mono_security_core_clr_check_override (class, cm, im);
3598 TRACE_INTERFACE_VTABLE (printf ("[NAME CHECK OK]"));
3599 return TRUE;
3600 } else {
3601 MonoClass *ic = im->klass;
3602 const char *ic_name_space = ic->name_space;
3603 const char *ic_name = ic->name;
3604 char *subname;
3606 if (! require_newslot) {
3607 TRACE_INTERFACE_VTABLE (printf ("[INJECTED METHOD REFUSED]"));
3608 return FALSE;
3610 if (cm->klass->rank == 0) {
3611 TRACE_INTERFACE_VTABLE (printf ("[RANK CHECK FAILED]"));
3612 return FALSE;
3614 cmsig = mono_method_signature (cm);
3615 imsig = mono_method_signature (im);
3616 if (!cmsig || !imsig) {
3617 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not resolve the signature of a virtual method"));
3618 return FALSE;
3621 if (! mono_metadata_signature_equal (cmsig, imsig)) {
3622 TRACE_INTERFACE_VTABLE (printf ("[(INJECTED) SIGNATURE CHECK FAILED "));
3623 TRACE_INTERFACE_VTABLE (print_method_signatures (im, cm));
3624 TRACE_INTERFACE_VTABLE (printf ("]"));
3625 return FALSE;
3627 if (mono_class_get_image (ic) != mono_defaults.corlib) {
3628 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE CORLIB CHECK FAILED]"));
3629 return FALSE;
3631 if ((ic_name_space == NULL) || (strcmp (ic_name_space, "System.Collections.Generic") != 0)) {
3632 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAMESPACE CHECK FAILED]"));
3633 return FALSE;
3635 if ((ic_name == NULL) || ((strcmp (ic_name, "IEnumerable`1") != 0) && (strcmp (ic_name, "ICollection`1") != 0) && (strcmp (ic_name, "IList`1") != 0))) {
3636 TRACE_INTERFACE_VTABLE (printf ("[INTERFACE NAME CHECK FAILED]"));
3637 return FALSE;
3640 subname = strstr (cm->name, ic_name_space);
3641 if (subname != cm->name) {
3642 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL NAMESPACE CHECK FAILED]"));
3643 return FALSE;
3645 subname += strlen (ic_name_space);
3646 if (subname [0] != '.') {
3647 TRACE_INTERFACE_VTABLE (printf ("[FIRST DOT CHECK FAILED]"));
3648 return FALSE;
3650 subname ++;
3651 if (strstr (subname, ic_name) != subname) {
3652 TRACE_INTERFACE_VTABLE (printf ("[ACTUAL CLASS NAME CHECK FAILED]"));
3653 return FALSE;
3655 subname += strlen (ic_name);
3656 if (subname [0] != '.') {
3657 TRACE_INTERFACE_VTABLE (printf ("[SECOND DOT CHECK FAILED]"));
3658 return FALSE;
3660 subname ++;
3661 if (strcmp (subname, im->name) != 0) {
3662 TRACE_INTERFACE_VTABLE (printf ("[METHOD NAME CHECK FAILED]"));
3663 return FALSE;
3666 TRACE_INTERFACE_VTABLE (printf ("[SECURITY CHECKS (INJECTED CASE)]"));
3667 /* CAS - SecurityAction.InheritanceDemand on interface */
3668 if (security_enabled && (im->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
3669 mono_secman_inheritancedemand_method (cm, im);
3672 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
3673 mono_security_core_clr_check_override (class, cm, im);
3675 TRACE_INTERFACE_VTABLE (printf ("[INJECTED INTERFACE CHECK OK]"));
3676 return TRUE;
3680 #if (TRACE_INTERFACE_VTABLE_CODE|DEBUG_INTERFACE_VTABLE_CODE)
3681 static void
3682 foreach_override (gpointer key, gpointer value, gpointer user_data) {
3683 MonoMethod *method = key;
3684 MonoMethod *override = value;
3685 MonoClass *method_class = mono_method_get_class (method);
3686 MonoClass *override_class = mono_method_get_class (override);
3688 printf (" Method '%s.%s:%s' has override '%s.%s:%s'\n",
3689 mono_class_get_namespace (method_class), mono_class_get_name (method_class), mono_method_get_name (method),
3690 mono_class_get_namespace (override_class), mono_class_get_name (override_class), mono_method_get_name (override));
3692 static void
3693 print_overrides (GHashTable *override_map, const char *message) {
3694 if (override_map) {
3695 printf ("Override map \"%s\" START:\n", message);
3696 g_hash_table_foreach (override_map, foreach_override, NULL);
3697 printf ("Override map \"%s\" END.\n", message);
3698 } else {
3699 printf ("Override map \"%s\" EMPTY.\n", message);
3702 static void
3703 print_vtable_full (MonoClass *class, MonoMethod** vtable, int size, int first_non_interface_slot, const char *message, gboolean print_interfaces) {
3704 char *full_name = mono_type_full_name (&class->byval_arg);
3705 int i;
3706 int parent_size;
3708 printf ("*** Vtable for class '%s' at \"%s\" (size %d)\n", full_name, message, size);
3710 if (print_interfaces) {
3711 print_implemented_interfaces (class);
3712 printf ("* Interfaces for class '%s' done.\nStarting vtable (size %d):\n", full_name, size);
3715 if (class->parent) {
3716 parent_size = class->parent->vtable_size;
3717 } else {
3718 parent_size = 0;
3720 for (i = 0; i < size; ++i) {
3721 MonoMethod *cm = vtable [i];
3722 if (cm) {
3723 char *cm_name = mono_method_full_name (cm, TRUE);
3724 char newness = (i < parent_size) ? 'O' : ((i < first_non_interface_slot) ? 'I' : 'N');
3725 printf (" [%c][%03d][INDEX %03d] %s\n", newness, i, cm->slot, cm_name);
3726 g_free (cm_name);
3730 g_free (full_name);
3732 #endif
3734 #if VERIFY_INTERFACE_VTABLE_CODE
3735 static int
3736 mono_method_try_get_vtable_index (MonoMethod *method)
3738 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
3739 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3740 if (imethod->declaring->is_generic)
3741 return imethod->declaring->slot;
3743 return method->slot;
3746 static void
3747 mono_class_verify_vtable (MonoClass *class)
3749 int i;
3750 char *full_name = mono_type_full_name (&class->byval_arg);
3752 printf ("*** Verifying VTable of class '%s' \n", full_name);
3753 g_free (full_name);
3754 full_name = NULL;
3756 if (!class->methods)
3757 return;
3759 for (i = 0; i < class->method.count; ++i) {
3760 MonoMethod *cm = class->methods [i];
3761 int slot;
3763 if (!(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
3764 continue;
3766 g_free (full_name);
3767 full_name = mono_method_full_name (cm, TRUE);
3769 slot = mono_method_try_get_vtable_index (cm);
3770 if (slot >= 0) {
3771 if (slot >= class->vtable_size) {
3772 printf ("\tInvalid method %s at index %d with vtable of length %d\n", full_name, slot, class->vtable_size);
3773 continue;
3776 if (slot >= 0 && class->vtable [slot] != cm && (class->vtable [slot])) {
3777 char *other_name = class->vtable [slot] ? mono_method_full_name (class->vtable [slot], TRUE) : g_strdup ("[null value]");
3778 printf ("\tMethod %s has slot %d but vtable has %s on it\n", full_name, slot, other_name);
3779 g_free (other_name);
3781 } else
3782 printf ("\tVirtual method %s does n't have an assigned slot\n", full_name);
3784 g_free (full_name);
3786 #endif
3788 static void
3789 print_unimplemented_interface_method_info (MonoClass *class, MonoClass *ic, MonoMethod *im, int im_slot, MonoMethod **overrides, int onum) {
3790 int index;
3791 char *method_signature;
3792 char *type_name;
3794 for (index = 0; index < onum; ++index) {
3795 mono_trace_warning (MONO_TRACE_TYPE, " at slot %d: %s (%d) overrides %s (%d)\n", im_slot, overrides [index*2+1]->name,
3796 overrides [index*2+1]->slot, overrides [index*2]->name, overrides [index*2]->slot);
3798 method_signature = mono_signature_get_desc (mono_method_signature (im), FALSE);
3799 type_name = mono_type_full_name (&class->byval_arg);
3800 mono_trace_warning (MONO_TRACE_TYPE, "no implementation for interface method %s::%s(%s) in class %s\n",
3801 mono_type_get_name (&ic->byval_arg), im->name, method_signature, type_name);
3802 g_free (method_signature);
3803 g_free (type_name);
3804 mono_class_setup_methods (class);
3805 if (class->exception_type) {
3806 char *name = mono_type_get_full_name (class);
3807 mono_trace_warning (MONO_TRACE_TYPE, "CLASS %s failed to resolve methods\n", name);
3808 g_free (name);
3809 return;
3811 for (index = 0; index < class->method.count; ++index) {
3812 MonoMethod *cm = class->methods [index];
3813 method_signature = mono_signature_get_desc (mono_method_signature (cm), TRUE);
3815 mono_trace_warning (MONO_TRACE_TYPE, "METHOD %s(%s)\n", cm->name, method_signature);
3816 g_free (method_signature);
3820 static gboolean
3821 verify_class_overrides (MonoClass *class, MonoMethod **overrides, int onum)
3823 int i;
3825 for (i = 0; i < onum; ++i) {
3826 MonoMethod *decl = overrides [i * 2];
3827 MonoMethod *body = overrides [i * 2 + 1];
3829 if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (class)) {
3830 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method belongs to a different class than the declared one"));
3831 return FALSE;
3834 if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
3835 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3836 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must not be static to override a base type"));
3837 else
3838 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method must be virtual to override a base type"));
3839 return FALSE;
3842 if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
3843 if (body->flags & METHOD_ATTRIBUTE_STATIC)
3844 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a static method in a base type"));
3845 else
3846 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cannot override a non virtual method in a base type"));
3847 return FALSE;
3850 if (!mono_class_is_assignable_from_slow (decl->klass, class)) {
3851 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Method overrides a class or interface that extended or implemented by this type"));
3852 return FALSE;
3855 return TRUE;
3858 static gboolean
3859 mono_class_need_stelemref_method (MonoClass *class)
3861 return class->rank == 1 && MONO_TYPE_IS_REFERENCE (&class->element_class->byval_arg);
3865 * LOCKING: this is supposed to be called with the loader lock held.
3867 void
3868 mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int onum, GList *in_setup)
3870 MonoError error;
3871 MonoClass *k, *ic;
3872 MonoMethod **vtable;
3873 int i, max_vtsize = 0, max_iid, cur_slot = 0;
3874 GPtrArray *ifaces = NULL;
3875 GHashTable *override_map = NULL;
3876 gboolean security_enabled = mono_is_security_manager_active ();
3877 MonoMethod *cm;
3878 gpointer class_iter;
3879 #if (DEBUG_INTERFACE_VTABLE_CODE|TRACE_INTERFACE_VTABLE_CODE)
3880 int first_non_interface_slot;
3881 #endif
3882 GSList *virt_methods = NULL, *l;
3883 int stelemref_slot = 0;
3885 if (class->vtable)
3886 return;
3888 if (overrides && !verify_class_overrides (class, overrides, onum))
3889 return;
3891 ifaces = mono_class_get_implemented_interfaces (class, &error);
3892 if (!mono_error_ok (&error)) {
3893 char *name = mono_type_get_full_name (class);
3894 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)));
3895 g_free (name);
3896 mono_error_cleanup (&error);
3897 return;
3898 } else if (ifaces) {
3899 for (i = 0; i < ifaces->len; i++) {
3900 MonoClass *ic = g_ptr_array_index (ifaces, i);
3901 max_vtsize += ic->method.count;
3903 g_ptr_array_free (ifaces, TRUE);
3904 ifaces = NULL;
3907 if (class->parent) {
3908 mono_class_init (class->parent);
3909 mono_class_setup_vtable_full (class->parent, in_setup);
3911 if (class->parent->exception_type) {
3912 char *name = mono_type_get_full_name (class->parent);
3913 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Parent %s failed to load", name));
3914 g_free (name);
3915 return;
3918 max_vtsize += class->parent->vtable_size;
3919 cur_slot = class->parent->vtable_size;
3922 max_vtsize += class->method.count;
3924 /*Array have a slot for stelemref*/
3925 if (mono_class_need_stelemref_method (class)) {
3926 stelemref_slot = cur_slot;
3927 ++max_vtsize;
3928 ++cur_slot;
3931 vtable = alloca (sizeof (gpointer) * max_vtsize);
3932 memset (vtable, 0, sizeof (gpointer) * max_vtsize);
3934 /* printf ("METAINIT %s.%s\n", class->name_space, class->name); */
3936 cur_slot = setup_interface_offsets (class, cur_slot);
3937 if (cur_slot == -1) /*setup_interface_offsets fails the type.*/
3938 return;
3940 max_iid = class->max_interface_id;
3941 DEBUG_INTERFACE_VTABLE (first_non_interface_slot = cur_slot);
3943 /* Optimized version for generic instances */
3944 if (class->generic_class) {
3945 MonoError error;
3946 MonoClass *gklass = class->generic_class->container_class;
3947 MonoMethod **tmp;
3949 mono_class_setup_vtable_full (gklass, in_setup);
3950 if (gklass->exception_type != MONO_EXCEPTION_NONE) {
3951 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
3952 return;
3955 tmp = mono_class_alloc0 (class, sizeof (gpointer) * gklass->vtable_size);
3956 class->vtable_size = gklass->vtable_size;
3957 for (i = 0; i < gklass->vtable_size; ++i)
3958 if (gklass->vtable [i]) {
3959 MonoMethod *inflated = mono_class_inflate_generic_method_full_checked (gklass->vtable [i], class, mono_class_get_context (class), &error);
3960 if (!mono_error_ok (&error)) {
3961 char *err_msg = g_strdup_printf ("Could not inflate method due to %s", mono_error_get_message (&error));
3962 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
3963 g_free (err_msg);
3964 mono_error_cleanup (&error);
3965 return;
3967 tmp [i] = inflated;
3968 tmp [i]->slot = gklass->vtable [i]->slot;
3970 mono_memory_barrier ();
3971 class->vtable = tmp;
3973 /* Have to set method->slot for abstract virtual methods */
3974 if (class->methods && gklass->methods) {
3975 for (i = 0; i < class->method.count; ++i)
3976 if (class->methods [i]->slot == -1)
3977 class->methods [i]->slot = gklass->methods [i]->slot;
3980 return;
3983 if (class->parent && class->parent->vtable_size) {
3984 MonoClass *parent = class->parent;
3985 int i;
3987 memcpy (vtable, parent->vtable, sizeof (gpointer) * parent->vtable_size);
3989 // Also inherit parent interface vtables, just as a starting point.
3990 // This is needed otherwise bug-77127.exe fails when the property methods
3991 // have different names in the iterface and the class, because for child
3992 // classes the ".override" information is not used anymore.
3993 for (i = 0; i < parent->interface_offsets_count; i++) {
3994 MonoClass *parent_interface = parent->interfaces_packed [i];
3995 int interface_offset = mono_class_interface_offset (class, parent_interface);
3996 /*FIXME this is now dead code as this condition will never hold true.
3997 Since interface offsets are inherited then the offset of an interface implemented
3998 by a parent will never be the out of it's vtable boundary.
4000 if (interface_offset >= parent->vtable_size) {
4001 int parent_interface_offset = mono_class_interface_offset (parent, parent_interface);
4002 int j;
4004 mono_class_setup_methods (parent_interface); /*FIXME Just kill this whole chunk of dead code*/
4005 TRACE_INTERFACE_VTABLE (printf (" +++ Inheriting interface %s.%s\n", parent_interface->name_space, parent_interface->name));
4006 for (j = 0; j < parent_interface->method.count && !class->exception_type; j++) {
4007 vtable [interface_offset + j] = parent->vtable [parent_interface_offset + j];
4008 TRACE_INTERFACE_VTABLE (printf (" --- Inheriting: [%03d][(%03d)+(%03d)] => [%03d][(%03d)+(%03d)]\n",
4009 parent_interface_offset + j, parent_interface_offset, j,
4010 interface_offset + j, interface_offset, j));
4017 /*Array have a slot for stelemref*/
4018 if (mono_class_need_stelemref_method (class)) {
4019 MonoMethod *method = mono_marshal_get_virtual_stelemref (class);
4020 if (!method->slot)
4021 method->slot = stelemref_slot;
4022 else
4023 g_assert (method->slot == stelemref_slot);
4025 vtable [stelemref_slot] = method;
4028 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER INHERITING PARENT VTABLE", TRUE));
4029 /* override interface methods */
4030 for (i = 0; i < onum; i++) {
4031 MonoMethod *decl = overrides [i*2];
4032 if (MONO_CLASS_IS_INTERFACE (decl->klass)) {
4033 int dslot;
4034 dslot = mono_method_get_vtable_slot (decl);
4035 if (dslot == -1) {
4036 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4037 return;
4040 dslot += mono_class_interface_offset (class, decl->klass);
4041 vtable [dslot] = overrides [i*2 + 1];
4042 vtable [dslot]->slot = dslot;
4043 if (!override_map)
4044 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4046 g_hash_table_insert (override_map, overrides [i * 2], overrides [i * 2 + 1]);
4048 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4049 mono_security_core_clr_check_override (class, vtable [dslot], decl);
4052 TRACE_INTERFACE_VTABLE (print_overrides (override_map, "AFTER OVERRIDING INTERFACE METHODS"));
4053 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER OVERRIDING INTERFACE METHODS", FALSE));
4056 * Create a list of virtual methods to avoid calling
4057 * mono_class_get_virtual_methods () which is slow because of the metadata
4058 * optimization.
4061 gpointer iter = NULL;
4062 MonoMethod *cm;
4064 virt_methods = NULL;
4065 while ((cm = mono_class_get_virtual_methods (class, &iter))) {
4066 virt_methods = g_slist_prepend (virt_methods, cm);
4068 if (class->exception_type)
4069 goto fail;
4072 // Loop on all implemented interfaces...
4073 for (i = 0; i < class->interface_offsets_count; i++) {
4074 MonoClass *parent = class->parent;
4075 int ic_offset;
4076 gboolean interface_is_explicitly_implemented_by_class;
4077 int im_index;
4079 ic = class->interfaces_packed [i];
4080 ic_offset = mono_class_interface_offset (class, ic);
4082 mono_class_setup_methods (ic);
4083 if (ic->exception_type)
4084 goto fail;
4086 // Check if this interface is explicitly implemented (instead of just inherited)
4087 if (parent != NULL) {
4088 int implemented_interfaces_index;
4089 interface_is_explicitly_implemented_by_class = FALSE;
4090 for (implemented_interfaces_index = 0; implemented_interfaces_index < class->interface_count; implemented_interfaces_index++) {
4091 if (ic == class->interfaces [implemented_interfaces_index]) {
4092 interface_is_explicitly_implemented_by_class = TRUE;
4093 break;
4096 } else {
4097 interface_is_explicitly_implemented_by_class = TRUE;
4100 // Loop on all interface methods...
4101 for (im_index = 0; im_index < ic->method.count; im_index++) {
4102 MonoMethod *im = ic->methods [im_index];
4103 int im_slot = ic_offset + im->slot;
4104 MonoMethod *override_im = (override_map != NULL) ? g_hash_table_lookup (override_map, im) : NULL;
4106 if (im->flags & METHOD_ATTRIBUTE_STATIC)
4107 continue;
4109 // If there is an explicit implementation, just use it right away,
4110 // otherwise look for a matching method
4111 if (override_im == NULL) {
4112 int cm_index;
4113 gpointer iter;
4114 MonoMethod *cm;
4116 // First look for a suitable method among the class methods
4117 iter = NULL;
4118 for (l = virt_methods; l; l = l->next) {
4119 cm = l->data;
4120 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)));
4121 if (check_interface_method_override (class, im, cm, TRUE, interface_is_explicitly_implemented_by_class, (vtable [im_slot] == NULL), security_enabled)) {
4122 TRACE_INTERFACE_VTABLE (printf ("[check ok]: ASSIGNING"));
4123 vtable [im_slot] = cm;
4124 /* Why do we need this? */
4125 if (cm->slot < 0) {
4126 cm->slot = im_slot;
4129 TRACE_INTERFACE_VTABLE (printf ("\n"));
4130 if (class->exception_type) /*Might be set by check_interface_method_override*/
4131 goto fail;
4134 // If the slot is still empty, look in all the inherited virtual methods...
4135 if ((vtable [im_slot] == NULL) && class->parent != NULL) {
4136 MonoClass *parent = class->parent;
4137 // Reverse order, so that last added methods are preferred
4138 for (cm_index = parent->vtable_size - 1; cm_index >= 0; cm_index--) {
4139 MonoMethod *cm = parent->vtable [cm_index];
4141 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));
4142 if ((cm != NULL) && check_interface_method_override (class, im, cm, FALSE, FALSE, TRUE, security_enabled)) {
4143 TRACE_INTERFACE_VTABLE (printf ("[everything ok]: ASSIGNING"));
4144 vtable [im_slot] = cm;
4145 /* Why do we need this? */
4146 if (cm->slot < 0) {
4147 cm->slot = im_slot;
4149 break;
4151 if (class->exception_type) /*Might be set by check_interface_method_override*/
4152 goto fail;
4153 TRACE_INTERFACE_VTABLE ((cm != NULL) && printf ("\n"));
4156 } else {
4157 g_assert (vtable [im_slot] == override_im);
4162 // If the class is not abstract, check that all its interface slots are full.
4163 // The check is done here and not directly at the end of the loop above because
4164 // it can happen (for injected generic array interfaces) that the same slot is
4165 // processed multiple times (those interfaces have overlapping slots), and it
4166 // will not always be the first pass the one that fills the slot.
4167 if (! (class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
4168 for (i = 0; i < class->interface_offsets_count; i++) {
4169 int ic_offset;
4170 int im_index;
4172 ic = class->interfaces_packed [i];
4173 ic_offset = mono_class_interface_offset (class, ic);
4175 for (im_index = 0; im_index < ic->method.count; im_index++) {
4176 MonoMethod *im = ic->methods [im_index];
4177 int im_slot = ic_offset + im->slot;
4179 if (im->flags & METHOD_ATTRIBUTE_STATIC)
4180 continue;
4182 TRACE_INTERFACE_VTABLE (printf (" [class is not abstract, checking slot %d for interface '%s'.'%s', method %s, slot check is %d]\n",
4183 im_slot, ic->name_space, ic->name, im->name, (vtable [im_slot] == NULL)));
4184 if (vtable [im_slot] == NULL) {
4185 print_unimplemented_interface_method_info (class, ic, im, im_slot, overrides, onum);
4186 goto fail;
4192 TRACE_INTERFACE_VTABLE (print_vtable_full (class, vtable, cur_slot, first_non_interface_slot, "AFTER SETTING UP INTERFACE METHODS", FALSE));
4193 class_iter = NULL;
4194 for (l = virt_methods; l; l = l->next) {
4195 cm = l->data;
4197 * If the method is REUSE_SLOT, we must check in the
4198 * base class for a method to override.
4200 if (!(cm->flags & METHOD_ATTRIBUTE_NEW_SLOT)) {
4201 int slot = -1;
4202 for (k = class->parent; k ; k = k->parent) {
4203 gpointer k_iter;
4204 MonoMethod *m1;
4206 k_iter = NULL;
4207 while ((m1 = mono_class_get_virtual_methods (k, &k_iter))) {
4208 MonoMethodSignature *cmsig, *m1sig;
4210 cmsig = mono_method_signature (cm);
4211 m1sig = mono_method_signature (m1);
4213 if (!cmsig || !m1sig) {
4214 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4215 return;
4218 if (!strcmp(cm->name, m1->name) &&
4219 mono_metadata_signature_equal (cmsig, m1sig)) {
4221 /* CAS - SecurityAction.InheritanceDemand */
4222 if (security_enabled && (m1->flags & METHOD_ATTRIBUTE_HAS_SECURITY)) {
4223 mono_secman_inheritancedemand_method (cm, m1);
4226 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4227 mono_security_core_clr_check_override (class, cm, m1);
4229 slot = mono_method_get_vtable_slot (m1);
4230 if (slot == -1)
4231 goto fail;
4233 g_assert (cm->slot < max_vtsize);
4234 if (!override_map)
4235 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4236 g_hash_table_insert (override_map, m1, cm);
4237 break;
4240 if (k->exception_type)
4241 goto fail;
4243 if (slot >= 0)
4244 break;
4246 if (slot >= 0)
4247 cm->slot = slot;
4250 /*Non final newslot methods must be given a non-interface vtable slot*/
4251 if ((cm->flags & METHOD_ATTRIBUTE_NEW_SLOT) && !(cm->flags & METHOD_ATTRIBUTE_FINAL) && cm->slot >= 0)
4252 cm->slot = -1;
4254 if (cm->slot < 0)
4255 cm->slot = cur_slot++;
4257 if (!(cm->flags & METHOD_ATTRIBUTE_ABSTRACT))
4258 vtable [cm->slot] = cm;
4261 /* override non interface methods */
4262 for (i = 0; i < onum; i++) {
4263 MonoMethod *decl = overrides [i*2];
4264 if (!MONO_CLASS_IS_INTERFACE (decl->klass)) {
4265 g_assert (decl->slot != -1);
4266 vtable [decl->slot] = overrides [i*2 + 1];
4267 overrides [i * 2 + 1]->slot = decl->slot;
4268 if (!override_map)
4269 override_map = g_hash_table_new (mono_aligned_addr_hash, NULL);
4270 g_hash_table_insert (override_map, decl, overrides [i * 2 + 1]);
4272 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4273 mono_security_core_clr_check_override (class, vtable [decl->slot], decl);
4278 * If a method occupies more than one place in the vtable, and it is
4279 * overriden, then change the other occurances too.
4281 if (override_map) {
4282 for (i = 0; i < max_vtsize; ++i)
4283 if (vtable [i]) {
4284 MonoMethod *cm = g_hash_table_lookup (override_map, vtable [i]);
4285 if (cm)
4286 vtable [i] = cm;
4289 g_hash_table_destroy (override_map);
4290 override_map = NULL;
4293 g_slist_free (virt_methods);
4294 virt_methods = NULL;
4296 /* Ensure that all vtable slots are filled with concrete instance methods */
4297 if (!(class->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
4298 for (i = 0; i < cur_slot; ++i) {
4299 if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
4300 char *type_name = mono_type_get_full_name (class);
4301 char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
4302 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));
4303 g_free (type_name);
4304 g_free (method_name);
4305 return;
4310 if (class->generic_class) {
4311 MonoClass *gklass = class->generic_class->container_class;
4313 mono_class_init (gklass);
4315 class->vtable_size = MAX (gklass->vtable_size, cur_slot);
4316 } else {
4317 /* Check that the vtable_size value computed in mono_class_init () is correct */
4318 if (class->vtable_size)
4319 g_assert (cur_slot == class->vtable_size);
4320 class->vtable_size = cur_slot;
4323 /* Try to share the vtable with our parent. */
4324 if (class->parent && (class->parent->vtable_size == class->vtable_size) && (memcmp (class->parent->vtable, vtable, sizeof (gpointer) * class->vtable_size) == 0)) {
4325 mono_memory_barrier ();
4326 class->vtable = class->parent->vtable;
4327 } else {
4328 MonoMethod **tmp = mono_class_alloc0 (class, sizeof (gpointer) * class->vtable_size);
4329 memcpy (tmp, vtable, sizeof (gpointer) * class->vtable_size);
4330 mono_memory_barrier ();
4331 class->vtable = tmp;
4334 DEBUG_INTERFACE_VTABLE (print_vtable_full (class, class->vtable, class->vtable_size, first_non_interface_slot, "FINALLY", FALSE));
4335 if (mono_print_vtable) {
4336 int icount = 0;
4338 print_implemented_interfaces (class);
4340 for (i = 0; i <= max_iid; i++)
4341 if (MONO_CLASS_IMPLEMENTS_INTERFACE (class, i))
4342 icount++;
4344 printf ("VTable %s (vtable entries = %d, interfaces = %d)\n", mono_type_full_name (&class->byval_arg),
4345 class->vtable_size, icount);
4347 for (i = 0; i < cur_slot; ++i) {
4348 MonoMethod *cm;
4350 cm = vtable [i];
4351 if (cm) {
4352 printf (" slot assigned: %03d, slot index: %03d %s\n", i, cm->slot,
4353 mono_method_full_name (cm, TRUE));
4358 if (icount) {
4359 printf ("Interfaces %s.%s (max_iid = %d)\n", class->name_space,
4360 class->name, max_iid);
4362 for (i = 0; i < class->interface_count; i++) {
4363 ic = class->interfaces [i];
4364 printf (" slot offset: %03d, method count: %03d, iid: %03d %s\n",
4365 mono_class_interface_offset (class, ic),
4366 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
4369 for (k = class->parent; k ; k = k->parent) {
4370 for (i = 0; i < k->interface_count; i++) {
4371 ic = k->interfaces [i];
4372 printf (" parent slot offset: %03d, method count: %03d, iid: %03d %s\n",
4373 mono_class_interface_offset (class, ic),
4374 count_virtual_methods (ic), ic->interface_id, mono_type_full_name (&ic->byval_arg));
4380 VERIFY_INTERFACE_VTABLE (mono_class_verify_vtable (class));
4381 return;
4383 fail:
4385 char *name = mono_type_get_full_name (class);
4386 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("VTable setup of type %s failed", name));
4387 g_free (name);
4388 if (override_map)
4389 g_hash_table_destroy (override_map);
4390 if (virt_methods)
4391 g_slist_free (virt_methods);
4396 * mono_method_get_vtable_slot:
4398 * Returns method->slot, computing it if neccesary. Return -1 on failure.
4399 * LOCKING: Acquires the loader lock.
4401 * FIXME Use proper MonoError machinery here.
4404 mono_method_get_vtable_slot (MonoMethod *method)
4406 if (method->slot == -1) {
4407 mono_class_setup_vtable (method->klass);
4408 if (method->klass->exception_type)
4409 return -1;
4410 g_assert (method->slot != -1);
4412 return method->slot;
4416 * mono_method_get_vtable_index:
4417 * @method: a method
4419 * Returns the index into the runtime vtable to access the method or,
4420 * in the case of a virtual generic method, the virtual generic method
4421 * thunk. Returns -1 on failure.
4423 * FIXME Use proper MonoError machinery here.
4426 mono_method_get_vtable_index (MonoMethod *method)
4428 if (method->is_inflated && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4429 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4430 if (imethod->declaring->is_generic)
4431 return mono_method_get_vtable_slot (imethod->declaring);
4433 return mono_method_get_vtable_slot (method);
4436 static MonoMethod *default_ghc = NULL;
4437 static MonoMethod *default_finalize = NULL;
4438 static int finalize_slot = -1;
4439 static int ghc_slot = -1;
4441 static void
4442 initialize_object_slots (MonoClass *class)
4444 int i;
4445 if (default_ghc)
4446 return;
4447 if (class == mono_defaults.object_class) {
4448 mono_class_setup_vtable (class);
4449 for (i = 0; i < class->vtable_size; ++i) {
4450 MonoMethod *cm = class->vtable [i];
4452 if (!strcmp (cm->name, "GetHashCode"))
4453 ghc_slot = i;
4454 else if (!strcmp (cm->name, "Finalize"))
4455 finalize_slot = i;
4458 g_assert (ghc_slot > 0);
4459 default_ghc = class->vtable [ghc_slot];
4461 g_assert (finalize_slot > 0);
4462 default_finalize = class->vtable [finalize_slot];
4466 typedef struct {
4467 MonoMethod *array_method;
4468 char *name;
4469 } GenericArrayMethodInfo;
4471 static int generic_array_method_num = 0;
4472 static GenericArrayMethodInfo *generic_array_method_info = NULL;
4474 static int
4475 generic_array_methods (MonoClass *class)
4477 int i, count_generic = 0;
4478 GList *list = NULL, *tmp;
4479 if (generic_array_method_num)
4480 return generic_array_method_num;
4481 mono_class_setup_methods (class->parent); /*This is setting up System.Array*/
4482 g_assert (!class->parent->exception_type); /*So hitting this assert is a huge problem*/
4483 for (i = 0; i < class->parent->method.count; i++) {
4484 MonoMethod *m = class->parent->methods [i];
4485 if (!strncmp (m->name, "InternalArray__", 15)) {
4486 count_generic++;
4487 list = g_list_prepend (list, m);
4490 list = g_list_reverse (list);
4491 generic_array_method_info = mono_image_alloc (mono_defaults.corlib, sizeof (GenericArrayMethodInfo) * count_generic);
4492 i = 0;
4493 for (tmp = list; tmp; tmp = tmp->next) {
4494 const char *mname, *iname;
4495 gchar *name;
4496 MonoMethod *m = tmp->data;
4497 generic_array_method_info [i].array_method = m;
4498 if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
4499 iname = "System.Collections.Generic.ICollection`1.";
4500 mname = m->name + 27;
4501 } else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
4502 iname = "System.Collections.Generic.IEnumerable`1.";
4503 mname = m->name + 27;
4504 } else if (!strncmp (m->name, "InternalArray__", 15)) {
4505 iname = "System.Collections.Generic.IList`1.";
4506 mname = m->name + 15;
4507 } else {
4508 g_assert_not_reached ();
4511 name = mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
4512 strcpy (name, iname);
4513 strcpy (name + strlen (iname), mname);
4514 generic_array_method_info [i].name = name;
4515 i++;
4517 /*g_print ("array generic methods: %d\n", count_generic);*/
4519 generic_array_method_num = count_generic;
4520 g_list_free (list);
4521 return generic_array_method_num;
4524 static void
4525 setup_generic_array_ifaces (MonoClass *class, MonoClass *iface, MonoMethod **methods, int pos)
4527 MonoGenericContext tmp_context;
4528 int i;
4530 tmp_context.class_inst = NULL;
4531 tmp_context.method_inst = iface->generic_class->context.class_inst;
4532 //g_print ("setting up array interface: %s\n", mono_type_get_name_full (&iface->byval_arg, 0));
4534 for (i = 0; i < generic_array_method_num; i++) {
4535 MonoMethod *m = generic_array_method_info [i].array_method;
4536 MonoMethod *inflated;
4538 inflated = mono_class_inflate_generic_method (m, &tmp_context);
4539 methods [pos++] = mono_marshal_get_generic_array_helper (class, iface, generic_array_method_info [i].name, inflated);
4543 static char*
4544 concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
4546 int null_length = strlen ("(null)");
4547 int len = (s1 ? strlen (s1) : null_length) + (s2 ? strlen (s2) : null_length) + 2;
4548 char *s = mono_image_alloc (image, len);
4549 int result;
4551 result = g_snprintf (s, len, "%s%c%s", s1 ? s1 : "(null)", '\0', s2 ? s2 : "(null)");
4552 g_assert (result == len - 1);
4554 return s;
4557 static void
4558 set_failure_from_loader_error (MonoClass *class, MonoLoaderError *error)
4560 gpointer exception_data = NULL;
4562 switch (error->exception_type) {
4563 case MONO_EXCEPTION_TYPE_LOAD:
4564 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->assembly_name);
4565 break;
4567 case MONO_EXCEPTION_MISSING_METHOD:
4568 exception_data = concat_two_strings_with_zero (class->image, error->class_name, error->member_name);
4569 break;
4571 case MONO_EXCEPTION_MISSING_FIELD: {
4572 const char *name_space = error->klass->name_space ? error->klass->name_space : NULL;
4573 const char *class_name;
4575 if (name_space)
4576 class_name = g_strdup_printf ("%s.%s", name_space, error->klass->name);
4577 else
4578 class_name = error->klass->name;
4580 exception_data = concat_two_strings_with_zero (class->image, class_name, error->member_name);
4582 if (name_space)
4583 g_free ((void*)class_name);
4584 break;
4587 case MONO_EXCEPTION_FILE_NOT_FOUND: {
4588 const char *msg;
4590 if (error->ref_only)
4591 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.";
4592 else
4593 msg = "Could not load file or assembly '%s' or one of its dependencies.";
4595 exception_data = concat_two_strings_with_zero (class->image, msg, error->assembly_name);
4596 break;
4599 case MONO_EXCEPTION_BAD_IMAGE:
4600 exception_data = error->msg;
4601 break;
4603 default :
4604 g_assert_not_reached ();
4607 mono_class_set_failure (class, error->exception_type, exception_data);
4611 * mono_class_init:
4612 * @class: the class to initialize
4614 * Compute the instance_size, class_size and other infos that cannot be
4615 * computed at mono_class_get() time. Also compute vtable_size if possible.
4616 * Returns TRUE on success or FALSE if there was a problem in loading
4617 * the type (incorrect assemblies, missing assemblies, methods, etc).
4619 * LOCKING: Acquires the loader lock.
4621 gboolean
4622 mono_class_init (MonoClass *class)
4624 int i;
4625 MonoCachedClassInfo cached_info;
4626 gboolean has_cached_info;
4628 g_assert (class);
4630 /* Double-checking locking pattern */
4631 if (class->inited || class->exception_type)
4632 return class->exception_type == MONO_EXCEPTION_NONE;
4634 /*g_print ("Init class %s\n", mono_type_get_full_name (class));*/
4636 /* We do everything inside the lock to prevent races */
4637 mono_loader_lock ();
4639 if (class->inited || class->exception_type) {
4640 mono_loader_unlock ();
4641 /* Somebody might have gotten in before us */
4642 return class->exception_type == MONO_EXCEPTION_NONE;
4645 if (class->init_pending) {
4646 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Recursive type definition detected"));
4647 goto leave;
4650 class->init_pending = 1;
4652 if (mono_verifier_is_enabled_for_class (class) && !mono_verifier_verify_class (class)) {
4653 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (class->image, class->name, class->image->assembly_name));
4654 goto leave;
4658 if (class->byval_arg.type == MONO_TYPE_ARRAY || class->byval_arg.type == MONO_TYPE_SZARRAY) {
4659 MonoClass *element_class = class->element_class;
4660 if (!element_class->inited)
4661 mono_class_init (element_class);
4662 if (element_class->exception_type != MONO_EXCEPTION_NONE) {
4663 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4664 goto leave;
4668 /* CAS - SecurityAction.InheritanceDemand */
4669 if (mono_is_security_manager_active () && class->parent && (class->parent->flags & TYPE_ATTRIBUTE_HAS_SECURITY)) {
4670 mono_secman_inheritancedemand_class (class, class->parent);
4673 mono_stats.initialized_class_count++;
4675 if (class->generic_class && !class->generic_class->is_dynamic) {
4676 MonoClass *gklass = class->generic_class->container_class;
4678 mono_stats.generic_class_count++;
4680 class->method = gklass->method;
4681 class->field = gklass->field;
4683 mono_class_init (gklass);
4684 // FIXME: Why is this needed ?
4685 if (!gklass->exception_type)
4686 mono_class_setup_methods (gklass);
4687 if (gklass->exception_type) {
4688 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Generic Type Defintion failed to init"));
4689 goto leave;
4692 if (MONO_CLASS_IS_INTERFACE (class))
4693 class->interface_id = mono_get_unique_iid (class);
4696 if (class->parent && !class->parent->inited)
4697 mono_class_init (class->parent);
4699 has_cached_info = mono_class_get_cached_class_info (class, &cached_info);
4701 if (class->generic_class || class->image->dynamic || !class->type_token || (has_cached_info && !cached_info.has_nested_classes))
4702 class->nested_classes_inited = TRUE;
4705 * Computes the size used by the fields, and their locations
4707 if (has_cached_info) {
4708 class->instance_size = cached_info.instance_size;
4709 class->sizes.class_size = cached_info.class_size;
4710 class->packing_size = cached_info.packing_size;
4711 class->min_align = cached_info.min_align;
4712 class->blittable = cached_info.blittable;
4713 class->has_references = cached_info.has_references;
4714 class->has_static_refs = cached_info.has_static_refs;
4715 class->no_special_static_fields = cached_info.no_special_static_fields;
4717 else
4718 if (!class->size_inited){
4719 mono_class_setup_fields (class);
4720 if (class->exception_type || mono_loader_get_last_error ())
4721 goto leave;
4724 /* Initialize arrays */
4725 if (class->rank) {
4726 class->method.count = 3 + (class->rank > 1? 2: 1);
4728 if (class->interface_count) {
4729 int count_generic = generic_array_methods (class);
4730 class->method.count += class->interface_count * count_generic;
4734 mono_class_setup_supertypes (class);
4736 if (!default_ghc)
4737 initialize_object_slots (class);
4740 * Initialize the rest of the data without creating a generic vtable if possible.
4741 * If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
4742 * also avoid computing a generic vtable.
4744 if (has_cached_info) {
4745 /* AOT case */
4746 class->vtable_size = cached_info.vtable_size;
4747 class->has_finalize = cached_info.has_finalize;
4748 class->has_finalize_inited = TRUE;
4749 class->ghcimpl = cached_info.ghcimpl;
4750 class->has_cctor = cached_info.has_cctor;
4751 } else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
4752 /* SZARRAY can have 2 vtable layouts, with and without the stelemref method.
4753 * The first slot if for array with.
4755 static int szarray_vtable_size[2] = { 0 };
4757 int slot = MONO_TYPE_IS_REFERENCE (&class->element_class->byval_arg) ? 0 : 1;
4759 /* SZARRAY case */
4760 if (!szarray_vtable_size [slot]) {
4761 mono_class_setup_vtable (class);
4762 szarray_vtable_size [slot] = class->vtable_size;
4763 } else {
4764 class->vtable_size = szarray_vtable_size[slot];
4766 class->has_finalize_inited = TRUE;
4767 } else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
4768 MonoClass *gklass = class->generic_class->container_class;
4770 /* Generic instance case */
4771 class->ghcimpl = gklass->ghcimpl;
4772 class->has_finalize = mono_class_has_finalizer (gklass);
4773 class->has_finalize_inited = TRUE;
4774 class->has_cctor = gklass->has_cctor;
4776 mono_class_setup_vtable (gklass);
4777 if (gklass->exception_type) {
4778 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4779 goto leave;
4782 class->vtable_size = gklass->vtable_size;
4783 } else {
4784 /* General case */
4786 /* ghcimpl is not currently used
4787 class->ghcimpl = 1;
4788 if (class->parent) {
4789 MonoMethod *cmethod = class->vtable [ghc_slot];
4790 if (cmethod->is_inflated)
4791 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4792 if (cmethod == default_ghc) {
4793 class->ghcimpl = 0;
4798 /* C# doesn't allow interfaces to have cctors */
4799 if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
4800 MonoMethod *cmethod = NULL;
4802 if (class->type_token) {
4803 cmethod = find_method_in_metadata (class, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
4804 /* The find_method function ignores the 'flags' argument */
4805 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
4806 class->has_cctor = 1;
4807 } else {
4808 mono_class_setup_methods (class);
4809 if (class->exception_type)
4810 goto leave;
4812 for (i = 0; i < class->method.count; ++i) {
4813 MonoMethod *method = class->methods [i];
4814 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4815 (strcmp (".cctor", method->name) == 0)) {
4816 class->has_cctor = 1;
4817 break;
4824 if (class->parent) {
4825 int first_iface_slot;
4826 /* This will compute class->parent->vtable_size for some classes */
4827 mono_class_init (class->parent);
4828 if (class->parent->exception_type) {
4829 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4830 goto leave;
4832 if (mono_loader_get_last_error ())
4833 goto leave;
4834 if (!class->parent->vtable_size) {
4835 /* FIXME: Get rid of this somehow */
4836 mono_class_setup_vtable (class->parent);
4837 if (class->parent->exception_type) {
4838 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
4839 goto leave;
4841 if (mono_loader_get_last_error ())
4842 goto leave;
4844 first_iface_slot = class->parent->vtable_size;
4845 if (mono_class_need_stelemref_method (class))
4846 ++first_iface_slot;
4847 setup_interface_offsets (class, first_iface_slot);
4848 } else {
4849 setup_interface_offsets (class, 0);
4852 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
4853 mono_security_core_clr_check_inheritance (class);
4855 if (mono_loader_get_last_error ()) {
4856 if (class->exception_type == MONO_EXCEPTION_NONE) {
4857 set_failure_from_loader_error (class, mono_loader_get_last_error ());
4859 mono_loader_clear_error ();
4862 if (class->generic_class && !mono_verifier_class_is_valid_generic_instantiation (class))
4863 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Invalid generic instantiation"));
4865 goto leave;
4867 leave:
4868 /* Because of the double-checking locking pattern */
4869 mono_memory_barrier ();
4870 class->inited = 1;
4871 class->init_pending = 0;
4873 mono_loader_unlock ();
4875 if (mono_debugger_class_init_func)
4876 mono_debugger_class_init_func (class);
4878 return class->exception_type == MONO_EXCEPTION_NONE;
4882 * mono_class_has_finalizer:
4884 * Return whenever KLASS has a finalizer, initializing klass->has_finalizer in the
4885 * process.
4887 gboolean
4888 mono_class_has_finalizer (MonoClass *klass)
4890 if (!klass->has_finalize_inited) {
4891 MonoClass *class = klass;
4893 mono_loader_lock ();
4895 /* Interfaces and valuetypes are not supposed to have finalizers */
4896 if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
4897 MonoMethod *cmethod = NULL;
4899 if (class->parent && class->parent->has_finalize) {
4900 class->has_finalize = 1;
4901 } else {
4902 if (class->parent) {
4904 * Can't search in metadata for a method named Finalize, because that
4905 * ignores overrides.
4907 mono_class_setup_vtable (class);
4908 if (class->exception_type || mono_loader_get_last_error ())
4909 goto leave;
4910 cmethod = class->vtable [finalize_slot];
4913 if (cmethod) {
4914 g_assert (class->vtable_size > finalize_slot);
4916 class->has_finalize = 0;
4917 if (class->parent) {
4918 if (cmethod->is_inflated)
4919 cmethod = ((MonoMethodInflated*)cmethod)->declaring;
4920 if (cmethod != default_finalize) {
4921 class->has_finalize = 1;
4928 mono_memory_barrier ();
4929 klass->has_finalize_inited = TRUE;
4931 mono_loader_unlock ();
4934 return klass->has_finalize;
4936 leave:
4937 mono_loader_unlock ();
4938 return FALSE;
4941 gboolean
4942 mono_is_corlib_image (MonoImage *image)
4944 /* FIXME: allow the dynamic case for our compilers and with full trust */
4945 if (image->dynamic)
4946 return image->assembly && !strcmp (image->assembly->aname.name, "mscorlib");
4947 else
4948 return image == mono_defaults.corlib;
4952 * LOCKING: this assumes the loader lock is held
4954 void
4955 mono_class_setup_mono_type (MonoClass *class)
4957 const char *name = class->name;
4958 const char *nspace = class->name_space;
4959 gboolean is_corlib = mono_is_corlib_image (class->image);
4961 class->this_arg.byref = 1;
4962 class->this_arg.data.klass = class;
4963 class->this_arg.type = MONO_TYPE_CLASS;
4964 class->byval_arg.data.klass = class;
4965 class->byval_arg.type = MONO_TYPE_CLASS;
4967 if (is_corlib && !strcmp (nspace, "System")) {
4968 if (!strcmp (name, "ValueType")) {
4970 * do not set the valuetype bit for System.ValueType.
4971 * class->valuetype = 1;
4973 class->blittable = TRUE;
4974 } else if (!strcmp (name, "Enum")) {
4976 * do not set the valuetype bit for System.Enum.
4977 * class->valuetype = 1;
4979 class->valuetype = 0;
4980 class->enumtype = 0;
4981 } else if (!strcmp (name, "Object")) {
4982 class->this_arg.type = class->byval_arg.type = MONO_TYPE_OBJECT;
4983 } else if (!strcmp (name, "String")) {
4984 class->this_arg.type = class->byval_arg.type = MONO_TYPE_STRING;
4985 } else if (!strcmp (name, "TypedReference")) {
4986 class->this_arg.type = class->byval_arg.type = MONO_TYPE_TYPEDBYREF;
4990 if (class->valuetype) {
4991 int t = MONO_TYPE_VALUETYPE;
4993 if (is_corlib && !strcmp (nspace, "System")) {
4994 switch (*name) {
4995 case 'B':
4996 if (!strcmp (name, "Boolean")) {
4997 t = MONO_TYPE_BOOLEAN;
4998 } else if (!strcmp(name, "Byte")) {
4999 t = MONO_TYPE_U1;
5000 class->blittable = TRUE;
5002 break;
5003 case 'C':
5004 if (!strcmp (name, "Char")) {
5005 t = MONO_TYPE_CHAR;
5007 break;
5008 case 'D':
5009 if (!strcmp (name, "Double")) {
5010 t = MONO_TYPE_R8;
5011 class->blittable = TRUE;
5013 break;
5014 case 'I':
5015 if (!strcmp (name, "Int32")) {
5016 t = MONO_TYPE_I4;
5017 class->blittable = TRUE;
5018 } else if (!strcmp(name, "Int16")) {
5019 t = MONO_TYPE_I2;
5020 class->blittable = TRUE;
5021 } else if (!strcmp(name, "Int64")) {
5022 t = MONO_TYPE_I8;
5023 class->blittable = TRUE;
5024 } else if (!strcmp(name, "IntPtr")) {
5025 t = MONO_TYPE_I;
5026 class->blittable = TRUE;
5028 break;
5029 case 'S':
5030 if (!strcmp (name, "Single")) {
5031 t = MONO_TYPE_R4;
5032 class->blittable = TRUE;
5033 } else if (!strcmp(name, "SByte")) {
5034 t = MONO_TYPE_I1;
5035 class->blittable = TRUE;
5037 break;
5038 case 'U':
5039 if (!strcmp (name, "UInt32")) {
5040 t = MONO_TYPE_U4;
5041 class->blittable = TRUE;
5042 } else if (!strcmp(name, "UInt16")) {
5043 t = MONO_TYPE_U2;
5044 class->blittable = TRUE;
5045 } else if (!strcmp(name, "UInt64")) {
5046 t = MONO_TYPE_U8;
5047 class->blittable = TRUE;
5048 } else if (!strcmp(name, "UIntPtr")) {
5049 t = MONO_TYPE_U;
5050 class->blittable = TRUE;
5052 break;
5053 case 'T':
5054 if (!strcmp (name, "TypedReference")) {
5055 t = MONO_TYPE_TYPEDBYREF;
5056 class->blittable = TRUE;
5058 break;
5059 case 'V':
5060 if (!strcmp (name, "Void")) {
5061 t = MONO_TYPE_VOID;
5063 break;
5064 default:
5065 break;
5068 class->this_arg.type = class->byval_arg.type = t;
5071 if (MONO_CLASS_IS_INTERFACE (class))
5072 class->interface_id = mono_get_unique_iid (class);
5077 * COM initialization (using mono_init_com_types) is delayed until needed.
5078 * However when a [ComImport] attribute is present on a type it will trigger
5079 * the initialization. This is not a problem unless the BCL being executed
5080 * lacks the types that COM depends on (e.g. Variant on Silverlight).
5082 static void
5083 init_com_from_comimport (MonoClass *class)
5085 /* we don't always allow COM initialization under the CoreCLR (e.g. Moonlight does not require it) */
5086 if ((mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)) {
5087 /* but some other CoreCLR user could requires it for their platform (i.e. trusted) code */
5088 if (!mono_security_core_clr_determine_platform_image (class->image)) {
5089 /* but it can not be made available for application (i.e. user code) since all COM calls
5090 * are considered native calls. In this case we fail with a TypeLoadException (just like
5091 * Silverlight 2 does */
5092 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5093 return;
5096 /* FIXME : we should add an extra checks to ensure COM can be initialized properly before continuing */
5097 mono_init_com_types ();
5101 * LOCKING: this assumes the loader lock is held
5103 void
5104 mono_class_setup_parent (MonoClass *class, MonoClass *parent)
5106 gboolean system_namespace;
5107 gboolean is_corlib = mono_is_corlib_image (class->image);
5109 system_namespace = !strcmp (class->name_space, "System") && is_corlib;
5111 /* if root of the hierarchy */
5112 if (system_namespace && !strcmp (class->name, "Object")) {
5113 class->parent = NULL;
5114 class->instance_size = sizeof (MonoObject);
5115 return;
5117 if (!strcmp (class->name, "<Module>")) {
5118 class->parent = NULL;
5119 class->instance_size = 0;
5120 return;
5123 if (!MONO_CLASS_IS_INTERFACE (class)) {
5124 /* Imported COM Objects always derive from __ComObject. */
5125 if (MONO_CLASS_IS_IMPORT (class)) {
5126 init_com_from_comimport (class);
5127 if (parent == mono_defaults.object_class)
5128 parent = mono_defaults.com_object_class;
5130 if (!parent) {
5131 /* set the parent to something useful and safe, but mark the type as broken */
5132 parent = mono_defaults.object_class;
5133 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5136 class->parent = parent;
5138 if (parent->generic_class && !parent->name) {
5140 * If the parent is a generic instance, we may get
5141 * called before it is fully initialized, especially
5142 * before it has its name.
5144 return;
5147 class->marshalbyref = parent->marshalbyref;
5148 class->contextbound = parent->contextbound;
5149 class->delegate = parent->delegate;
5150 if (MONO_CLASS_IS_IMPORT (class))
5151 class->is_com_object = 1;
5152 else
5153 class->is_com_object = parent->is_com_object;
5155 if (system_namespace) {
5156 if (*class->name == 'M' && !strcmp (class->name, "MarshalByRefObject"))
5157 class->marshalbyref = 1;
5159 if (*class->name == 'C' && !strcmp (class->name, "ContextBoundObject"))
5160 class->contextbound = 1;
5162 if (*class->name == 'D' && !strcmp (class->name, "Delegate"))
5163 class->delegate = 1;
5166 if (class->parent->enumtype || (mono_is_corlib_image (class->parent->image) && (strcmp (class->parent->name, "ValueType") == 0) &&
5167 (strcmp (class->parent->name_space, "System") == 0)))
5168 class->valuetype = 1;
5169 if (mono_is_corlib_image (class->parent->image) && ((strcmp (class->parent->name, "Enum") == 0) && (strcmp (class->parent->name_space, "System") == 0))) {
5170 class->valuetype = class->enumtype = 1;
5172 /*class->enumtype = class->parent->enumtype; */
5173 mono_class_setup_supertypes (class);
5174 } else {
5175 /* initialize com types if COM interfaces are present */
5176 if (MONO_CLASS_IS_IMPORT (class))
5177 init_com_from_comimport (class);
5178 class->parent = NULL;
5184 * mono_class_setup_supertypes:
5185 * @class: a class
5187 * Build the data structure needed to make fast type checks work.
5188 * This currently sets two fields in @class:
5189 * - idepth: distance between @class and System.Object in the type
5190 * hierarchy + 1
5191 * - supertypes: array of classes: each element has a class in the hierarchy
5192 * starting from @class up to System.Object
5194 * LOCKING: this assumes the loader lock is held
5196 void
5197 mono_class_setup_supertypes (MonoClass *class)
5199 int ms;
5201 if (class->supertypes)
5202 return;
5204 if (class->parent && !class->parent->supertypes)
5205 mono_class_setup_supertypes (class->parent);
5206 if (class->parent)
5207 class->idepth = class->parent->idepth + 1;
5208 else
5209 class->idepth = 1;
5211 ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, class->idepth);
5212 class->supertypes = mono_class_alloc0 (class, sizeof (MonoClass *) * ms);
5214 if (class->parent) {
5215 class->supertypes [class->idepth - 1] = class;
5216 memcpy (class->supertypes, class->parent->supertypes, class->parent->idepth * sizeof (gpointer));
5217 } else {
5218 class->supertypes [0] = class;
5223 * mono_class_create_from_typedef:
5224 * @image: image where the token is valid
5225 * @type_token: typedef token
5227 * Create the MonoClass* representing the specified type token.
5228 * @type_token must be a TypeDef token.
5230 * FIXME: don't return NULL on failure, just the the caller figure it out.
5232 static MonoClass *
5233 mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
5235 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
5236 MonoClass *class, *parent = NULL;
5237 guint32 cols [MONO_TYPEDEF_SIZE];
5238 guint32 cols_next [MONO_TYPEDEF_SIZE];
5239 guint tidx = mono_metadata_token_index (type_token);
5240 MonoGenericContext *context = NULL;
5241 const char *name, *nspace;
5242 guint icount = 0;
5243 MonoClass **interfaces;
5244 guint32 field_last, method_last;
5245 guint32 nesting_tokeen;
5247 if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || tidx > tt->rows)
5248 return NULL;
5250 mono_loader_lock ();
5252 if ((class = mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
5253 mono_loader_unlock ();
5254 return class;
5257 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
5259 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
5260 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
5262 class = mono_image_alloc0 (image, sizeof (MonoClass));
5264 class->name = name;
5265 class->name_space = nspace;
5267 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
5269 class->image = image;
5270 class->type_token = type_token;
5271 class->flags = cols [MONO_TYPEDEF_FLAGS];
5273 mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), class);
5275 classes_size += sizeof (MonoClass);
5278 * Check whether we're a generic type definition.
5280 class->generic_container = mono_metadata_load_generic_params (image, class->type_token, NULL);
5281 if (class->generic_container) {
5282 class->is_generic = 1;
5283 class->generic_container->owner.klass = class;
5284 context = &class->generic_container->context;
5287 if (cols [MONO_TYPEDEF_EXTENDS]) {
5288 MonoClass *tmp;
5289 guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
5291 if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
5292 /*WARNING: this must satisfy mono_metadata_type_hash*/
5293 class->this_arg.byref = 1;
5294 class->this_arg.data.klass = class;
5295 class->this_arg.type = MONO_TYPE_CLASS;
5296 class->byval_arg.data.klass = class;
5297 class->byval_arg.type = MONO_TYPE_CLASS;
5299 parent = mono_class_get_full (image, parent_token, context);
5301 if (parent == NULL){
5302 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load parent type"));
5303 mono_loader_clear_error ();
5304 goto parent_failure;
5307 for (tmp = parent; tmp; tmp = tmp->parent) {
5308 if (tmp == class) {
5309 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Cycle found while resolving parent"));
5310 goto parent_failure;
5312 if (class->generic_container && tmp->generic_class && tmp->generic_class->container_class == class) {
5313 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Parent extends generic instance of this type"));
5314 goto parent_failure;
5319 mono_class_setup_parent (class, parent);
5321 /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
5322 mono_class_setup_mono_type (class);
5325 * This might access class->byval_arg for recursion generated by generic constraints,
5326 * so it has to come after setup_mono_type ().
5328 if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token))) {
5329 class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
5330 if (!class->nested_in) {
5331 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load nestedin type"));
5332 mono_loader_unlock ();
5333 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5334 return NULL;
5338 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
5339 class->unicode = 1;
5341 #ifdef HOST_WIN32
5342 if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
5343 class->unicode = 1;
5344 #endif
5346 class->cast_class = class->element_class = class;
5348 if (!class->enumtype) {
5349 if (!mono_metadata_interfaces_from_typedef_full (
5350 image, type_token, &interfaces, &icount, FALSE, context)){
5351 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load interfaces"));
5352 mono_loader_unlock ();
5353 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5354 return NULL;
5357 class->interfaces = interfaces;
5358 class->interface_count = icount;
5359 class->interfaces_inited = 1;
5362 /*g_print ("Load class %s\n", name);*/
5365 * Compute the field and method lists
5367 class->field.first = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
5368 class->method.first = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
5370 if (tt->rows > tidx){
5371 mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
5372 field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
5373 method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
5374 } else {
5375 field_last = image->tables [MONO_TABLE_FIELD].rows;
5376 method_last = image->tables [MONO_TABLE_METHOD].rows;
5379 if (cols [MONO_TYPEDEF_FIELD_LIST] &&
5380 cols [MONO_TYPEDEF_FIELD_LIST] <= image->tables [MONO_TABLE_FIELD].rows)
5381 class->field.count = field_last - class->field.first;
5382 else
5383 class->field.count = 0;
5385 if (cols [MONO_TYPEDEF_METHOD_LIST] <= image->tables [MONO_TABLE_METHOD].rows)
5386 class->method.count = method_last - class->method.first;
5387 else
5388 class->method.count = 0;
5390 /* reserve space to store vector pointer in arrays */
5391 if (mono_is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
5392 class->instance_size += 2 * sizeof (gpointer);
5393 g_assert (class->field.count == 0);
5396 if (class->enumtype) {
5397 MonoType *enum_basetype = mono_class_find_enum_basetype (class);
5398 if (!enum_basetype) {
5399 /*set it to a default value as the whole runtime can't handle this to be null*/
5400 class->cast_class = class->element_class = mono_defaults.int32_class;
5401 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
5402 mono_loader_unlock ();
5403 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5404 return NULL;
5406 class->cast_class = class->element_class = mono_class_from_mono_type (enum_basetype);
5410 * If we're a generic type definition, load the constraints.
5411 * We must do this after the class has been constructed to make certain recursive scenarios
5412 * work.
5414 if (class->generic_container && !mono_metadata_load_generic_param_constraints_full (image, type_token, class->generic_container)){
5415 char *class_name = g_strdup_printf("%s.%s", class->name_space, class->name);
5416 char *error = concat_two_strings_with_zero (class->image, class_name, class->image->assembly_name);
5417 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, error);
5418 g_free (class_name);
5419 mono_loader_unlock ();
5420 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5421 return NULL;
5424 if (class->image->assembly_name && !strcmp (class->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
5425 if (!strncmp (name, "Vector", 6))
5426 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");
5429 mono_loader_unlock ();
5431 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
5433 return class;
5435 parent_failure:
5436 mono_class_setup_mono_type (class);
5437 mono_loader_unlock ();
5438 mono_profiler_class_loaded (class, MONO_PROFILE_FAILED);
5439 return NULL;
5443 /** is klass Nullable<T>? */
5444 gboolean
5445 mono_class_is_nullable (MonoClass *klass)
5447 return klass->generic_class != NULL &&
5448 klass->generic_class->container_class == mono_defaults.generic_nullable_class;
5452 /** if klass is T? return T */
5453 MonoClass*
5454 mono_class_get_nullable_param (MonoClass *klass)
5456 g_assert (mono_class_is_nullable (klass));
5457 return mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
5461 * Create the `MonoClass' for an instantiation of a generic type.
5462 * We only do this if we actually need it.
5464 MonoClass*
5465 mono_generic_class_get_class (MonoGenericClass *gclass)
5467 MonoClass *klass, *gklass;
5469 mono_loader_lock ();
5470 if (gclass->cached_class) {
5471 mono_loader_unlock ();
5472 return gclass->cached_class;
5475 gclass->cached_class = mono_image_set_alloc0 (gclass->owner, sizeof (MonoClass));
5476 klass = gclass->cached_class;
5478 gklass = gclass->container_class;
5480 if (gklass->nested_in) {
5481 /* The nested_in type should not be inflated since it's possible to produce a nested type with less generic arguments*/
5482 klass->nested_in = gklass->nested_in;
5485 klass->name = gklass->name;
5486 klass->name_space = gklass->name_space;
5488 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
5490 klass->image = gklass->image;
5491 klass->flags = gklass->flags;
5492 klass->type_token = gklass->type_token;
5493 klass->field.count = gklass->field.count;
5495 klass->is_inflated = 1;
5496 klass->generic_class = gclass;
5498 klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
5499 klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
5500 klass->this_arg.byref = TRUE;
5501 klass->enumtype = gklass->enumtype;
5502 klass->valuetype = gklass->valuetype;
5504 klass->cast_class = klass->element_class = klass;
5506 if (mono_class_is_nullable (klass))
5507 klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
5510 * We're not interested in the nested classes of a generic instance.
5511 * We use the generic type definition to look for nested classes.
5514 if (gklass->parent) {
5515 MonoError error;
5516 klass->parent = mono_class_inflate_generic_class_checked (gklass->parent, mono_generic_class_get_context (gclass), &error);
5517 if (!mono_error_ok (&error)) {
5518 /*Set parent to something safe as the runtime doesn't handle well this kind of failure.*/
5519 klass->parent = mono_defaults.object_class;
5520 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
5521 mono_error_cleanup (&error);
5525 if (klass->parent)
5526 mono_class_setup_parent (klass, klass->parent);
5528 if (klass->enumtype) {
5529 klass->cast_class = gklass->cast_class;
5530 klass->element_class = gklass->element_class;
5533 if (gclass->is_dynamic) {
5534 klass->inited = 1;
5536 mono_class_setup_supertypes (klass);
5538 if (klass->enumtype) {
5540 * For enums, gklass->fields might not been set, but instance_size etc. is
5541 * already set in mono_reflection_create_internal_class (). For non-enums,
5542 * these will be computed normally in mono_class_layout_fields ().
5544 klass->instance_size = gklass->instance_size;
5545 klass->sizes.class_size = gklass->sizes.class_size;
5546 klass->size_inited = 1;
5550 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
5552 inflated_classes ++;
5553 inflated_classes_size += sizeof (MonoClass);
5555 mono_loader_unlock ();
5557 return klass;
5560 static MonoClass*
5561 make_generic_param_class (MonoGenericParam *param, MonoImage *image, gboolean is_mvar, MonoGenericParamInfo *pinfo)
5563 MonoClass *klass, **ptr;
5564 int count, pos, i;
5565 MonoGenericContainer *container = mono_generic_param_owner (param);
5567 if (!image)
5568 /* FIXME: */
5569 image = mono_defaults.corlib;
5571 klass = mono_image_alloc0 (image, sizeof (MonoClass));
5572 classes_size += sizeof (MonoClass);
5574 if (pinfo) {
5575 klass->name = pinfo->name;
5576 } else {
5577 int n = mono_generic_param_num (param);
5578 klass->name = mono_image_alloc0 (image, 16);
5579 sprintf ((char*)klass->name, "%d", n);
5582 if (container) {
5583 if (is_mvar) {
5584 MonoMethod *omethod = container->owner.method;
5585 klass->name_space = (omethod && omethod->klass) ? omethod->klass->name_space : "";
5586 } else {
5587 MonoClass *oklass = container->owner.klass;
5588 klass->name_space = oklass ? oklass->name_space : "";
5590 } else {
5591 klass->name_space = "";
5594 mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
5596 count = 0;
5597 if (pinfo)
5598 for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
5601 pos = 0;
5602 if ((count > 0) && !MONO_CLASS_IS_INTERFACE (pinfo->constraints [0])) {
5603 klass->parent = pinfo->constraints [0];
5604 pos++;
5605 } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT)
5606 klass->parent = mono_class_from_name (mono_defaults.corlib, "System", "ValueType");
5607 else
5608 klass->parent = mono_defaults.object_class;
5611 if (count - pos > 0) {
5612 klass->interface_count = count - pos;
5613 klass->interfaces = mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos));
5614 klass->interfaces_inited = TRUE;
5615 for (i = pos; i < count; i++)
5616 klass->interfaces [i - pos] = pinfo->constraints [i];
5619 klass->image = image;
5621 klass->inited = TRUE;
5622 klass->cast_class = klass->element_class = klass;
5623 klass->flags = TYPE_ATTRIBUTE_PUBLIC;
5625 klass->this_arg.type = klass->byval_arg.type = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
5626 klass->this_arg.data.generic_param = klass->byval_arg.data.generic_param = param;
5627 klass->this_arg.byref = TRUE;
5629 /* We don't use type_token for VAR since only classes can use it (not arrays, pointer, VARs, etc) */
5630 klass->sizes.generic_param_token = pinfo ? pinfo->token : 0;
5632 /*Init these fields to sane values*/
5633 klass->min_align = 1;
5634 klass->instance_size = sizeof (gpointer);
5635 klass->size_inited = 1;
5637 mono_class_setup_supertypes (klass);
5639 if (count - pos > 0) {
5640 mono_class_setup_vtable (klass->parent);
5641 if (klass->parent->exception_type)
5642 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Failed to setup parent interfaces"));
5643 else
5644 setup_interface_offsets (klass, klass->parent->vtable_size);
5647 return klass;
5650 #define FAST_CACHE_SIZE 16
5652 static MonoClass *
5653 get_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar)
5655 int n = mono_generic_param_num (param);
5656 MonoImage *image = param->image;
5657 GHashTable *ht;
5659 g_assert (image);
5661 if (n < FAST_CACHE_SIZE) {
5662 if (is_mvar)
5663 return image->mvar_cache_fast ? image->mvar_cache_fast [n] : NULL;
5664 else
5665 return image->var_cache_fast ? image->var_cache_fast [n] : NULL;
5666 } else {
5667 ht = is_mvar ? image->mvar_cache_slow : image->var_cache_slow;
5668 return ht ? g_hash_table_lookup (ht, GINT_TO_POINTER (n)) : NULL;
5673 * LOCKING: Acquires the loader lock.
5675 static void
5676 set_anon_gparam_class (MonoGenericParam *param, gboolean is_mvar, MonoClass *klass)
5678 int n = mono_generic_param_num (param);
5679 MonoImage *image = param->image;
5680 GHashTable *ht;
5682 g_assert (image);
5684 if (n < FAST_CACHE_SIZE) {
5685 if (is_mvar) {
5686 /* No locking needed */
5687 if (!image->mvar_cache_fast)
5688 image->mvar_cache_fast = mono_image_alloc0 (image, sizeof (MonoClass*) * FAST_CACHE_SIZE);
5689 image->mvar_cache_fast [n] = klass;
5690 } else {
5691 if (!image->var_cache_fast)
5692 image->var_cache_fast = mono_image_alloc0 (image, sizeof (MonoClass*) * FAST_CACHE_SIZE);
5693 image->var_cache_fast [n] = klass;
5695 return;
5697 ht = is_mvar ? image->mvar_cache_slow : image->var_cache_slow;
5698 if (!ht) {
5699 mono_loader_lock ();
5700 ht = is_mvar ? image->mvar_cache_slow : image->var_cache_slow;
5701 if (!ht) {
5702 ht = g_hash_table_new (NULL, NULL);
5703 mono_memory_barrier ();
5704 if (is_mvar)
5705 image->mvar_cache_slow = ht;
5706 else
5707 image->var_cache_slow = ht;
5709 mono_loader_unlock ();
5712 g_hash_table_insert (ht, GINT_TO_POINTER (n), klass);
5716 * LOCKING: Acquires the loader lock.
5718 MonoClass *
5719 mono_class_from_generic_parameter (MonoGenericParam *param, MonoImage *image, gboolean is_mvar)
5721 MonoGenericContainer *container = mono_generic_param_owner (param);
5722 MonoGenericParamInfo *pinfo;
5723 MonoClass *klass;
5725 mono_loader_lock ();
5727 if (container) {
5728 pinfo = mono_generic_param_info (param);
5729 if (pinfo->pklass) {
5730 mono_loader_unlock ();
5731 return pinfo->pklass;
5733 } else {
5734 pinfo = NULL;
5735 image = NULL;
5737 klass = get_anon_gparam_class (param, is_mvar);
5738 if (klass) {
5739 mono_loader_unlock ();
5740 return klass;
5744 if (!image && container) {
5745 if (is_mvar) {
5746 MonoMethod *method = container->owner.method;
5747 image = (method && method->klass) ? method->klass->image : NULL;
5748 } else {
5749 MonoClass *klass = container->owner.klass;
5750 // FIXME: 'klass' should not be null
5751 // But, monodis creates GenericContainers without associating a owner to it
5752 image = klass ? klass->image : NULL;
5756 klass = make_generic_param_class (param, image, is_mvar, pinfo);
5758 mono_memory_barrier ();
5760 if (container)
5761 pinfo->pklass = klass;
5762 else
5763 set_anon_gparam_class (param, is_mvar, klass);
5765 mono_loader_unlock ();
5767 /* FIXME: Should this go inside 'make_generic_param_klass'? */
5768 mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
5770 return klass;
5773 MonoClass *
5774 mono_ptr_class_get (MonoType *type)
5776 MonoClass *result;
5777 MonoClass *el_class;
5778 MonoImage *image;
5779 char *name;
5781 el_class = mono_class_from_mono_type (type);
5782 image = el_class->image;
5784 mono_loader_lock ();
5786 if (!image->ptr_cache)
5787 image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
5789 if ((result = g_hash_table_lookup (image->ptr_cache, el_class))) {
5790 mono_loader_unlock ();
5791 return result;
5793 result = mono_image_alloc0 (image, sizeof (MonoClass));
5795 classes_size += sizeof (MonoClass);
5797 result->parent = NULL; /* no parent for PTR types */
5798 result->name_space = el_class->name_space;
5799 name = g_strdup_printf ("%s*", el_class->name);
5800 result->name = mono_image_strdup (image, name);
5801 g_free (name);
5803 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5805 result->image = el_class->image;
5806 result->inited = TRUE;
5807 result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
5808 /* Can pointers get boxed? */
5809 result->instance_size = sizeof (gpointer);
5810 result->cast_class = result->element_class = el_class;
5811 result->blittable = TRUE;
5813 result->this_arg.type = result->byval_arg.type = MONO_TYPE_PTR;
5814 result->this_arg.data.type = result->byval_arg.data.type = &result->element_class->byval_arg;
5815 result->this_arg.byref = TRUE;
5817 mono_class_setup_supertypes (result);
5819 g_hash_table_insert (image->ptr_cache, el_class, result);
5821 mono_loader_unlock ();
5823 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5825 return result;
5828 static MonoClass *
5829 mono_fnptr_class_get (MonoMethodSignature *sig)
5831 MonoClass *result;
5832 static GHashTable *ptr_hash = NULL;
5834 /* FIXME: These should be allocate from a mempool as well, but which one ? */
5836 mono_loader_lock ();
5838 if (!ptr_hash)
5839 ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5841 if ((result = g_hash_table_lookup (ptr_hash, sig))) {
5842 mono_loader_unlock ();
5843 return result;
5845 result = g_new0 (MonoClass, 1);
5847 result->parent = NULL; /* no parent for PTR types */
5848 result->name_space = "System";
5849 result->name = "MonoFNPtrFakeClass";
5851 mono_profiler_class_event (result, MONO_PROFILE_START_LOAD);
5853 result->image = mono_defaults.corlib; /* need to fix... */
5854 result->inited = TRUE;
5855 result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
5856 /* Can pointers get boxed? */
5857 result->instance_size = sizeof (gpointer);
5858 result->cast_class = result->element_class = result;
5859 result->blittable = TRUE;
5861 result->this_arg.type = result->byval_arg.type = MONO_TYPE_FNPTR;
5862 result->this_arg.data.method = result->byval_arg.data.method = sig;
5863 result->this_arg.byref = TRUE;
5864 result->blittable = TRUE;
5866 mono_class_setup_supertypes (result);
5868 g_hash_table_insert (ptr_hash, sig, result);
5870 mono_loader_unlock ();
5872 mono_profiler_class_loaded (result, MONO_PROFILE_OK);
5874 return result;
5877 MonoClass *
5878 mono_class_from_mono_type (MonoType *type)
5880 switch (type->type) {
5881 case MONO_TYPE_OBJECT:
5882 return type->data.klass? type->data.klass: mono_defaults.object_class;
5883 case MONO_TYPE_VOID:
5884 return type->data.klass? type->data.klass: mono_defaults.void_class;
5885 case MONO_TYPE_BOOLEAN:
5886 return type->data.klass? type->data.klass: mono_defaults.boolean_class;
5887 case MONO_TYPE_CHAR:
5888 return type->data.klass? type->data.klass: mono_defaults.char_class;
5889 case MONO_TYPE_I1:
5890 return type->data.klass? type->data.klass: mono_defaults.sbyte_class;
5891 case MONO_TYPE_U1:
5892 return type->data.klass? type->data.klass: mono_defaults.byte_class;
5893 case MONO_TYPE_I2:
5894 return type->data.klass? type->data.klass: mono_defaults.int16_class;
5895 case MONO_TYPE_U2:
5896 return type->data.klass? type->data.klass: mono_defaults.uint16_class;
5897 case MONO_TYPE_I4:
5898 return type->data.klass? type->data.klass: mono_defaults.int32_class;
5899 case MONO_TYPE_U4:
5900 return type->data.klass? type->data.klass: mono_defaults.uint32_class;
5901 case MONO_TYPE_I:
5902 return type->data.klass? type->data.klass: mono_defaults.int_class;
5903 case MONO_TYPE_U:
5904 return type->data.klass? type->data.klass: mono_defaults.uint_class;
5905 case MONO_TYPE_I8:
5906 return type->data.klass? type->data.klass: mono_defaults.int64_class;
5907 case MONO_TYPE_U8:
5908 return type->data.klass? type->data.klass: mono_defaults.uint64_class;
5909 case MONO_TYPE_R4:
5910 return type->data.klass? type->data.klass: mono_defaults.single_class;
5911 case MONO_TYPE_R8:
5912 return type->data.klass? type->data.klass: mono_defaults.double_class;
5913 case MONO_TYPE_STRING:
5914 return type->data.klass? type->data.klass: mono_defaults.string_class;
5915 case MONO_TYPE_TYPEDBYREF:
5916 return type->data.klass? type->data.klass: mono_defaults.typed_reference_class;
5917 case MONO_TYPE_ARRAY:
5918 return mono_bounded_array_class_get (type->data.array->eklass, type->data.array->rank, TRUE);
5919 case MONO_TYPE_PTR:
5920 return mono_ptr_class_get (type->data.type);
5921 case MONO_TYPE_FNPTR:
5922 return mono_fnptr_class_get (type->data.method);
5923 case MONO_TYPE_SZARRAY:
5924 return mono_array_class_get (type->data.klass, 1);
5925 case MONO_TYPE_CLASS:
5926 case MONO_TYPE_VALUETYPE:
5927 return type->data.klass;
5928 case MONO_TYPE_GENERICINST:
5929 return mono_generic_class_get_class (type->data.generic_class);
5930 case MONO_TYPE_VAR:
5931 return mono_class_from_generic_parameter (type->data.generic_param, NULL, FALSE);
5932 case MONO_TYPE_MVAR:
5933 return mono_class_from_generic_parameter (type->data.generic_param, NULL, TRUE);
5934 default:
5935 g_warning ("mono_class_from_mono_type: implement me 0x%02x\n", type->type);
5936 g_assert_not_reached ();
5939 return NULL;
5943 * mono_type_retrieve_from_typespec
5944 * @image: context where the image is created
5945 * @type_spec: typespec token
5946 * @context: the generic context used to evaluate generic instantiations in
5948 static MonoType *
5949 mono_type_retrieve_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, gboolean *did_inflate, MonoError *error)
5951 MonoType *t = mono_type_create_from_typespec (image, type_spec);
5953 mono_error_init (error);
5954 *did_inflate = FALSE;
5956 if (!t) {
5957 char *name = mono_class_name_from_token (image, type_spec);
5958 char *assembly = mono_assembly_name_from_token (image, type_spec);
5959 mono_error_set_type_load_name (error, name, assembly, "Could not resolve typespec token %08x", type_spec);
5960 return NULL;
5963 if (context && (context->class_inst || context->method_inst)) {
5964 MonoType *inflated = inflate_generic_type (NULL, t, context, error);
5966 if (!mono_error_ok (error))
5967 return NULL;
5969 if (inflated) {
5970 t = inflated;
5971 *did_inflate = TRUE;
5974 return t;
5978 * mono_class_create_from_typespec
5979 * @image: context where the image is created
5980 * @type_spec: typespec token
5981 * @context: the generic context used to evaluate generic instantiations in
5983 static MonoClass *
5984 mono_class_create_from_typespec (MonoImage *image, guint32 type_spec, MonoGenericContext *context, MonoError *error)
5986 MonoClass *ret;
5987 gboolean inflated = FALSE;
5988 MonoType *t = mono_type_retrieve_from_typespec (image, type_spec, context, &inflated, error);
5989 if (!mono_error_ok (error))
5990 return NULL;
5991 ret = mono_class_from_mono_type (t);
5992 if (inflated)
5993 mono_metadata_free_type (t);
5994 return ret;
5998 * mono_bounded_array_class_get:
5999 * @element_class: element class
6000 * @rank: the dimension of the array class
6001 * @bounded: whenever the array has non-zero bounds
6003 * Returns: a class object describing the array with element type @element_type and
6004 * dimension @rank.
6006 MonoClass *
6007 mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
6009 MonoImage *image;
6010 MonoClass *class;
6011 MonoClass *parent = NULL;
6012 GSList *list, *rootlist = NULL;
6013 int nsize;
6014 char *name;
6015 gboolean corlib_type = FALSE;
6017 g_assert (rank <= 255);
6019 if (rank > 1)
6020 /* bounded only matters for one-dimensional arrays */
6021 bounded = FALSE;
6023 image = eclass->image;
6025 if (rank == 1 && !bounded) {
6027 * This case is very frequent not just during compilation because of calls
6028 * from mono_class_from_mono_type (), mono_array_new (),
6029 * Array:CreateInstance (), etc, so use a separate cache + a separate lock.
6031 EnterCriticalSection (&image->szarray_cache_lock);
6032 if (!image->szarray_cache)
6033 image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
6034 class = g_hash_table_lookup (image->szarray_cache, eclass);
6035 LeaveCriticalSection (&image->szarray_cache_lock);
6036 if (class)
6037 return class;
6039 mono_loader_lock ();
6040 } else {
6041 mono_loader_lock ();
6043 if (!image->array_cache)
6044 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
6046 if ((rootlist = list = g_hash_table_lookup (image->array_cache, eclass))) {
6047 for (; list; list = list->next) {
6048 class = list->data;
6049 if ((class->rank == rank) && (class->byval_arg.type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
6050 mono_loader_unlock ();
6051 return class;
6057 /* for the building corlib use System.Array from it */
6058 if (image->assembly && image->assembly->dynamic && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) {
6059 parent = mono_class_from_name (image, "System", "Array");
6060 corlib_type = TRUE;
6061 } else {
6062 parent = mono_defaults.array_class;
6063 if (!parent->inited)
6064 mono_class_init (parent);
6067 class = mono_image_alloc0 (image, sizeof (MonoClass));
6069 class->image = image;
6070 class->name_space = eclass->name_space;
6071 nsize = strlen (eclass->name);
6072 name = g_malloc (nsize + 2 + rank + 1);
6073 memcpy (name, eclass->name, nsize);
6074 name [nsize] = '[';
6075 if (rank > 1)
6076 memset (name + nsize + 1, ',', rank - 1);
6077 if (bounded)
6078 name [nsize + rank] = '*';
6079 name [nsize + rank + bounded] = ']';
6080 name [nsize + rank + bounded + 1] = 0;
6081 class->name = mono_image_strdup (image, name);
6082 g_free (name);
6084 mono_profiler_class_event (class, MONO_PROFILE_START_LOAD);
6086 classes_size += sizeof (MonoClass);
6088 class->type_token = 0;
6089 /* all arrays are marked serializable and sealed, bug #42779 */
6090 class->flags = TYPE_ATTRIBUTE_CLASS | TYPE_ATTRIBUTE_SERIALIZABLE | TYPE_ATTRIBUTE_SEALED | TYPE_ATTRIBUTE_PUBLIC;
6091 class->parent = parent;
6092 class->instance_size = mono_class_instance_size (class->parent);
6094 if (eclass->byval_arg.type == MONO_TYPE_TYPEDBYREF || eclass->byval_arg.type == MONO_TYPE_VOID) {
6095 /*Arrays of those two types are invalid.*/
6096 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
6097 } else if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
6098 if (!eclass->ref_info_handle || eclass->wastypebuilder) {
6099 g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
6100 g_assert (eclass->ref_info_handle && !eclass->wastypebuilder);
6102 /* element_size -1 is ok as this is not an instantitable type*/
6103 class->sizes.element_size = -1;
6104 } else
6105 class->sizes.element_size = mono_class_array_element_size (eclass);
6107 mono_class_setup_supertypes (class);
6109 if (eclass->generic_class)
6110 mono_class_init (eclass);
6111 if (!eclass->size_inited)
6112 mono_class_setup_fields (eclass);
6113 if (eclass->exception_type) /*FIXME we fail the array type, but we have to let other fields be set.*/
6114 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
6116 class->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
6118 class->rank = rank;
6120 if (eclass->enumtype)
6121 class->cast_class = eclass->element_class;
6122 else
6123 class->cast_class = eclass;
6125 switch (class->cast_class->byval_arg.type) {
6126 case MONO_TYPE_I1:
6127 class->cast_class = mono_defaults.byte_class;
6128 break;
6129 case MONO_TYPE_U2:
6130 class->cast_class = mono_defaults.int16_class;
6131 break;
6132 case MONO_TYPE_U4:
6133 #if SIZEOF_VOID_P == 4
6134 case MONO_TYPE_I:
6135 case MONO_TYPE_U:
6136 #endif
6137 class->cast_class = mono_defaults.int32_class;
6138 break;
6139 case MONO_TYPE_U8:
6140 #if SIZEOF_VOID_P == 8
6141 case MONO_TYPE_I:
6142 case MONO_TYPE_U:
6143 #endif
6144 class->cast_class = mono_defaults.int64_class;
6145 break;
6148 class->element_class = eclass;
6150 if ((rank > 1) || bounded) {
6151 MonoArrayType *at = mono_image_alloc0 (image, sizeof (MonoArrayType));
6152 class->byval_arg.type = MONO_TYPE_ARRAY;
6153 class->byval_arg.data.array = at;
6154 at->eklass = eclass;
6155 at->rank = rank;
6156 /* FIXME: complete.... */
6157 } else {
6158 class->byval_arg.type = MONO_TYPE_SZARRAY;
6159 class->byval_arg.data.klass = eclass;
6161 class->this_arg = class->byval_arg;
6162 class->this_arg.byref = 1;
6163 if (corlib_type) {
6164 class->inited = 1;
6167 class->generic_container = eclass->generic_container;
6169 if (rank == 1 && !bounded) {
6170 MonoClass *prev_class;
6172 EnterCriticalSection (&image->szarray_cache_lock);
6173 prev_class = g_hash_table_lookup (image->szarray_cache, eclass);
6174 if (prev_class)
6175 /* Someone got in before us */
6176 class = prev_class;
6177 else
6178 g_hash_table_insert (image->szarray_cache, eclass, class);
6179 LeaveCriticalSection (&image->szarray_cache_lock);
6180 } else {
6181 list = g_slist_append (rootlist, class);
6182 g_hash_table_insert (image->array_cache, eclass, list);
6185 mono_loader_unlock ();
6187 mono_profiler_class_loaded (class, MONO_PROFILE_OK);
6189 return class;
6193 * mono_array_class_get:
6194 * @element_class: element class
6195 * @rank: the dimension of the array class
6197 * Returns: a class object describing the array with element type @element_type and
6198 * dimension @rank.
6200 MonoClass *
6201 mono_array_class_get (MonoClass *eclass, guint32 rank)
6203 return mono_bounded_array_class_get (eclass, rank, FALSE);
6207 * mono_class_instance_size:
6208 * @klass: a class
6210 * Returns: the size of an object instance
6212 gint32
6213 mono_class_instance_size (MonoClass *klass)
6215 if (!klass->size_inited)
6216 mono_class_init (klass);
6218 return klass->instance_size;
6222 * mono_class_min_align:
6223 * @klass: a class
6225 * Returns: minimm alignment requirements
6227 gint32
6228 mono_class_min_align (MonoClass *klass)
6230 if (!klass->size_inited)
6231 mono_class_init (klass);
6233 return klass->min_align;
6237 * mono_class_value_size:
6238 * @klass: a class
6240 * This function is used for value types, and return the
6241 * space and the alignment to store that kind of value object.
6243 * Returns: the size of a value of kind @klass
6245 gint32
6246 mono_class_value_size (MonoClass *klass, guint32 *align)
6248 gint32 size;
6250 /* fixme: check disable, because we still have external revereces to
6251 * mscorlib and Dummy Objects
6253 /*g_assert (klass->valuetype);*/
6255 size = mono_class_instance_size (klass) - sizeof (MonoObject);
6257 if (align)
6258 *align = klass->min_align;
6260 return size;
6264 * mono_class_data_size:
6265 * @klass: a class
6267 * Returns: the size of the static class data
6269 gint32
6270 mono_class_data_size (MonoClass *klass)
6272 if (!klass->inited)
6273 mono_class_init (klass);
6275 /* in arrays, sizes.class_size is unioned with element_size
6276 * and arrays have no static fields
6278 if (klass->rank)
6279 return 0;
6280 return klass->sizes.class_size;
6284 * Auxiliary routine to mono_class_get_field
6286 * Takes a field index instead of a field token.
6288 static MonoClassField *
6289 mono_class_get_field_idx (MonoClass *class, int idx)
6291 mono_class_setup_fields_locking (class);
6292 if (class->exception_type)
6293 return NULL;
6295 while (class) {
6296 if (class->image->uncompressed_metadata) {
6298 * class->field.first points to the FieldPtr table, while idx points into the
6299 * Field table, so we have to do a search.
6301 /*FIXME this is broken for types with multiple fields with the same name.*/
6302 const char *name = mono_metadata_string_heap (class->image, mono_metadata_decode_row_col (&class->image->tables [MONO_TABLE_FIELD], idx, MONO_FIELD_NAME));
6303 int i;
6305 for (i = 0; i < class->field.count; ++i)
6306 if (mono_field_get_name (&class->fields [i]) == name)
6307 return &class->fields [i];
6308 g_assert_not_reached ();
6309 } else {
6310 if (class->field.count) {
6311 if ((idx >= class->field.first) && (idx < class->field.first + class->field.count)){
6312 return &class->fields [idx - class->field.first];
6316 class = class->parent;
6318 return NULL;
6322 * mono_class_get_field:
6323 * @class: the class to lookup the field.
6324 * @field_token: the field token
6326 * Returns: A MonoClassField representing the type and offset of
6327 * the field, or a NULL value if the field does not belong to this
6328 * class.
6330 MonoClassField *
6331 mono_class_get_field (MonoClass *class, guint32 field_token)
6333 int idx = mono_metadata_token_index (field_token);
6335 g_assert (mono_metadata_token_code (field_token) == MONO_TOKEN_FIELD_DEF);
6337 return mono_class_get_field_idx (class, idx - 1);
6341 * mono_class_get_field_from_name:
6342 * @klass: the class to lookup the field.
6343 * @name: the field name
6345 * Search the class @klass and it's parents for a field with the name @name.
6347 * Returns: the MonoClassField pointer of the named field or NULL
6349 MonoClassField *
6350 mono_class_get_field_from_name (MonoClass *klass, const char *name)
6352 return mono_class_get_field_from_name_full (klass, name, NULL);
6356 * mono_class_get_field_from_name_full:
6357 * @klass: the class to lookup the field.
6358 * @name: the field name
6359 * @type: the type of the fields. This optional.
6361 * Search the class @klass and it's parents for a field with the name @name and type @type.
6363 * If @klass is an inflated generic type, the type comparison is done with the equivalent field
6364 * of its generic type definition.
6366 * Returns: the MonoClassField pointer of the named field or NULL
6368 MonoClassField *
6369 mono_class_get_field_from_name_full (MonoClass *klass, const char *name, MonoType *type)
6371 int i;
6373 mono_class_setup_fields_locking (klass);
6374 if (klass->exception_type)
6375 return NULL;
6377 while (klass) {
6378 for (i = 0; i < klass->field.count; ++i) {
6379 MonoClassField *field = &klass->fields [i];
6381 if (strcmp (name, mono_field_get_name (field)) != 0)
6382 continue;
6384 if (type) {
6385 MonoType *field_type = mono_metadata_get_corresponding_field_from_generic_type_definition (field)->type;
6386 if (!mono_metadata_type_equal_full (type, field_type, TRUE))
6387 continue;
6389 return field;
6391 klass = klass->parent;
6393 return NULL;
6397 * mono_class_get_field_token:
6398 * @field: the field we need the token of
6400 * Get the token of a field. Note that the tokesn is only valid for the image
6401 * the field was loaded from. Don't use this function for fields in dynamic types.
6403 * Returns: the token representing the field in the image it was loaded from.
6405 guint32
6406 mono_class_get_field_token (MonoClassField *field)
6408 MonoClass *klass = field->parent;
6409 int i;
6411 mono_class_setup_fields_locking (klass);
6412 if (klass->exception_type)
6413 return 0;
6415 while (klass) {
6416 for (i = 0; i < klass->field.count; ++i) {
6417 if (&klass->fields [i] == field) {
6418 int idx = klass->field.first + i + 1;
6420 if (klass->image->uncompressed_metadata)
6421 idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_FIELD, idx);
6422 return mono_metadata_make_token (MONO_TABLE_FIELD, idx);
6425 klass = klass->parent;
6428 g_assert_not_reached ();
6429 return 0;
6432 static int
6433 mono_field_get_index (MonoClassField *field)
6435 int index = field - field->parent->fields;
6437 g_assert (index >= 0 && index < field->parent->field.count);
6439 return index;
6443 * mono_class_get_field_default_value:
6445 * Return the default value of the field as a pointer into the metadata blob.
6447 const char*
6448 mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_type)
6450 guint32 cindex;
6451 guint32 constant_cols [MONO_CONSTANT_SIZE];
6452 int field_index;
6453 MonoClass *klass = field->parent;
6455 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT);
6457 if (!klass->ext || !klass->ext->field_def_values) {
6458 mono_loader_lock ();
6459 mono_class_alloc_ext (klass);
6460 if (!klass->ext->field_def_values)
6461 klass->ext->field_def_values = mono_class_alloc0 (klass, sizeof (MonoFieldDefaultValue) * klass->field.count);
6462 mono_loader_unlock ();
6465 field_index = mono_field_get_index (field);
6467 if (!klass->ext->field_def_values [field_index].data) {
6468 cindex = mono_metadata_get_constant_index (field->parent->image, mono_class_get_field_token (field), 0);
6469 g_assert (cindex);
6470 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA));
6472 mono_metadata_decode_row (&field->parent->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
6473 klass->ext->field_def_values [field_index].def_type = constant_cols [MONO_CONSTANT_TYPE];
6474 klass->ext->field_def_values [field_index].data = (gpointer)mono_metadata_blob_heap (field->parent->image, constant_cols [MONO_CONSTANT_VALUE]);
6477 *def_type = klass->ext->field_def_values [field_index].def_type;
6478 return klass->ext->field_def_values [field_index].data;
6481 static int
6482 mono_property_get_index (MonoProperty *prop)
6484 int index = prop - prop->parent->ext->properties;
6486 g_assert (index >= 0 && index < prop->parent->ext->property.count);
6488 return index;
6492 * mono_class_get_property_default_value:
6494 * Return the default value of the field as a pointer into the metadata blob.
6496 const char*
6497 mono_class_get_property_default_value (MonoProperty *property, MonoTypeEnum *def_type)
6499 guint32 cindex;
6500 guint32 constant_cols [MONO_CONSTANT_SIZE];
6501 MonoClass *klass = property->parent;
6503 g_assert (property->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT);
6505 * We don't cache here because it is not used by C# so it's quite rare, but
6506 * we still do the lookup in klass->ext because that is where the data
6507 * is stored for dynamic assemblies.
6510 if (klass->image->dynamic) {
6511 int prop_index = mono_property_get_index (property);
6512 if (klass->ext->prop_def_values && klass->ext->prop_def_values [prop_index].data) {
6513 *def_type = klass->ext->prop_def_values [prop_index].def_type;
6514 return klass->ext->prop_def_values [prop_index].data;
6516 return NULL;
6518 cindex = mono_metadata_get_constant_index (klass->image, mono_class_get_property_token (property), 0);
6519 if (!cindex)
6520 return NULL;
6522 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
6523 *def_type = constant_cols [MONO_CONSTANT_TYPE];
6524 return (gpointer)mono_metadata_blob_heap (klass->image, constant_cols [MONO_CONSTANT_VALUE]);
6527 guint32
6528 mono_class_get_event_token (MonoEvent *event)
6530 MonoClass *klass = event->parent;
6531 int i;
6533 while (klass) {
6534 if (klass->ext) {
6535 for (i = 0; i < klass->ext->event.count; ++i) {
6536 if (&klass->ext->events [i] == event)
6537 return mono_metadata_make_token (MONO_TABLE_EVENT, klass->ext->event.first + i + 1);
6540 klass = klass->parent;
6543 g_assert_not_reached ();
6544 return 0;
6547 MonoProperty*
6548 mono_class_get_property_from_name (MonoClass *klass, const char *name)
6550 while (klass) {
6551 MonoProperty* p;
6552 gpointer iter = NULL;
6553 while ((p = mono_class_get_properties (klass, &iter))) {
6554 if (! strcmp (name, p->name))
6555 return p;
6557 klass = klass->parent;
6559 return NULL;
6562 guint32
6563 mono_class_get_property_token (MonoProperty *prop)
6565 MonoClass *klass = prop->parent;
6566 while (klass) {
6567 MonoProperty* p;
6568 int i = 0;
6569 gpointer iter = NULL;
6570 while ((p = mono_class_get_properties (klass, &iter))) {
6571 if (&klass->ext->properties [i] == prop)
6572 return mono_metadata_make_token (MONO_TABLE_PROPERTY, klass->ext->property.first + i + 1);
6574 i ++;
6576 klass = klass->parent;
6579 g_assert_not_reached ();
6580 return 0;
6583 char *
6584 mono_class_name_from_token (MonoImage *image, guint32 type_token)
6586 const char *name, *nspace;
6587 if (image->dynamic)
6588 return g_strdup_printf ("DynamicType 0x%08x", type_token);
6590 switch (type_token & 0xff000000){
6591 case MONO_TOKEN_TYPE_DEF: {
6592 guint32 cols [MONO_TYPEDEF_SIZE];
6593 MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
6594 guint tidx = mono_metadata_token_index (type_token);
6596 if (tidx > tt->rows)
6597 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6599 mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
6600 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6601 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6602 if (strlen (nspace) == 0)
6603 return g_strdup_printf ("%s", name);
6604 else
6605 return g_strdup_printf ("%s.%s", nspace, name);
6608 case MONO_TOKEN_TYPE_REF: {
6609 MonoError error;
6610 guint32 cols [MONO_TYPEREF_SIZE];
6611 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
6612 guint tidx = mono_metadata_token_index (type_token);
6614 if (tidx > t->rows)
6615 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6617 if (!mono_verifier_verify_typeref_row (image, tidx - 1, &error)) {
6618 char *msg = g_strdup_printf ("Invalid type token 0x%08x due to '%s'", type_token, mono_error_get_message (&error));
6619 mono_error_cleanup (&error);
6620 return msg;
6623 mono_metadata_decode_row (t, tidx-1, cols, MONO_TYPEREF_SIZE);
6624 name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
6625 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
6626 if (strlen (nspace) == 0)
6627 return g_strdup_printf ("%s", name);
6628 else
6629 return g_strdup_printf ("%s.%s", nspace, name);
6632 case MONO_TOKEN_TYPE_SPEC:
6633 return g_strdup_printf ("Typespec 0x%08x", type_token);
6634 default:
6635 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6639 static char *
6640 mono_assembly_name_from_token (MonoImage *image, guint32 type_token)
6642 if (image->dynamic)
6643 return g_strdup_printf ("DynamicAssembly %s", image->name);
6645 switch (type_token & 0xff000000){
6646 case MONO_TOKEN_TYPE_DEF:
6647 if (image->assembly)
6648 return mono_stringify_assembly_name (&image->assembly->aname);
6649 else if (image->assembly_name)
6650 return g_strdup (image->assembly_name);
6651 return g_strdup_printf ("%s", image->name ? image->name : "[Could not resolve assembly name");
6652 case MONO_TOKEN_TYPE_REF: {
6653 MonoError error;
6654 MonoAssemblyName aname;
6655 guint32 cols [MONO_TYPEREF_SIZE];
6656 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
6657 guint32 idx = mono_metadata_token_index (type_token);
6659 if (idx > t->rows)
6660 return g_strdup_printf ("Invalid type token 0x%08x", type_token);
6662 if (!mono_verifier_verify_typeref_row (image, idx - 1, &error)) {
6663 char *msg = g_strdup_printf ("Invalid type token 0x%08x due to '%s'", type_token, mono_error_get_message (&error));
6664 mono_error_cleanup (&error);
6665 return msg;
6667 mono_metadata_decode_row (t, idx-1, cols, MONO_TYPEREF_SIZE);
6669 idx = cols [MONO_TYPEREF_SCOPE] >> MONO_RESOLTION_SCOPE_BITS;
6670 switch (cols [MONO_TYPEREF_SCOPE] & MONO_RESOLTION_SCOPE_MASK) {
6671 case MONO_RESOLTION_SCOPE_MODULE:
6672 /* FIXME: */
6673 return g_strdup ("");
6674 case MONO_RESOLTION_SCOPE_MODULEREF:
6675 /* FIXME: */
6676 return g_strdup ("");
6677 case MONO_RESOLTION_SCOPE_TYPEREF:
6678 /* FIXME: */
6679 return g_strdup ("");
6680 case MONO_RESOLTION_SCOPE_ASSEMBLYREF:
6681 mono_assembly_get_assemblyref (image, idx - 1, &aname);
6682 return mono_stringify_assembly_name (&aname);
6683 default:
6684 g_assert_not_reached ();
6686 break;
6688 case MONO_TOKEN_TYPE_SPEC:
6689 /* FIXME: */
6690 return g_strdup ("");
6691 default:
6692 g_assert_not_reached ();
6695 return NULL;
6699 * mono_class_get_full:
6700 * @image: the image where the class resides
6701 * @type_token: the token for the class
6702 * @context: the generic context used to evaluate generic instantiations in
6704 * Returns: the MonoClass that represents @type_token in @image
6706 MonoClass *
6707 mono_class_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
6709 MonoError error;
6710 MonoClass *class = NULL;
6712 if (image->dynamic) {
6713 int table = mono_metadata_token_table (type_token);
6715 if (table != MONO_TABLE_TYPEDEF && table != MONO_TABLE_TYPEREF && table != MONO_TABLE_TYPESPEC) {
6716 mono_loader_set_error_bad_image (g_strdup ("Bad type token."));
6717 return NULL;
6719 return mono_lookup_dynamic_token (image, type_token, context);
6722 switch (type_token & 0xff000000){
6723 case MONO_TOKEN_TYPE_DEF:
6724 class = mono_class_create_from_typedef (image, type_token);
6725 break;
6726 case MONO_TOKEN_TYPE_REF:
6727 class = mono_class_from_typeref (image, type_token);
6728 break;
6729 case MONO_TOKEN_TYPE_SPEC:
6730 class = mono_class_create_from_typespec (image, type_token, context, &error);
6731 if (!mono_error_ok (&error)) {
6732 /*FIXME don't swallow the error message*/
6733 mono_error_cleanup (&error);
6735 break;
6736 default:
6737 g_warning ("unknown token type %x", type_token & 0xff000000);
6738 g_assert_not_reached ();
6741 if (!class){
6742 char *name = mono_class_name_from_token (image, type_token);
6743 char *assembly = mono_assembly_name_from_token (image, type_token);
6744 mono_loader_set_error_type_load (name, assembly);
6745 g_free (name);
6746 g_free (assembly);
6749 return class;
6754 * mono_type_get_full:
6755 * @image: the image where the type resides
6756 * @type_token: the token for the type
6757 * @context: the generic context used to evaluate generic instantiations in
6759 * This functions exists to fullfill the fact that sometimes it's desirable to have access to the
6761 * Returns: the MonoType that represents @type_token in @image
6763 MonoType *
6764 mono_type_get_full (MonoImage *image, guint32 type_token, MonoGenericContext *context)
6766 MonoError error;
6767 MonoType *type = NULL;
6768 gboolean inflated = FALSE;
6770 //FIXME: this will not fix the very issue for which mono_type_get_full exists -but how to do it then?
6771 if (image->dynamic)
6772 return mono_class_get_type (mono_lookup_dynamic_token (image, type_token, context));
6774 if ((type_token & 0xff000000) != MONO_TOKEN_TYPE_SPEC) {
6775 MonoClass *class = mono_class_get_full (image, type_token, context);
6776 return class ? mono_class_get_type (class) : NULL;
6779 type = mono_type_retrieve_from_typespec (image, type_token, context, &inflated, &error);
6781 if (!mono_error_ok (&error)) {
6782 /*FIXME don't swalloc the error message.*/
6783 char *name = mono_class_name_from_token (image, type_token);
6784 char *assembly = mono_assembly_name_from_token (image, type_token);
6786 g_warning ("Error loading type %s from %s due to %s", name, assembly, mono_error_get_message (&error));
6788 mono_error_cleanup (&error);
6789 mono_loader_set_error_type_load (name, assembly);
6790 return NULL;
6793 if (inflated) {
6794 MonoType *tmp = type;
6795 type = mono_class_get_type (mono_class_from_mono_type (type));
6796 /* FIXME: This is a workaround fo the fact that a typespec token sometimes reference to the generic type definition.
6797 * A MonoClass::byval_arg of a generic type definion has type CLASS.
6798 * Some parts of mono create a GENERICINST to reference a generic type definition and this generates confict with byval_arg.
6800 * The long term solution is to chaise this places and make then set MonoType::type correctly.
6801 * */
6802 if (type->type != tmp->type)
6803 type = tmp;
6804 else
6805 mono_metadata_free_type (tmp);
6807 return type;
6811 MonoClass *
6812 mono_class_get (MonoImage *image, guint32 type_token)
6814 return mono_class_get_full (image, type_token, NULL);
6818 * mono_image_init_name_cache:
6820 * Initializes the class name cache stored in image->name_cache.
6822 * LOCKING: Acquires the corresponding image lock.
6824 void
6825 mono_image_init_name_cache (MonoImage *image)
6827 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
6828 guint32 cols [MONO_TYPEDEF_SIZE];
6829 const char *name;
6830 const char *nspace;
6831 guint32 i, visib, nspace_index;
6832 GHashTable *name_cache2, *nspace_table;
6834 mono_image_lock (image);
6836 if (image->name_cache) {
6837 mono_image_unlock (image);
6838 return;
6841 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
6843 if (image->dynamic) {
6844 mono_image_unlock (image);
6845 return;
6848 /* Temporary hash table to avoid lookups in the nspace_table */
6849 name_cache2 = g_hash_table_new (NULL, NULL);
6851 for (i = 1; i <= t->rows; ++i) {
6852 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
6853 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
6855 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
6856 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
6858 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
6859 continue;
6860 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
6861 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
6863 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
6864 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6865 if (!nspace_table) {
6866 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6867 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6868 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6869 nspace_table);
6871 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
6874 /* Load type names from EXPORTEDTYPES table */
6876 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6877 guint32 cols [MONO_EXP_TYPE_SIZE];
6878 int i;
6880 for (i = 0; i < t->rows; ++i) {
6881 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
6882 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
6883 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
6885 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
6886 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
6887 if (!nspace_table) {
6888 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6889 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
6890 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
6891 nspace_table);
6893 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
6897 g_hash_table_destroy (name_cache2);
6898 mono_image_unlock (image);
6901 /*FIXME Only dynamic assemblies should allow this operation.*/
6902 void
6903 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
6904 const char *name, guint32 index)
6906 GHashTable *nspace_table;
6907 GHashTable *name_cache;
6908 guint32 old_index;
6910 mono_image_lock (image);
6912 if (!image->name_cache)
6913 mono_image_init_name_cache (image);
6915 name_cache = image->name_cache;
6916 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
6917 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
6918 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
6921 if ((old_index = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, (char*) name))))
6922 g_error ("overrwritting old token %x on image %s for type %s::%s", old_index, image->name, nspace, name);
6924 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
6926 mono_image_unlock (image);
6929 typedef struct {
6930 gconstpointer key;
6931 gpointer value;
6932 } FindUserData;
6934 static void
6935 find_nocase (gpointer key, gpointer value, gpointer user_data)
6937 char *name = (char*)key;
6938 FindUserData *data = (FindUserData*)user_data;
6940 if (!data->value && (mono_utf8_strcasecmp (name, (char*)data->key) == 0))
6941 data->value = value;
6945 * mono_class_from_name_case:
6946 * @image: The MonoImage where the type is looked up in
6947 * @name_space: the type namespace
6948 * @name: the type short name.
6950 * Obtains a MonoClass with a given namespace and a given name which
6951 * is located in the given MonoImage. The namespace and name
6952 * lookups are case insensitive.
6954 MonoClass *
6955 mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name)
6957 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
6958 guint32 cols [MONO_TYPEDEF_SIZE];
6959 const char *n;
6960 const char *nspace;
6961 guint32 i, visib;
6963 if (image->dynamic) {
6964 guint32 token = 0;
6965 FindUserData user_data;
6967 mono_image_lock (image);
6969 if (!image->name_cache)
6970 mono_image_init_name_cache (image);
6972 user_data.key = name_space;
6973 user_data.value = NULL;
6974 g_hash_table_foreach (image->name_cache, find_nocase, &user_data);
6976 if (user_data.value) {
6977 GHashTable *nspace_table = (GHashTable*)user_data.value;
6979 user_data.key = name;
6980 user_data.value = NULL;
6982 g_hash_table_foreach (nspace_table, find_nocase, &user_data);
6984 if (user_data.value)
6985 token = GPOINTER_TO_UINT (user_data.value);
6988 mono_image_unlock (image);
6990 if (token)
6991 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | token);
6992 else
6993 return NULL;
6997 /* add a cache if needed */
6998 for (i = 1; i <= t->rows; ++i) {
6999 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
7000 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
7002 * Nested types are accessed from the nesting name. We use the fact that nested types use different visibility flags
7003 * than toplevel types, thus avoiding the need to grovel through the NESTED_TYPE table
7005 if (visib >= TYPE_ATTRIBUTE_NESTED_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
7006 continue;
7007 n = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
7008 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
7009 if (mono_utf8_strcasecmp (n, name) == 0 && mono_utf8_strcasecmp (nspace, name_space) == 0)
7010 return mono_class_get (image, MONO_TOKEN_TYPE_DEF | i);
7012 return NULL;
7015 static MonoClass*
7016 return_nested_in (MonoClass *class, char *nested)
7018 MonoClass *found;
7019 char *s = strchr (nested, '/');
7020 gpointer iter = NULL;
7022 if (s) {
7023 *s = 0;
7024 s++;
7027 while ((found = mono_class_get_nested_types (class, &iter))) {
7028 if (strcmp (found->name, nested) == 0) {
7029 if (s)
7030 return return_nested_in (found, s);
7031 return found;
7034 return NULL;
7037 static MonoClass*
7038 search_modules (MonoImage *image, const char *name_space, const char *name)
7040 MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE];
7041 MonoImage *file_image;
7042 MonoClass *class;
7043 int i;
7046 * The EXPORTEDTYPES table only contains public types, so have to search the
7047 * modules as well.
7048 * Note: image->modules contains the contents of the MODULEREF table, while
7049 * the real module list is in the FILE table.
7051 for (i = 0; i < file_table->rows; i++) {
7052 guint32 cols [MONO_FILE_SIZE];
7053 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
7054 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
7055 continue;
7057 file_image = mono_image_load_file_for_image (image, i + 1);
7058 if (file_image) {
7059 class = mono_class_from_name (file_image, name_space, name);
7060 if (class)
7061 return class;
7065 return NULL;
7069 * mono_class_from_name:
7070 * @image: The MonoImage where the type is looked up in
7071 * @name_space: the type namespace
7072 * @name: the type short name.
7074 * Obtains a MonoClass with a given namespace and a given name which
7075 * is located in the given MonoImage.
7077 MonoClass *
7078 mono_class_from_name (MonoImage *image, const char* name_space, const char *name)
7080 GHashTable *nspace_table;
7081 MonoImage *loaded_image;
7082 guint32 token = 0;
7083 int i;
7084 MonoClass *class;
7085 char *nested;
7086 char buf [1024];
7088 if ((nested = strchr (name, '/'))) {
7089 int pos = nested - name;
7090 int len = strlen (name);
7091 if (len > 1023)
7092 return NULL;
7093 memcpy (buf, name, len + 1);
7094 buf [pos] = 0;
7095 nested = buf + pos + 1;
7096 name = buf;
7099 /* FIXME: get_class_from_name () can't handle types in the EXPORTEDTYPE table */
7100 if (get_class_from_name && image->tables [MONO_TABLE_EXPORTEDTYPE].rows == 0) {
7101 gboolean res = get_class_from_name (image, name_space, name, &class);
7102 if (res) {
7103 if (!class)
7104 class = search_modules (image, name_space, name);
7105 if (nested)
7106 return class ? return_nested_in (class, nested) : NULL;
7107 else
7108 return class;
7112 mono_image_lock (image);
7114 if (!image->name_cache)
7115 mono_image_init_name_cache (image);
7117 nspace_table = g_hash_table_lookup (image->name_cache, name_space);
7119 if (nspace_table)
7120 token = GPOINTER_TO_UINT (g_hash_table_lookup (nspace_table, name));
7122 mono_image_unlock (image);
7124 if (!token && image->dynamic && image->modules) {
7125 /* Search modules as well */
7126 for (i = 0; i < image->module_count; ++i) {
7127 MonoImage *module = image->modules [i];
7129 class = mono_class_from_name (module, name_space, name);
7130 if (class)
7131 return class;
7135 if (!token) {
7136 class = search_modules (image, name_space, name);
7137 if (class)
7138 return class;
7141 if (!token)
7142 return NULL;
7144 if (mono_metadata_token_table (token) == MONO_TABLE_EXPORTEDTYPE) {
7145 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
7146 guint32 cols [MONO_EXP_TYPE_SIZE];
7147 guint32 idx, impl;
7149 idx = mono_metadata_token_index (token);
7151 mono_metadata_decode_row (t, idx - 1, cols, MONO_EXP_TYPE_SIZE);
7153 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
7154 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
7155 loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
7156 if (!loaded_image)
7157 return NULL;
7158 class = mono_class_from_name (loaded_image, name_space, name);
7159 if (nested)
7160 return return_nested_in (class, nested);
7161 return class;
7162 } else if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
7163 guint32 assembly_idx;
7165 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
7167 mono_assembly_load_reference (image, assembly_idx - 1);
7168 g_assert (image->references [assembly_idx - 1]);
7169 if (image->references [assembly_idx - 1] == (gpointer)-1)
7170 return NULL;
7171 else
7172 /* FIXME: Cycle detection */
7173 return mono_class_from_name (image->references [assembly_idx - 1]->image, name_space, name);
7174 } else {
7175 g_error ("not yet implemented");
7179 token = MONO_TOKEN_TYPE_DEF | token;
7181 class = mono_class_get (image, token);
7182 if (nested)
7183 return return_nested_in (class, nested);
7184 return class;
7187 /*FIXME test for interfaces with variant generic arguments*/
7188 gboolean
7189 mono_class_is_subclass_of (MonoClass *klass, MonoClass *klassc,
7190 gboolean check_interfaces)
7192 g_assert (klassc->idepth > 0);
7193 if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && !MONO_CLASS_IS_INTERFACE (klass)) {
7194 if (MONO_CLASS_IMPLEMENTS_INTERFACE (klass, klassc->interface_id))
7195 return TRUE;
7196 } else if (check_interfaces && MONO_CLASS_IS_INTERFACE (klassc) && MONO_CLASS_IS_INTERFACE (klass)) {
7197 int i;
7199 for (i = 0; i < klass->interface_count; i ++) {
7200 MonoClass *ic = klass->interfaces [i];
7201 if (ic == klassc)
7202 return TRUE;
7204 } else {
7205 if (!MONO_CLASS_IS_INTERFACE (klass) && mono_class_has_parent (klass, klassc))
7206 return TRUE;
7210 * MS.NET thinks interfaces are a subclass of Object, so we think it as
7211 * well.
7213 if (klassc == mono_defaults.object_class)
7214 return TRUE;
7216 return FALSE;
7219 gboolean
7220 mono_class_has_variant_generic_params (MonoClass *klass)
7222 int i;
7223 MonoGenericContainer *container;
7225 if (!klass->generic_class)
7226 return FALSE;
7228 container = klass->generic_class->container_class->generic_container;
7230 for (i = 0; i < container->type_argc; ++i)
7231 if (mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT))
7232 return TRUE;
7234 return FALSE;
7238 * @container the generic container from the GTD
7239 * @klass: the class to be assigned to
7240 * @oklass: the source class
7242 * Both klass and oklass must be instances of the same generic interface.
7243 * Return true if @klass can be assigned to a @klass variable
7245 static gboolean
7246 mono_class_is_variant_compatible (MonoClass *klass, MonoClass *oklass)
7248 int j;
7249 MonoType **klass_argv, **oklass_argv;
7250 MonoClass *klass_gtd = mono_class_get_generic_type_definition (klass);
7251 MonoClass *oklass_gtd = mono_class_get_generic_type_definition (oklass);
7252 MonoGenericContainer *container = klass_gtd->generic_container;
7254 /*Viable candidates are instances of the same generic interface*/
7255 if (mono_class_get_generic_type_definition (oklass) != klass_gtd || oklass == klass_gtd)
7256 return FALSE;
7258 klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
7259 oklass_argv = &oklass->generic_class->context.class_inst->type_argv [0];
7261 for (j = 0; j < container->type_argc; ++j) {
7262 MonoClass *param1_class = mono_class_from_mono_type (klass_argv [j]);
7263 MonoClass *param2_class = mono_class_from_mono_type (oklass_argv [j]);
7265 if (param1_class->valuetype != param2_class->valuetype || (param1_class->valuetype && param1_class != param2_class))
7266 return FALSE;
7269 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
7270 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
7272 if (param1_class != param2_class) {
7273 if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_VARIANT) {
7274 if (!mono_class_is_assignable_from (param1_class, param2_class))
7275 return FALSE;
7276 } else if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_COVARIANT) {
7277 if (!mono_class_is_assignable_from (param2_class, param1_class))
7278 return FALSE;
7279 } else
7280 return FALSE;
7283 return TRUE;
7287 * mono_class_is_assignable_from:
7288 * @klass: the class to be assigned to
7289 * @oklass: the source class
7291 * Return: true if an instance of object oklass can be assigned to an
7292 * instance of object @klass
7294 gboolean
7295 mono_class_is_assignable_from (MonoClass *klass, MonoClass *oklass)
7297 /*FIXME this will cause a lot of irrelevant stuff to be loaded.*/
7298 if (!klass->inited)
7299 mono_class_init (klass);
7301 if (!oklass->inited)
7302 mono_class_init (oklass);
7304 if (klass->exception_type || oklass->exception_type)
7305 return FALSE;
7307 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
7308 return klass == oklass;
7310 if (MONO_CLASS_IS_INTERFACE (klass)) {
7311 if ((oklass->byval_arg.type == MONO_TYPE_VAR) || (oklass->byval_arg.type == MONO_TYPE_MVAR)) {
7312 MonoGenericParam *gparam = oklass->byval_arg.data.generic_param;
7313 MonoClass **constraints = mono_generic_container_get_param_info (gparam->owner, gparam->num)->constraints;
7314 int i;
7316 if (constraints) {
7317 for (i = 0; constraints [i]; ++i) {
7318 if (mono_class_is_assignable_from (klass, constraints [i]))
7319 return TRUE;
7323 return FALSE;
7326 /* interface_offsets might not be set for dynamic classes */
7327 if (oklass->ref_info_handle && !oklass->interface_bitmap)
7329 * oklass might be a generic type parameter but they have
7330 * interface_offsets set.
7332 return mono_reflection_call_is_assignable_to (oklass, klass);
7333 if (!oklass->interface_bitmap)
7334 /* Happens with generic instances of not-yet created dynamic types */
7335 return FALSE;
7336 if (MONO_CLASS_IMPLEMENTS_INTERFACE (oklass, klass->interface_id))
7337 return TRUE;
7339 if (mono_class_has_variant_generic_params (klass)) {
7340 MonoError error;
7341 int i;
7342 mono_class_setup_interfaces (oklass, &error);
7343 if (!mono_error_ok (&error)) {
7344 mono_error_cleanup (&error);
7345 return FALSE;
7348 /*klass is a generic variant interface, We need to extract from oklass a list of ifaces which are viable candidates.*/
7349 for (i = 0; i < oklass->interface_offsets_count; ++i) {
7350 MonoClass *iface = oklass->interfaces_packed [i];
7352 if (mono_class_is_variant_compatible (klass, iface))
7353 return TRUE;
7356 return FALSE;
7357 } else if (klass->delegate) {
7358 if (mono_class_has_variant_generic_params (klass) && mono_class_is_variant_compatible (klass, oklass))
7359 return TRUE;
7360 }else if (klass->rank) {
7361 MonoClass *eclass, *eoclass;
7363 if (oklass->rank != klass->rank)
7364 return FALSE;
7366 /* vectors vs. one dimensional arrays */
7367 if (oklass->byval_arg.type != klass->byval_arg.type)
7368 return FALSE;
7370 eclass = klass->cast_class;
7371 eoclass = oklass->cast_class;
7374 * a is b does not imply a[] is b[] when a is a valuetype, and
7375 * b is a reference type.
7378 if (eoclass->valuetype) {
7379 if ((eclass == mono_defaults.enum_class) ||
7380 (eclass == mono_defaults.enum_class->parent) ||
7381 (eclass == mono_defaults.object_class))
7382 return FALSE;
7385 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
7386 } else if (mono_class_is_nullable (klass)) {
7387 if (mono_class_is_nullable (oklass))
7388 return mono_class_is_assignable_from (klass->cast_class, oklass->cast_class);
7389 else
7390 return mono_class_is_assignable_from (klass->cast_class, oklass);
7391 } else if (klass == mono_defaults.object_class)
7392 return TRUE;
7394 return mono_class_has_parent (oklass, klass);
7397 /*Check if @oklass is variant compatible with @klass.*/
7398 static gboolean
7399 mono_class_is_variant_compatible_slow (MonoClass *klass, MonoClass *oklass)
7401 int j;
7402 MonoType **klass_argv, **oklass_argv;
7403 MonoClass *klass_gtd = mono_class_get_generic_type_definition (klass);
7404 MonoGenericContainer *container = klass_gtd->generic_container;
7406 /*Viable candidates are instances of the same generic interface*/
7407 if (mono_class_get_generic_type_definition (oklass) != klass_gtd || oklass == klass_gtd)
7408 return FALSE;
7410 klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
7411 oklass_argv = &oklass->generic_class->context.class_inst->type_argv [0];
7413 for (j = 0; j < container->type_argc; ++j) {
7414 MonoClass *param1_class = mono_class_from_mono_type (klass_argv [j]);
7415 MonoClass *param2_class = mono_class_from_mono_type (oklass_argv [j]);
7417 if (param1_class->valuetype != param2_class->valuetype)
7418 return FALSE;
7421 * The _VARIANT and _COVARIANT constants should read _COVARIANT and
7422 * _CONTRAVARIANT, but they are in a public header so we can't fix it.
7424 if (param1_class != param2_class) {
7425 if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_VARIANT) {
7426 if (!mono_class_is_assignable_from_slow (param1_class, param2_class))
7427 return FALSE;
7428 } else if (mono_generic_container_get_param_info (container, j)->flags & MONO_GEN_PARAM_COVARIANT) {
7429 if (!mono_class_is_assignable_from_slow (param2_class, param1_class))
7430 return FALSE;
7431 } else
7432 return FALSE;
7435 return TRUE;
7437 /*Check if @candidate implements the interface @target*/
7438 static gboolean
7439 mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
7441 MonoError error;
7442 int i;
7443 gboolean is_variant = mono_class_has_variant_generic_params (target);
7445 if (is_variant && MONO_CLASS_IS_INTERFACE (candidate)) {
7446 if (mono_class_is_variant_compatible_slow (target, candidate))
7447 return TRUE;
7450 do {
7451 if (candidate == target)
7452 return TRUE;
7454 /*A TypeBuilder can have more interfaces on tb->interfaces than on candidate->interfaces*/
7455 if (candidate->image->dynamic && !candidate->wastypebuilder) {
7456 MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (candidate);
7457 int j;
7458 if (tb && tb->interfaces) {
7459 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
7460 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
7461 MonoClass *iface_class;
7463 /* we can't realize the type here since it can do pretty much anything. */
7464 if (!iface->type)
7465 continue;
7466 iface_class = mono_class_from_mono_type (iface->type);
7467 if (iface_class == target)
7468 return TRUE;
7469 if (is_variant && mono_class_is_variant_compatible_slow (target, iface_class))
7470 return TRUE;
7471 if (mono_class_implement_interface_slow (target, iface_class))
7472 return TRUE;
7475 } else {
7476 /*setup_interfaces don't mono_class_init anything*/
7477 mono_class_setup_interfaces (candidate, &error);
7478 if (!mono_error_ok (&error)) {
7479 mono_error_cleanup (&error);
7480 return FALSE;
7483 for (i = 0; i < candidate->interface_count; ++i) {
7484 if (candidate->interfaces [i] == target)
7485 return TRUE;
7487 if (is_variant && mono_class_is_variant_compatible_slow (target, candidate->interfaces [i]))
7488 return TRUE;
7490 if (mono_class_implement_interface_slow (target, candidate->interfaces [i]))
7491 return TRUE;
7494 candidate = candidate->parent;
7495 } while (candidate);
7497 return FALSE;
7501 * Check if @oklass can be assigned to @klass.
7502 * This function does the same as mono_class_is_assignable_from but is safe to be used from mono_class_init context.
7504 gboolean
7505 mono_class_is_assignable_from_slow (MonoClass *target, MonoClass *candidate)
7507 if (candidate == target)
7508 return TRUE;
7509 if (target == mono_defaults.object_class)
7510 return TRUE;
7512 /*setup_supertypes don't mono_class_init anything */
7513 mono_class_setup_supertypes (candidate);
7514 mono_class_setup_supertypes (target);
7516 if (mono_class_has_parent (candidate, target))
7517 return TRUE;
7519 /*If target is not an interface there is no need to check them.*/
7520 if (MONO_CLASS_IS_INTERFACE (target))
7521 return mono_class_implement_interface_slow (target, candidate);
7523 if (target->delegate && mono_class_has_variant_generic_params (target))
7524 return mono_class_is_variant_compatible (target, candidate);
7526 /*FIXME properly handle nullables and arrays */
7528 return FALSE;
7532 * mono_class_get_cctor:
7533 * @klass: A MonoClass pointer
7535 * Returns: the static constructor of @klass if it exists, NULL otherwise.
7537 MonoMethod*
7538 mono_class_get_cctor (MonoClass *klass)
7540 MonoCachedClassInfo cached_info;
7542 if (klass->image->dynamic) {
7544 * has_cctor is not set for these classes because mono_class_init () is
7545 * not run for them.
7547 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
7550 if (!klass->has_cctor)
7551 return NULL;
7553 if (mono_class_get_cached_class_info (klass, &cached_info))
7554 return mono_get_method (klass->image, cached_info.cctor_token, klass);
7556 if (klass->generic_class && !klass->methods)
7557 return mono_class_get_inflated_method (klass, mono_class_get_cctor (klass->generic_class->container_class));
7559 return mono_class_get_method_from_name_flags (klass, ".cctor", -1, METHOD_ATTRIBUTE_SPECIAL_NAME);
7563 * mono_class_get_finalizer:
7564 * @klass: The MonoClass pointer
7566 * Returns: the finalizer method of @klass if it exists, NULL otherwise.
7568 MonoMethod*
7569 mono_class_get_finalizer (MonoClass *klass)
7571 MonoCachedClassInfo cached_info;
7573 if (!klass->inited)
7574 mono_class_init (klass);
7575 if (!mono_class_has_finalizer (klass))
7576 return NULL;
7578 if (mono_class_get_cached_class_info (klass, &cached_info))
7579 return mono_get_method (cached_info.finalize_image, cached_info.finalize_token, NULL);
7580 else {
7581 mono_class_setup_vtable (klass);
7582 return klass->vtable [finalize_slot];
7587 * mono_class_needs_cctor_run:
7588 * @klass: the MonoClass pointer
7589 * @caller: a MonoMethod describing the caller
7591 * Determines whenever the class has a static constructor and whenever it
7592 * needs to be called when executing CALLER.
7594 gboolean
7595 mono_class_needs_cctor_run (MonoClass *klass, MonoMethod *caller)
7597 MonoMethod *method;
7599 method = mono_class_get_cctor (klass);
7600 if (method)
7601 return (method == caller) ? FALSE : TRUE;
7602 else
7603 return FALSE;
7607 * mono_class_array_element_size:
7608 * @klass:
7610 * Returns: the number of bytes an element of type @klass
7611 * uses when stored into an array.
7613 gint32
7614 mono_class_array_element_size (MonoClass *klass)
7616 MonoType *type = &klass->byval_arg;
7618 handle_enum:
7619 switch (type->type) {
7620 case MONO_TYPE_I1:
7621 case MONO_TYPE_U1:
7622 case MONO_TYPE_BOOLEAN:
7623 return 1;
7624 case MONO_TYPE_I2:
7625 case MONO_TYPE_U2:
7626 case MONO_TYPE_CHAR:
7627 return 2;
7628 case MONO_TYPE_I4:
7629 case MONO_TYPE_U4:
7630 case MONO_TYPE_R4:
7631 return 4;
7632 case MONO_TYPE_I:
7633 case MONO_TYPE_U:
7634 case MONO_TYPE_PTR:
7635 case MONO_TYPE_CLASS:
7636 case MONO_TYPE_STRING:
7637 case MONO_TYPE_OBJECT:
7638 case MONO_TYPE_SZARRAY:
7639 case MONO_TYPE_ARRAY:
7640 case MONO_TYPE_VAR:
7641 case MONO_TYPE_MVAR:
7642 return sizeof (gpointer);
7643 case MONO_TYPE_I8:
7644 case MONO_TYPE_U8:
7645 case MONO_TYPE_R8:
7646 return 8;
7647 case MONO_TYPE_VALUETYPE:
7648 if (type->data.klass->enumtype) {
7649 type = mono_class_enum_basetype (type->data.klass);
7650 klass = klass->element_class;
7651 goto handle_enum;
7653 return mono_class_instance_size (klass) - sizeof (MonoObject);
7654 case MONO_TYPE_GENERICINST:
7655 type = &type->data.generic_class->container_class->byval_arg;
7656 goto handle_enum;
7658 case MONO_TYPE_VOID:
7659 return 0;
7661 default:
7662 g_error ("unknown type 0x%02x in mono_class_array_element_size", type->type);
7664 return -1;
7668 * mono_array_element_size:
7669 * @ac: pointer to a #MonoArrayClass
7671 * Returns: the size of single array element.
7673 gint32
7674 mono_array_element_size (MonoClass *ac)
7676 g_assert (ac->rank);
7677 return ac->sizes.element_size;
7680 gpointer
7681 mono_ldtoken (MonoImage *image, guint32 token, MonoClass **handle_class,
7682 MonoGenericContext *context)
7684 if (image->dynamic) {
7685 MonoClass *tmp_handle_class;
7686 gpointer obj = mono_lookup_dynamic_token_class (image, token, TRUE, &tmp_handle_class, context);
7688 g_assert (tmp_handle_class);
7689 if (handle_class)
7690 *handle_class = tmp_handle_class;
7692 if (tmp_handle_class == mono_defaults.typehandle_class)
7693 return &((MonoClass*)obj)->byval_arg;
7694 else
7695 return obj;
7698 switch (token & 0xff000000) {
7699 case MONO_TOKEN_TYPE_DEF:
7700 case MONO_TOKEN_TYPE_REF:
7701 case MONO_TOKEN_TYPE_SPEC: {
7702 MonoType *type;
7703 if (handle_class)
7704 *handle_class = mono_defaults.typehandle_class;
7705 type = mono_type_get_full (image, token, context);
7706 if (!type)
7707 return NULL;
7708 mono_class_init (mono_class_from_mono_type (type));
7709 /* We return a MonoType* as handle */
7710 return type;
7712 case MONO_TOKEN_FIELD_DEF: {
7713 MonoClass *class;
7714 guint32 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
7715 if (!type)
7716 return NULL;
7717 if (handle_class)
7718 *handle_class = mono_defaults.fieldhandle_class;
7719 class = mono_class_get_full (image, MONO_TOKEN_TYPE_DEF | type, context);
7720 if (!class)
7721 return NULL;
7722 mono_class_init (class);
7723 return mono_class_get_field (class, token);
7725 case MONO_TOKEN_METHOD_DEF:
7726 case MONO_TOKEN_METHOD_SPEC: {
7727 MonoMethod *meth;
7728 meth = mono_get_method_full (image, token, NULL, context);
7729 if (handle_class)
7730 *handle_class = mono_defaults.methodhandle_class;
7731 return meth;
7733 case MONO_TOKEN_MEMBER_REF: {
7734 guint32 cols [MONO_MEMBERREF_SIZE];
7735 const char *sig;
7736 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
7737 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
7738 mono_metadata_decode_blob_size (sig, &sig);
7739 if (*sig == 0x6) { /* it's a field */
7740 MonoClass *klass;
7741 MonoClassField *field;
7742 field = mono_field_from_token (image, token, &klass, context);
7743 if (handle_class)
7744 *handle_class = mono_defaults.fieldhandle_class;
7745 return field;
7746 } else {
7747 MonoMethod *meth;
7748 meth = mono_get_method_full (image, token, NULL, context);
7749 if (handle_class)
7750 *handle_class = mono_defaults.methodhandle_class;
7751 return meth;
7754 default:
7755 g_warning ("Unknown token 0x%08x in ldtoken", token);
7756 break;
7758 return NULL;
7762 * This function might need to call runtime functions so it can't be part
7763 * of the metadata library.
7765 static MonoLookupDynamicToken lookup_dynamic = NULL;
7767 void
7768 mono_install_lookup_dynamic_token (MonoLookupDynamicToken func)
7770 lookup_dynamic = func;
7773 gpointer
7774 mono_lookup_dynamic_token (MonoImage *image, guint32 token, MonoGenericContext *context)
7776 MonoClass *handle_class;
7778 return lookup_dynamic (image, token, TRUE, &handle_class, context);
7781 gpointer
7782 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
7784 return lookup_dynamic (image, token, valid_token, handle_class, context);
7787 static MonoGetCachedClassInfo get_cached_class_info = NULL;
7789 void
7790 mono_install_get_cached_class_info (MonoGetCachedClassInfo func)
7792 get_cached_class_info = func;
7795 static gboolean
7796 mono_class_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
7798 if (!get_cached_class_info)
7799 return FALSE;
7800 else
7801 return get_cached_class_info (klass, res);
7804 void
7805 mono_install_get_class_from_name (MonoGetClassFromName func)
7807 get_class_from_name = func;
7810 MonoImage*
7811 mono_class_get_image (MonoClass *klass)
7813 return klass->image;
7817 * mono_class_get_element_class:
7818 * @klass: the MonoClass to act on
7820 * Returns: the element class of an array or an enumeration.
7822 MonoClass*
7823 mono_class_get_element_class (MonoClass *klass)
7825 return klass->element_class;
7829 * mono_class_is_valuetype:
7830 * @klass: the MonoClass to act on
7832 * Returns: true if the MonoClass represents a ValueType.
7834 gboolean
7835 mono_class_is_valuetype (MonoClass *klass)
7837 return klass->valuetype;
7841 * mono_class_is_enum:
7842 * @klass: the MonoClass to act on
7844 * Returns: true if the MonoClass represents an enumeration.
7846 gboolean
7847 mono_class_is_enum (MonoClass *klass)
7849 return klass->enumtype;
7853 * mono_class_enum_basetype:
7854 * @klass: the MonoClass to act on
7856 * Returns: the underlying type representation for an enumeration.
7858 MonoType*
7859 mono_class_enum_basetype (MonoClass *klass)
7861 if (klass->element_class == klass)
7862 /* SRE or broken types */
7863 return NULL;
7864 else
7865 return &klass->element_class->byval_arg;
7869 * mono_class_get_parent
7870 * @klass: the MonoClass to act on
7872 * Returns: the parent class for this class.
7874 MonoClass*
7875 mono_class_get_parent (MonoClass *klass)
7877 return klass->parent;
7881 * mono_class_get_nesting_type;
7882 * @klass: the MonoClass to act on
7884 * Returns: the container type where this type is nested or NULL if this type is not a nested type.
7886 MonoClass*
7887 mono_class_get_nesting_type (MonoClass *klass)
7889 return klass->nested_in;
7893 * mono_class_get_rank:
7894 * @klass: the MonoClass to act on
7896 * Returns: the rank for the array (the number of dimensions).
7899 mono_class_get_rank (MonoClass *klass)
7901 return klass->rank;
7905 * mono_class_get_flags:
7906 * @klass: the MonoClass to act on
7908 * The type flags from the TypeDef table from the metadata.
7909 * see the TYPE_ATTRIBUTE_* definitions on tabledefs.h for the
7910 * different values.
7912 * Returns: the flags from the TypeDef table.
7914 guint32
7915 mono_class_get_flags (MonoClass *klass)
7917 return klass->flags;
7921 * mono_class_get_name
7922 * @klass: the MonoClass to act on
7924 * Returns: the name of the class.
7926 const char*
7927 mono_class_get_name (MonoClass *klass)
7929 return klass->name;
7933 * mono_class_get_namespace:
7934 * @klass: the MonoClass to act on
7936 * Returns: the namespace of the class.
7938 const char*
7939 mono_class_get_namespace (MonoClass *klass)
7941 return klass->name_space;
7945 * mono_class_get_type:
7946 * @klass: the MonoClass to act on
7948 * This method returns the internal Type representation for the class.
7950 * Returns: the MonoType from the class.
7952 MonoType*
7953 mono_class_get_type (MonoClass *klass)
7955 return &klass->byval_arg;
7959 * mono_class_get_type_token
7960 * @klass: the MonoClass to act on
7962 * This method returns type token for the class.
7964 * Returns: the type token for the class.
7966 guint32
7967 mono_class_get_type_token (MonoClass *klass)
7969 return klass->type_token;
7973 * mono_class_get_byref_type:
7974 * @klass: the MonoClass to act on
7978 MonoType*
7979 mono_class_get_byref_type (MonoClass *klass)
7981 return &klass->this_arg;
7985 * mono_class_num_fields:
7986 * @klass: the MonoClass to act on
7988 * Returns: the number of static and instance fields in the class.
7991 mono_class_num_fields (MonoClass *klass)
7993 return klass->field.count;
7997 * mono_class_num_methods:
7998 * @klass: the MonoClass to act on
8000 * Returns: the number of methods in the class.
8003 mono_class_num_methods (MonoClass *klass)
8005 return klass->method.count;
8009 * mono_class_num_properties
8010 * @klass: the MonoClass to act on
8012 * Returns: the number of properties in the class.
8015 mono_class_num_properties (MonoClass *klass)
8017 mono_class_setup_properties (klass);
8019 return klass->ext->property.count;
8023 * mono_class_num_events:
8024 * @klass: the MonoClass to act on
8026 * Returns: the number of events in the class.
8029 mono_class_num_events (MonoClass *klass)
8031 mono_class_setup_events (klass);
8033 return klass->ext->event.count;
8037 * mono_class_get_fields:
8038 * @klass: the MonoClass to act on
8040 * This routine is an iterator routine for retrieving the fields in a class.
8042 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8043 * iterate over all of the elements. When no more values are
8044 * available, the return value is NULL.
8046 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
8048 MonoClassField*
8049 mono_class_get_fields (MonoClass* klass, gpointer *iter)
8051 MonoClassField* field;
8052 if (!iter)
8053 return NULL;
8054 if (!*iter) {
8055 mono_class_setup_fields_locking (klass);
8056 if (klass->exception_type)
8057 return NULL;
8058 /* start from the first */
8059 if (klass->field.count) {
8060 return *iter = &klass->fields [0];
8061 } else {
8062 /* no fields */
8063 return NULL;
8066 field = *iter;
8067 field++;
8068 if (field < &klass->fields [klass->field.count]) {
8069 return *iter = field;
8071 return NULL;
8075 * mono_class_get_methods
8076 * @klass: the MonoClass to act on
8078 * This routine is an iterator routine for retrieving the fields in a class.
8080 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8081 * iterate over all of the elements. When no more values are
8082 * available, the return value is NULL.
8084 * Returns: a MonoMethod on each iteration or NULL when no more methods are available.
8086 MonoMethod*
8087 mono_class_get_methods (MonoClass* klass, gpointer *iter)
8089 MonoMethod** method;
8090 if (!iter)
8091 return NULL;
8092 if (!*iter) {
8093 mono_class_setup_methods (klass);
8096 * We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8097 * FIXME we should better report this error to the caller
8099 if (!klass->methods)
8100 return NULL;
8101 /* start from the first */
8102 if (klass->method.count) {
8103 *iter = &klass->methods [0];
8104 return klass->methods [0];
8105 } else {
8106 /* no method */
8107 return NULL;
8110 method = *iter;
8111 method++;
8112 if (method < &klass->methods [klass->method.count]) {
8113 *iter = method;
8114 return *method;
8116 return NULL;
8120 * mono_class_get_virtual_methods:
8122 * Iterate over the virtual methods of KLASS.
8124 * LOCKING: Assumes the loader lock is held (because of the klass->methods check).
8126 static MonoMethod*
8127 mono_class_get_virtual_methods (MonoClass* klass, gpointer *iter)
8129 MonoMethod** method;
8130 if (!iter)
8131 return NULL;
8132 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass) || mono_debug_using_mono_debugger ()) {
8133 if (!*iter) {
8134 mono_class_setup_methods (klass);
8136 * We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8137 * FIXME we should better report this error to the caller
8139 if (!klass->methods)
8140 return NULL;
8141 /* start from the first */
8142 method = &klass->methods [0];
8143 } else {
8144 method = *iter;
8145 method++;
8147 while (method < &klass->methods [klass->method.count]) {
8148 if (*method && ((*method)->flags & METHOD_ATTRIBUTE_VIRTUAL))
8149 break;
8150 method ++;
8152 if (method < &klass->methods [klass->method.count]) {
8153 *iter = method;
8154 return *method;
8155 } else {
8156 return NULL;
8158 } else {
8159 /* Search directly in metadata to avoid calling setup_methods () */
8160 MonoMethod *res = NULL;
8161 int i, start_index;
8163 if (!*iter) {
8164 start_index = 0;
8165 } else {
8166 start_index = GPOINTER_TO_UINT (*iter);
8169 for (i = start_index; i < klass->method.count; ++i) {
8170 guint32 flags;
8172 /* class->method.first points into the methodptr table */
8173 flags = mono_metadata_decode_table_row_col (klass->image, MONO_TABLE_METHOD, klass->method.first + i, MONO_METHOD_FLAGS);
8175 if (flags & METHOD_ATTRIBUTE_VIRTUAL)
8176 break;
8179 if (i < klass->method.count) {
8180 res = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
8181 /* Add 1 here so the if (*iter) check fails */
8182 *iter = GUINT_TO_POINTER (i + 1);
8183 return res;
8184 } else {
8185 return NULL;
8191 * mono_class_get_properties:
8192 * @klass: the MonoClass to act on
8194 * This routine is an iterator routine for retrieving the properties in a class.
8196 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8197 * iterate over all of the elements. When no more values are
8198 * available, the return value is NULL.
8200 * Returns: a @MonoProperty* on each invocation, or NULL when no more are available.
8202 MonoProperty*
8203 mono_class_get_properties (MonoClass* klass, gpointer *iter)
8205 MonoProperty* property;
8206 if (!iter)
8207 return NULL;
8208 if (!*iter) {
8209 mono_class_setup_properties (klass);
8210 /* start from the first */
8211 if (klass->ext->property.count) {
8212 return *iter = &klass->ext->properties [0];
8213 } else {
8214 /* no fields */
8215 return NULL;
8218 property = *iter;
8219 property++;
8220 if (property < &klass->ext->properties [klass->ext->property.count]) {
8221 return *iter = property;
8223 return NULL;
8227 * mono_class_get_events:
8228 * @klass: the MonoClass to act on
8230 * This routine is an iterator routine for retrieving the properties in a class.
8232 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8233 * iterate over all of the elements. When no more values are
8234 * available, the return value is NULL.
8236 * Returns: a @MonoEvent* on each invocation, or NULL when no more are available.
8238 MonoEvent*
8239 mono_class_get_events (MonoClass* klass, gpointer *iter)
8241 MonoEvent* event;
8242 if (!iter)
8243 return NULL;
8244 if (!*iter) {
8245 mono_class_setup_events (klass);
8246 /* start from the first */
8247 if (klass->ext->event.count) {
8248 return *iter = &klass->ext->events [0];
8249 } else {
8250 /* no fields */
8251 return NULL;
8254 event = *iter;
8255 event++;
8256 if (event < &klass->ext->events [klass->ext->event.count]) {
8257 return *iter = event;
8259 return NULL;
8263 * mono_class_get_interfaces
8264 * @klass: the MonoClass to act on
8266 * This routine is an iterator routine for retrieving the interfaces implemented by this class.
8268 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8269 * iterate over all of the elements. When no more values are
8270 * available, the return value is NULL.
8272 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
8274 MonoClass*
8275 mono_class_get_interfaces (MonoClass* klass, gpointer *iter)
8277 MonoError error;
8278 MonoClass** iface;
8279 if (!iter)
8280 return NULL;
8281 if (!*iter) {
8282 if (!klass->inited)
8283 mono_class_init (klass);
8284 if (!klass->interfaces_inited) {
8285 mono_class_setup_interfaces (klass, &error);
8286 if (!mono_error_ok (&error)) {
8287 mono_error_cleanup (&error);
8288 return NULL;
8291 /* start from the first */
8292 if (klass->interface_count) {
8293 *iter = &klass->interfaces [0];
8294 return klass->interfaces [0];
8295 } else {
8296 /* no interface */
8297 return NULL;
8300 iface = *iter;
8301 iface++;
8302 if (iface < &klass->interfaces [klass->interface_count]) {
8303 *iter = iface;
8304 return *iface;
8306 return NULL;
8310 * mono_class_get_nested_types
8311 * @klass: the MonoClass to act on
8313 * This routine is an iterator routine for retrieving the nested types of a class.
8314 * This works only if @klass is non-generic, or a generic type definition.
8316 * You must pass a gpointer that points to zero and is treated as an opaque handle to
8317 * iterate over all of the elements. When no more values are
8318 * available, the return value is NULL.
8320 * Returns: a @Monoclass* on each invocation, or NULL when no more are available.
8322 MonoClass*
8323 mono_class_get_nested_types (MonoClass* klass, gpointer *iter)
8325 GList *item;
8326 int i;
8328 if (!iter)
8329 return NULL;
8330 if (!klass->nested_classes_inited) {
8331 if (!klass->type_token)
8332 klass->nested_classes_inited = TRUE;
8333 mono_loader_lock ();
8334 if (!klass->nested_classes_inited) {
8335 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
8336 while (i) {
8337 MonoClass* nclass;
8338 guint32 cols [MONO_NESTED_CLASS_SIZE];
8339 mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
8340 nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED]);
8341 if (!nclass) {
8342 mono_loader_clear_error ();
8343 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
8344 continue;
8346 mono_class_alloc_ext (klass);
8347 klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, nclass);
8349 i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
8352 mono_memory_barrier ();
8353 klass->nested_classes_inited = TRUE;
8354 mono_loader_unlock ();
8357 if (!*iter) {
8358 /* start from the first */
8359 if (klass->ext && klass->ext->nested_classes) {
8360 *iter = klass->ext->nested_classes;
8361 return klass->ext->nested_classes->data;
8362 } else {
8363 /* no nested types */
8364 return NULL;
8367 item = *iter;
8368 item = item->next;
8369 if (item) {
8370 *iter = item;
8371 return item->data;
8373 return NULL;
8377 * mono_field_get_name:
8378 * @field: the MonoClassField to act on
8380 * Returns: the name of the field.
8382 const char*
8383 mono_field_get_name (MonoClassField *field)
8385 return field->name;
8389 * mono_field_get_type:
8390 * @field: the MonoClassField to act on
8392 * Returns: MonoType of the field.
8394 MonoType*
8395 mono_field_get_type (MonoClassField *field)
8397 MonoError error;
8398 MonoType *type = mono_field_get_type_checked (field, &error);
8399 if (!mono_error_ok (&error)) {
8400 mono_trace_warning (MONO_TRACE_TYPE, "Could not load field's type due to %s", mono_error_get_message (&error));
8401 mono_error_cleanup (&error);
8403 return type;
8408 * mono_field_get_type_checked:
8409 * @field: the MonoClassField to act on
8410 * @error: used to return any erro found while retrieving @field type
8412 * Returns: MonoType of the field.
8414 MonoType*
8415 mono_field_get_type_checked (MonoClassField *field, MonoError *error)
8417 mono_error_init (error);
8418 if (!field->type)
8419 mono_field_resolve_type (field, error);
8420 return field->type;
8424 * mono_field_get_parent:
8425 * @field: the MonoClassField to act on
8427 * Returns: MonoClass where the field was defined.
8429 MonoClass*
8430 mono_field_get_parent (MonoClassField *field)
8432 return field->parent;
8436 * mono_field_get_flags;
8437 * @field: the MonoClassField to act on
8439 * The metadata flags for a field are encoded using the
8440 * FIELD_ATTRIBUTE_* constants. See the tabledefs.h file for details.
8442 * Returns: the flags for the field.
8444 guint32
8445 mono_field_get_flags (MonoClassField *field)
8447 if (!field->type)
8448 return mono_field_resolve_flags (field);
8449 return field->type->attrs;
8453 * mono_field_get_offset;
8454 * @field: the MonoClassField to act on
8456 * Returns: the field offset.
8458 guint32
8459 mono_field_get_offset (MonoClassField *field)
8461 return field->offset;
8464 static const char *
8465 mono_field_get_rva (MonoClassField *field)
8467 guint32 rva;
8468 int field_index;
8469 MonoClass *klass = field->parent;
8471 g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA);
8473 if (!klass->ext || !klass->ext->field_def_values) {
8474 mono_loader_lock ();
8475 mono_class_alloc_ext (klass);
8476 if (!klass->ext->field_def_values)
8477 klass->ext->field_def_values = mono_class_alloc0 (klass, sizeof (MonoFieldDefaultValue) * klass->field.count);
8478 mono_loader_unlock ();
8481 field_index = mono_field_get_index (field);
8483 if (!klass->ext->field_def_values [field_index].data && !klass->image->dynamic) {
8484 mono_metadata_field_info (field->parent->image, klass->field.first + field_index, NULL, &rva, NULL);
8485 if (!rva)
8486 g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), field->parent->name);
8487 klass->ext->field_def_values [field_index].data = mono_image_rva_map (field->parent->image, rva);
8490 return klass->ext->field_def_values [field_index].data;
8494 * mono_field_get_data;
8495 * @field: the MonoClassField to act on
8497 * Returns: pointer to the metadata constant value or to the field
8498 * data if it has an RVA flag.
8500 const char *
8501 mono_field_get_data (MonoClassField *field)
8503 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT) {
8504 MonoTypeEnum def_type;
8506 return mono_class_get_field_default_value (field, &def_type);
8507 } else if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
8508 return mono_field_get_rva (field);
8509 } else {
8510 return NULL;
8515 * mono_property_get_name:
8516 * @prop: the MonoProperty to act on
8518 * Returns: the name of the property
8520 const char*
8521 mono_property_get_name (MonoProperty *prop)
8523 return prop->name;
8527 * mono_property_get_set_method
8528 * @prop: the MonoProperty to act on.
8530 * Returns: the setter method of the property (A MonoMethod)
8532 MonoMethod*
8533 mono_property_get_set_method (MonoProperty *prop)
8535 return prop->set;
8539 * mono_property_get_get_method
8540 * @prop: the MonoProperty to act on.
8542 * Returns: the setter method of the property (A MonoMethod)
8544 MonoMethod*
8545 mono_property_get_get_method (MonoProperty *prop)
8547 return prop->get;
8551 * mono_property_get_parent:
8552 * @prop: the MonoProperty to act on.
8554 * Returns: the MonoClass where the property was defined.
8556 MonoClass*
8557 mono_property_get_parent (MonoProperty *prop)
8559 return prop->parent;
8563 * mono_property_get_flags:
8564 * @prop: the MonoProperty to act on.
8566 * The metadata flags for a property are encoded using the
8567 * PROPERTY_ATTRIBUTE_* constants. See the tabledefs.h file for details.
8569 * Returns: the flags for the property.
8571 guint32
8572 mono_property_get_flags (MonoProperty *prop)
8574 return prop->attrs;
8578 * mono_event_get_name:
8579 * @event: the MonoEvent to act on
8581 * Returns: the name of the event.
8583 const char*
8584 mono_event_get_name (MonoEvent *event)
8586 return event->name;
8590 * mono_event_get_add_method:
8591 * @event: The MonoEvent to act on.
8593 * Returns: the @add' method for the event (a MonoMethod).
8595 MonoMethod*
8596 mono_event_get_add_method (MonoEvent *event)
8598 return event->add;
8602 * mono_event_get_remove_method:
8603 * @event: The MonoEvent to act on.
8605 * Returns: the @remove method for the event (a MonoMethod).
8607 MonoMethod*
8608 mono_event_get_remove_method (MonoEvent *event)
8610 return event->remove;
8614 * mono_event_get_raise_method:
8615 * @event: The MonoEvent to act on.
8617 * Returns: the @raise method for the event (a MonoMethod).
8619 MonoMethod*
8620 mono_event_get_raise_method (MonoEvent *event)
8622 return event->raise;
8626 * mono_event_get_parent:
8627 * @event: the MonoEvent to act on.
8629 * Returns: the MonoClass where the event is defined.
8631 MonoClass*
8632 mono_event_get_parent (MonoEvent *event)
8634 return event->parent;
8638 * mono_event_get_flags
8639 * @event: the MonoEvent to act on.
8641 * The metadata flags for an event are encoded using the
8642 * EVENT_* constants. See the tabledefs.h file for details.
8644 * Returns: the flags for the event.
8646 guint32
8647 mono_event_get_flags (MonoEvent *event)
8649 return event->attrs;
8653 * mono_class_get_method_from_name:
8654 * @klass: where to look for the method
8655 * @name_space: name of the method
8656 * @param_count: number of parameters. -1 for any number.
8658 * Obtains a MonoMethod with a given name and number of parameters.
8659 * It only works if there are no multiple signatures for any given method name.
8661 MonoMethod *
8662 mono_class_get_method_from_name (MonoClass *klass, const char *name, int param_count)
8664 return mono_class_get_method_from_name_flags (klass, name, param_count, 0);
8667 static MonoMethod*
8668 find_method_in_metadata (MonoClass *klass, const char *name, int param_count, int flags)
8670 MonoMethod *res = NULL;
8671 int i;
8673 /* Search directly in the metadata to avoid calling setup_methods () */
8674 for (i = 0; i < klass->method.count; ++i) {
8675 guint32 cols [MONO_METHOD_SIZE];
8676 MonoMethod *method;
8677 MonoMethodSignature *sig;
8679 /* class->method.first points into the methodptr table */
8680 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
8682 if (!strcmp (mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]), name)) {
8683 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
8684 if (param_count == -1) {
8685 res = method;
8686 break;
8688 sig = mono_method_signature (method);
8689 if (sig && sig->param_count == param_count) {
8690 res = method;
8691 break;
8696 return res;
8700 * mono_class_get_method_from_name_flags:
8701 * @klass: where to look for the method
8702 * @name_space: name of the method
8703 * @param_count: number of parameters. -1 for any number.
8704 * @flags: flags which must be set in the method
8706 * Obtains a MonoMethod with a given name and number of parameters.
8707 * It only works if there are no multiple signatures for any given method name.
8709 MonoMethod *
8710 mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int param_count, int flags)
8712 MonoMethod *res = NULL;
8713 int i;
8715 mono_class_init (klass);
8717 if (klass->generic_class && !klass->methods) {
8718 res = mono_class_get_method_from_name_flags (klass->generic_class->container_class, name, param_count, flags);
8719 if (res)
8720 res = mono_class_inflate_generic_method_full (res, klass, mono_class_get_context (klass));
8721 return res;
8724 if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
8725 mono_class_setup_methods (klass);
8727 We can't fail lookup of methods otherwise the runtime will burst in flames on all sort of places.
8728 See mono/tests/array_load_exception.il
8729 FIXME we should better report this error to the caller
8731 if (!klass->methods)
8732 return NULL;
8733 for (i = 0; i < klass->method.count; ++i) {
8734 MonoMethod *method = klass->methods [i];
8736 if (method->name[0] == name [0] &&
8737 !strcmp (name, method->name) &&
8738 (param_count == -1 || mono_method_signature (method)->param_count == param_count) &&
8739 ((method->flags & flags) == flags)) {
8740 res = method;
8741 break;
8745 else {
8746 res = find_method_in_metadata (klass, name, param_count, flags);
8749 return res;
8753 * mono_class_set_failure:
8754 * @klass: class in which the failure was detected
8755 * @ex_type: the kind of exception/error to be thrown (later)
8756 * @ex_data: exception data (specific to each type of exception/error)
8758 * Keep a detected failure informations in the class for later processing.
8759 * Note that only the first failure is kept.
8761 * LOCKING: Acquires the loader lock.
8763 gboolean
8764 mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
8766 if (klass->exception_type)
8767 return FALSE;
8769 mono_loader_lock ();
8770 klass->exception_type = ex_type;
8771 if (ex_data)
8772 mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
8773 mono_loader_unlock ();
8775 return TRUE;
8779 * mono_class_get_exception_data:
8781 * Return the exception_data property of KLASS.
8783 * LOCKING: Acquires the loader lock.
8785 gpointer
8786 mono_class_get_exception_data (MonoClass *klass)
8788 return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
8792 * mono_classes_init:
8794 * Initialize the resources used by this module.
8796 void
8797 mono_classes_init (void)
8799 mono_counters_register ("Inflated methods size",
8800 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_methods_size);
8801 mono_counters_register ("Inflated classes",
8802 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes);
8803 mono_counters_register ("Inflated classes size",
8804 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
8805 mono_counters_register ("MonoClass size",
8806 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
8807 mono_counters_register ("MonoClassExt size",
8808 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ext_size);
8812 * mono_classes_cleanup:
8814 * Free the resources used by this module.
8816 void
8817 mono_classes_cleanup (void)
8819 if (global_interface_bitset)
8820 mono_bitset_free (global_interface_bitset);
8824 * mono_class_get_exception_for_failure:
8825 * @klass: class in which the failure was detected
8827 * Return a constructed MonoException than the caller can then throw
8828 * using mono_raise_exception - or NULL if no failure is present (or
8829 * doesn't result in an exception).
8831 MonoException*
8832 mono_class_get_exception_for_failure (MonoClass *klass)
8834 gpointer exception_data = mono_class_get_exception_data (klass);
8836 switch (klass->exception_type) {
8837 case MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND: {
8838 MonoDomain *domain = mono_domain_get ();
8839 MonoSecurityManager* secman = mono_security_manager_get_methods ();
8840 MonoMethod *method = exception_data;
8841 guint32 error = (method) ? MONO_METADATA_INHERITANCEDEMAND_METHOD : MONO_METADATA_INHERITANCEDEMAND_CLASS;
8842 MonoObject *exc = NULL;
8843 gpointer args [4];
8845 args [0] = &error;
8846 args [1] = mono_assembly_get_object (domain, mono_image_get_assembly (klass->image));
8847 args [2] = mono_type_get_object (domain, &klass->byval_arg);
8848 args [3] = (method) ? mono_method_get_object (domain, method, NULL) : NULL;
8850 mono_runtime_invoke (secman->inheritsecurityexception, NULL, args, &exc);
8851 return (MonoException*) exc;
8853 case MONO_EXCEPTION_TYPE_LOAD: {
8854 MonoString *name;
8855 MonoException *ex;
8856 char *str = mono_type_get_full_name (klass);
8857 char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
8858 name = mono_string_new (mono_domain_get (), str);
8859 g_free (str);
8860 ex = mono_get_exception_type_load (name, astr);
8861 g_free (astr);
8862 return ex;
8864 case MONO_EXCEPTION_MISSING_METHOD: {
8865 char *class_name = exception_data;
8866 char *assembly_name = class_name + strlen (class_name) + 1;
8868 return mono_get_exception_missing_method (class_name, assembly_name);
8870 case MONO_EXCEPTION_MISSING_FIELD: {
8871 char *class_name = exception_data;
8872 char *member_name = class_name + strlen (class_name) + 1;
8874 return mono_get_exception_missing_field (class_name, member_name);
8876 case MONO_EXCEPTION_FILE_NOT_FOUND: {
8877 char *msg_format = exception_data;
8878 char *assembly_name = msg_format + strlen (msg_format) + 1;
8879 char *msg = g_strdup_printf (msg_format, assembly_name);
8880 MonoException *ex;
8882 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
8884 g_free (msg);
8886 return ex;
8888 case MONO_EXCEPTION_BAD_IMAGE: {
8889 return mono_get_exception_bad_image_format (exception_data);
8891 default: {
8892 MonoLoaderError *error;
8893 MonoException *ex;
8895 error = mono_loader_get_last_error ();
8896 if (error != NULL){
8897 ex = mono_loader_error_prepare_exception (error);
8898 return ex;
8901 /* TODO - handle other class related failures */
8902 return NULL;
8907 static gboolean
8908 is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
8910 outer_klass = mono_class_get_generic_type_definition (outer_klass);
8911 inner_klass = mono_class_get_generic_type_definition (inner_klass);
8912 do {
8913 if (outer_klass == inner_klass)
8914 return TRUE;
8915 inner_klass = inner_klass->nested_in;
8916 } while (inner_klass);
8917 return FALSE;
8920 MonoClass *
8921 mono_class_get_generic_type_definition (MonoClass *klass)
8923 return klass->generic_class ? klass->generic_class->container_class : klass;
8927 * Check if @klass is a subtype of @parent ignoring generic instantiations.
8929 * Generic instantiations are ignored for all super types of @klass.
8931 * Visibility checks ignoring generic instantiations.
8933 gboolean
8934 mono_class_has_parent_and_ignore_generics (MonoClass *klass, MonoClass *parent)
8936 int i;
8937 klass = mono_class_get_generic_type_definition (klass);
8938 parent = mono_class_get_generic_type_definition (parent);
8940 for (i = 0; i < klass->idepth; ++i) {
8941 if (parent == mono_class_get_generic_type_definition (klass->supertypes [i]))
8942 return TRUE;
8944 return FALSE;
8947 * Subtype can only access parent members with family protection if the site object
8948 * is subclass of Subtype. For example:
8949 * class A { protected int x; }
8950 * class B : A {
8951 * void valid_access () {
8952 * B b;
8953 * b.x = 0;
8955 * void invalid_access () {
8956 * A a;
8957 * a.x = 0;
8960 * */
8961 static gboolean
8962 is_valid_family_access (MonoClass *access_klass, MonoClass *member_klass, MonoClass *context_klass)
8964 if (!mono_class_has_parent_and_ignore_generics (access_klass, member_klass))
8965 return FALSE;
8967 if (context_klass == NULL)
8968 return TRUE;
8969 /*if access_klass is not member_klass context_klass must be type compat*/
8970 if (access_klass != member_klass && !mono_class_has_parent_and_ignore_generics (context_klass, access_klass))
8971 return FALSE;
8972 return TRUE;
8975 static gboolean
8976 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
8978 GSList *tmp;
8979 if (accessing == accessed)
8980 return TRUE;
8981 if (!accessed || !accessing)
8982 return FALSE;
8984 /* extra safety under CoreCLR - the runtime does not verify the strongname signatures
8985 * anywhere so untrusted friends are not safe to access platform's code internals */
8986 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8987 if (!mono_security_core_clr_can_access_internals (accessing->image, accessed->image))
8988 return FALSE;
8991 mono_assembly_load_friends (accessed);
8992 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
8993 MonoAssemblyName *friend = tmp->data;
8994 /* Be conservative with checks */
8995 if (!friend->name)
8996 continue;
8997 if (strcmp (accessing->aname.name, friend->name))
8998 continue;
8999 if (friend->public_key_token [0]) {
9000 if (!accessing->aname.public_key_token [0])
9001 continue;
9002 if (!mono_public_tokens_are_equal (friend->public_key_token, accessing->aname.public_key_token))
9003 continue;
9005 return TRUE;
9007 return FALSE;
9011 * If klass is a generic type or if it is derived from a generic type, return the
9012 * MonoClass of the generic definition
9013 * Returns NULL if not found
9015 static MonoClass*
9016 get_generic_definition_class (MonoClass *klass)
9018 while (klass) {
9019 if (klass->generic_class && klass->generic_class->container_class)
9020 return klass->generic_class->container_class;
9021 klass = klass->parent;
9023 return NULL;
9026 static gboolean
9027 can_access_instantiation (MonoClass *access_klass, MonoGenericInst *ginst)
9029 int i;
9030 for (i = 0; i < ginst->type_argc; ++i) {
9031 MonoType *type = ginst->type_argv[i];
9032 switch (type->type) {
9033 case MONO_TYPE_SZARRAY:
9034 if (!can_access_type (access_klass, type->data.klass))
9035 return FALSE;
9036 break;
9037 case MONO_TYPE_ARRAY:
9038 if (!can_access_type (access_klass, type->data.array->eklass))
9039 return FALSE;
9040 break;
9041 case MONO_TYPE_PTR:
9042 if (!can_access_type (access_klass, mono_class_from_mono_type (type->data.type)))
9043 return FALSE;
9044 break;
9045 case MONO_TYPE_CLASS:
9046 case MONO_TYPE_VALUETYPE:
9047 case MONO_TYPE_GENERICINST:
9048 if (!can_access_type (access_klass, mono_class_from_mono_type (type)))
9049 return FALSE;
9052 return TRUE;
9055 static gboolean
9056 can_access_type (MonoClass *access_klass, MonoClass *member_klass)
9058 int access_level;
9060 if (access_klass->element_class && !access_klass->enumtype)
9061 access_klass = access_klass->element_class;
9063 if (member_klass->element_class && !member_klass->enumtype)
9064 member_klass = member_klass->element_class;
9066 access_level = member_klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
9068 if (member_klass->byval_arg.type == MONO_TYPE_VAR || member_klass->byval_arg.type == MONO_TYPE_MVAR)
9069 return TRUE;
9071 if (member_klass->generic_class && !can_access_instantiation (access_klass, member_klass->generic_class->context.class_inst))
9072 return FALSE;
9074 if (is_nesting_type (access_klass, member_klass) || (access_klass->nested_in && is_nesting_type (access_klass->nested_in, member_klass)))
9075 return TRUE;
9077 if (member_klass->nested_in && !can_access_type (access_klass, member_klass->nested_in))
9078 return FALSE;
9080 /*Non nested type with nested visibility. We just fail it.*/
9081 if (access_level >= TYPE_ATTRIBUTE_NESTED_PRIVATE && access_level <= TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM && member_klass->nested_in == NULL)
9082 return FALSE;
9084 switch (access_level) {
9085 case TYPE_ATTRIBUTE_NOT_PUBLIC:
9086 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9088 case TYPE_ATTRIBUTE_PUBLIC:
9089 return TRUE;
9091 case TYPE_ATTRIBUTE_NESTED_PUBLIC:
9092 return TRUE;
9094 case TYPE_ATTRIBUTE_NESTED_PRIVATE:
9095 return is_nesting_type (member_klass, access_klass);
9097 case TYPE_ATTRIBUTE_NESTED_FAMILY:
9098 return mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
9100 case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
9101 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9103 case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
9104 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) &&
9105 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
9107 case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
9108 return can_access_internals (access_klass->image->assembly, member_klass->nested_in->image->assembly) ||
9109 mono_class_has_parent_and_ignore_generics (access_klass, member_klass->nested_in);
9111 return FALSE;
9114 /* FIXME: check visibility of type, too */
9115 static gboolean
9116 can_access_member (MonoClass *access_klass, MonoClass *member_klass, MonoClass* context_klass, int access_level)
9118 MonoClass *member_generic_def;
9119 if (((access_klass->generic_class && access_klass->generic_class->container_class) ||
9120 access_klass->generic_container) &&
9121 (member_generic_def = get_generic_definition_class (member_klass))) {
9122 MonoClass *access_container;
9124 if (access_klass->generic_container)
9125 access_container = access_klass;
9126 else
9127 access_container = access_klass->generic_class->container_class;
9129 if (can_access_member (access_container, member_generic_def, context_klass, access_level))
9130 return TRUE;
9133 /* Partition I 8.5.3.2 */
9134 /* the access level values are the same for fields and methods */
9135 switch (access_level) {
9136 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
9137 /* same compilation unit */
9138 return access_klass->image == member_klass->image;
9139 case FIELD_ATTRIBUTE_PRIVATE:
9140 return access_klass == member_klass;
9141 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
9142 if (is_valid_family_access (access_klass, member_klass, context_klass) &&
9143 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
9144 return TRUE;
9145 return FALSE;
9146 case FIELD_ATTRIBUTE_ASSEMBLY:
9147 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9148 case FIELD_ATTRIBUTE_FAMILY:
9149 if (is_valid_family_access (access_klass, member_klass, context_klass))
9150 return TRUE;
9151 return FALSE;
9152 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
9153 if (is_valid_family_access (access_klass, member_klass, context_klass))
9154 return TRUE;
9155 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
9156 case FIELD_ATTRIBUTE_PUBLIC:
9157 return TRUE;
9159 return FALSE;
9162 gboolean
9163 mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
9165 /* FIXME: check all overlapping fields */
9166 int can = can_access_member (method->klass, field->parent, NULL, mono_field_get_type (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9167 if (!can) {
9168 MonoClass *nested = method->klass->nested_in;
9169 while (nested) {
9170 can = can_access_member (nested, field->parent, NULL, mono_field_get_type (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9171 if (can)
9172 return TRUE;
9173 nested = nested->nested_in;
9176 return can;
9179 gboolean
9180 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
9182 int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9183 if (!can) {
9184 MonoClass *nested = method->klass->nested_in;
9185 while (nested) {
9186 can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9187 if (can)
9188 return TRUE;
9189 nested = nested->nested_in;
9193 * FIXME:
9194 * with generics calls to explicit interface implementations can be expressed
9195 * directly: the method is private, but we must allow it. This may be opening
9196 * a hole or the generics code should handle this differently.
9197 * Maybe just ensure the interface type is public.
9199 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
9200 return TRUE;
9201 return can;
9205 * mono_method_can_access_method_full:
9206 * @method: The caller method
9207 * @called: The called method
9208 * @context_klass: The static type on stack of the owner @called object used
9210 * This function must be used with instance calls, as they have more strict family accessibility.
9211 * It can be used with static methods, but context_klass should be NULL.
9213 * Returns: TRUE if caller have proper visibility and acessibility to @called
9215 gboolean
9216 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
9218 MonoClass *access_class = method->klass;
9219 MonoClass *member_class = called->klass;
9220 int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9221 if (!can) {
9222 MonoClass *nested = access_class->nested_in;
9223 while (nested) {
9224 can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
9225 if (can)
9226 break;
9227 nested = nested->nested_in;
9231 if (!can)
9232 return FALSE;
9234 can = can_access_type (access_class, member_class);
9235 if (!can) {
9236 MonoClass *nested = access_class->nested_in;
9237 while (nested) {
9238 can = can_access_type (nested, member_class);
9239 if (can)
9240 break;
9241 nested = nested->nested_in;
9245 if (!can)
9246 return FALSE;
9248 if (called->is_inflated) {
9249 MonoMethodInflated * infl = (MonoMethodInflated*)called;
9250 if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
9251 return FALSE;
9254 return TRUE;
9259 * mono_method_can_access_field_full:
9260 * @method: The caller method
9261 * @field: The accessed field
9262 * @context_klass: The static type on stack of the owner @field object used
9264 * This function must be used with instance fields, as they have more strict family accessibility.
9265 * It can be used with static fields, but context_klass should be NULL.
9267 * Returns: TRUE if caller have proper visibility and acessibility to @field
9269 gboolean
9270 mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass)
9272 MonoClass *access_class = method->klass;
9273 MonoClass *member_class = field->parent;
9274 /* FIXME: check all overlapping fields */
9275 int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9276 if (!can) {
9277 MonoClass *nested = access_class->nested_in;
9278 while (nested) {
9279 can = can_access_member (nested, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
9280 if (can)
9281 break;
9282 nested = nested->nested_in;
9286 if (!can)
9287 return FALSE;
9289 can = can_access_type (access_class, member_class);
9290 if (!can) {
9291 MonoClass *nested = access_class->nested_in;
9292 while (nested) {
9293 can = can_access_type (nested, member_class);
9294 if (can)
9295 break;
9296 nested = nested->nested_in;
9300 if (!can)
9301 return FALSE;
9302 return TRUE;
9306 * mono_type_is_valid_enum_basetype:
9307 * @type: The MonoType to check
9309 * Returns: TRUE if the type can be used as the basetype of an enum
9311 gboolean mono_type_is_valid_enum_basetype (MonoType * type) {
9312 switch (type->type) {
9313 case MONO_TYPE_I1:
9314 case MONO_TYPE_U1:
9315 case MONO_TYPE_BOOLEAN:
9316 case MONO_TYPE_I2:
9317 case MONO_TYPE_U2:
9318 case MONO_TYPE_CHAR:
9319 case MONO_TYPE_I4:
9320 case MONO_TYPE_U4:
9321 case MONO_TYPE_I8:
9322 case MONO_TYPE_U8:
9323 case MONO_TYPE_I:
9324 case MONO_TYPE_U:
9325 return TRUE;
9327 return FALSE;
9331 * mono_class_is_valid_enum:
9332 * @klass: An enum class to be validated
9334 * This method verify the required properties an enum should have.
9336 * Returns: TRUE if the informed enum class is valid
9338 * FIXME: TypeBuilder enums are allowed to implement interfaces, but since they cannot have methods, only empty interfaces are possible
9339 * FIXME: enum types are not allowed to have a cctor, but mono_reflection_create_runtime_class sets has_cctor to 1 for all types
9340 * FIXME: TypeBuilder enums can have any kind of static fields, but the spec is very explicit about that (P II 14.3)
9342 gboolean mono_class_is_valid_enum (MonoClass *klass) {
9343 MonoClassField * field;
9344 gpointer iter = NULL;
9345 gboolean found_base_field = FALSE;
9347 g_assert (klass->enumtype);
9348 /* we cannot test against mono_defaults.enum_class, or mcs won't be able to compile the System namespace*/
9349 if (!klass->parent || strcmp (klass->parent->name, "Enum") || strcmp (klass->parent->name_space, "System") ) {
9350 return FALSE;
9353 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)
9354 return FALSE;
9356 while ((field = mono_class_get_fields (klass, &iter))) {
9357 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
9358 if (found_base_field)
9359 return FALSE;
9360 found_base_field = TRUE;
9361 if (!mono_type_is_valid_enum_basetype (field->type))
9362 return FALSE;
9366 if (!found_base_field)
9367 return FALSE;
9369 if (klass->method.count > 0)
9370 return FALSE;
9372 return TRUE;
9375 gboolean
9376 mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass)
9378 return gklass->context.class_inst == gklass->container_class->generic_container->context.class_inst;
9382 * mono_class_setup_interface_id:
9384 * Initializes MonoClass::interface_id if required.
9386 * LOCKING: Acquires the loader lock.
9388 void
9389 mono_class_setup_interface_id (MonoClass *class)
9391 mono_loader_lock ();
9392 if (MONO_CLASS_IS_INTERFACE (class) && !class->interface_id)
9393 class->interface_id = mono_get_unique_iid (class);
9394 mono_loader_unlock ();
9398 * mono_class_alloc_ext:
9400 * Allocate klass->ext if not already done.
9401 * LOCKING: Assumes the loader lock is held.
9403 void
9404 mono_class_alloc_ext (MonoClass *klass)
9406 if (!klass->ext) {
9407 klass->ext = mono_class_alloc0 (klass, sizeof (MonoClassExt));
9408 class_ext_size += sizeof (MonoClassExt);
9413 * mono_class_setup_interfaces:
9415 * Initialize class->interfaces/interfaces_count.
9416 * LOCKING: Acquires the loader lock.
9417 * This function can fail the type.
9419 void
9420 mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
9422 int i;
9424 mono_error_init (error);
9426 if (klass->interfaces_inited)
9427 return;
9429 mono_loader_lock ();
9431 if (klass->interfaces_inited) {
9432 mono_loader_unlock ();
9433 return;
9436 if (klass->rank == 1 && klass->byval_arg.type != MONO_TYPE_ARRAY && mono_defaults.generic_ilist_class) {
9437 MonoType *args [1];
9439 /* generic IList, ICollection, IEnumerable */
9440 klass->interface_count = 1;
9441 klass->interfaces = mono_image_alloc0 (klass->image, sizeof (MonoClass*) * klass->interface_count);
9443 args [0] = &klass->element_class->byval_arg;
9444 klass->interfaces [0] = mono_class_bind_generic_parameters (
9445 mono_defaults.generic_ilist_class, 1, args, FALSE);
9446 } else if (klass->generic_class) {
9447 MonoClass *gklass = klass->generic_class->container_class;
9449 klass->interface_count = gklass->interface_count;
9450 klass->interfaces = mono_class_new0 (klass, MonoClass *, klass->interface_count);
9451 for (i = 0; i < klass->interface_count; i++) {
9452 klass->interfaces [i] = mono_class_inflate_generic_class_checked (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class), error);
9453 if (!mono_error_ok (error)) {
9454 mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not setup the interfaces"));
9455 klass->interfaces = NULL;
9456 return;
9461 mono_memory_barrier ();
9463 klass->interfaces_inited = TRUE;
9465 mono_loader_unlock ();
9468 static void
9469 mono_field_resolve_type (MonoClassField *field, MonoError *error)
9471 MonoClass *class = field->parent;
9472 MonoImage *image = class->image;
9473 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
9474 int field_idx = field - class->fields;
9476 mono_error_init (error);
9478 if (gtd) {
9479 MonoClassField *gfield = &gtd->fields [field_idx];
9480 MonoType *gtype = mono_field_get_type_checked (gfield, error);
9481 if (!mono_error_ok (error)) {
9482 char *err_msg = g_strdup_printf ("Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
9483 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
9484 g_free (err_msg);
9487 field->type = mono_class_inflate_generic_type_no_copy (image, gtype, mono_class_get_context (class), error);
9488 if (!mono_error_ok (error)) {
9489 char *err_msg = g_strdup_printf ("Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
9490 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
9491 g_free (err_msg);
9493 } else {
9494 const char *sig;
9495 guint32 cols [MONO_FIELD_SIZE];
9496 MonoGenericContainer *container = NULL;
9497 int idx = class->field.first + field_idx;
9499 /*FIXME, in theory we do not lazy load SRE fields*/
9500 g_assert (!image->dynamic);
9502 if (class->generic_container) {
9503 container = class->generic_container;
9504 } else if (gtd) {
9505 container = gtd->generic_container;
9506 g_assert (container);
9509 /* class->field.first and idx points into the fieldptr table */
9510 mono_metadata_decode_table_row (image, MONO_TABLE_FIELD, idx, cols, MONO_FIELD_SIZE);
9512 if (!mono_verifier_verify_field_signature (image, cols [MONO_FIELD_SIGNATURE], NULL)) {
9513 mono_error_set_type_load_class (error, class, "Could not verify field %s signature", field->name);
9514 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
9515 return;
9518 sig = mono_metadata_blob_heap (image, cols [MONO_FIELD_SIGNATURE]);
9520 mono_metadata_decode_value (sig, &sig);
9521 /* FIELD signature == 0x06 */
9522 g_assert (*sig == 0x06);
9523 field->type = mono_metadata_parse_type_full (image, container, MONO_PARSE_FIELD, cols [MONO_FIELD_FLAGS], sig + 1, &sig);
9524 if (!field->type) {
9525 mono_error_set_type_load_class (error, class, "Could not load field %s type", field->name);
9526 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
9527 mono_loader_clear_error ();
9532 static guint32
9533 mono_field_resolve_flags (MonoClassField *field)
9535 MonoClass *class = field->parent;
9536 MonoImage *image = class->image;
9537 MonoClass *gtd = class->generic_class ? mono_class_get_generic_type_definition (class) : NULL;
9538 int field_idx = field - class->fields;
9541 if (gtd) {
9542 MonoClassField *gfield = &gtd->fields [field_idx];
9543 return mono_field_get_flags (gfield);
9544 } else {
9545 int idx = class->field.first + field_idx;
9547 /*FIXME, in theory we do not lazy load SRE fields*/
9548 g_assert (!image->dynamic);
9550 return mono_metadata_decode_table_row_col (image, MONO_TABLE_FIELD, idx, MONO_FIELD_FLAGS);
9555 * mono_class_setup_basic_field_info:
9556 * @class: The class to initialize
9558 * Initializes the class->fields array of fields.
9559 * Aquires the loader lock.
9561 static void
9562 mono_class_setup_basic_field_info_locking (MonoClass *class)
9564 mono_loader_lock ();
9565 mono_class_setup_basic_field_info (class);
9566 mono_loader_unlock ();
9570 * mono_class_get_fields_lazy:
9571 * @klass: the MonoClass to act on
9573 * This routine is an iterator routine for retrieving the fields in a class.
9574 * Only minimal information about fields are loaded. Accessors must be used
9575 * for all MonoClassField returned.
9577 * You must pass a gpointer that points to zero and is treated as an opaque handle to
9578 * iterate over all of the elements. When no more values are
9579 * available, the return value is NULL.
9581 * Returns: a @MonoClassField* on each iteration, or NULL when no more fields are available.
9583 MonoClassField*
9584 mono_class_get_fields_lazy (MonoClass* klass, gpointer *iter)
9586 MonoClassField* field;
9587 if (!iter)
9588 return NULL;
9589 if (!*iter) {
9590 mono_class_setup_basic_field_info_locking (klass);
9591 if (!klass->fields)
9592 return NULL;
9593 /* start from the first */
9594 if (klass->field.count) {
9595 return *iter = &klass->fields [0];
9596 } else {
9597 /* no fields */
9598 return NULL;
9601 field = *iter;
9602 field++;
9603 if (field < &klass->fields [klass->field.count]) {
9604 return *iter = field;
9606 return NULL;