2 * reflection.c: System.Type icalls and related reflection queries.
5 * Paolo Molaro (lupus@ximian.com)
7 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9 * Copyright 2011 Rodrigo Kumpera
10 * Copyright 2016 Microsoft
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #include "mono/utils/mono-membar.h"
16 #include "mono/metadata/reflection-internals.h"
17 #include "mono/metadata/tabledefs.h"
18 #include "mono/metadata/metadata-internals.h"
19 #include <mono/metadata/profiler-private.h>
20 #include "mono/metadata/class-internals.h"
21 #include "mono/metadata/gc-internals.h"
22 #include "mono/metadata/domain-internals.h"
23 #include "mono/metadata/opcodes.h"
24 #include "mono/metadata/assembly.h"
25 #include "mono/metadata/object-internals.h"
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/metadata/security-manager.h>
29 #include <mono/metadata/reflection-cache.h>
30 #include <mono/metadata/sre-internals.h>
39 #include "mono-endian.h"
40 #include <mono/metadata/gc-internals.h>
41 #include <mono/metadata/mempool-internals.h>
42 #include <mono/metadata/security-core-clr.h>
43 #include <mono/metadata/debug-helpers.h>
44 #include <mono/metadata/verify-internals.h>
45 #include <mono/metadata/mono-ptr-array.h>
46 #include <mono/utils/mono-string.h>
47 #include <mono/utils/mono-error-internals.h>
48 #include <mono/utils/checked-build.h>
50 static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types);
51 static MonoType* mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve, MonoError *error);
53 /* Class lazy loading functions */
54 static GENERATE_GET_CLASS_WITH_CACHE (mono_assembly, System.Reflection, MonoAssembly)
55 static GENERATE_GET_CLASS_WITH_CACHE (mono_module, System.Reflection, MonoModule)
56 static GENERATE_GET_CLASS_WITH_CACHE (mono_method, System.Reflection, MonoMethod);
57 static GENERATE_GET_CLASS_WITH_CACHE (mono_cmethod, System.Reflection, MonoCMethod);
58 static GENERATE_GET_CLASS_WITH_CACHE (mono_field, System.Reflection, MonoField);
59 static GENERATE_GET_CLASS_WITH_CACHE (mono_event, System.Reflection, MonoEvent);
60 static GENERATE_GET_CLASS_WITH_CACHE (mono_property, System.Reflection, MonoProperty);
61 static GENERATE_GET_CLASS_WITH_CACHE (mono_parameter_info, System.Reflection, MonoParameterInfo);
62 static GENERATE_GET_CLASS_WITH_CACHE (missing, System.Reflection, Missing);
63 static GENERATE_GET_CLASS_WITH_CACHE (method_body, System.Reflection, MethodBody);
64 static GENERATE_GET_CLASS_WITH_CACHE (local_variable_info, System.Reflection, LocalVariableInfo);
65 static GENERATE_GET_CLASS_WITH_CACHE (exception_handling_clause, System.Reflection, ExceptionHandlingClause);
66 static GENERATE_GET_CLASS_WITH_CACHE (type_builder, System.Reflection.Emit, TypeBuilder);
67 static GENERATE_GET_CLASS_WITH_CACHE (dbnull, System, DBNull);
70 mono_reflection_init (void)
72 mono_reflection_emit_init ();
76 * mono_class_get_ref_info:
78 * Return the type builder/generic param builder corresponding to KLASS, if it exists.
81 mono_class_get_ref_info (MonoClass *klass)
83 MONO_REQ_GC_UNSAFE_MODE;
85 if (klass->ref_info_handle == 0)
88 return mono_gchandle_get_target (klass->ref_info_handle);
92 mono_class_set_ref_info (MonoClass *klass, gpointer obj)
94 MONO_REQ_GC_UNSAFE_MODE;
96 klass->ref_info_handle = mono_gchandle_new ((MonoObject*)obj, FALSE);
97 g_assert (klass->ref_info_handle != 0);
101 mono_class_free_ref_info (MonoClass *klass)
103 MONO_REQ_GC_NEUTRAL_MODE;
105 if (klass->ref_info_handle) {
106 mono_gchandle_free (klass->ref_info_handle);
107 klass->ref_info_handle = 0;
113 mono_custom_attrs_free (MonoCustomAttrInfo *ainfo)
115 MONO_REQ_GC_NEUTRAL_MODE;
117 if (ainfo && !ainfo->cached)
123 reflected_equal (gconstpointer a, gconstpointer b)
125 const ReflectedEntry *ea = (const ReflectedEntry *)a;
126 const ReflectedEntry *eb = (const ReflectedEntry *)b;
128 return (ea->item == eb->item) && (ea->refclass == eb->refclass);
132 reflected_hash (gconstpointer a) {
133 const ReflectedEntry *ea = (const ReflectedEntry *)a;
134 return mono_aligned_addr_hash (ea->item);
139 clear_cached_object (MonoDomain *domain, gpointer o, MonoClass *klass)
141 mono_domain_lock (domain);
142 if (domain->refobject_hash) {
144 gpointer orig_pe, orig_value;
148 if (mono_g_hash_table_lookup_extended (domain->refobject_hash, &pe, &orig_pe, &orig_value)) {
149 mono_g_hash_table_remove (domain->refobject_hash, &pe);
150 FREE_REFENTRY (orig_pe);
153 mono_domain_unlock (domain);
156 #ifdef REFENTRY_REQUIRES_CLEANUP
158 cleanup_refobject_hash (gpointer key, gpointer value, gpointer user_data)
165 mono_reflection_cleanup_domain (MonoDomain *domain)
167 if (domain->refobject_hash) {
168 /*let's avoid scanning the whole hashtable if not needed*/
169 #ifdef REFENTRY_REQUIRES_CLEANUP
170 mono_g_hash_table_foreach (domain->refobject_hash, cleanup_refobject_hash, NULL);
172 mono_g_hash_table_destroy (domain->refobject_hash);
173 domain->refobject_hash = NULL;
179 * mono_assembly_get_object:
180 * @domain: an app domain
181 * @assembly: an assembly
183 * Return an System.Reflection.Assembly object representing the MonoAssembly @assembly.
185 MonoReflectionAssembly*
186 mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly)
189 MonoReflectionAssembly *result;
190 result = mono_assembly_get_object_checked (domain, assembly, &error);
191 mono_error_cleanup (&error); /* FIXME new API that doesn't swallow the error */
195 * mono_assembly_get_object_checked:
196 * @domain: an app domain
197 * @assembly: an assembly
199 * Return an System.Reflection.Assembly object representing the MonoAssembly @assembly.
201 MonoReflectionAssembly*
202 mono_assembly_get_object_checked (MonoDomain *domain, MonoAssembly *assembly, MonoError *error)
204 MonoReflectionAssembly *res;
206 mono_error_init (error);
208 CHECK_OBJECT (MonoReflectionAssembly *, assembly, NULL);
209 res = (MonoReflectionAssembly *)mono_object_new_checked (domain, mono_class_get_mono_assembly_class (), error);
212 res->assembly = assembly;
214 CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
219 MonoReflectionModule*
220 mono_module_get_object (MonoDomain *domain, MonoImage *image)
223 MonoReflectionModule *result;
224 result = mono_module_get_object_checked (domain, image, &error);
225 mono_error_cleanup (&error);
229 MonoReflectionModule*
230 mono_module_get_object_checked (MonoDomain *domain, MonoImage *image, MonoError *error)
232 MonoReflectionModule *res;
235 mono_error_init (error);
236 CHECK_OBJECT (MonoReflectionModule *, image, NULL);
237 res = (MonoReflectionModule *)mono_object_new_checked (domain, mono_class_get_mono_module_class (), error);
242 MonoReflectionAssembly *assm_obj = mono_assembly_get_object_checked (domain, image->assembly, error);
245 MONO_OBJECT_SETREF (res, assembly, assm_obj);
247 MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, image->name));
248 basename = g_path_get_basename (image->name);
249 MONO_OBJECT_SETREF (res, name, mono_string_new (domain, basename));
250 MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, image->module_name));
254 if (image->assembly->image == image) {
255 res->token = mono_metadata_make_token (MONO_TABLE_MODULE, 1);
259 if (image->assembly->image->modules) {
260 for (i = 0; i < image->assembly->image->module_count; i++) {
261 if (image->assembly->image->modules [i] == image)
262 res->token = mono_metadata_make_token (MONO_TABLE_MODULEREF, i + 1);
264 g_assert (res->token);
268 CACHE_OBJECT (MonoReflectionModule *, image, res, NULL);
271 MonoReflectionModule*
272 mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_index)
275 MonoReflectionModule *result;
276 result = mono_module_file_get_object_checked (domain, image, table_index, &error);
277 mono_error_cleanup (&error);
281 MonoReflectionModule*
282 mono_module_file_get_object_checked (MonoDomain *domain, MonoImage *image, int table_index, MonoError *error)
284 MonoReflectionModule *res;
285 MonoTableInfo *table;
286 guint32 cols [MONO_FILE_SIZE];
291 mono_error_init (error);
293 res = (MonoReflectionModule *)mono_object_new_checked (domain, mono_class_get_mono_module_class (), error);
297 table = &image->tables [MONO_TABLE_FILE];
298 g_assert (table_index < table->rows);
299 mono_metadata_decode_row (table, table_index, cols, MONO_FILE_SIZE);
302 MonoReflectionAssembly *assm_obj = mono_assembly_get_object_checked (domain, image->assembly, error);
305 MONO_OBJECT_SETREF (res, assembly, assm_obj);
306 name = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
308 /* Check whenever the row has a corresponding row in the moduleref table */
309 table = &image->tables [MONO_TABLE_MODULEREF];
310 for (i = 0; i < table->rows; ++i) {
311 name_idx = mono_metadata_decode_row_col (table, i, MONO_MODULEREF_NAME);
312 val = mono_metadata_string_heap (image, name_idx);
313 if (strcmp (val, name) == 0)
314 res->image = image->modules [i];
317 MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, name));
318 MONO_OBJECT_SETREF (res, name, mono_string_new (domain, name));
319 MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, name));
320 res->is_resource = cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA;
321 res->token = mono_metadata_make_token (MONO_TABLE_FILE, table_index + 1);
327 verify_safe_for_managed_space (MonoType *type)
329 switch (type->type) {
331 case MONO_TYPE_ARRAY:
332 return verify_safe_for_managed_space (&type->data.array->eklass->byval_arg);
334 return verify_safe_for_managed_space (type->data.type);
335 case MONO_TYPE_SZARRAY:
336 return verify_safe_for_managed_space (&type->data.klass->byval_arg);
337 case MONO_TYPE_GENERICINST: {
338 MonoGenericInst *inst = type->data.generic_class->inst;
342 for (i = 0; i < inst->type_argc; ++i)
343 if (!verify_safe_for_managed_space (inst->type_argv [i]))
357 mono_type_normalize (MonoType *type)
360 MonoGenericClass *gclass;
361 MonoGenericInst *ginst;
363 MonoGenericContainer *gcontainer;
364 MonoType **argv = NULL;
365 gboolean is_denorm_gtd = TRUE, requires_rebind = FALSE;
367 if (type->type != MONO_TYPE_GENERICINST)
370 gclass = type->data.generic_class;
371 ginst = gclass->context.class_inst;
375 gtd = gclass->container_class;
376 gcontainer = gtd->generic_container;
377 argv = g_newa (MonoType*, ginst->type_argc);
379 for (i = 0; i < ginst->type_argc; ++i) {
380 MonoType *t = ginst->type_argv [i], *norm;
381 if (t->type != MONO_TYPE_VAR || t->data.generic_param->num != i || t->data.generic_param->owner != gcontainer)
382 is_denorm_gtd = FALSE;
383 norm = mono_type_normalize (t);
386 requires_rebind = TRUE;
390 return type->byref == gtd->byval_arg.byref ? >d->byval_arg : >d->this_arg;
392 if (requires_rebind) {
393 MonoClass *klass = mono_class_bind_generic_parameters (gtd, ginst->type_argc, argv, gclass->is_dynamic);
394 return type->byref == klass->byval_arg.byref ? &klass->byval_arg : &klass->this_arg;
400 * mono_type_get_object:
401 * @domain: an app domain
404 * Return an System.MonoType object representing the type @type.
407 mono_type_get_object (MonoDomain *domain, MonoType *type)
410 MonoReflectionType *ret = mono_type_get_object_checked (domain, type, &error);
411 mono_error_cleanup (&error);
417 mono_type_get_object_checked (MonoDomain *domain, MonoType *type, MonoError *error)
420 MonoReflectionType *res;
423 mono_error_init (error);
425 klass = mono_class_from_mono_type (type);
427 /*we must avoid using @type as it might have come
428 * from a mono_metadata_type_dup and the caller
429 * expects that is can be freed.
430 * Using the right type from
432 type = klass->byval_arg.byref == type->byref ? &klass->byval_arg : &klass->this_arg;
434 /* void is very common */
435 if (type->type == MONO_TYPE_VOID && domain->typeof_void)
436 return (MonoReflectionType*)domain->typeof_void;
439 * If the vtable of the given class was already created, we can use
440 * the MonoType from there and avoid all locking and hash table lookups.
442 * We cannot do this for TypeBuilders as mono_reflection_create_runtime_class expects
443 * that the resulting object is different.
445 if (type == &klass->byval_arg && !image_is_dynamic (klass->image)) {
446 MonoVTable *vtable = mono_class_try_get_vtable (domain, klass);
447 if (vtable && vtable->type)
448 return (MonoReflectionType *)vtable->type;
451 mono_loader_lock (); /*FIXME mono_class_init and mono_class_vtable acquire it*/
452 mono_domain_lock (domain);
453 if (!domain->type_hash)
454 domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mono_metadata_type_hash,
455 (GCompareFunc)mono_metadata_type_equal, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DOMAIN, "domain reflection types table");
456 if ((res = (MonoReflectionType *)mono_g_hash_table_lookup (domain->type_hash, type))) {
457 mono_domain_unlock (domain);
458 mono_loader_unlock ();
462 /*Types must be normalized so a generic instance of the GTD get's the same inner type.
463 * For example in: Foo<A,B>; Bar<A> : Foo<A, Bar<A>>
464 * The second Bar will be encoded a generic instance of Bar with <A> as parameter.
465 * On all other places, Bar<A> will be encoded as the GTD itself. This is an implementation
466 * artifact of how generics are encoded and should be transparent to managed code so we
467 * need to weed out this diference when retrieving managed System.Type objects.
469 norm_type = mono_type_normalize (type);
470 if (norm_type != type) {
471 res = mono_type_get_object_checked (domain, norm_type, error);
472 if (!mono_error_ok (error))
474 mono_g_hash_table_insert (domain->type_hash, type, res);
475 mono_domain_unlock (domain);
476 mono_loader_unlock ();
480 /* This MonoGenericClass hack is no longer necessary. Let's leave it here until we finish with the 2-stage type-builder setup.*/
481 if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder)
484 if (!verify_safe_for_managed_space (type)) {
485 mono_domain_unlock (domain);
486 mono_loader_unlock ();
487 mono_error_set_generic_error (error, "System", "InvalidOperationException", "This type cannot be propagated to managed space");
491 if (mono_class_get_ref_info (klass) && !klass->wastypebuilder) {
492 gboolean is_type_done = TRUE;
493 /* Generic parameters have reflection_info set but they are not finished together with their enclosing type.
494 * We must ensure that once a type is finished we don't return a GenericTypeParameterBuilder.
495 * We can't simply close the types as this will interfere with other parts of the generics machinery.
497 if (klass->byval_arg.type == MONO_TYPE_MVAR || klass->byval_arg.type == MONO_TYPE_VAR) {
498 MonoGenericParam *gparam = klass->byval_arg.data.generic_param;
500 if (gparam->owner && gparam->owner->is_method) {
501 MonoMethod *method = gparam->owner->owner.method;
502 if (method && mono_class_get_generic_type_definition (method->klass)->wastypebuilder)
503 is_type_done = FALSE;
504 } else if (gparam->owner && !gparam->owner->is_method) {
505 MonoClass *klass = gparam->owner->owner.klass;
506 if (klass && mono_class_get_generic_type_definition (klass)->wastypebuilder)
507 is_type_done = FALSE;
511 /* g_assert_not_reached (); */
512 /* should this be considered an error condition? */
513 if (is_type_done && !type->byref) {
514 mono_domain_unlock (domain);
515 mono_loader_unlock ();
516 return (MonoReflectionType *)mono_class_get_ref_info (klass);
519 /* This is stored in vtables/JITted code so it has to be pinned */
520 res = (MonoReflectionType *)mono_object_new_pinned (domain, mono_defaults.runtimetype_class, error);
521 if (!mono_error_ok (error))
525 mono_g_hash_table_insert (domain->type_hash, type, res);
527 if (type->type == MONO_TYPE_VOID)
528 domain->typeof_void = (MonoObject*)res;
530 mono_domain_unlock (domain);
531 mono_loader_unlock ();
536 * mono_method_get_object:
537 * @domain: an app domain
539 * @refclass: the reflected type (can be NULL)
541 * Return an System.Reflection.MonoMethod object representing the method @method.
543 MonoReflectionMethod*
544 mono_method_get_object (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
547 MonoReflectionMethod *ret = NULL;
548 ret = mono_method_get_object_checked (domain, method, refclass, &error);
549 mono_error_cleanup (&error);
554 * mono_method_get_object_checked:
555 * @domain: an app domain
557 * @refclass: the reflected type (can be NULL)
558 * @error: set on error.
560 * Return an System.Reflection.MonoMethod object representing the method @method.
561 * Returns NULL and sets @error on error.
563 MonoReflectionMethod*
564 mono_method_get_object_checked (MonoDomain *domain, MonoMethod *method, MonoClass *refclass, MonoError *error)
567 * We use the same C representation for methods and constructors, but the type
568 * name in C# is different.
570 MonoReflectionType *rt;
572 MonoReflectionMethod *ret;
574 mono_error_init (error);
577 refclass = method->klass;
579 CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
580 if (*method->name == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)) {
581 klass = mono_class_get_mono_cmethod_class ();
584 klass = mono_class_get_mono_method_class ();
586 ret = (MonoReflectionMethod*)mono_object_new_checked (domain, klass, error);
587 if (!mono_error_ok (error))
589 ret->method = method;
591 rt = mono_type_get_object_checked (domain, &refclass->byval_arg, error);
592 if (!mono_error_ok (error))
595 MONO_OBJECT_SETREF (ret, reftype, rt);
597 CACHE_OBJECT (MonoReflectionMethod *, method, ret, refclass);
600 g_assert (!mono_error_ok (error));
605 * mono_method_clear_object:
607 * Clear the cached reflection objects for the dynamic method METHOD.
610 mono_method_clear_object (MonoDomain *domain, MonoMethod *method)
613 g_assert (method_is_dynamic (method));
615 klass = method->klass;
617 clear_cached_object (domain, method, klass);
618 klass = klass->parent;
620 /* Added by mono_param_get_objects () */
621 clear_cached_object (domain, &(method->signature), NULL);
622 klass = method->klass;
624 clear_cached_object (domain, &(method->signature), klass);
625 klass = klass->parent;
630 * mono_field_get_object:
631 * @domain: an app domain
635 * Return an System.Reflection.MonoField object representing the field @field
639 mono_field_get_object (MonoDomain *domain, MonoClass *klass, MonoClassField *field)
642 MonoReflectionField *result;
643 result = mono_field_get_object_checked (domain, klass, field, &error);
644 mono_error_cleanup (&error);
649 * mono_field_get_object_checked:
650 * @domain: an app domain
653 * @error: set on error
655 * Return an System.Reflection.MonoField object representing the field @field
656 * in class @klass. On error, returns NULL and sets @error.
659 mono_field_get_object_checked (MonoDomain *domain, MonoClass *klass, MonoClassField *field, MonoError *error)
661 MonoReflectionType *rt;
662 MonoReflectionField *res;
664 mono_error_init (error);
666 CHECK_OBJECT (MonoReflectionField *, field, klass);
667 res = (MonoReflectionField *)mono_object_new_checked (domain, mono_class_get_mono_field_class (), error);
672 MONO_OBJECT_SETREF (res, name, mono_string_new (domain, mono_field_get_name (field)));
675 rt = mono_type_get_object_checked (domain, field->type, error);
676 if (!mono_error_ok (error))
679 MONO_OBJECT_SETREF (res, type, rt);
681 res->attrs = mono_field_get_flags (field);
682 CACHE_OBJECT (MonoReflectionField *, field, res, klass);
686 * mono_property_get_object:
687 * @domain: an app domain
689 * @property: a property
691 * Return an System.Reflection.MonoProperty object representing the property @property
694 MonoReflectionProperty*
695 mono_property_get_object (MonoDomain *domain, MonoClass *klass, MonoProperty *property)
698 MonoReflectionProperty *result;
699 result = mono_property_get_object_checked (domain, klass, property, &error);
700 mono_error_cleanup (&error);
705 * mono_property_get_object:
706 * @domain: an app domain
708 * @property: a property
709 * @error: set on error
711 * Return an System.Reflection.MonoProperty object representing the property @property
712 * in class @klass. On error returns NULL and sets @error.
714 MonoReflectionProperty*
715 mono_property_get_object_checked (MonoDomain *domain, MonoClass *klass, MonoProperty *property, MonoError *error)
717 MonoReflectionProperty *res;
719 mono_error_init (error);
721 CHECK_OBJECT (MonoReflectionProperty *, property, klass);
722 res = (MonoReflectionProperty *)mono_object_new_checked (domain, mono_class_get_mono_property_class (), error);
726 res->property = property;
727 CACHE_OBJECT (MonoReflectionProperty *, property, res, klass);
731 * mono_event_get_object:
732 * @domain: an app domain
736 * Return an System.Reflection.MonoEvent object representing the event @event
740 mono_event_get_object (MonoDomain *domain, MonoClass *klass, MonoEvent *event)
743 MonoReflectionEvent *result;
744 result = mono_event_get_object_checked (domain, klass, event, &error);
745 mono_error_cleanup (&error);
750 * mono_event_get_object_checked:
751 * @domain: an app domain
754 * @error: set on error
756 * Return an System.Reflection.MonoEvent object representing the event @event
757 * in class @klass. On failure sets @error and returns NULL
760 mono_event_get_object_checked (MonoDomain *domain, MonoClass *klass, MonoEvent *event, MonoError *error)
762 MonoReflectionEvent *res;
763 MonoReflectionMonoEvent *mono_event;
765 mono_error_init (error);
766 CHECK_OBJECT (MonoReflectionEvent *, event, klass);
767 mono_event = (MonoReflectionMonoEvent *)mono_object_new_checked (domain, mono_class_get_mono_event_class (), error);
770 mono_event->klass = klass;
771 mono_event->event = event;
772 res = (MonoReflectionEvent*)mono_event;
773 CACHE_OBJECT (MonoReflectionEvent *, event, res, klass);
777 * mono_get_reflection_missing_object:
778 * @domain: Domain where the object lives
780 * Returns the System.Reflection.Missing.Value singleton object
781 * (of type System.Reflection.Missing).
783 * Used as the value for ParameterInfo.DefaultValue when Optional
787 mono_get_reflection_missing_object (MonoDomain *domain)
791 static MonoClassField *missing_value_field = NULL;
793 if (!missing_value_field) {
794 MonoClass *missing_klass;
795 missing_klass = mono_class_get_missing_class ();
796 mono_class_init (missing_klass);
797 missing_value_field = mono_class_get_field_from_name (missing_klass, "Value");
798 g_assert (missing_value_field);
800 obj = mono_field_get_value_object_checked (domain, missing_value_field, NULL, &error);
801 mono_error_assert_ok (&error);
806 get_dbnull (MonoDomain *domain, MonoObject **dbnull)
809 *dbnull = mono_get_dbnull_object (domain);
814 get_reflection_missing (MonoDomain *domain, MonoObject **reflection_missing)
816 if (!*reflection_missing)
817 *reflection_missing = mono_get_reflection_missing_object (domain);
818 return *reflection_missing;
822 * mono_param_get_objects:
823 * @domain: an app domain
826 * Return an System.Reflection.ParameterInfo array object representing the parameters
827 * in the method @method.
830 mono_param_get_objects_internal (MonoDomain *domain, MonoMethod *method, MonoClass *refclass, MonoError *error)
832 static MonoClass *System_Reflection_ParameterInfo;
833 static MonoClass *System_Reflection_ParameterInfo_array;
834 MonoArray *res = NULL;
835 MonoReflectionMethod *member = NULL;
836 MonoReflectionParameter *param = NULL;
837 char **names = NULL, **blobs = NULL;
838 guint32 *types = NULL;
839 MonoType *type = NULL;
840 MonoObject *dbnull = NULL;
841 MonoObject *missing = NULL;
842 MonoMarshalSpec **mspecs = NULL;
843 MonoMethodSignature *sig = NULL;
844 MonoVTable *pinfo_vtable;
845 MonoReflectionType *rt;
848 mono_error_init (error);
850 if (!System_Reflection_ParameterInfo_array) {
853 klass = mono_class_get_mono_parameter_info_class ();
855 mono_memory_barrier ();
856 System_Reflection_ParameterInfo = klass;
859 klass = mono_array_class_get (klass, 1);
860 mono_memory_barrier ();
861 System_Reflection_ParameterInfo_array = klass;
864 sig = mono_method_signature_checked (method, error);
865 if (!mono_error_ok (error))
868 if (!sig->param_count) {
869 res = mono_array_new_specific_checked (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), 0, error);
876 /* Note: the cache is based on the address of the signature into the method
877 * since we already cache MethodInfos with the method as keys.
879 CHECK_OBJECT (MonoArray*, &(method->signature), refclass);
881 member = mono_method_get_object_checked (domain, method, refclass, error);
884 names = g_new (char *, sig->param_count);
885 mono_method_get_param_names (method, (const char **) names);
887 mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
888 mono_method_get_marshal_info (method, mspecs);
890 res = mono_array_new_specific_checked (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), sig->param_count, error);
894 pinfo_vtable = mono_class_vtable (domain, System_Reflection_ParameterInfo);
895 for (i = 0; i < sig->param_count; ++i) {
896 param = (MonoReflectionParameter *) mono_object_new_specific_checked (pinfo_vtable, error);
900 rt = mono_type_get_object_checked (domain, sig->params [i], error);
904 MONO_OBJECT_SETREF (param, ClassImpl, rt);
906 MONO_OBJECT_SETREF (param, MemberImpl, (MonoObject*)member);
908 MONO_OBJECT_SETREF (param, NameImpl, mono_string_new (domain, names [i]));
910 param->PositionImpl = i;
911 param->AttrsImpl = sig->params [i]->attrs;
913 if (!(param->AttrsImpl & PARAM_ATTRIBUTE_HAS_DEFAULT)) {
914 if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
915 MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
917 MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
921 blobs = g_new0 (char *, sig->param_count);
922 types = g_new0 (guint32, sig->param_count);
923 get_default_param_value_blobs (method, blobs, types);
926 /* Build MonoType for the type from the Constant Table */
928 type = g_new0 (MonoType, 1);
929 type->type = (MonoTypeEnum)types [i];
930 type->data.klass = NULL;
931 if (types [i] == MONO_TYPE_CLASS)
932 type->data.klass = mono_defaults.object_class;
933 else if ((sig->params [i]->type == MONO_TYPE_VALUETYPE) && sig->params [i]->data.klass->enumtype) {
934 /* For enums, types [i] contains the base type */
936 type->type = MONO_TYPE_VALUETYPE;
937 type->data.klass = mono_class_from_mono_type (sig->params [i]);
939 type->data.klass = mono_class_from_mono_type (type);
941 MonoObject *default_val_obj = mono_get_object_from_blob (domain, type, blobs [i], error);
944 MONO_OBJECT_SETREF (param, DefaultValueImpl, default_val_obj);
946 /* Type in the Constant table is MONO_TYPE_CLASS for nulls */
947 if (types [i] != MONO_TYPE_CLASS && !param->DefaultValueImpl) {
948 if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
949 MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
951 MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
956 if (mspecs [i + 1]) {
957 MonoReflectionMarshalAsAttribute* mobj;
958 mobj = mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [i + 1], error);
961 MONO_OBJECT_SETREF (param, MarshalAsImpl, (MonoObject*)mobj);
964 mono_array_setref (res, i, param);
974 for (i = sig->param_count; i >= 0; i--) {
976 mono_metadata_free_marshal_spec (mspecs [i]);
984 CACHE_OBJECT (MonoArray *, &(method->signature), res, refclass);
988 mono_param_get_objects (MonoDomain *domain, MonoMethod *method)
991 MonoArray *result = mono_param_get_objects_internal (domain, method, NULL, &error);
992 mono_error_assert_ok (&error);
997 * mono_method_body_get_object:
998 * @domain: an app domain
1001 * Return an System.Reflection.MethodBody object representing the method @method.
1003 MonoReflectionMethodBody*
1004 mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
1007 MonoReflectionMethodBody *result = mono_method_body_get_object_checked (domain, method, &error);
1008 mono_error_cleanup (&error);
1013 * mono_method_body_get_object_checked:
1014 * @domain: an app domain
1016 * @error: set on error
1018 * Return an System.Reflection.MethodBody object representing the
1019 * method @method. On failure, returns NULL and sets @error.
1021 MonoReflectionMethodBody*
1022 mono_method_body_get_object_checked (MonoDomain *domain, MonoMethod *method, MonoError *error)
1024 MonoReflectionMethodBody *ret;
1025 MonoMethodHeader *header;
1027 MonoReflectionType *rt;
1028 guint32 method_rva, local_var_sig_token;
1030 unsigned char format, flags;
1033 mono_error_init (error);
1035 /* for compatibility with .net */
1036 if (method_is_dynamic (method)) {
1037 mono_error_set_generic_error (error, "System", "InvalidOperationException", "");
1041 CHECK_OBJECT (MonoReflectionMethodBody *, method, NULL);
1043 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1044 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
1045 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1046 (method->klass->image->raw_data && method->klass->image->raw_data [1] != 'Z') ||
1047 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME))
1050 image = method->klass->image;
1051 header = mono_method_get_header_checked (method, error);
1052 return_val_if_nok (error, NULL);
1054 if (!image_is_dynamic (image)) {
1055 /* Obtain local vars signature token */
1056 method_rva = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD], mono_metadata_token_index (method->token) - 1, MONO_METHOD_RVA);
1057 ptr = mono_image_rva_map (image, method_rva);
1058 flags = *(const unsigned char *) ptr;
1059 format = flags & METHOD_HEADER_FORMAT_MASK;
1061 case METHOD_HEADER_TINY_FORMAT:
1062 local_var_sig_token = 0;
1064 case METHOD_HEADER_FAT_FORMAT:
1068 local_var_sig_token = read32 (ptr);
1071 g_assert_not_reached ();
1074 local_var_sig_token = 0; //FIXME
1076 ret = (MonoReflectionMethodBody*)mono_object_new_checked (domain, mono_class_get_method_body_class (), error);
1080 ret->init_locals = header->init_locals;
1081 ret->max_stack = header->max_stack;
1082 ret->local_var_sig_token = local_var_sig_token;
1083 MonoArray *il_arr = mono_array_new_cached (domain, mono_defaults.byte_class, header->code_size, error);
1086 MONO_OBJECT_SETREF (ret, il, il_arr);
1087 memcpy (mono_array_addr (ret->il, guint8, 0), header->code, header->code_size);
1090 MonoArray *locals_arr = mono_array_new_cached (domain, mono_class_get_local_variable_info_class (), header->num_locals, error);
1093 MONO_OBJECT_SETREF (ret, locals, locals_arr);
1094 for (i = 0; i < header->num_locals; ++i) {
1095 MonoReflectionLocalVariableInfo *info = (MonoReflectionLocalVariableInfo*)mono_object_new_checked (domain, mono_class_get_local_variable_info_class (), error);
1099 rt = mono_type_get_object_checked (domain, header->locals [i], error);
1103 MONO_OBJECT_SETREF (info, local_type, rt);
1105 info->is_pinned = header->locals [i]->pinned;
1106 info->local_index = i;
1107 mono_array_setref (ret->locals, i, info);
1111 MonoArray *exn_clauses = mono_array_new_cached (domain, mono_class_get_exception_handling_clause_class (), header->num_clauses, error);
1114 MONO_OBJECT_SETREF (ret, clauses, exn_clauses);
1115 for (i = 0; i < header->num_clauses; ++i) {
1116 MonoReflectionExceptionHandlingClause *info = (MonoReflectionExceptionHandlingClause*)mono_object_new_checked (domain, mono_class_get_exception_handling_clause_class (), error);
1119 MonoExceptionClause *clause = &header->clauses [i];
1121 info->flags = clause->flags;
1122 info->try_offset = clause->try_offset;
1123 info->try_length = clause->try_len;
1124 info->handler_offset = clause->handler_offset;
1125 info->handler_length = clause->handler_len;
1126 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
1127 info->filter_offset = clause->data.filter_offset;
1128 else if (clause->data.catch_class) {
1129 rt = mono_type_get_object_checked (mono_domain_get (), &clause->data.catch_class->byval_arg, error);
1133 MONO_OBJECT_SETREF (info, catch_type, rt);
1136 mono_array_setref (ret->clauses, i, info);
1139 mono_metadata_free_mh (header);
1140 CACHE_OBJECT (MonoReflectionMethodBody *, method, ret, NULL);
1144 mono_metadata_free_mh (header);
1149 * mono_get_dbnull_object:
1150 * @domain: Domain where the object lives
1152 * Returns the System.DBNull.Value singleton object
1154 * Used as the value for ParameterInfo.DefaultValue
1157 mono_get_dbnull_object (MonoDomain *domain)
1161 static MonoClassField *dbnull_value_field = NULL;
1163 if (!dbnull_value_field) {
1164 MonoClass *dbnull_klass;
1165 dbnull_klass = mono_class_get_dbnull_class ();
1166 dbnull_value_field = mono_class_get_field_from_name (dbnull_klass, "Value");
1167 g_assert (dbnull_value_field);
1169 obj = mono_field_get_value_object_checked (domain, dbnull_value_field, NULL, &error);
1170 mono_error_assert_ok (&error);
1175 get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types)
1177 guint32 param_index, i, lastp, crow = 0;
1178 guint32 param_cols [MONO_PARAM_SIZE], const_cols [MONO_CONSTANT_SIZE];
1181 MonoClass *klass = method->klass;
1182 MonoImage *image = klass->image;
1183 MonoMethodSignature *methodsig = mono_method_signature (method);
1185 MonoTableInfo *constt;
1186 MonoTableInfo *methodt;
1187 MonoTableInfo *paramt;
1189 if (!methodsig->param_count)
1192 mono_class_init (klass);
1194 if (image_is_dynamic (klass->image)) {
1195 MonoReflectionMethodAux *aux;
1196 if (method->is_inflated)
1197 method = ((MonoMethodInflated*)method)->declaring;
1198 aux = (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1199 if (aux && aux->param_defaults) {
1200 memcpy (blobs, &(aux->param_defaults [1]), methodsig->param_count * sizeof (char*));
1201 memcpy (types, &(aux->param_default_types [1]), methodsig->param_count * sizeof (guint32));
1206 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1207 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1208 constt = &image->tables [MONO_TABLE_CONSTANT];
1210 idx = mono_method_get_index (method) - 1;
1211 g_assert (idx != -1);
1213 param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1214 if (idx + 1 < methodt->rows)
1215 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
1217 lastp = paramt->rows + 1;
1219 for (i = param_index; i < lastp; ++i) {
1222 mono_metadata_decode_row (paramt, i - 1, param_cols, MONO_PARAM_SIZE);
1223 paramseq = param_cols [MONO_PARAM_SEQUENCE];
1225 if (!(param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT))
1228 crow = mono_metadata_get_constant_index (image, MONO_TOKEN_PARAM_DEF | i, crow + 1);
1233 mono_metadata_decode_row (constt, crow - 1, const_cols, MONO_CONSTANT_SIZE);
1234 blobs [paramseq - 1] = (char *)mono_metadata_blob_heap (image, const_cols [MONO_CONSTANT_VALUE]);
1235 types [paramseq - 1] = const_cols [MONO_CONSTANT_TYPE];
1242 mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob, MonoError *error)
1247 MonoType *basetype = type;
1249 mono_error_init (error);
1254 klass = mono_class_from_mono_type (type);
1255 if (klass->valuetype) {
1256 object = mono_object_new_checked (domain, klass, error);
1257 return_val_if_nok (error, NULL);
1258 retval = ((gchar *) object + sizeof (MonoObject));
1259 if (klass->enumtype)
1260 basetype = mono_class_enum_basetype (klass);
1265 if (!mono_get_constant_value_from_blob (domain, basetype->type, blob, retval, error))
1272 assembly_name_to_aname (MonoAssemblyName *assembly, char *p) {
1275 gboolean quoted = FALSE;
1277 memset (assembly, 0, sizeof (MonoAssemblyName));
1278 assembly->culture = "";
1279 memset (assembly->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1286 while (*p && (isalnum (*p) || *p == '.' || *p == '-' || *p == '_' || *p == '$' || *p == '@' || g_ascii_isspace (*p)))
1297 /* Remove trailing whitespace */
1299 while (*s && g_ascii_isspace (*s))
1302 while (g_ascii_isspace (*p))
1305 if (*p == 'V' && g_ascii_strncasecmp (p, "Version=", 8) == 0) {
1307 assembly->major = strtoul (p, &s, 10);
1308 if (s == p || *s != '.')
1311 assembly->minor = strtoul (p, &s, 10);
1312 if (s == p || *s != '.')
1315 assembly->build = strtoul (p, &s, 10);
1316 if (s == p || *s != '.')
1319 assembly->revision = strtoul (p, &s, 10);
1323 } else if (*p == 'C' && g_ascii_strncasecmp (p, "Culture=", 8) == 0) {
1325 if (g_ascii_strncasecmp (p, "neutral", 7) == 0) {
1326 assembly->culture = "";
1329 assembly->culture = p;
1330 while (*p && *p != ',') {
1334 } else if (*p == 'P' && g_ascii_strncasecmp (p, "PublicKeyToken=", 15) == 0) {
1336 if (strncmp (p, "null", 4) == 0) {
1341 while (*p && *p != ',') {
1344 len = (p - start + 1);
1345 if (len > MONO_PUBLIC_KEY_TOKEN_LENGTH)
1346 len = MONO_PUBLIC_KEY_TOKEN_LENGTH;
1347 g_strlcpy ((char*)assembly->public_key_token, start, len);
1350 while (*p && *p != ',')
1354 while (g_ascii_isspace (*p) || *p == ',') {
1368 * mono_reflection_parse_type:
1371 * Parse a type name as accepted by the GetType () method and output the info
1372 * extracted in the info structure.
1373 * the name param will be mangled, so, make a copy before passing it to this function.
1374 * The fields in info will be valid until the memory pointed to by name is valid.
1376 * See also mono_type_get_name () below.
1378 * Returns: 0 on parse error.
1381 _mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed,
1382 MonoTypeNameParse *info)
1384 char *start, *p, *w, *last_point, *startn;
1385 int in_modifiers = 0;
1386 int isbyref = 0, rank = 0, isptr = 0;
1388 start = p = w = name;
1390 //FIXME could we just zero the whole struct? memset (&info, 0, sizeof (MonoTypeNameParse))
1391 memset (&info->assembly, 0, sizeof (MonoAssemblyName));
1392 info->name = info->name_space = NULL;
1393 info->nested = NULL;
1394 info->modifiers = NULL;
1395 info->type_arguments = NULL;
1397 /* last_point separates the namespace from the name */
1400 while (*p == ' ') p++, start++, w++, name++;
1405 *p = 0; /* NULL terminate the name */
1407 info->nested = g_list_append (info->nested, startn);
1408 /* we have parsed the nesting namespace + name */
1412 info->name_space = start;
1414 info->name = last_point + 1;
1416 info->name_space = (char *)"";
1444 info->name_space = start;
1446 info->name = last_point + 1;
1448 info->name_space = (char *)"";
1455 if (isbyref) /* only one level allowed by the spec */
1459 info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (0));
1463 if (isbyref) /* pointer to ref not okay */
1465 info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-1));
1470 if (isbyref) /* array of ref and generic ref are not okay */
1472 //Decide if it's an array of a generic argument list
1477 if (*p == ',' || *p == '*' || *p == ']') { //array
1485 else if (*p == '*') /* '*' means unknown lower bound */
1486 info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-2));
1493 info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (rank));
1495 if (rank || isptr) /* generic args after array spec or ptr*/ //XXX test
1498 info->type_arguments = g_ptr_array_new ();
1500 MonoTypeNameParse *subinfo = g_new0 (MonoTypeNameParse, 1);
1501 gboolean fqname = FALSE;
1503 g_ptr_array_add (info->type_arguments, subinfo);
1505 while (*p == ' ') p++;
1511 if (!_mono_reflection_parse_type (p, &p, TRUE, subinfo))
1514 /*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/
1515 if (fqname && (*p != ']')) {
1523 while (*p && (*p != ']'))
1531 if (g_ascii_isspace (*aname)) {
1538 !assembly_name_to_aname (&subinfo->assembly, aname))
1540 } else if (fqname && (*p == ']')) {
1562 if (g_ascii_isspace (*p)) {
1569 return 0; /* missing assembly name */
1570 if (!assembly_name_to_aname (&info->assembly, p))
1576 if (info->assembly.name)
1579 // *w = 0; /* terminate class name */
1581 if (!info->name || !*info->name)
1585 /* add other consistency checks */
1591 * mono_identifier_unescape_type_name_chars:
1592 * @identifier: the display name of a mono type
1595 * The name in internal form, that is without escaping backslashes.
1597 * The string is modified in place!
1600 mono_identifier_unescape_type_name_chars(char* identifier)
1605 for (w = r = identifier; *r != 0; r++)
1623 mono_identifier_unescape_info (MonoTypeNameParse* info);
1626 unescape_each_type_argument(void* data, void* user_data)
1628 MonoTypeNameParse* info = (MonoTypeNameParse*)data;
1629 mono_identifier_unescape_info (info);
1633 unescape_each_nested_name (void* data, void* user_data)
1635 char* nested_name = (char*) data;
1636 mono_identifier_unescape_type_name_chars(nested_name);
1640 * mono_identifier_unescape_info:
1642 * @info: a parsed display form of an (optionally assembly qualified) full type name.
1646 * Destructively updates the info by unescaping the identifiers that
1647 * comprise the type namespace, name, nested types (if any) and
1648 * generic type arguments (if any).
1650 * The resulting info has the names in internal form.
1654 mono_identifier_unescape_info (MonoTypeNameParse *info)
1658 mono_identifier_unescape_type_name_chars(info->name_space);
1659 mono_identifier_unescape_type_name_chars(info->name);
1660 // but don't escape info->assembly
1661 if (info->type_arguments)
1662 g_ptr_array_foreach(info->type_arguments, &unescape_each_type_argument, NULL);
1664 g_list_foreach(info->nested, &unescape_each_nested_name, NULL);
1668 mono_reflection_parse_type (char *name, MonoTypeNameParse *info)
1670 int ok = _mono_reflection_parse_type (name, NULL, FALSE, info);
1672 mono_identifier_unescape_info (info);
1678 _mono_reflection_get_type_from_info (MonoTypeNameParse *info, MonoImage *image, gboolean ignorecase, MonoError *error)
1680 gboolean type_resolve = FALSE;
1682 MonoImage *rootimage = image;
1684 mono_error_init (error);
1686 if (info->assembly.name) {
1687 MonoAssembly *assembly = mono_assembly_loaded (&info->assembly);
1688 if (!assembly && image && image->assembly && mono_assembly_names_equal (&info->assembly, &image->assembly->aname))
1690 * This could happen in the AOT compiler case when the search hook is not
1693 assembly = image->assembly;
1695 /* then we must load the assembly ourselve - see #60439 */
1696 assembly = mono_assembly_load (&info->assembly, image->assembly->basedir, NULL);
1700 image = assembly->image;
1701 } else if (!image) {
1702 image = mono_defaults.corlib;
1705 type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve, error);
1706 if (type == NULL && !info->assembly.name && image != mono_defaults.corlib) {
1707 /* ignore the error and try again */
1708 mono_error_cleanup (error);
1709 mono_error_init (error);
1710 image = mono_defaults.corlib;
1711 type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve, error);
1718 * mono_reflection_get_type_internal:
1720 * Returns: may return NULL on success, sets error on failure.
1723 mono_reflection_get_type_internal (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, MonoError *error)
1728 gboolean bounded = FALSE;
1730 mono_error_init (error);
1732 image = mono_defaults.corlib;
1735 rootimage = mono_defaults.corlib;
1738 klass = mono_class_from_name_case_checked (image, info->name_space, info->name, error);
1740 klass = mono_class_from_name_checked (image, info->name_space, info->name, error);
1745 for (mod = info->nested; mod; mod = mod->next) {
1746 gpointer iter = NULL;
1750 mono_class_init (parent);
1752 while ((klass = mono_class_get_nested_types (parent, &iter))) {
1754 char *nested_name, *nested_nspace;
1755 gboolean match = TRUE;
1757 lastp = strrchr ((const char *)mod->data, '.');
1759 /* Nested classes can have namespaces */
1762 nested_name = g_strdup (lastp + 1);
1763 nspace_len = lastp - (char*)mod->data;
1764 nested_nspace = (char *)g_malloc (nspace_len + 1);
1765 memcpy (nested_nspace, mod->data, nspace_len);
1766 nested_nspace [nspace_len] = '\0';
1769 nested_name = (char *)mod->data;
1770 nested_nspace = NULL;
1773 if (nested_nspace) {
1775 if (!(klass->name_space && mono_utf8_strcasecmp (klass->name_space, nested_nspace) == 0))
1778 if (!(klass->name_space && strcmp (klass->name_space, nested_nspace) == 0))
1784 if (mono_utf8_strcasecmp (klass->name, nested_name) != 0)
1787 if (strcmp (klass->name, nested_name) != 0)
1792 g_free (nested_name);
1793 g_free (nested_nspace);
1805 if (info->type_arguments) {
1806 MonoType **type_args = g_new0 (MonoType *, info->type_arguments->len);
1807 MonoReflectionType *the_type;
1811 for (i = 0; i < info->type_arguments->len; i++) {
1812 MonoTypeNameParse *subinfo = (MonoTypeNameParse *)g_ptr_array_index (info->type_arguments, i);
1814 type_args [i] = _mono_reflection_get_type_from_info (subinfo, rootimage, ignorecase, error);
1815 if (!type_args [i]) {
1821 the_type = mono_type_get_object_checked (mono_domain_get (), &klass->byval_arg, error);
1825 instance = mono_reflection_bind_generic_parameters (
1826 the_type, info->type_arguments->len, type_args, error);
1832 klass = mono_class_from_mono_type (instance);
1835 for (mod = info->modifiers; mod; mod = mod->next) {
1836 modval = GPOINTER_TO_UINT (mod->data);
1837 if (!modval) { /* byref: must be last modifier */
1838 return &klass->this_arg;
1839 } else if (modval == -1) {
1840 klass = mono_ptr_class_get (&klass->byval_arg);
1841 } else if (modval == -2) {
1843 } else { /* array rank */
1844 klass = mono_bounded_array_class_get (klass, modval, bounded);
1848 return &klass->byval_arg;
1852 * mono_reflection_get_type:
1853 * @image: a metadata context
1854 * @info: type description structure
1855 * @ignorecase: flag for case-insensitive string compares
1856 * @type_resolve: whenever type resolve was already tried
1858 * Build a MonoType from the type description in @info.
1863 mono_reflection_get_type (MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve) {
1865 MonoType *result = mono_reflection_get_type_with_rootimage (image, image, info, ignorecase, type_resolve, &error);
1866 mono_error_cleanup (&error);
1871 * mono_reflection_get_type_checked:
1872 * @rootimage: the image of the currently active managed caller
1873 * @image: a metadata context
1874 * @info: type description structure
1875 * @ignorecase: flag for case-insensitive string compares
1876 * @type_resolve: whenever type resolve was already tried
1877 * @error: set on error.
1879 * Build a MonoType from the type description in @info. On failure returns NULL and sets @error.
1883 mono_reflection_get_type_checked (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve, MonoError *error) {
1884 mono_error_init (error);
1885 return mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, type_resolve, error);
1890 mono_reflection_get_type_internal_dynamic (MonoImage *rootimage, MonoAssembly *assembly, MonoTypeNameParse *info, gboolean ignorecase, MonoError *error)
1892 MonoReflectionAssemblyBuilder *abuilder;
1896 mono_error_init (error);
1897 g_assert (assembly_is_dynamic (assembly));
1898 abuilder = (MonoReflectionAssemblyBuilder*)mono_assembly_get_object_checked (((MonoDynamicAssembly*)assembly)->domain, assembly, error);
1902 /* Enumerate all modules */
1905 if (abuilder->modules) {
1906 for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
1907 MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
1908 type = mono_reflection_get_type_internal (rootimage, &mb->dynamic_image->image, info, ignorecase, error);
1911 if (!mono_error_ok (error))
1916 if (!type && abuilder->loaded_modules) {
1917 for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
1918 MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
1919 type = mono_reflection_get_type_internal (rootimage, mod->image, info, ignorecase, error);
1922 if (!mono_error_ok (error))
1931 mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve, MonoError *error)
1934 MonoReflectionAssembly *assembly;
1938 mono_error_init (error);
1940 if (image && image_is_dynamic (image))
1941 type = mono_reflection_get_type_internal_dynamic (rootimage, image->assembly, info, ignorecase, error);
1943 type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase, error);
1945 return_val_if_nok (error, NULL);
1949 if (!mono_domain_has_type_resolve (mono_domain_get ()))
1956 *type_resolve = TRUE;
1959 /* Reconstruct the type name */
1960 fullName = g_string_new ("");
1961 if (info->name_space && (info->name_space [0] != '\0'))
1962 g_string_printf (fullName, "%s.%s", info->name_space, info->name);
1964 g_string_printf (fullName, "%s", info->name);
1965 for (mod = info->nested; mod; mod = mod->next)
1966 g_string_append_printf (fullName, "+%s", (char*)mod->data);
1968 assembly = mono_domain_try_type_resolve_checked ( mono_domain_get (), fullName->str, NULL, error);
1969 if (!is_ok (error)) {
1970 g_string_free (fullName, TRUE);
1975 if (assembly_is_dynamic (assembly->assembly))
1976 type = mono_reflection_get_type_internal_dynamic (rootimage, assembly->assembly,
1977 info, ignorecase, error);
1979 type = mono_reflection_get_type_internal (rootimage, assembly->assembly->image,
1980 info, ignorecase, error);
1982 g_string_free (fullName, TRUE);
1983 return_val_if_nok (error, NULL);
1988 mono_reflection_free_type_info (MonoTypeNameParse *info)
1990 g_list_free (info->modifiers);
1991 g_list_free (info->nested);
1993 if (info->type_arguments) {
1996 for (i = 0; i < info->type_arguments->len; i++) {
1997 MonoTypeNameParse *subinfo = (MonoTypeNameParse *)g_ptr_array_index (info->type_arguments, i);
1999 mono_reflection_free_type_info (subinfo);
2000 /*We free the subinfo since it is allocated by _mono_reflection_parse_type*/
2004 g_ptr_array_free (info->type_arguments, TRUE);
2009 * mono_reflection_type_from_name:
2011 * @image: a metadata context (can be NULL).
2013 * Retrieves a MonoType from its @name. If the name is not fully qualified,
2014 * it defaults to get the type from @image or, if @image is NULL or loading
2015 * from it fails, uses corlib.
2019 mono_reflection_type_from_name (char *name, MonoImage *image)
2022 MonoType *result = mono_reflection_type_from_name_checked (name, image, &error);
2023 mono_error_cleanup (&error);
2028 * mono_reflection_type_from_name_checked:
2030 * @image: a metadata context (can be NULL).
2031 * @error: set on errror.
2033 * Retrieves a MonoType from its @name. If the name is not fully qualified,
2034 * it defaults to get the type from @image or, if @image is NULL or loading
2035 * from it fails, uses corlib. On failure returns NULL and sets @error.
2039 mono_reflection_type_from_name_checked (char *name, MonoImage *image, MonoError *error)
2041 MonoType *type = NULL;
2042 MonoTypeNameParse info;
2045 mono_error_init (error);
2046 /* Make a copy since parse_type modifies its argument */
2047 tmp = g_strdup (name);
2049 /*g_print ("requested type %s\n", str);*/
2050 if (mono_reflection_parse_type (tmp, &info)) {
2051 type = _mono_reflection_get_type_from_info (&info, image, FALSE, error);
2052 if (!is_ok (error)) {
2054 mono_reflection_free_type_info (&info);
2060 mono_reflection_free_type_info (&info);
2065 * mono_reflection_get_token:
2067 * Return the metadata token of OBJ which should be an object
2068 * representing a metadata element.
2071 mono_reflection_get_token (MonoObject *obj)
2074 guint32 result = mono_reflection_get_token_checked (obj, &error);
2075 mono_error_assert_ok (&error);
2080 * mono_reflection_get_token_checked:
2082 * @error: set on error
2084 * Return the metadata token of @obj which should be an object
2085 * representing a metadata element. On failure sets @error.
2088 mono_reflection_get_token_checked (MonoObject *obj, MonoError *error)
2093 mono_error_init (error);
2095 klass = obj->vtable->klass;
2097 if (strcmp (klass->name, "MethodBuilder") == 0) {
2098 MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
2100 token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
2101 } else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
2102 MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
2104 token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
2105 } else if (strcmp (klass->name, "FieldBuilder") == 0) {
2106 MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
2108 token = fb->table_idx | MONO_TOKEN_FIELD_DEF;
2109 } else if (strcmp (klass->name, "TypeBuilder") == 0) {
2110 MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
2111 token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
2112 } else if (strcmp (klass->name, "RuntimeType") == 0) {
2113 MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj, error);
2114 return_val_if_nok (error, 0);
2115 MonoClass *mc = mono_class_from_mono_type (type);
2116 if (!mono_class_init (mc)) {
2117 mono_error_set_for_class_failure (error, mc);
2121 token = mc->type_token;
2122 } else if (strcmp (klass->name, "MonoCMethod") == 0 ||
2123 strcmp (klass->name, "MonoMethod") == 0) {
2124 MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
2125 if (m->method->is_inflated) {
2126 MonoMethodInflated *inflated = (MonoMethodInflated *) m->method;
2127 return inflated->declaring->token;
2129 token = m->method->token;
2131 } else if (strcmp (klass->name, "MonoField") == 0) {
2132 MonoReflectionField *f = (MonoReflectionField*)obj;
2134 token = mono_class_get_field_token (f->field);
2135 } else if (strcmp (klass->name, "MonoProperty") == 0) {
2136 MonoReflectionProperty *p = (MonoReflectionProperty*)obj;
2138 token = mono_class_get_property_token (p->property);
2139 } else if (strcmp (klass->name, "MonoEvent") == 0) {
2140 MonoReflectionMonoEvent *p = (MonoReflectionMonoEvent*)obj;
2142 token = mono_class_get_event_token (p->event);
2143 } else if (strcmp (klass->name, "ParameterInfo") == 0 || strcmp (klass->name, "MonoParameterInfo") == 0) {
2144 MonoReflectionParameter *p = (MonoReflectionParameter*)obj;
2145 MonoClass *member_class = mono_object_class (p->MemberImpl);
2146 g_assert (mono_class_is_reflection_method_or_constructor (member_class));
2148 token = mono_method_get_param_token (((MonoReflectionMethod*)p->MemberImpl)->method, p->PositionImpl);
2149 } else if (strcmp (klass->name, "Module") == 0 || strcmp (klass->name, "MonoModule") == 0) {
2150 MonoReflectionModule *m = (MonoReflectionModule*)obj;
2153 } else if (strcmp (klass->name, "Assembly") == 0 || strcmp (klass->name, "MonoAssembly") == 0) {
2154 token = mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1);
2156 mono_error_set_not_implemented (error, "MetadataToken is not supported for type '%s.%s'",
2157 klass->name_space, klass->name);
2166 mono_reflection_is_usertype (MonoReflectionType *ref)
2168 MonoClass *klass = mono_object_class (ref);
2169 return klass->image != mono_defaults.corlib || strcmp ("TypeDelegator", klass->name) == 0;
2173 * mono_reflection_bind_generic_parameters:
2174 * @type: a managed type object (which should be some kind of generic (instance? definition?))
2175 * @type_args: the number of type arguments to bind
2176 * @types: array of type arguments
2177 * @error: set on error
2179 * Given a managed type object for a generic type instance, binds each of its arguments to the specified types.
2180 * Returns the MonoType* for the resulting type instantiation. On failure returns NULL and sets @error.
2183 mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc, MonoType **types, MonoError *error)
2186 MonoReflectionTypeBuilder *tb = NULL;
2187 gboolean is_dynamic = FALSE;
2190 mono_error_init (error);
2192 mono_loader_lock ();
2194 if (mono_is_sre_type_builder (mono_object_class (type))) {
2195 tb = (MonoReflectionTypeBuilder *) type;
2198 } else if (mono_is_sre_generic_instance (mono_object_class (type))) {
2199 MonoReflectionGenericClass *rgi = (MonoReflectionGenericClass *) type;
2200 MonoReflectionType *gtd = rgi->generic_type;
2202 if (mono_is_sre_type_builder (mono_object_class (gtd))) {
2203 tb = (MonoReflectionTypeBuilder *)gtd;
2208 /* FIXME: fix the CreateGenericParameters protocol to avoid the two stage setup of TypeBuilders */
2209 if (tb && tb->generic_container) {
2210 if (!mono_reflection_create_generic_class (tb, error)) {
2211 mono_loader_unlock ();
2216 MonoType *t = mono_reflection_type_get_handle (type, error);
2217 if (!is_ok (error)) {
2218 mono_loader_unlock ();
2222 klass = mono_class_from_mono_type (t);
2223 if (!klass->generic_container) {
2224 mono_loader_unlock ();
2225 mono_error_set_type_load_class (error, klass, "Cannot bind generic parameters of a non-generic type");
2229 if (klass->wastypebuilder) {
2230 tb = (MonoReflectionTypeBuilder *) mono_class_get_ref_info (klass);
2235 mono_loader_unlock ();
2237 geninst = mono_class_bind_generic_parameters (klass, type_argc, types, is_dynamic);
2239 return &geninst->byval_arg;
2243 mono_class_bind_generic_parameters (MonoClass *klass, int type_argc, MonoType **types, gboolean is_dynamic)
2245 MonoGenericClass *gclass;
2246 MonoGenericInst *inst;
2248 g_assert (klass->generic_container);
2250 inst = mono_metadata_get_generic_inst (type_argc, types);
2251 gclass = mono_metadata_lookup_generic_class (klass, inst, is_dynamic);
2253 return mono_generic_class_get_class (gclass);
2256 static MonoReflectionMethod*
2257 reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoArray *types, MonoError *error)
2260 MonoMethod *method, *inflated;
2261 MonoMethodInflated *imethod;
2262 MonoGenericContext tmp_context;
2263 MonoGenericInst *ginst;
2264 MonoType **type_argv;
2267 mono_error_init (error);
2269 /*FIXME but this no longer should happen*/
2270 if (!strcmp (rmethod->object.vtable->klass->name, "MethodBuilder")) {
2271 method = mono_reflection_method_builder_to_mono_method ((MonoReflectionMethodBuilder*)rmethod, error);
2272 return_val_if_nok (error, NULL);
2274 method = rmethod->method;
2277 klass = method->klass;
2279 if (method->is_inflated)
2280 method = ((MonoMethodInflated *) method)->declaring;
2282 count = mono_method_signature (method)->generic_param_count;
2283 if (count != mono_array_length (types))
2286 type_argv = g_new0 (MonoType *, count);
2287 for (i = 0; i < count; i++) {
2288 MonoReflectionType *garg = (MonoReflectionType *)mono_array_get (types, gpointer, i);
2289 type_argv [i] = mono_reflection_type_get_handle (garg, error);
2290 if (!is_ok (error)) {
2295 ginst = mono_metadata_get_generic_inst (count, type_argv);
2298 tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
2299 tmp_context.method_inst = ginst;
2301 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
2302 mono_error_assert_ok (error);
2303 imethod = (MonoMethodInflated *) inflated;
2305 /*FIXME but I think this is no longer necessary*/
2306 if (image_is_dynamic (method->klass->image)) {
2307 MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
2309 * This table maps metadata structures representing inflated methods/fields
2310 * to the reflection objects representing their generic definitions.
2312 mono_image_lock ((MonoImage*)image);
2313 mono_g_hash_table_insert (image->generic_def_objects, imethod, rmethod);
2314 mono_image_unlock ((MonoImage*)image);
2317 if (!mono_verifier_is_method_valid_generic_instantiation (inflated)) {
2318 mono_error_set_argument (error, "typeArguments", "Invalid generic arguments");
2322 MonoReflectionMethod *ret = mono_method_get_object_checked (mono_object_domain (rmethod), inflated, NULL, error);
2326 MonoReflectionMethod*
2327 ves_icall_MethodBuilder_MakeGenericMethod (MonoReflectionMethod *rmethod, MonoArray *types)
2330 MonoReflectionMethod *result = reflection_bind_generic_method_parameters (rmethod, types, &error);
2331 mono_error_set_pending_exception (&error);
2335 MonoReflectionMethod*
2336 ves_icall_MonoMethod_MakeGenericMethod_impl (MonoReflectionMethod *rmethod, MonoArray *types)
2339 MonoReflectionMethod *result = reflection_bind_generic_method_parameters (rmethod, types, &error);
2340 mono_error_set_pending_exception (&error);
2345 /* SECURITY_ACTION_* are defined in mono/metadata/tabledefs.h */
2346 const static guint32 declsec_flags_map[] = {
2347 0x00000000, /* empty */
2348 MONO_DECLSEC_FLAG_REQUEST, /* SECURITY_ACTION_REQUEST (x01) */
2349 MONO_DECLSEC_FLAG_DEMAND, /* SECURITY_ACTION_DEMAND (x02) */
2350 MONO_DECLSEC_FLAG_ASSERT, /* SECURITY_ACTION_ASSERT (x03) */
2351 MONO_DECLSEC_FLAG_DENY, /* SECURITY_ACTION_DENY (x04) */
2352 MONO_DECLSEC_FLAG_PERMITONLY, /* SECURITY_ACTION_PERMITONLY (x05) */
2353 MONO_DECLSEC_FLAG_LINKDEMAND, /* SECURITY_ACTION_LINKDEMAND (x06) */
2354 MONO_DECLSEC_FLAG_INHERITANCEDEMAND, /* SECURITY_ACTION_INHERITANCEDEMAND (x07) */
2355 MONO_DECLSEC_FLAG_REQUEST_MINIMUM, /* SECURITY_ACTION_REQUEST_MINIMUM (x08) */
2356 MONO_DECLSEC_FLAG_REQUEST_OPTIONAL, /* SECURITY_ACTION_REQUEST_OPTIONAL (x09) */
2357 MONO_DECLSEC_FLAG_REQUEST_REFUSE, /* SECURITY_ACTION_REQUEST_REFUSE (x0A) */
2358 MONO_DECLSEC_FLAG_PREJIT_GRANT, /* SECURITY_ACTION_PREJIT_GRANT (x0B) */
2359 MONO_DECLSEC_FLAG_PREJIT_DENY, /* SECURITY_ACTION_PREJIT_DENY (x0C) */
2360 MONO_DECLSEC_FLAG_NONCAS_DEMAND, /* SECURITY_ACTION_NONCAS_DEMAND (x0D) */
2361 MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND, /* SECURITY_ACTION_NONCAS_LINKDEMAND (x0E) */
2362 MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND, /* SECURITY_ACTION_NONCAS_INHERITANCEDEMAND (x0F) */
2363 MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE, /* SECURITY_ACTION_LINKDEMAND_CHOICE (x10) */
2364 MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE, /* SECURITY_ACTION_INHERITANCEDEMAND_CHOICE (x11) */
2365 MONO_DECLSEC_FLAG_DEMAND_CHOICE, /* SECURITY_ACTION_DEMAND_CHOICE (x12) */
2369 * Returns flags that includes all available security action associated to the handle.
2370 * @token: metadata token (either for a class or a method)
2371 * @image: image where resides the metadata.
2374 mono_declsec_get_flags (MonoImage *image, guint32 token)
2376 int index = mono_metadata_declsec_from_index (image, token);
2377 MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY];
2382 /* HasSecurity can be present for other, not specially encoded, attributes,
2383 e.g. SuppressUnmanagedCodeSecurityAttribute */
2387 for (i = index; i < t->rows; i++) {
2388 guint32 cols [MONO_DECL_SECURITY_SIZE];
2390 mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
2391 if (cols [MONO_DECL_SECURITY_PARENT] != token)
2394 action = cols [MONO_DECL_SECURITY_ACTION];
2395 if ((action >= MONO_DECLSEC_ACTION_MIN) && (action <= MONO_DECLSEC_ACTION_MAX)) {
2396 result |= declsec_flags_map [action];
2398 g_assert_not_reached ();
2405 * Get the security actions (in the form of flags) associated with the specified method.
2407 * @method: The method for which we want the declarative security flags.
2408 * Return the declarative security flags for the method (only).
2410 * Note: To keep MonoMethod size down we do not cache the declarative security flags
2411 * (except for the stack modifiers which are kept in the MonoJitInfo structure)
2414 mono_declsec_flags_from_method (MonoMethod *method)
2416 if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2417 /* FIXME: No cache (for the moment) */
2418 guint32 idx = mono_method_get_index (method);
2419 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2420 idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
2421 return mono_declsec_get_flags (method->klass->image, idx);
2427 * Get the security actions (in the form of flags) associated with the specified class.
2429 * @klass: The class for which we want the declarative security flags.
2430 * Return the declarative security flags for the class.
2432 * Note: We cache the flags inside the MonoClass structure as this will get
2433 * called very often (at least for each method).
2436 mono_declsec_flags_from_class (MonoClass *klass)
2438 if (klass->flags & TYPE_ATTRIBUTE_HAS_SECURITY) {
2439 if (!klass->ext || !klass->ext->declsec_flags) {
2442 idx = mono_metadata_token_index (klass->type_token);
2443 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2444 idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
2445 mono_loader_lock ();
2446 mono_class_alloc_ext (klass);
2447 mono_loader_unlock ();
2448 /* we cache the flags on classes */
2449 klass->ext->declsec_flags = mono_declsec_get_flags (klass->image, idx);
2451 return klass->ext->declsec_flags;
2457 * Get the security actions (in the form of flags) associated with the specified assembly.
2459 * @assembly: The assembly for which we want the declarative security flags.
2460 * Return the declarative security flags for the assembly.
2463 mono_declsec_flags_from_assembly (MonoAssembly *assembly)
2465 guint32 idx = 1; /* there is only one assembly */
2466 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2467 idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
2468 return mono_declsec_get_flags (assembly->image, idx);
2473 * Fill actions for the specific index (which may either be an encoded class token or
2474 * an encoded method token) from the metadata image.
2475 * Returns TRUE if some actions requiring code generation are present, FALSE otherwise.
2478 fill_actions_from_index (MonoImage *image, guint32 token, MonoDeclSecurityActions* actions,
2479 guint32 id_std, guint32 id_noncas, guint32 id_choice)
2481 MonoBoolean result = FALSE;
2483 guint32 cols [MONO_DECL_SECURITY_SIZE];
2484 int index = mono_metadata_declsec_from_index (image, token);
2487 t = &image->tables [MONO_TABLE_DECLSECURITY];
2488 for (i = index; i < t->rows; i++) {
2489 mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
2491 if (cols [MONO_DECL_SECURITY_PARENT] != token)
2494 /* if present only replace (class) permissions with method permissions */
2495 /* if empty accept either class or method permissions */
2496 if (cols [MONO_DECL_SECURITY_ACTION] == id_std) {
2497 if (!actions->demand.blob) {
2498 const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
2499 actions->demand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
2500 actions->demand.blob = (char*) (blob + 2);
2501 actions->demand.size = mono_metadata_decode_blob_size (blob, &blob);
2504 } else if (cols [MONO_DECL_SECURITY_ACTION] == id_noncas) {
2505 if (!actions->noncasdemand.blob) {
2506 const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
2507 actions->noncasdemand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
2508 actions->noncasdemand.blob = (char*) (blob + 2);
2509 actions->noncasdemand.size = mono_metadata_decode_blob_size (blob, &blob);
2512 } else if (cols [MONO_DECL_SECURITY_ACTION] == id_choice) {
2513 if (!actions->demandchoice.blob) {
2514 const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
2515 actions->demandchoice.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
2516 actions->demandchoice.blob = (char*) (blob + 2);
2517 actions->demandchoice.size = mono_metadata_decode_blob_size (blob, &blob);
2527 mono_declsec_get_class_demands_params (MonoClass *klass, MonoDeclSecurityActions* demands,
2528 guint32 id_std, guint32 id_noncas, guint32 id_choice)
2530 guint32 idx = mono_metadata_token_index (klass->type_token);
2531 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2532 idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
2533 return fill_actions_from_index (klass->image, idx, demands, id_std, id_noncas, id_choice);
2537 mono_declsec_get_method_demands_params (MonoMethod *method, MonoDeclSecurityActions* demands,
2538 guint32 id_std, guint32 id_noncas, guint32 id_choice)
2540 guint32 idx = mono_method_get_index (method);
2541 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2542 idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
2543 return fill_actions_from_index (method->klass->image, idx, demands, id_std, id_noncas, id_choice);
2547 * Collect all actions (that requires to generate code in mini) assigned for
2548 * the specified method.
2549 * Note: Don't use the content of actions if the function return FALSE.
2552 mono_declsec_get_demands (MonoMethod *method, MonoDeclSecurityActions* demands)
2554 guint32 mask = MONO_DECLSEC_FLAG_DEMAND | MONO_DECLSEC_FLAG_NONCAS_DEMAND |
2555 MONO_DECLSEC_FLAG_DEMAND_CHOICE;
2556 MonoBoolean result = FALSE;
2559 /* quick exit if no declarative security is present in the metadata */
2560 if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
2563 /* we want the original as the wrapper is "free" of the security informations */
2564 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
2565 method = mono_marshal_method_from_wrapper (method);
2570 /* First we look for method-level attributes */
2571 if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2572 mono_class_init (method->klass);
2573 memset (demands, 0, sizeof (MonoDeclSecurityActions));
2575 result = mono_declsec_get_method_demands_params (method, demands,
2576 SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
2579 /* Here we use (or create) the class declarative cache to look for demands */
2580 flags = mono_declsec_flags_from_class (method->klass);
2583 mono_class_init (method->klass);
2584 memset (demands, 0, sizeof (MonoDeclSecurityActions));
2586 result |= mono_declsec_get_class_demands_params (method->klass, demands,
2587 SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
2590 /* The boolean return value is used as a shortcut in case nothing needs to
2591 be generated (e.g. LinkDemand[Choice] and InheritanceDemand[Choice]) */
2597 * Collect all Link actions: LinkDemand, NonCasLinkDemand and LinkDemandChoice (2.0).
2599 * Note: Don't use the content of actions if the function return FALSE.
2602 mono_declsec_get_linkdemands (MonoMethod *method, MonoDeclSecurityActions* klass, MonoDeclSecurityActions *cmethod)
2604 MonoBoolean result = FALSE;
2607 /* quick exit if no declarative security is present in the metadata */
2608 if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
2611 /* we want the original as the wrapper is "free" of the security informations */
2612 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
2613 method = mono_marshal_method_from_wrapper (method);
2618 /* results are independant - zeroize both */
2619 memset (cmethod, 0, sizeof (MonoDeclSecurityActions));
2620 memset (klass, 0, sizeof (MonoDeclSecurityActions));
2622 /* First we look for method-level attributes */
2623 if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2624 mono_class_init (method->klass);
2626 result = mono_declsec_get_method_demands_params (method, cmethod,
2627 SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
2630 /* Here we use (or create) the class declarative cache to look for demands */
2631 flags = mono_declsec_flags_from_class (method->klass);
2632 if (flags & (MONO_DECLSEC_FLAG_LINKDEMAND | MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND | MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE)) {
2633 mono_class_init (method->klass);
2635 result |= mono_declsec_get_class_demands_params (method->klass, klass,
2636 SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
2643 * Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
2645 * @klass The inherited class - this is the class that provides the security check (attributes)
2647 * return TRUE if inheritance demands (any kind) are present, FALSE otherwise.
2649 * Note: Don't use the content of actions if the function return FALSE.
2652 mono_declsec_get_inheritdemands_class (MonoClass *klass, MonoDeclSecurityActions* demands)
2654 MonoBoolean result = FALSE;
2657 /* quick exit if no declarative security is present in the metadata */
2658 if (!klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
2661 /* Here we use (or create) the class declarative cache to look for demands */
2662 flags = mono_declsec_flags_from_class (klass);
2663 if (flags & (MONO_DECLSEC_FLAG_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE)) {
2664 mono_class_init (klass);
2665 memset (demands, 0, sizeof (MonoDeclSecurityActions));
2667 result |= mono_declsec_get_class_demands_params (klass, demands,
2668 SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
2675 * Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
2677 * Note: Don't use the content of actions if the function return FALSE.
2680 mono_declsec_get_inheritdemands_method (MonoMethod *method, MonoDeclSecurityActions* demands)
2682 /* quick exit if no declarative security is present in the metadata */
2683 if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
2686 /* we want the original as the wrapper is "free" of the security informations */
2687 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
2688 method = mono_marshal_method_from_wrapper (method);
2693 if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2694 mono_class_init (method->klass);
2695 memset (demands, 0, sizeof (MonoDeclSecurityActions));
2697 return mono_declsec_get_method_demands_params (method, demands,
2698 SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
2705 get_declsec_action (MonoImage *image, guint32 token, guint32 action, MonoDeclSecurityEntry *entry)
2707 guint32 cols [MONO_DECL_SECURITY_SIZE];
2711 int index = mono_metadata_declsec_from_index (image, token);
2715 t = &image->tables [MONO_TABLE_DECLSECURITY];
2716 for (i = index; i < t->rows; i++) {
2717 mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
2719 /* shortcut - index are ordered */
2720 if (token != cols [MONO_DECL_SECURITY_PARENT])
2723 if (cols [MONO_DECL_SECURITY_ACTION] == action) {
2724 const char *metadata = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
2725 entry->blob = (char*) (metadata + 2);
2726 entry->size = mono_metadata_decode_blob_size (metadata, &metadata);
2735 mono_declsec_get_method_action (MonoMethod *method, guint32 action, MonoDeclSecurityEntry *entry)
2737 if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2738 guint32 idx = mono_method_get_index (method);
2739 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2740 idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
2741 return get_declsec_action (method->klass->image, idx, action, entry);
2747 mono_declsec_get_class_action (MonoClass *klass, guint32 action, MonoDeclSecurityEntry *entry)
2750 guint32 flags = mono_declsec_flags_from_class (klass);
2751 if (declsec_flags_map [action] & flags) {
2752 guint32 idx = mono_metadata_token_index (klass->type_token);
2753 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2754 idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
2755 return get_declsec_action (klass->image, idx, action, entry);
2761 mono_declsec_get_assembly_action (MonoAssembly *assembly, guint32 action, MonoDeclSecurityEntry *entry)
2763 guint32 idx = 1; /* there is only one assembly */
2764 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2765 idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
2767 return get_declsec_action (assembly->image, idx, action, entry);
2771 mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass, MonoError *error)
2773 MonoObject *res, *exc;
2775 static MonoMethod *method = NULL;
2777 mono_error_init (error);
2779 if (method == NULL) {
2780 method = mono_class_get_method_from_name (mono_class_get_type_builder_class (), "IsAssignableTo", 1);
2785 * The result of mono_type_get_object_checked () might be a System.MonoType but we
2786 * need a TypeBuilder so use mono_class_get_ref_info (klass).
2788 g_assert (mono_class_get_ref_info (klass));
2789 g_assert (!strcmp (((MonoObject*)(mono_class_get_ref_info (klass)))->vtable->klass->name, "TypeBuilder"));
2791 params [0] = mono_type_get_object_checked (mono_domain_get (), &oklass->byval_arg, error);
2792 return_val_if_nok (error, FALSE);
2794 MonoError inner_error;
2795 res = mono_runtime_try_invoke (method, (MonoObject*)(mono_class_get_ref_info (klass)), params, &exc, &inner_error);
2797 if (exc || !is_ok (&inner_error)) {
2798 mono_error_cleanup (&inner_error);
2801 return *(MonoBoolean*)mono_object_unbox (res);
2805 * mono_reflection_type_get_type:
2806 * @reftype: the System.Type object
2808 * Returns the MonoType* associated with the C# System.Type object @reftype.
2811 mono_reflection_type_get_type (MonoReflectionType *reftype)
2816 MonoType *result = mono_reflection_type_get_handle (reftype, &error);
2817 mono_error_assert_ok (&error);
2822 * mono_reflection_assembly_get_assembly:
2823 * @refassembly: the System.Reflection.Assembly object
2825 * Returns the MonoAssembly* associated with the C# System.Reflection.Assembly object @refassembly.
2828 mono_reflection_assembly_get_assembly (MonoReflectionAssembly *refassembly)
2830 g_assert (refassembly);
2832 return refassembly->assembly;
2836 * mono_class_from_mono_type_handle:
2837 * @reftype: the System.Type handle
2839 * Returns the MonoClass* corresponding to the given type.
2842 mono_class_from_mono_type_handle (MonoReflectionTypeHandle reftype)
2844 return mono_class_from_mono_type (MONO_HANDLE_RAW (reftype)->type);