5 * Dietmar Maurer (dietmar@ximian.com)
6 * Paolo Molaro (lupus@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
8 * Marek Safar (marek.safar@gmail.com)
10 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 * Copyright 2011-2014 Xamarin Inc (http://www.xamarin.com).
23 #ifdef HAVE_SYS_TIME_H
29 #if defined (HOST_WIN32)
32 #if defined (HAVE_WCHAR_H)
36 #include "mono/utils/mono-membar.h"
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/threads.h>
39 #include <mono/metadata/threads-types.h>
40 #include <mono/metadata/threadpool.h>
41 #include <mono/metadata/monitor.h>
42 #include <mono/metadata/reflection.h>
43 #include <mono/metadata/assembly.h>
44 #include <mono/metadata/tabledefs.h>
45 #include <mono/metadata/exception.h>
46 #include <mono/metadata/file-io.h>
47 #include <mono/metadata/console-io.h>
48 #include <mono/metadata/mono-route.h>
49 #include <mono/metadata/socket-io.h>
50 #include <mono/metadata/mono-endian.h>
51 #include <mono/metadata/tokentype.h>
52 #include <mono/metadata/domain-internals.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/class-internals.h>
55 #include <mono/metadata/marshal.h>
56 #include <mono/metadata/gc-internal.h>
57 #include <mono/metadata/mono-gc.h>
58 #include <mono/metadata/rand.h>
59 #include <mono/metadata/sysmath.h>
60 #include <mono/metadata/string-icalls.h>
61 #include <mono/metadata/debug-helpers.h>
62 #include <mono/metadata/process.h>
63 #include <mono/metadata/environment.h>
64 #include <mono/metadata/profiler-private.h>
65 #include <mono/metadata/locales.h>
66 #include <mono/metadata/filewatcher.h>
67 #include <mono/metadata/char-conversions.h>
68 #include <mono/metadata/security.h>
69 #include <mono/metadata/mono-config.h>
70 #include <mono/metadata/cil-coff.h>
71 #include <mono/metadata/number-formatter.h>
72 #include <mono/metadata/security-manager.h>
73 #include <mono/metadata/security-core-clr.h>
74 #include <mono/metadata/mono-perfcounters.h>
75 #include <mono/metadata/mono-debug.h>
76 #include <mono/metadata/mono-ptr-array.h>
77 #include <mono/metadata/verify-internals.h>
78 #include <mono/metadata/runtime.h>
79 #include <mono/metadata/file-mmap.h>
80 #include <mono/io-layer/io-layer.h>
81 #include <mono/utils/strtod.h>
82 #include <mono/utils/monobitset.h>
83 #include <mono/utils/mono-time.h>
84 #include <mono/utils/mono-proclib.h>
85 #include <mono/utils/mono-string.h>
86 #include <mono/utils/mono-error-internals.h>
87 #include <mono/utils/mono-mmap.h>
88 #include <mono/utils/mono-io-portability.h>
89 #include <mono/utils/mono-digest.h>
90 #include <mono/utils/bsearch.h>
91 #include <mono/utils/mono-mutex.h>
92 #include <mono/utils/mono-threads.h>
94 #if defined (HOST_WIN32)
98 #include "decimal-ms.h"
100 extern MonoString* ves_icall_System_Environment_GetOSVersionString (void) MONO_INTERNAL;
102 ICALL_EXPORT MonoReflectionAssembly* ves_icall_System_Reflection_Assembly_GetCallingAssembly (void);
105 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional);
107 static inline MonoBoolean
108 is_generic_parameter (MonoType *type)
110 return !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR);
114 mono_class_init_or_throw (MonoClass *klass)
116 if (!mono_class_init (klass))
117 mono_raise_exception (mono_class_get_exception_for_failure (klass));
121 * We expect a pointer to a char, not a string
123 ICALL_EXPORT gboolean
124 mono_double_ParseImpl (char *ptr, double *result)
126 gchar *endptr = NULL;
130 /* mono_strtod () is not thread-safe */
131 mono_mutex_lock (&mono_strtod_mutex);
132 *result = mono_strtod (ptr, &endptr);
133 mono_mutex_unlock (&mono_strtod_mutex);
136 if (!*ptr || (endptr && *endptr))
142 ICALL_EXPORT MonoObject *
143 ves_icall_System_Array_GetValueImpl (MonoObject *this, guint32 pos)
150 ao = (MonoArray *)this;
151 ac = (MonoClass *)ao->obj.vtable->klass;
153 esize = mono_array_element_size (ac);
154 ea = (gpointer*)((char*)ao->vector + (pos * esize));
156 if (ac->element_class->valuetype)
157 return mono_value_box (this->vtable->domain, ac->element_class, ea);
162 ICALL_EXPORT MonoObject *
163 ves_icall_System_Array_GetValue (MonoObject *this, MonoObject *idxs)
169 MONO_CHECK_ARG_NULL (idxs);
171 io = (MonoArray *)idxs;
172 ic = (MonoClass *)io->obj.vtable->klass;
174 ao = (MonoArray *)this;
175 ac = (MonoClass *)ao->obj.vtable->klass;
177 g_assert (ic->rank == 1);
178 if (io->bounds != NULL || io->max_length != ac->rank)
179 mono_raise_exception (mono_get_exception_argument (NULL, NULL));
181 ind = (gint32 *)io->vector;
183 if (ao->bounds == NULL) {
184 if (*ind < 0 || *ind >= ao->max_length)
185 mono_raise_exception (mono_get_exception_index_out_of_range ());
187 return ves_icall_System_Array_GetValueImpl (this, *ind);
190 for (i = 0; i < ac->rank; i++)
191 if ((ind [i] < ao->bounds [i].lower_bound) ||
192 (ind [i] >= (mono_array_lower_bound_t)ao->bounds [i].length + ao->bounds [i].lower_bound))
193 mono_raise_exception (mono_get_exception_index_out_of_range ());
195 pos = ind [0] - ao->bounds [0].lower_bound;
196 for (i = 1; i < ac->rank; i++)
197 pos = pos*ao->bounds [i].length + ind [i] -
198 ao->bounds [i].lower_bound;
200 return ves_icall_System_Array_GetValueImpl (this, pos);
204 ves_icall_System_Array_SetValueImpl (MonoArray *this, MonoObject *value, guint32 pos)
206 MonoClass *ac, *vc, *ec;
216 vc = value->vtable->klass;
220 ac = this->obj.vtable->klass;
221 ec = ac->element_class;
223 esize = mono_array_element_size (ac);
224 ea = (gpointer*)((char*)this->vector + (pos * esize));
225 va = (gpointer*)((char*)value + sizeof (MonoObject));
227 if (mono_class_is_nullable (ec)) {
228 mono_nullable_init ((guint8*)ea, value, ec);
233 mono_gc_bzero_atomic (ea, esize);
237 #define NO_WIDENING_CONVERSION G_STMT_START{\
238 mono_raise_exception (mono_get_exception_argument ( \
239 "value", "not a widening conversion")); \
242 #define CHECK_WIDENING_CONVERSION(extra) G_STMT_START{\
243 if (esize < vsize + (extra)) \
244 mono_raise_exception (mono_get_exception_argument ( \
245 "value", "not a widening conversion")); \
248 #define INVALID_CAST G_STMT_START{ \
249 mono_get_runtime_callbacks ()->set_cast_details (vc, ec); \
250 mono_raise_exception (mono_get_exception_invalid_cast ()); \
253 /* Check element (destination) type. */
254 switch (ec->byval_arg.type) {
255 case MONO_TYPE_STRING:
256 switch (vc->byval_arg.type) {
257 case MONO_TYPE_STRING:
263 case MONO_TYPE_BOOLEAN:
264 switch (vc->byval_arg.type) {
265 case MONO_TYPE_BOOLEAN:
278 NO_WIDENING_CONVERSION;
285 if (!ec->valuetype) {
286 if (!mono_object_isinst (value, ec))
288 mono_gc_wbarrier_set_arrayref (this, ea, (MonoObject*)value);
292 if (mono_object_isinst (value, ec)) {
293 if (ec->has_references)
294 mono_value_copy (ea, (char*)value + sizeof (MonoObject), ec);
296 mono_gc_memmove_atomic (ea, (char *)value + sizeof (MonoObject), esize);
303 vsize = mono_class_instance_size (vc) - sizeof (MonoObject);
305 et = ec->byval_arg.type;
306 if (et == MONO_TYPE_VALUETYPE && ec->byval_arg.data.klass->enumtype)
307 et = mono_class_enum_basetype (ec->byval_arg.data.klass)->type;
309 vt = vc->byval_arg.type;
310 if (vt == MONO_TYPE_VALUETYPE && vc->byval_arg.data.klass->enumtype)
311 vt = mono_class_enum_basetype (vc->byval_arg.data.klass)->type;
313 #define ASSIGN_UNSIGNED(etype) G_STMT_START{\
319 case MONO_TYPE_CHAR: \
320 CHECK_WIDENING_CONVERSION(0); \
321 *(etype *) ea = (etype) u64; \
323 /* You can't assign a signed value to an unsigned array. */ \
328 /* You can't assign a floating point number to an integer array. */ \
331 NO_WIDENING_CONVERSION; \
335 #define ASSIGN_SIGNED(etype) G_STMT_START{\
341 CHECK_WIDENING_CONVERSION(0); \
342 *(etype *) ea = (etype) i64; \
344 /* You can assign an unsigned value to a signed array if the array's */ \
345 /* element size is larger than the value size. */ \
350 case MONO_TYPE_CHAR: \
351 CHECK_WIDENING_CONVERSION(1); \
352 *(etype *) ea = (etype) u64; \
354 /* You can't assign a floating point number to an integer array. */ \
357 NO_WIDENING_CONVERSION; \
361 #define ASSIGN_REAL(etype) G_STMT_START{\
365 CHECK_WIDENING_CONVERSION(0); \
366 *(etype *) ea = (etype) r64; \
368 /* All integer values fit into a floating point array, so we don't */ \
369 /* need to CHECK_WIDENING_CONVERSION here. */ \
374 *(etype *) ea = (etype) i64; \
380 case MONO_TYPE_CHAR: \
381 *(etype *) ea = (etype) u64; \
388 u64 = *(guint8 *) va;
391 u64 = *(guint16 *) va;
394 u64 = *(guint32 *) va;
397 u64 = *(guint64 *) va;
403 i64 = *(gint16 *) va;
406 i64 = *(gint32 *) va;
409 i64 = *(gint64 *) va;
412 r64 = *(gfloat *) va;
415 r64 = *(gdouble *) va;
418 u64 = *(guint16 *) va;
420 case MONO_TYPE_BOOLEAN:
421 /* Boolean is only compatible with itself. */
434 NO_WIDENING_CONVERSION;
441 /* If we can't do a direct copy, let's try a widening conversion. */
444 ASSIGN_UNSIGNED (guint16);
446 ASSIGN_UNSIGNED (guint8);
448 ASSIGN_UNSIGNED (guint16);
450 ASSIGN_UNSIGNED (guint32);
452 ASSIGN_UNSIGNED (guint64);
454 ASSIGN_SIGNED (gint8);
456 ASSIGN_SIGNED (gint16);
458 ASSIGN_SIGNED (gint32);
460 ASSIGN_SIGNED (gint64);
462 ASSIGN_REAL (gfloat);
464 ASSIGN_REAL (gdouble);
468 /* Not reached, INVALID_CAST does not return. Just to avoid a compiler warning ... */
472 #undef NO_WIDENING_CONVERSION
473 #undef CHECK_WIDENING_CONVERSION
474 #undef ASSIGN_UNSIGNED
480 ves_icall_System_Array_SetValue (MonoArray *this, MonoObject *value,
486 MONO_CHECK_ARG_NULL (idxs);
488 ic = idxs->obj.vtable->klass;
489 ac = this->obj.vtable->klass;
491 g_assert (ic->rank == 1);
492 if (idxs->bounds != NULL || idxs->max_length != ac->rank)
493 mono_raise_exception (mono_get_exception_argument (NULL, NULL));
495 ind = (gint32 *)idxs->vector;
497 if (this->bounds == NULL) {
498 if (*ind < 0 || *ind >= this->max_length)
499 mono_raise_exception (mono_get_exception_index_out_of_range ());
501 ves_icall_System_Array_SetValueImpl (this, value, *ind);
505 for (i = 0; i < ac->rank; i++)
506 if ((ind [i] < this->bounds [i].lower_bound) ||
507 (ind [i] >= (mono_array_lower_bound_t)this->bounds [i].length + this->bounds [i].lower_bound))
508 mono_raise_exception (mono_get_exception_index_out_of_range ());
510 pos = ind [0] - this->bounds [0].lower_bound;
511 for (i = 1; i < ac->rank; i++)
512 pos = pos * this->bounds [i].length + ind [i] -
513 this->bounds [i].lower_bound;
515 ves_icall_System_Array_SetValueImpl (this, value, pos);
518 ICALL_EXPORT MonoArray *
519 ves_icall_System_Array_CreateInstanceImpl (MonoReflectionType *type, MonoArray *lengths, MonoArray *bounds)
521 MonoClass *aklass, *klass;
524 gboolean bounded = FALSE;
526 MONO_CHECK_ARG_NULL (type);
527 MONO_CHECK_ARG_NULL (lengths);
529 MONO_CHECK_ARG (lengths, mono_array_length (lengths) > 0);
531 MONO_CHECK_ARG (bounds, mono_array_length (lengths) == mono_array_length (bounds));
533 for (i = 0; i < mono_array_length (lengths); i++)
534 if (mono_array_get (lengths, gint32, i) < 0)
535 mono_raise_exception (mono_get_exception_argument_out_of_range (NULL));
537 klass = mono_class_from_mono_type (type->type);
538 mono_class_init_or_throw (klass);
540 if (bounds && (mono_array_length (bounds) == 1) && (mono_array_get (bounds, gint32, 0) != 0))
541 /* vectors are not the same as one dimensional arrays with no-zero bounds */
546 aklass = mono_bounded_array_class_get (klass, mono_array_length (lengths), bounded);
548 sizes = alloca (aklass->rank * sizeof(intptr_t) * 2);
549 for (i = 0; i < aklass->rank; ++i) {
550 sizes [i] = mono_array_get (lengths, guint32, i);
552 sizes [i + aklass->rank] = mono_array_get (bounds, gint32, i);
554 sizes [i + aklass->rank] = 0;
557 array = mono_array_new_full (mono_object_domain (type), aklass, sizes, (intptr_t*)sizes + aklass->rank);
562 ICALL_EXPORT MonoArray *
563 ves_icall_System_Array_CreateInstanceImpl64 (MonoReflectionType *type, MonoArray *lengths, MonoArray *bounds)
565 MonoClass *aklass, *klass;
568 gboolean bounded = FALSE;
570 MONO_CHECK_ARG_NULL (type);
571 MONO_CHECK_ARG_NULL (lengths);
573 MONO_CHECK_ARG (lengths, mono_array_length (lengths) > 0);
575 MONO_CHECK_ARG (bounds, mono_array_length (lengths) == mono_array_length (bounds));
577 for (i = 0; i < mono_array_length (lengths); i++)
578 if ((mono_array_get (lengths, gint64, i) < 0) ||
579 (mono_array_get (lengths, gint64, i) > MONO_ARRAY_MAX_INDEX))
580 mono_raise_exception (mono_get_exception_argument_out_of_range (NULL));
582 klass = mono_class_from_mono_type (type->type);
583 mono_class_init_or_throw (klass);
585 if (bounds && (mono_array_length (bounds) == 1) && (mono_array_get (bounds, gint64, 0) != 0))
586 /* vectors are not the same as one dimensional arrays with no-zero bounds */
591 aklass = mono_bounded_array_class_get (klass, mono_array_length (lengths), bounded);
593 sizes = alloca (aklass->rank * sizeof(intptr_t) * 2);
594 for (i = 0; i < aklass->rank; ++i) {
595 sizes [i] = mono_array_get (lengths, guint64, i);
597 sizes [i + aklass->rank] = (mono_array_size_t) mono_array_get (bounds, guint64, i);
599 sizes [i + aklass->rank] = 0;
602 array = mono_array_new_full (mono_object_domain (type), aklass, sizes, (intptr_t*)sizes + aklass->rank);
608 ves_icall_System_Array_GetRank (MonoObject *this)
610 return this->vtable->klass->rank;
614 ves_icall_System_Array_GetLength (MonoArray *this, gint32 dimension)
616 gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
619 if ((dimension < 0) || (dimension >= rank))
620 mono_raise_exception (mono_get_exception_index_out_of_range ());
622 if (this->bounds == NULL)
623 length = this->max_length;
625 length = this->bounds [dimension].length;
627 #ifdef MONO_BIG_ARRAYS
628 if (length > G_MAXINT32)
629 mono_raise_exception (mono_get_exception_overflow ());
635 ves_icall_System_Array_GetLongLength (MonoArray *this, gint32 dimension)
637 gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
639 if ((dimension < 0) || (dimension >= rank))
640 mono_raise_exception (mono_get_exception_index_out_of_range ());
642 if (this->bounds == NULL)
643 return this->max_length;
645 return this->bounds [dimension].length;
649 ves_icall_System_Array_GetLowerBound (MonoArray *this, gint32 dimension)
651 gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
653 if ((dimension < 0) || (dimension >= rank))
654 mono_raise_exception (mono_get_exception_index_out_of_range ());
656 if (this->bounds == NULL)
659 return this->bounds [dimension].lower_bound;
663 ves_icall_System_Array_ClearInternal (MonoArray *arr, int idx, int length)
665 int sz = mono_array_element_size (mono_object_class (arr));
666 mono_gc_bzero_atomic (mono_array_addr_with_size_fast (arr, sz, idx), length * sz);
669 ICALL_EXPORT gboolean
670 ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* dest, int dest_idx, int length)
675 MonoVTable *src_vtable;
676 MonoVTable *dest_vtable;
677 MonoClass *src_class;
678 MonoClass *dest_class;
680 src_vtable = source->obj.vtable;
681 dest_vtable = dest->obj.vtable;
683 if (src_vtable->rank != dest_vtable->rank)
686 if (source->bounds || dest->bounds)
689 /* there's no integer overflow since mono_array_length returns an unsigned integer */
690 if ((dest_idx + length > mono_array_length_fast (dest)) ||
691 (source_idx + length > mono_array_length_fast (source)))
694 src_class = src_vtable->klass->element_class;
695 dest_class = dest_vtable->klass->element_class;
698 * Handle common cases.
701 /* Case1: object[] -> valuetype[] (ArrayList::ToArray)
702 We fallback to managed here since we need to typecheck each boxed valuetype before storing them in the dest array.
704 if (src_class == mono_defaults.object_class && dest_class->valuetype)
707 /* Check if we're copying a char[] <==> (u)short[] */
708 if (src_class != dest_class) {
709 if (dest_class->valuetype || dest_class->enumtype || src_class->valuetype || src_class->enumtype)
712 /* It's only safe to copy between arrays if we can ensure the source will always have a subtype of the destination. We bail otherwise. */
713 if (!mono_class_is_subclass_of (src_class, dest_class, FALSE))
717 if (dest_class->valuetype) {
718 element_size = mono_array_element_size (source->obj.vtable->klass);
719 source_addr = mono_array_addr_with_size_fast (source, element_size, source_idx);
720 if (dest_class->has_references) {
721 mono_value_copy_array (dest, dest_idx, source_addr, length);
723 dest_addr = mono_array_addr_with_size_fast (dest, element_size, dest_idx);
724 mono_gc_memmove_atomic (dest_addr, source_addr, element_size * length);
727 mono_array_memcpy_refs_fast (dest, dest_idx, source, source_idx, length);
734 ves_icall_System_Array_GetGenericValueImpl (MonoObject *this, guint32 pos, gpointer value)
741 ao = (MonoArray *)this;
742 ac = (MonoClass *)ao->obj.vtable->klass;
744 esize = mono_array_element_size (ac);
745 ea = (gpointer*)((char*)ao->vector + (pos * esize));
747 mono_gc_memmove_atomic (value, ea, esize);
751 ves_icall_System_Array_SetGenericValueImpl (MonoObject *this, guint32 pos, gpointer value)
758 ao = (MonoArray *)this;
759 ac = (MonoClass *)ao->obj.vtable->klass;
760 ec = ac->element_class;
762 esize = mono_array_element_size (ac);
763 ea = (gpointer*)((char*)ao->vector + (pos * esize));
765 if (MONO_TYPE_IS_REFERENCE (&ec->byval_arg)) {
766 g_assert (esize == sizeof (gpointer));
767 mono_gc_wbarrier_generic_store (ea, *(gpointer*)value);
769 g_assert (ec->inited);
770 g_assert (esize == mono_class_value_size (ec, NULL));
771 if (ec->has_references)
772 mono_gc_wbarrier_value_copy (ea, value, 1, ec);
774 mono_gc_memmove_atomic (ea, value, esize);
779 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArray *array, MonoClassField *field_handle)
781 MonoClass *klass = array->obj.vtable->klass;
782 guint32 size = mono_array_element_size (klass);
783 MonoType *type = mono_type_get_underlying_type (&klass->element_class->byval_arg);
785 const char *field_data;
787 if (MONO_TYPE_IS_REFERENCE (type) || type->type == MONO_TYPE_VALUETYPE) {
788 MonoException *exc = mono_get_exception_argument("array",
789 "Cannot initialize array of non-primitive type.");
790 mono_raise_exception (exc);
793 if (!(field_handle->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
794 MonoException *exc = mono_get_exception_argument("field_handle",
795 "Field doesn't have an RVA");
796 mono_raise_exception (exc);
799 size *= array->max_length;
800 field_data = mono_field_get_data (field_handle);
802 if (size > mono_type_size (field_handle->type, &align)) {
803 MonoException *exc = mono_get_exception_argument("field_handle",
804 "Field not large enough to fill array");
805 mono_raise_exception (exc);
808 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
810 guint ## n *data = (guint ## n *) mono_array_addr (array, char, 0); \
811 guint ## n *src = (guint ## n *) field_data; \
812 guint ## n *end = (guint ## n *)((char*)src + size); \
814 for (; src < end; data++, src++) { \
815 *data = read ## n (src); \
819 /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
821 switch (type->type) {
838 memcpy (mono_array_addr (array, char, 0), field_data, size);
842 memcpy (mono_array_addr (array, char, 0), field_data, size);
847 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
849 return offsetof (MonoString, chars);
852 ICALL_EXPORT MonoObject *
853 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObject *obj)
855 if ((obj == NULL) || (! (obj->vtable->klass->valuetype)))
858 return mono_object_clone (obj);
862 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle)
867 MONO_CHECK_ARG_NULL (handle);
869 klass = mono_class_from_mono_type (handle);
870 MONO_CHECK_ARG (handle, klass);
872 vtable = mono_class_vtable_full (mono_domain_get (), klass, TRUE);
874 /* This will call the type constructor */
875 mono_runtime_class_init (vtable);
879 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (MonoImage *image)
883 mono_image_check_for_module_cctor (image);
884 if (image->has_module_cctor) {
885 MonoClass *module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, &error);
886 mono_error_raise_exception (&error);
887 /*It's fine to raise the exception here*/
888 mono_runtime_class_init (mono_class_vtable_full (mono_domain_get (), module_klass, TRUE));
892 ICALL_EXPORT MonoBoolean
893 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
898 /* later make this configurable and per-arch */
899 int min_size = 4096 * 4 * sizeof (void*);
900 mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
901 /* if we have no info we are optimistic and assume there is enough room */
905 // FIXME: Windows dynamically extends the stack, so stack_addr might be close
909 current = (guint8 *)&stack_addr;
910 if (current > stack_addr) {
911 if ((current - stack_addr) < min_size)
914 if (current - (stack_addr - stack_size) < min_size)
920 ICALL_EXPORT MonoObject *
921 ves_icall_System_Object_MemberwiseClone (MonoObject *this)
923 return mono_object_clone (this);
927 ves_icall_System_ValueType_InternalGetHashCode (MonoObject *this, MonoArray **fields)
930 MonoObject **values = NULL;
933 gint32 result = (int)(gsize)mono_defaults.int32_class;
934 MonoClassField* field;
937 klass = mono_object_class (this);
939 if (mono_class_num_fields (klass) == 0)
943 * Compute the starting value of the hashcode for fields of primitive
944 * types, and return the remaining fields in an array to the managed side.
945 * This way, we can avoid costly reflection operations in managed code.
948 while ((field = mono_class_get_fields (klass, &iter))) {
949 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
951 if (mono_field_is_deleted (field))
953 /* FIXME: Add more types */
954 switch (field->type->type) {
956 result ^= *(gint32*)((guint8*)this + field->offset);
958 case MONO_TYPE_STRING: {
960 s = *(MonoString**)((guint8*)this + field->offset);
962 result ^= mono_string_hash (s);
967 values = g_newa (MonoObject*, mono_class_num_fields (klass));
968 o = mono_field_get_value_object (mono_object_domain (this), field, this);
969 values [count++] = o;
975 mono_gc_wbarrier_generic_store (fields, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.object_class, count));
976 for (i = 0; i < count; ++i)
977 mono_array_setref (*fields, i, values [i]);
984 ICALL_EXPORT MonoBoolean
985 ves_icall_System_ValueType_Equals (MonoObject *this, MonoObject *that, MonoArray **fields)
988 MonoObject **values = NULL;
990 MonoClassField* field;
994 MONO_CHECK_ARG_NULL (that);
996 if (this->vtable != that->vtable)
999 klass = mono_object_class (this);
1001 if (klass->enumtype && mono_class_enum_basetype (klass) && mono_class_enum_basetype (klass)->type == MONO_TYPE_I4)
1002 return (*(gint32*)((guint8*)this + sizeof (MonoObject)) == *(gint32*)((guint8*)that + sizeof (MonoObject)));
1005 * Do the comparison for fields of primitive type and return a result if
1006 * possible. Otherwise, return the remaining fields in an array to the
1007 * managed side. This way, we can avoid costly reflection operations in
1012 while ((field = mono_class_get_fields (klass, &iter))) {
1013 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1015 if (mono_field_is_deleted (field))
1017 /* FIXME: Add more types */
1018 switch (field->type->type) {
1021 case MONO_TYPE_BOOLEAN:
1022 if (*((guint8*)this + field->offset) != *((guint8*)that + field->offset))
1027 case MONO_TYPE_CHAR:
1028 if (*(gint16*)((guint8*)this + field->offset) != *(gint16*)((guint8*)that + field->offset))
1033 if (*(gint32*)((guint8*)this + field->offset) != *(gint32*)((guint8*)that + field->offset))
1038 if (*(gint64*)((guint8*)this + field->offset) != *(gint64*)((guint8*)that + field->offset))
1042 if (*(float*)((guint8*)this + field->offset) != *(float*)((guint8*)that + field->offset))
1046 if (*(double*)((guint8*)this + field->offset) != *(double*)((guint8*)that + field->offset))
1051 case MONO_TYPE_STRING: {
1052 MonoString *s1, *s2;
1053 guint32 s1len, s2len;
1054 s1 = *(MonoString**)((guint8*)this + field->offset);
1055 s2 = *(MonoString**)((guint8*)that + field->offset);
1058 if ((s1 == NULL) || (s2 == NULL))
1060 s1len = mono_string_length (s1);
1061 s2len = mono_string_length (s2);
1065 if (memcmp (mono_string_chars (s1), mono_string_chars (s2), s1len * sizeof (gunichar2)) != 0)
1071 values = g_newa (MonoObject*, mono_class_num_fields (klass) * 2);
1072 o = mono_field_get_value_object (mono_object_domain (this), field, this);
1073 values [count++] = o;
1074 o = mono_field_get_value_object (mono_object_domain (this), field, that);
1075 values [count++] = o;
1078 if (klass->enumtype)
1079 /* enums only have one non-static field */
1085 mono_gc_wbarrier_generic_store (fields, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.object_class, count));
1086 for (i = 0; i < count; ++i)
1087 mono_array_setref_fast (*fields, i, values [i]);
1094 ICALL_EXPORT MonoReflectionType *
1095 ves_icall_System_Object_GetType (MonoObject *obj)
1097 #ifndef DISABLE_REMOTING
1098 if (obj->vtable->klass == mono_defaults.transparent_proxy_class)
1099 return mono_type_get_object (mono_object_domain (obj), &((MonoTransparentProxy*)obj)->remote_class->proxy_class->byval_arg);
1102 return mono_type_get_object (mono_object_domain (obj), &obj->vtable->klass->byval_arg);
1106 mono_type_type_from_obj (MonoReflectionType *mtype, MonoObject *obj)
1108 mtype->type = &obj->vtable->klass->byval_arg;
1109 g_assert (mtype->type->type);
1113 ves_icall_ModuleBuilder_getToken (MonoReflectionModuleBuilder *mb, MonoObject *obj, gboolean create_open_instance)
1115 MONO_CHECK_ARG_NULL (obj);
1117 return mono_image_create_token (mb->dynamic_image, obj, create_open_instance, TRUE);
1121 ves_icall_ModuleBuilder_getMethodToken (MonoReflectionModuleBuilder *mb,
1122 MonoReflectionMethod *method,
1123 MonoArray *opt_param_types)
1125 MONO_CHECK_ARG_NULL (method);
1127 return mono_image_create_method_token (
1128 mb->dynamic_image, (MonoObject *) method, opt_param_types);
1132 ves_icall_ModuleBuilder_WriteToFile (MonoReflectionModuleBuilder *mb, HANDLE file)
1134 mono_image_create_pefile (mb, file);
1138 ves_icall_ModuleBuilder_build_metadata (MonoReflectionModuleBuilder *mb)
1140 mono_image_build_metadata (mb);
1144 ves_icall_ModuleBuilder_RegisterToken (MonoReflectionModuleBuilder *mb, MonoObject *obj, guint32 token)
1146 mono_image_register_token (mb->dynamic_image, token, obj);
1150 get_caller (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1152 MonoMethod **dest = data;
1154 /* skip unmanaged frames */
1170 get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1172 MonoMethod **dest = data;
1174 /* skip unmanaged frames */
1179 if (!strcmp (m->klass->name_space, "System.Reflection"))
1188 get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1190 MonoMethod **dest = data;
1192 /* skip unmanaged frames */
1196 if (m->wrapper_type != MONO_WRAPPER_NONE)
1199 if (m->klass->image == mono_defaults.corlib && !strcmp (m->klass->name_space, "System.Reflection"))
1213 static MonoReflectionType *
1214 type_from_name (const char *str, MonoBoolean ignoreCase)
1216 MonoMethod *m, *dest;
1218 MonoType *type = NULL;
1219 MonoAssembly *assembly = NULL;
1220 MonoTypeNameParse info;
1221 char *temp_str = g_strdup (str);
1222 gboolean type_resolve = FALSE;
1224 /* mono_reflection_parse_type() mangles the string */
1225 if (!mono_reflection_parse_type (temp_str, &info)) {
1226 mono_reflection_free_type_info (&info);
1233 * We must compute the calling assembly as type loading must happen under a metadata context.
1234 * For example. The main assembly is a.exe and Type.GetType is called from dir/b.dll. Without
1235 * the metadata context (basedir currently) set to dir/b.dll we won't be able to load a dir/c.dll.
1237 m = mono_method_get_last_managed ();
1240 mono_stack_walk_no_il (get_caller_no_reflection, &dest);
1245 * FIXME: mono_method_get_last_managed() sometimes returns NULL, thus
1246 * causing ves_icall_System_Reflection_Assembly_GetCallingAssembly()
1247 * to crash. This only seems to happen in some strange remoting
1248 * scenarios and I was unable to figure out what's happening there.
1249 * Dec 10, 2005 - Martin.
1253 assembly = dest->klass->image->assembly;
1254 type_resolve = TRUE;
1256 g_warning (G_STRLOC);
1259 if (info.assembly.name)
1260 assembly = mono_assembly_load (&info.assembly, assembly ? assembly->basedir : NULL, NULL);
1264 /* When loading from the current assembly, AppDomain.TypeResolve will not be called yet */
1265 type = mono_reflection_get_type (assembly->image, &info, ignoreCase, &type_resolve);
1268 if (!info.assembly.name && !type) /* try mscorlib */
1269 type = mono_reflection_get_type (NULL, &info, ignoreCase, &type_resolve);
1271 if (assembly && !type && type_resolve) {
1272 type_resolve = FALSE; /* This will invoke TypeResolve if not done in the first 'if' */
1273 type = mono_reflection_get_type (assembly->image, &info, ignoreCase, &type_resolve);
1276 mono_reflection_free_type_info (&info);
1282 return mono_type_get_object (mono_domain_get (), type);
1286 MonoReflectionType *
1287 mono_type_get (const char *str)
1289 char *copy = g_strdup (str);
1290 MonoReflectionType *type = type_from_name (copy, FALSE);
1297 ICALL_EXPORT MonoReflectionType*
1298 ves_icall_type_from_name (MonoString *name,
1299 MonoBoolean throwOnError,
1300 MonoBoolean ignoreCase)
1302 char *str = mono_string_to_utf8 (name);
1303 MonoReflectionType *type;
1305 type = type_from_name (str, ignoreCase);
1308 MonoException *e = NULL;
1311 e = mono_get_exception_type_load (name, NULL);
1313 mono_loader_clear_error ();
1315 mono_raise_exception (e);
1322 ICALL_EXPORT MonoReflectionType*
1323 ves_icall_type_from_handle (MonoType *handle)
1325 MonoDomain *domain = mono_domain_get ();
1327 return mono_type_get_object (domain, handle);
1330 ICALL_EXPORT MonoBoolean
1331 ves_icall_System_Type_EqualsInternal (MonoReflectionType *type, MonoReflectionType *c)
1333 if (c && type->type && c->type)
1334 return mono_metadata_type_equal (type->type, c->type);
1336 return (type == c) ? TRUE : FALSE;
1339 /* System.TypeCode */
1358 TYPECODE_STRING = 18
1361 ICALL_EXPORT guint32
1362 ves_icall_type_GetTypeCodeInternal (MonoReflectionType *type)
1364 int t = type->type->type;
1366 if (type->type->byref)
1367 return TYPECODE_OBJECT;
1371 case MONO_TYPE_VOID:
1372 return TYPECODE_OBJECT;
1373 case MONO_TYPE_BOOLEAN:
1374 return TYPECODE_BOOLEAN;
1376 return TYPECODE_BYTE;
1378 return TYPECODE_SBYTE;
1380 return TYPECODE_UINT16;
1382 return TYPECODE_INT16;
1383 case MONO_TYPE_CHAR:
1384 return TYPECODE_CHAR;
1388 return TYPECODE_OBJECT;
1390 return TYPECODE_UINT32;
1392 return TYPECODE_INT32;
1394 return TYPECODE_UINT64;
1396 return TYPECODE_INT64;
1398 return TYPECODE_SINGLE;
1400 return TYPECODE_DOUBLE;
1401 case MONO_TYPE_VALUETYPE: {
1402 MonoClass *klass = type->type->data.klass;
1404 if (klass->enumtype) {
1405 t = mono_class_enum_basetype (klass)->type;
1407 } else if (mono_is_corlib_image (klass->image)) {
1408 if (strcmp (klass->name_space, "System") == 0) {
1409 if (strcmp (klass->name, "Decimal") == 0)
1410 return TYPECODE_DECIMAL;
1411 else if (strcmp (klass->name, "DateTime") == 0)
1412 return TYPECODE_DATETIME;
1415 return TYPECODE_OBJECT;
1417 case MONO_TYPE_STRING:
1418 return TYPECODE_STRING;
1419 case MONO_TYPE_SZARRAY:
1420 case MONO_TYPE_ARRAY:
1421 case MONO_TYPE_OBJECT:
1423 case MONO_TYPE_MVAR:
1424 case MONO_TYPE_TYPEDBYREF:
1425 return TYPECODE_OBJECT;
1426 case MONO_TYPE_CLASS:
1428 MonoClass *klass = type->type->data.klass;
1429 if (klass->image == mono_defaults.corlib && strcmp (klass->name_space, "System") == 0) {
1430 if (strcmp (klass->name, "DBNull") == 0)
1431 return TYPECODE_DBNULL;
1434 return TYPECODE_OBJECT;
1435 case MONO_TYPE_GENERICINST:
1436 return TYPECODE_OBJECT;
1438 g_error ("type 0x%02x not handled in GetTypeCode()", t);
1443 ICALL_EXPORT guint32
1444 ves_icall_type_is_subtype_of (MonoReflectionType *type, MonoReflectionType *c, MonoBoolean check_interfaces)
1450 g_assert (type != NULL);
1452 domain = ((MonoObject *)type)->vtable->domain;
1454 if (!c) /* FIXME: dont know what do do here */
1457 klass = mono_class_from_mono_type (type->type);
1458 klassc = mono_class_from_mono_type (c->type);
1460 /* Interface check requires a more complex setup so we
1461 * only do for them. Otherwise we simply avoid mono_class_init.
1463 if (check_interfaces) {
1464 mono_class_init_or_throw (klass);
1465 mono_class_init_or_throw (klassc);
1466 } else if (!klass->supertypes || !klassc->supertypes) {
1467 mono_class_setup_supertypes (klass);
1468 mono_class_setup_supertypes (klassc);
1471 if (type->type->byref)
1472 return klassc == mono_defaults.object_class;
1474 return mono_class_is_subclass_of (klass, klassc, check_interfaces);
1478 mono_type_is_primitive (MonoType *type)
1480 return (type->type >= MONO_TYPE_BOOLEAN && type->type <= MONO_TYPE_R8) ||
1481 type-> type == MONO_TYPE_I || type->type == MONO_TYPE_U;
1485 mono_type_get_underlying_type_ignore_byref (MonoType *type)
1487 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
1488 return mono_class_enum_basetype (type->data.klass);
1489 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
1490 return mono_class_enum_basetype (type->data.generic_class->container_class);
1494 ICALL_EXPORT guint32
1495 ves_icall_type_is_assignable_from (MonoReflectionType *type, MonoReflectionType *c)
1501 g_assert (type != NULL);
1503 domain = ((MonoObject *)type)->vtable->domain;
1505 klass = mono_class_from_mono_type (type->type);
1506 klassc = mono_class_from_mono_type (c->type);
1508 if (type->type->byref ^ c->type->byref)
1511 if (type->type->byref) {
1512 MonoType *t = mono_type_get_underlying_type_ignore_byref (type->type);
1513 MonoType *ot = mono_type_get_underlying_type_ignore_byref (c->type);
1515 klass = mono_class_from_mono_type (t);
1516 klassc = mono_class_from_mono_type (ot);
1518 if (mono_type_is_primitive (t)) {
1519 return mono_type_is_primitive (ot) && klass->instance_size == klassc->instance_size;
1520 } else if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) {
1521 return t->type == ot->type && t->data.generic_param->num == ot->data.generic_param->num;
1522 } else if (t->type == MONO_TYPE_PTR || t->type == MONO_TYPE_FNPTR) {
1523 return t->type == ot->type;
1525 if (ot->type == MONO_TYPE_VAR || ot->type == MONO_TYPE_MVAR)
1528 if (klass->valuetype)
1529 return klass == klassc;
1530 return klass->valuetype == klassc->valuetype;
1533 return mono_class_is_assignable_from (klass, klassc);
1536 ICALL_EXPORT guint32
1537 ves_icall_type_IsInstanceOfType (MonoReflectionType *type, MonoObject *obj)
1539 MonoClass *klass = mono_class_from_mono_type (type->type);
1540 mono_class_init_or_throw (klass);
1541 return mono_object_isinst (obj, klass) != NULL;
1544 ICALL_EXPORT guint32
1545 ves_icall_get_attributes (MonoReflectionType *type)
1547 MonoClass *klass = mono_class_from_mono_type (type->type);
1548 return klass->flags;
1551 ICALL_EXPORT MonoReflectionMarshalAsAttribute*
1552 ves_icall_System_Reflection_FieldInfo_get_marshal_info (MonoReflectionField *field)
1554 MonoClass *klass = field->field->parent;
1555 MonoMarshalType *info;
1559 if (klass->generic_container ||
1560 (klass->generic_class && klass->generic_class->context.class_inst->is_open))
1563 ftype = mono_field_get_type (field->field);
1564 if (ftype && !(ftype->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL))
1567 info = mono_marshal_load_type_info (klass);
1569 for (i = 0; i < info->num_fields; ++i) {
1570 if (info->fields [i].field == field->field) {
1571 if (!info->fields [i].mspec)
1574 return mono_reflection_marshal_as_attribute_from_marshal_spec (field->object.vtable->domain, klass, info->fields [i].mspec);
1581 ICALL_EXPORT MonoReflectionField*
1582 ves_icall_System_Reflection_FieldInfo_internal_from_handle_type (MonoClassField *handle, MonoType *type)
1584 gboolean found = FALSE;
1591 klass = handle->parent;
1593 klass = mono_class_from_mono_type (type);
1595 /* Check that the field belongs to the class */
1596 for (k = klass; k; k = k->parent) {
1597 if (k == handle->parent) {
1604 /* The managed code will throw the exception */
1608 return mono_field_get_object (mono_domain_get (), klass, handle);
1611 ICALL_EXPORT MonoArray*
1612 ves_icall_System_Reflection_FieldInfo_GetTypeModifiers (MonoReflectionField *field, MonoBoolean optional)
1615 MonoType *type = mono_field_get_type_checked (field->field, &error);
1616 mono_error_raise_exception (&error);
1618 return type_array_from_modifiers (field->field->parent->image, type, optional);
1622 vell_icall_get_method_attributes (MonoMethod *method)
1624 return method->flags;
1628 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info)
1631 MonoDomain *domain = mono_domain_get ();
1632 MonoMethodSignature* sig;
1634 sig = mono_method_signature_checked (method, &error);
1635 if (!mono_error_ok (&error))
1636 mono_error_raise_exception (&error);
1639 MONO_STRUCT_SETREF (info, parent, mono_type_get_object (domain, &method->klass->byval_arg));
1640 MONO_STRUCT_SETREF (info, ret, mono_type_get_object (domain, sig->ret));
1641 info->attrs = method->flags;
1642 info->implattrs = method->iflags;
1643 if (sig->call_convention == MONO_CALL_DEFAULT)
1644 info->callconv = sig->sentinelpos >= 0 ? 2 : 1;
1646 if (sig->call_convention == MONO_CALL_VARARG || sig->sentinelpos >= 0)
1651 info->callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6);
1654 ICALL_EXPORT MonoArray*
1655 ves_icall_get_parameter_info (MonoMethod *method, MonoReflectionMethod *member)
1657 MonoDomain *domain = mono_domain_get ();
1659 return mono_param_get_objects_internal (domain, method, member->reftype ? mono_class_from_mono_type (member->reftype->type) : NULL);
1662 ICALL_EXPORT MonoReflectionMarshalAsAttribute*
1663 ves_icall_System_MonoMethodInfo_get_retval_marshal (MonoMethod *method)
1665 MonoDomain *domain = mono_domain_get ();
1666 MonoReflectionMarshalAsAttribute* res = NULL;
1667 MonoMarshalSpec **mspecs;
1670 mspecs = g_new (MonoMarshalSpec*, mono_method_signature (method)->param_count + 1);
1671 mono_method_get_marshal_info (method, mspecs);
1674 res = mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [0]);
1676 for (i = mono_method_signature (method)->param_count; i >= 0; i--)
1678 mono_metadata_free_marshal_spec (mspecs [i]);
1685 ves_icall_MonoField_GetFieldOffset (MonoReflectionField *field)
1687 MonoClass *parent = field->field->parent;
1688 if (!parent->size_inited)
1689 mono_class_init (parent);
1690 mono_class_setup_fields_locking (parent);
1692 return field->field->offset - sizeof (MonoObject);
1695 ICALL_EXPORT MonoReflectionType*
1696 ves_icall_MonoField_GetParentType (MonoReflectionField *field, MonoBoolean declaring)
1700 parent = declaring? field->field->parent: field->klass;
1702 return mono_type_get_object (mono_object_domain (field), &parent->byval_arg);
1705 ICALL_EXPORT MonoObject *
1706 ves_icall_MonoField_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
1708 MonoClass *fklass = field->klass;
1709 MonoClassField *cf = field->field;
1710 MonoDomain *domain = mono_object_domain (field);
1712 if (fklass->image->assembly->ref_only)
1713 mono_raise_exception (mono_get_exception_invalid_operation (
1714 "It is illegal to get the value on a field on a type loaded using the ReflectionOnly methods."));
1716 if (mono_security_core_clr_enabled ())
1717 mono_security_core_clr_ensure_reflection_access_field (cf);
1719 return mono_field_get_value_object (domain, cf, obj);
1723 ves_icall_MonoField_SetValueInternal (MonoReflectionField *field, MonoObject *obj, MonoObject *value)
1726 MonoClassField *cf = field->field;
1730 if (field->klass->image->assembly->ref_only)
1731 mono_raise_exception (mono_get_exception_invalid_operation (
1732 "It is illegal to set the value on a field on a type loaded using the ReflectionOnly methods."));
1734 if (mono_security_core_clr_enabled ())
1735 mono_security_core_clr_ensure_reflection_access_field (cf);
1737 type = mono_field_get_type_checked (cf, &error);
1738 if (!mono_error_ok (&error))
1739 mono_error_raise_exception (&error);
1741 v = (gchar *) value;
1743 switch (type->type) {
1746 case MONO_TYPE_BOOLEAN:
1749 case MONO_TYPE_CHAR:
1758 case MONO_TYPE_VALUETYPE:
1761 v += sizeof (MonoObject);
1763 case MONO_TYPE_STRING:
1764 case MONO_TYPE_OBJECT:
1765 case MONO_TYPE_CLASS:
1766 case MONO_TYPE_ARRAY:
1767 case MONO_TYPE_SZARRAY:
1770 case MONO_TYPE_GENERICINST: {
1771 MonoGenericClass *gclass = type->data.generic_class;
1772 g_assert (!gclass->context.class_inst->is_open);
1774 if (mono_class_is_nullable (mono_class_from_mono_type (type))) {
1775 MonoClass *nklass = mono_class_from_mono_type (type);
1776 MonoObject *nullable;
1779 * Convert the boxed vtype into a Nullable structure.
1780 * This is complicated by the fact that Nullables have
1781 * a variable structure.
1783 nullable = mono_object_new (mono_domain_get (), nklass);
1785 mono_nullable_init (mono_object_unbox (nullable), value, nklass);
1787 v = mono_object_unbox (nullable);
1790 if (gclass->container_class->valuetype && (v != NULL))
1791 v += sizeof (MonoObject);
1795 g_error ("type 0x%x not handled in "
1796 "ves_icall_FieldInfo_SetValueInternal", type->type);
1801 if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
1802 MonoVTable *vtable = mono_class_vtable_full (mono_object_domain (field), cf->parent, TRUE);
1803 if (!vtable->initialized)
1804 mono_runtime_class_init (vtable);
1805 mono_field_static_set_value (vtable, cf, v);
1807 mono_field_set_value (obj, cf, v);
1811 ICALL_EXPORT MonoObject *
1812 ves_icall_MonoField_GetRawConstantValue (MonoReflectionField *this)
1814 MonoObject *o = NULL;
1815 MonoClassField *field = this->field;
1817 MonoDomain *domain = mono_object_domain (this);
1819 MonoTypeEnum def_type;
1820 const char *def_value;
1824 mono_class_init (field->parent);
1826 t = mono_field_get_type_checked (field, &error);
1827 if (!mono_error_ok (&error))
1828 mono_error_raise_exception (&error);
1830 if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT))
1831 mono_raise_exception (mono_get_exception_invalid_operation (NULL));
1833 if (image_is_dynamic (field->parent->image)) {
1834 MonoClass *klass = field->parent;
1835 int fidx = field - klass->fields;
1837 g_assert (fidx >= 0 && fidx < klass->field.count);
1838 g_assert (klass->ext);
1839 g_assert (klass->ext->field_def_values);
1840 def_type = klass->ext->field_def_values [fidx].def_type;
1841 def_value = klass->ext->field_def_values [fidx].data;
1842 if (def_type == MONO_TYPE_END)
1843 mono_raise_exception (mono_get_exception_invalid_operation (NULL));
1845 def_value = mono_class_get_field_default_value (field, &def_type);
1846 /* FIXME, maybe we should try to raise TLE if field->parent is broken */
1848 mono_raise_exception (mono_get_exception_invalid_operation (NULL));
1851 /*FIXME unify this with reflection.c:mono_get_object_from_blob*/
1855 case MONO_TYPE_BOOLEAN:
1858 case MONO_TYPE_CHAR:
1866 case MONO_TYPE_R8: {
1869 /* boxed value type */
1870 t = g_new0 (MonoType, 1);
1872 klass = mono_class_from_mono_type (t);
1874 o = mono_object_new (domain, klass);
1875 v = ((gchar *) o) + sizeof (MonoObject);
1876 mono_get_constant_value_from_blob (domain, def_type, def_value, v);
1879 case MONO_TYPE_STRING:
1880 case MONO_TYPE_CLASS:
1881 mono_get_constant_value_from_blob (domain, def_type, def_value, &o);
1884 g_assert_not_reached ();
1890 ICALL_EXPORT MonoReflectionType*
1891 ves_icall_MonoField_ResolveType (MonoReflectionField *ref_field)
1894 MonoClassField *field = ref_field->field;
1895 MonoType *type = mono_field_get_type_checked (field, &error);
1896 if (!mono_error_ok (&error))
1897 mono_error_raise_exception (&error);
1898 return mono_type_get_object (mono_object_domain (ref_field), type);
1901 ICALL_EXPORT MonoReflectionType*
1902 ves_icall_MonoGenericMethod_get_ReflectedType (MonoReflectionGenericMethod *rmethod)
1904 MonoMethod *method = rmethod->method.method;
1906 return mono_type_get_object (mono_object_domain (rmethod), &method->klass->byval_arg);
1909 /* From MonoProperty.cs */
1911 PInfo_Attributes = 1,
1912 PInfo_GetMethod = 1 << 1,
1913 PInfo_SetMethod = 1 << 2,
1914 PInfo_ReflectedType = 1 << 3,
1915 PInfo_DeclaringType = 1 << 4,
1920 ves_icall_get_property_info (MonoReflectionProperty *property, MonoPropertyInfo *info, PInfo req_info)
1922 MonoDomain *domain = mono_object_domain (property);
1924 if ((req_info & PInfo_ReflectedType) != 0)
1925 MONO_STRUCT_SETREF (info, parent, mono_type_get_object (domain, &property->klass->byval_arg));
1926 if ((req_info & PInfo_DeclaringType) != 0)
1927 MONO_STRUCT_SETREF (info, declaring_type, mono_type_get_object (domain, &property->property->parent->byval_arg));
1929 if ((req_info & PInfo_Name) != 0)
1930 MONO_STRUCT_SETREF (info, name, mono_string_new (domain, property->property->name));
1932 if ((req_info & PInfo_Attributes) != 0)
1933 info->attrs = property->property->attrs;
1935 if ((req_info & PInfo_GetMethod) != 0)
1936 MONO_STRUCT_SETREF (info, get, property->property->get ?
1937 mono_method_get_object (domain, property->property->get, property->klass): NULL);
1939 if ((req_info & PInfo_SetMethod) != 0)
1940 MONO_STRUCT_SETREF (info, set, property->property->set ?
1941 mono_method_get_object (domain, property->property->set, property->klass): NULL);
1943 * There may be other methods defined for properties, though, it seems they are not exposed
1944 * in the reflection API
1949 ves_icall_get_event_info (MonoReflectionMonoEvent *event, MonoEventInfo *info)
1951 MonoDomain *domain = mono_object_domain (event);
1953 MONO_STRUCT_SETREF (info, reflected_type, mono_type_get_object (domain, &event->klass->byval_arg));
1954 MONO_STRUCT_SETREF (info, declaring_type, mono_type_get_object (domain, &event->event->parent->byval_arg));
1956 MONO_STRUCT_SETREF (info, name, mono_string_new (domain, event->event->name));
1957 info->attrs = event->event->attrs;
1958 MONO_STRUCT_SETREF (info, add_method, event->event->add ? mono_method_get_object (domain, event->event->add, NULL): NULL);
1959 MONO_STRUCT_SETREF (info, remove_method, event->event->remove ? mono_method_get_object (domain, event->event->remove, NULL): NULL);
1960 MONO_STRUCT_SETREF (info, raise_method, event->event->raise ? mono_method_get_object (domain, event->event->raise, NULL): NULL);
1962 #ifndef MONO_SMALL_CONFIG
1963 if (event->event->other) {
1965 while (event->event->other [n])
1967 MONO_STRUCT_SETREF (info, other_methods, mono_array_new (domain, mono_defaults.method_info_class, n));
1969 for (i = 0; i < n; i++)
1970 mono_array_setref (info->other_methods, i, mono_method_get_object (domain, event->event->other [i], NULL));
1976 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
1981 mono_class_setup_interfaces (klass, error);
1982 if (!mono_error_ok (error))
1985 for (i = 0; i < klass->interface_count; i++) {
1986 ic = klass->interfaces [i];
1987 g_hash_table_insert (ifaces, ic, ic);
1989 collect_interfaces (ic, ifaces, error);
1990 if (!mono_error_ok (error))
1996 MonoArray *iface_array;
1997 MonoGenericContext *context;
2001 } FillIfaceArrayData;
2004 fill_iface_array (gpointer key, gpointer value, gpointer user_data)
2006 FillIfaceArrayData *data = user_data;
2007 MonoClass *ic = key;
2008 MonoType *ret = &ic->byval_arg, *inflated = NULL;
2010 if (!mono_error_ok (data->error))
2013 if (data->context && ic->generic_class && ic->generic_class->context.class_inst->is_open) {
2014 inflated = ret = mono_class_inflate_generic_type_checked (ret, data->context, data->error);
2015 if (!mono_error_ok (data->error))
2019 mono_array_setref (data->iface_array, data->next_idx++, mono_type_get_object (data->domain, ret));
2022 mono_metadata_free_type (inflated);
2025 ICALL_EXPORT MonoArray*
2026 ves_icall_Type_GetInterfaces (MonoReflectionType* type)
2029 MonoClass *class = mono_class_from_mono_type (type->type);
2031 FillIfaceArrayData data = { 0 };
2034 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
2036 if (class->generic_class && class->generic_class->context.class_inst->is_open) {
2037 data.context = mono_class_get_context (class);
2038 class = class->generic_class->container_class;
2041 for (parent = class; parent; parent = parent->parent) {
2042 mono_class_setup_interfaces (parent, &error);
2043 if (!mono_error_ok (&error))
2045 collect_interfaces (parent, iface_hash, &error);
2046 if (!mono_error_ok (&error))
2050 data.error = &error;
2051 data.domain = mono_object_domain (type);
2053 len = g_hash_table_size (iface_hash);
2055 g_hash_table_destroy (iface_hash);
2056 if (!data.domain->empty_types)
2057 data.domain->empty_types = mono_array_new_cached (data.domain, mono_defaults.monotype_class, 0);
2058 return data.domain->empty_types;
2061 data.iface_array = mono_array_new_cached (data.domain, mono_defaults.monotype_class, len);
2062 g_hash_table_foreach (iface_hash, fill_iface_array, &data);
2063 if (!mono_error_ok (&error))
2066 g_hash_table_destroy (iface_hash);
2067 return data.iface_array;
2070 g_hash_table_destroy (iface_hash);
2071 mono_error_raise_exception (&error);
2076 ves_icall_Type_GetInterfaceMapData (MonoReflectionType *type, MonoReflectionType *iface, MonoArray **targets, MonoArray **methods)
2078 gboolean variance_used;
2079 MonoClass *class = mono_class_from_mono_type (type->type);
2080 MonoClass *iclass = mono_class_from_mono_type (iface->type);
2081 MonoReflectionMethod *member;
2084 int i = 0, len, ioffset;
2087 mono_class_init_or_throw (class);
2088 mono_class_init_or_throw (iclass);
2090 mono_class_setup_vtable (class);
2092 ioffset = mono_class_interface_offset_with_variance (class, iclass, &variance_used);
2096 len = mono_class_num_methods (iclass);
2097 domain = mono_object_domain (type);
2098 mono_gc_wbarrier_generic_store (targets, (MonoObject*) mono_array_new (domain, mono_defaults.method_info_class, len));
2099 mono_gc_wbarrier_generic_store (methods, (MonoObject*) mono_array_new (domain, mono_defaults.method_info_class, len));
2101 while ((method = mono_class_get_methods (iclass, &iter))) {
2102 member = mono_method_get_object (domain, method, iclass);
2103 mono_array_setref (*methods, i, member);
2104 member = mono_method_get_object (domain, class->vtable [i + ioffset], class);
2105 mono_array_setref (*targets, i, member);
2112 ves_icall_Type_GetPacking (MonoReflectionType *type, guint32 *packing, guint32 *size)
2114 MonoClass *klass = mono_class_from_mono_type (type->type);
2115 mono_class_init_or_throw (klass);
2117 if (image_is_dynamic (klass->image)) {
2118 MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)type;
2119 *packing = tb->packing_size;
2120 *size = tb->class_size;
2122 mono_metadata_packing_from_typedef (klass->image, klass->type_token, packing, size);
2126 ICALL_EXPORT MonoReflectionType*
2127 ves_icall_MonoType_GetElementType (MonoReflectionType *type)
2131 if (!type->type->byref && type->type->type == MONO_TYPE_SZARRAY)
2132 return mono_type_get_object (mono_object_domain (type), &type->type->data.klass->byval_arg);
2134 class = mono_class_from_mono_type (type->type);
2135 mono_class_init_or_throw (class);
2137 // GetElementType should only return a type for:
2138 // Array Pointer PassedByRef
2139 if (type->type->byref)
2140 return mono_type_get_object (mono_object_domain (type), &class->byval_arg);
2141 else if (class->element_class && MONO_CLASS_IS_ARRAY (class))
2142 return mono_type_get_object (mono_object_domain (type), &class->element_class->byval_arg);
2143 else if (class->element_class && type->type->type == MONO_TYPE_PTR)
2144 return mono_type_get_object (mono_object_domain (type), &class->element_class->byval_arg);
2149 ICALL_EXPORT MonoReflectionType*
2150 ves_icall_get_type_parent (MonoReflectionType *type)
2152 MonoClass *class = mono_class_from_mono_type (type->type);
2153 return class->parent ? mono_type_get_object (mono_object_domain (type), &class->parent->byval_arg): NULL;
2156 ICALL_EXPORT MonoBoolean
2157 ves_icall_type_ispointer (MonoReflectionType *type)
2159 return type->type->type == MONO_TYPE_PTR;
2162 ICALL_EXPORT MonoBoolean
2163 ves_icall_type_isprimitive (MonoReflectionType *type)
2165 return (!type->type->byref && (((type->type->type >= MONO_TYPE_BOOLEAN) && (type->type->type <= MONO_TYPE_R8)) || (type->type->type == MONO_TYPE_I) || (type->type->type == MONO_TYPE_U)));
2168 ICALL_EXPORT MonoBoolean
2169 ves_icall_type_isbyref (MonoReflectionType *type)
2171 return type->type->byref;
2174 ICALL_EXPORT MonoBoolean
2175 ves_icall_type_iscomobject (MonoReflectionType *type)
2177 MonoClass *klass = mono_class_from_mono_type (type->type);
2178 mono_class_init_or_throw (klass);
2180 return mono_class_is_com_object (klass);
2183 ICALL_EXPORT MonoReflectionModule*
2184 ves_icall_MonoType_get_Module (MonoReflectionType *type)
2186 MonoClass *class = mono_class_from_mono_type (type->type);
2187 return mono_module_get_object (mono_object_domain (type), class->image);
2190 ICALL_EXPORT MonoReflectionAssembly*
2191 ves_icall_MonoType_get_Assembly (MonoReflectionType *type)
2193 MonoDomain *domain = mono_domain_get ();
2194 MonoClass *class = mono_class_from_mono_type (type->type);
2195 return mono_assembly_get_object (domain, class->image->assembly);
2198 ICALL_EXPORT MonoReflectionType*
2199 ves_icall_MonoType_get_DeclaringType (MonoReflectionType *type)
2201 MonoDomain *domain = mono_domain_get ();
2204 if (type->type->byref)
2206 if (type->type->type == MONO_TYPE_VAR) {
2207 MonoGenericContainer *param = mono_type_get_generic_param_owner (type->type);
2208 class = param ? param->owner.klass : NULL;
2209 } else if (type->type->type == MONO_TYPE_MVAR) {
2210 MonoGenericContainer *param = mono_type_get_generic_param_owner (type->type);
2211 class = param ? param->owner.method->klass : NULL;
2213 class = mono_class_from_mono_type (type->type)->nested_in;
2216 return class ? mono_type_get_object (domain, &class->byval_arg) : NULL;
2219 ICALL_EXPORT MonoString*
2220 ves_icall_MonoType_get_Name (MonoReflectionType *type)
2222 MonoDomain *domain = mono_domain_get ();
2223 MonoClass *class = mono_class_from_mono_type (type->type);
2225 if (type->type->byref) {
2226 char *n = g_strdup_printf ("%s&", class->name);
2227 MonoString *res = mono_string_new (domain, n);
2233 return mono_string_new (domain, class->name);
2237 ICALL_EXPORT MonoString*
2238 ves_icall_MonoType_get_Namespace (MonoReflectionType *type)
2240 MonoDomain *domain = mono_domain_get ();
2241 MonoClass *class = mono_class_from_mono_type (type->type);
2243 while (class->nested_in)
2244 class = class->nested_in;
2246 if (class->name_space [0] == '\0')
2249 return mono_string_new (domain, class->name_space);
2253 ves_icall_MonoType_GetArrayRank (MonoReflectionType *type)
2257 if (type->type->type != MONO_TYPE_ARRAY && type->type->type != MONO_TYPE_SZARRAY)
2258 mono_raise_exception (mono_get_exception_argument ("type", "Type must be an array type"));
2260 class = mono_class_from_mono_type (type->type);
2265 ICALL_EXPORT MonoArray*
2266 ves_icall_MonoType_GetGenericArguments (MonoReflectionType *type)
2269 MonoClass *klass, *pklass;
2270 MonoDomain *domain = mono_object_domain (type);
2271 MonoVTable *array_vtable = mono_class_vtable_full (domain, mono_array_class_get_cached (mono_defaults.systemtype_class, 1), TRUE);
2274 klass = mono_class_from_mono_type (type->type);
2276 if (klass->generic_container) {
2277 MonoGenericContainer *container = klass->generic_container;
2278 res = mono_array_new_specific (array_vtable, container->type_argc);
2279 for (i = 0; i < container->type_argc; ++i) {
2280 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
2281 mono_array_setref (res, i, mono_type_get_object (domain, &pklass->byval_arg));
2283 } else if (klass->generic_class) {
2284 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2285 res = mono_array_new_specific (array_vtable, inst->type_argc);
2286 for (i = 0; i < inst->type_argc; ++i)
2287 mono_array_setref (res, i, mono_type_get_object (domain, inst->type_argv [i]));
2289 res = mono_array_new_specific (array_vtable, 0);
2294 ICALL_EXPORT gboolean
2295 ves_icall_Type_get_IsGenericTypeDefinition (MonoReflectionType *type)
2299 if (!IS_MONOTYPE (type))
2302 if (type->type->byref)
2305 klass = mono_class_from_mono_type (type->type);
2306 return klass->generic_container != NULL;
2309 ICALL_EXPORT MonoReflectionType*
2310 ves_icall_Type_GetGenericTypeDefinition_impl (MonoReflectionType *type)
2314 if (type->type->byref)
2317 klass = mono_class_from_mono_type (type->type);
2319 if (klass->generic_container) {
2320 return type; /* check this one */
2322 if (klass->generic_class) {
2323 MonoClass *generic_class = klass->generic_class->container_class;
2326 tb = mono_class_get_ref_info (generic_class);
2328 if (generic_class->wastypebuilder && tb)
2331 return mono_type_get_object (mono_object_domain (type), &generic_class->byval_arg);
2336 ICALL_EXPORT MonoReflectionType*
2337 ves_icall_Type_MakeGenericType (MonoReflectionType *type, MonoArray *type_array)
2340 MonoType *geninst, **types;
2343 g_assert (IS_MONOTYPE (type));
2344 mono_class_init_or_throw (mono_class_from_mono_type (type->type));
2346 count = mono_array_length (type_array);
2347 types = g_new0 (MonoType *, count);
2349 for (i = 0; i < count; i++) {
2350 MonoReflectionType *t = mono_array_get (type_array, gpointer, i);
2351 types [i] = t->type;
2354 geninst = mono_reflection_bind_generic_parameters (type, count, types);
2359 class = mono_class_from_mono_type (geninst);
2361 /*we might inflate to the GTD*/
2362 if (class->generic_class && !mono_verifier_class_is_valid_generic_instantiation (class))
2363 mono_raise_exception (mono_get_exception_argument ("typeArguments", "Invalid generic arguments"));
2365 return mono_type_get_object (mono_object_domain (type), geninst);
2368 ICALL_EXPORT gboolean
2369 ves_icall_Type_get_IsGenericInstance (MonoReflectionType *type)
2373 if (type->type->byref)
2376 klass = mono_class_from_mono_type (type->type);
2378 return klass->generic_class != NULL;
2381 ICALL_EXPORT gboolean
2382 ves_icall_Type_get_IsGenericType (MonoReflectionType *type)
2386 if (!IS_MONOTYPE (type))
2389 if (type->type->byref)
2392 klass = mono_class_from_mono_type (type->type);
2393 return klass->generic_class != NULL || klass->generic_container != NULL;
2397 ves_icall_Type_GetGenericParameterPosition (MonoReflectionType *type)
2399 if (!IS_MONOTYPE (type))
2402 if (is_generic_parameter (type->type))
2403 return mono_type_get_generic_param_num (type->type);
2407 ICALL_EXPORT GenericParameterAttributes
2408 ves_icall_Type_GetGenericParameterAttributes (MonoReflectionType *type)
2410 g_assert (IS_MONOTYPE (type));
2411 g_assert (is_generic_parameter (type->type));
2412 return mono_generic_param_info (type->type->data.generic_param)->flags;
2415 ICALL_EXPORT MonoArray *
2416 ves_icall_Type_GetGenericParameterConstraints (MonoReflectionType *type)
2418 MonoGenericParamInfo *param_info;
2424 g_assert (IS_MONOTYPE (type));
2426 domain = mono_object_domain (type);
2427 param_info = mono_generic_param_info (type->type->data.generic_param);
2428 for (count = 0, ptr = param_info->constraints; ptr && *ptr; ptr++, count++)
2431 res = mono_array_new (domain, mono_defaults.monotype_class, count);
2432 for (i = 0; i < count; i++)
2433 mono_array_setref (res, i, mono_type_get_object (domain, ¶m_info->constraints [i]->byval_arg));
2439 ICALL_EXPORT MonoBoolean
2440 ves_icall_MonoType_get_IsGenericParameter (MonoReflectionType *type)
2442 return is_generic_parameter (type->type);
2445 ICALL_EXPORT MonoBoolean
2446 ves_icall_TypeBuilder_get_IsGenericParameter (MonoReflectionTypeBuilder *tb)
2448 return is_generic_parameter (tb->type.type);
2452 ves_icall_EnumBuilder_setup_enum_type (MonoReflectionType *enumtype,
2453 MonoReflectionType *t)
2455 enumtype->type = t->type;
2458 ICALL_EXPORT MonoReflectionMethod*
2459 ves_icall_MonoType_GetCorrespondingInflatedMethod (MonoReflectionType *type,
2460 MonoReflectionMethod* generic)
2467 domain = ((MonoObject *)type)->vtable->domain;
2469 klass = mono_class_from_mono_type (type->type);
2470 mono_class_init_or_throw (klass);
2473 while ((method = mono_class_get_methods (klass, &iter))) {
2474 if (method->token == generic->method->token)
2475 return mono_method_get_object (domain, method, klass);
2483 ICALL_EXPORT MonoReflectionMethod *
2484 ves_icall_MonoType_get_DeclaringMethod (MonoReflectionType *ref_type)
2487 MonoType *type = ref_type->type;
2489 if (type->byref || (type->type != MONO_TYPE_MVAR && type->type != MONO_TYPE_VAR))
2490 mono_raise_exception (mono_get_exception_invalid_operation ("DeclaringMethod can only be used on generic arguments"));
2491 if (type->type == MONO_TYPE_VAR)
2494 method = mono_type_get_generic_param_owner (type)->owner.method;
2496 return mono_method_get_object (mono_object_domain (ref_type), method, method->klass);
2499 ICALL_EXPORT MonoReflectionDllImportAttribute*
2500 ves_icall_MonoMethod_GetDllImportAttribute (MonoMethod *method)
2502 static MonoClass *DllImportAttributeClass = NULL;
2503 MonoDomain *domain = mono_domain_get ();
2504 MonoReflectionDllImportAttribute *attr;
2505 MonoImage *image = method->klass->image;
2506 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
2507 MonoTableInfo *tables = image->tables;
2508 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
2509 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
2510 guint32 im_cols [MONO_IMPLMAP_SIZE];
2511 guint32 scope_token;
2512 const char *import = NULL;
2513 const char *scope = NULL;
2516 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2519 if (!DllImportAttributeClass) {
2520 DllImportAttributeClass =
2521 mono_class_from_name (mono_defaults.corlib,
2522 "System.Runtime.InteropServices", "DllImportAttribute");
2523 g_assert (DllImportAttributeClass);
2526 if (image_is_dynamic (method->klass->image)) {
2527 MonoReflectionMethodAux *method_aux =
2528 g_hash_table_lookup (
2529 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2531 import = method_aux->dllentry;
2532 scope = method_aux->dll;
2535 if (!import || !scope) {
2536 mono_raise_exception (mono_get_exception_argument ("method", "System.Reflection.Emit method with invalid pinvoke information"));
2541 if (piinfo->implmap_idx) {
2542 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
2544 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
2545 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
2546 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
2547 scope = mono_metadata_string_heap (image, scope_token);
2550 flags = piinfo->piflags;
2552 attr = (MonoReflectionDllImportAttribute*)mono_object_new (domain, DllImportAttributeClass);
2554 MONO_OBJECT_SETREF (attr, dll, mono_string_new (domain, scope));
2555 MONO_OBJECT_SETREF (attr, entry_point, mono_string_new (domain, import));
2556 attr->call_conv = (flags & 0x700) >> 8;
2557 attr->charset = ((flags & 0x6) >> 1) + 1;
2558 if (attr->charset == 1)
2560 attr->exact_spelling = (flags & 0x1) != 0;
2561 attr->set_last_error = (flags & 0x40) != 0;
2562 attr->best_fit_mapping = (flags & 0x30) == 0x10;
2563 attr->throw_on_unmappable = (flags & 0x3000) == 0x1000;
2564 attr->preserve_sig = FALSE;
2569 ICALL_EXPORT MonoReflectionMethod *
2570 ves_icall_MonoMethod_GetGenericMethodDefinition (MonoReflectionMethod *method)
2572 MonoMethodInflated *imethod;
2575 if (method->method->is_generic)
2578 if (!method->method->is_inflated)
2581 imethod = (MonoMethodInflated *) method->method;
2583 result = imethod->declaring;
2584 /* Not a generic method. */
2585 if (!result->is_generic)
2588 if (image_is_dynamic (method->method->klass->image)) {
2589 MonoDynamicImage *image = (MonoDynamicImage*)method->method->klass->image;
2590 MonoReflectionMethod *res;
2593 * FIXME: Why is this stuff needed at all ? Why can't the code below work for
2594 * the dynamic case as well ?
2596 mono_image_lock ((MonoImage*)image);
2597 res = mono_g_hash_table_lookup (image->generic_def_objects, imethod);
2598 mono_image_unlock ((MonoImage*)image);
2604 if (imethod->context.class_inst) {
2605 MonoClass *klass = ((MonoMethod *) imethod)->klass;
2606 /*Generic methods gets the context of the GTD.*/
2607 if (mono_class_get_context (klass)) {
2609 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
2610 mono_error_raise_exception (&error);
2614 return mono_method_get_object (mono_object_domain (method), result, NULL);
2617 ICALL_EXPORT gboolean
2618 ves_icall_MonoMethod_get_IsGenericMethod (MonoReflectionMethod *method)
2620 return mono_method_signature (method->method)->generic_param_count != 0;
2623 ICALL_EXPORT gboolean
2624 ves_icall_MonoMethod_get_IsGenericMethodDefinition (MonoReflectionMethod *method)
2626 return method->method->is_generic;
2629 ICALL_EXPORT MonoArray*
2630 ves_icall_MonoMethod_GetGenericArguments (MonoReflectionMethod *method)
2636 domain = mono_object_domain (method);
2638 if (method->method->is_inflated) {
2639 MonoGenericInst *inst = mono_method_get_context (method->method)->method_inst;
2642 count = inst->type_argc;
2643 res = mono_array_new (domain, mono_defaults.systemtype_class, count);
2645 for (i = 0; i < count; i++)
2646 mono_array_setref (res, i, mono_type_get_object (domain, inst->type_argv [i]));
2652 count = mono_method_signature (method->method)->generic_param_count;
2653 res = mono_array_new (domain, mono_defaults.systemtype_class, count);
2655 for (i = 0; i < count; i++) {
2656 MonoGenericContainer *container = mono_method_get_generic_container (method->method);
2657 MonoGenericParam *param = mono_generic_container_get_param (container, i);
2658 MonoClass *pklass = mono_class_from_generic_parameter (
2659 param, method->method->klass->image, TRUE);
2660 mono_array_setref (res, i,
2661 mono_type_get_object (domain, &pklass->byval_arg));
2667 ICALL_EXPORT MonoObject *
2668 ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this, MonoArray *params, MonoException **exc)
2671 * Invoke from reflection is supposed to always be a virtual call (the API
2672 * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
2673 * greater flexibility.
2675 MonoMethod *m = method->method;
2676 MonoMethodSignature *sig = mono_method_signature (m);
2683 if (mono_security_core_clr_enabled ())
2684 mono_security_core_clr_ensure_reflection_access_method (m);
2686 if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
2687 if (!mono_class_vtable_full (mono_object_domain (method), m->klass, FALSE)) {
2688 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_class_get_exception_for_failure (m->klass));
2693 if (!mono_object_isinst (this, m->klass)) {
2694 char *this_name = mono_type_get_full_name (mono_object_get_class (this));
2695 char *target_name = mono_type_get_full_name (m->klass);
2696 char *msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
2697 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", msg));
2699 g_free (target_name);
2703 m = mono_object_get_virtual_method (this, m);
2704 /* must pass the pointer to the value for valuetype methods */
2705 if (m->klass->valuetype)
2706 obj = mono_object_unbox (this);
2707 } else if (strcmp (m->name, ".ctor") && !m->wrapper_type) {
2708 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Non-static method requires a target."));
2713 if (sig->ret->byref) {
2714 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method returning ByRef type via reflection"));
2718 pcount = params? mono_array_length (params): 0;
2719 if (pcount != sig->param_count) {
2720 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetParameterCountException"));
2724 if ((m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT) && !strcmp (m->name, ".ctor") && !this) {
2725 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Cannot invoke constructor of an abstract class."));
2729 image = m->klass->image;
2730 if (image->assembly->ref_only) {
2731 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_get_exception_invalid_operation ("It is illegal to invoke a method on a type loaded using the ReflectionOnly api."));
2735 if (image_is_dynamic (image) && !((MonoDynamicImage*)image)->run) {
2736 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_get_exception_not_supported ("Cannot invoke a method in a dynamic assembly without run access."));
2740 if (m->klass->rank && !strcmp (m->name, ".ctor")) {
2743 intptr_t *lower_bounds;
2744 pcount = mono_array_length (params);
2745 lengths = alloca (sizeof (uintptr_t) * pcount);
2746 /* Note: the synthetized array .ctors have int32 as argument type */
2747 for (i = 0; i < pcount; ++i)
2748 lengths [i] = *(int32_t*) ((char*)mono_array_get (params, gpointer, i) + sizeof (MonoObject));
2750 if (m->klass->rank == 1 && sig->param_count == 2 && m->klass->element_class->rank) {
2751 /* This is a ctor for jagged arrays. MS creates an array of arrays. */
2752 MonoArray *arr = mono_array_new_full (mono_object_domain (params), m->klass, lengths, NULL);
2754 for (i = 0; i < mono_array_length (arr); ++i) {
2755 MonoArray *subarray = mono_array_new_full (mono_object_domain (params), m->klass->element_class, &lengths [1], NULL);
2757 mono_array_setref_fast (arr, i, subarray);
2759 return (MonoObject*)arr;
2762 if (m->klass->rank == pcount) {
2763 /* Only lengths provided. */
2764 lower_bounds = NULL;
2766 g_assert (pcount == (m->klass->rank * 2));
2767 /* lower bounds are first. */
2768 lower_bounds = (intptr_t*)lengths;
2769 lengths += m->klass->rank;
2772 return (MonoObject*)mono_array_new_full (mono_object_domain (params), m->klass, lengths, lower_bounds);
2774 return mono_runtime_invoke_array (m, obj, params, NULL);
2777 #ifndef DISABLE_REMOTING
2778 ICALL_EXPORT MonoObject *
2779 ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this, MonoArray *params, MonoArray **outArgs)
2781 MonoDomain *domain = mono_object_domain (method);
2782 MonoMethod *m = method->method;
2783 MonoMethodSignature *sig = mono_method_signature (m);
2784 MonoArray *out_args;
2786 int i, j, outarg_count = 0;
2788 if (m->klass == mono_defaults.object_class) {
2789 if (!strcmp (m->name, "FieldGetter")) {
2790 MonoClass *k = this->vtable->klass;
2794 /* If this is a proxy, then it must be a CBO */
2795 if (k == mono_defaults.transparent_proxy_class) {
2796 MonoTransparentProxy *tp = (MonoTransparentProxy*) this;
2797 this = tp->rp->unwrapped_server;
2799 k = this->vtable->klass;
2802 name = mono_array_get (params, MonoString *, 1);
2803 str = mono_string_to_utf8 (name);
2806 MonoClassField* field = mono_class_get_field_from_name (k, str);
2808 MonoClass *field_klass = mono_class_from_mono_type (field->type);
2809 if (field_klass->valuetype)
2810 result = mono_value_box (domain, field_klass, (char *)this + field->offset);
2812 result = *((gpointer *)((char *)this + field->offset));
2814 out_args = mono_array_new (domain, mono_defaults.object_class, 1);
2815 mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
2816 mono_array_setref (out_args, 0, result);
2824 g_assert_not_reached ();
2826 } else if (!strcmp (m->name, "FieldSetter")) {
2827 MonoClass *k = this->vtable->klass;
2833 /* If this is a proxy, then it must be a CBO */
2834 if (k == mono_defaults.transparent_proxy_class) {
2835 MonoTransparentProxy *tp = (MonoTransparentProxy*) this;
2836 this = tp->rp->unwrapped_server;
2838 k = this->vtable->klass;
2841 name = mono_array_get (params, MonoString *, 1);
2842 str = mono_string_to_utf8 (name);
2845 MonoClassField* field = mono_class_get_field_from_name (k, str);
2847 MonoClass *field_klass = mono_class_from_mono_type (field->type);
2848 MonoObject *val = mono_array_get (params, gpointer, 2);
2850 if (field_klass->valuetype) {
2851 size = mono_type_size (field->type, &align);
2852 g_assert (size == mono_class_value_size (field_klass, NULL));
2853 mono_gc_wbarrier_value_copy ((char *)this + field->offset, (char*)val + sizeof (MonoObject), 1, field_klass);
2855 mono_gc_wbarrier_set_field (this, (char*)this + field->offset, val);
2858 out_args = mono_array_new (domain, mono_defaults.object_class, 0);
2859 mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
2869 g_assert_not_reached ();
2874 for (i = 0; i < mono_array_length (params); i++) {
2875 if (sig->params [i]->byref)
2879 out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
2881 /* handle constructors only for objects already allocated */
2882 if (!strcmp (method->method->name, ".ctor"))
2885 /* This can be called only on MBR objects, so no need to unbox for valuetypes. */
2886 g_assert (!method->method->klass->valuetype);
2887 result = mono_runtime_invoke_array (method->method, this, params, NULL);
2889 for (i = 0, j = 0; i < mono_array_length (params); i++) {
2890 if (sig->params [i]->byref) {
2892 arg = mono_array_get (params, gpointer, i);
2893 mono_array_setref (out_args, j, arg);
2898 mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
2905 read_enum_value (char *mem, int type)
2908 case MONO_TYPE_BOOLEAN:
2910 return *(guint8*)mem;
2912 return *(gint8*)mem;
2913 case MONO_TYPE_CHAR:
2915 return *(guint16*)mem;
2917 return *(gint16*)mem;
2919 return *(guint32*)mem;
2921 return *(gint32*)mem;
2923 return *(guint64*)mem;
2925 return *(gint64*)mem;
2927 g_assert_not_reached ();
2933 write_enum_value (char *mem, int type, guint64 value)
2937 case MONO_TYPE_I1: {
2938 guint8 *p = (guint8*)mem;
2943 case MONO_TYPE_I2: {
2944 guint16 *p = (void*)mem;
2949 case MONO_TYPE_I4: {
2950 guint32 *p = (void*)mem;
2955 case MONO_TYPE_I8: {
2956 guint64 *p = (void*)mem;
2961 g_assert_not_reached ();
2966 ICALL_EXPORT MonoObject *
2967 ves_icall_System_Enum_ToObject (MonoReflectionType *enumType, MonoObject *value)
2970 MonoClass *enumc, *objc;
2975 MONO_CHECK_ARG_NULL (enumType);
2976 MONO_CHECK_ARG_NULL (value);
2978 domain = mono_object_domain (enumType);
2979 enumc = mono_class_from_mono_type (enumType->type);
2981 mono_class_init_or_throw (enumc);
2983 objc = value->vtable->klass;
2985 if (!enumc->enumtype)
2986 mono_raise_exception (mono_get_exception_argument ("enumType", "Type provided must be an Enum."));
2987 if (!((objc->enumtype) || (objc->byval_arg.type >= MONO_TYPE_BOOLEAN && objc->byval_arg.type <= MONO_TYPE_U8)))
2988 mono_raise_exception (mono_get_exception_argument ("value", "The value passed in must be an enum base or an underlying type for an enum, such as an Int32."));
2990 etype = mono_class_enum_basetype (enumc);
2992 /* MS throws this for typebuilders */
2993 mono_raise_exception (mono_get_exception_argument ("Type must be a type provided by the runtime.", "enumType"));
2995 res = mono_object_new (domain, enumc);
2996 val = read_enum_value ((char *)value + sizeof (MonoObject), objc->enumtype? mono_class_enum_basetype (objc)->type: objc->byval_arg.type);
2997 write_enum_value ((char *)res + sizeof (MonoObject), etype->type, val);
3002 ICALL_EXPORT MonoBoolean
3003 ves_icall_System_Enum_InternalHasFlag (MonoObject *a, MonoObject *b)
3005 int size = mono_class_value_size (a->vtable->klass, NULL);
3006 guint64 a_val = 0, b_val = 0;
3008 memcpy (&a_val, mono_object_unbox (a), size);
3009 memcpy (&b_val, mono_object_unbox (b), size);
3011 return (a_val & b_val) == b_val;
3014 ICALL_EXPORT MonoObject *
3015 ves_icall_System_Enum_get_value (MonoObject *this)
3026 g_assert (this->vtable->klass->enumtype);
3028 enumc = mono_class_from_mono_type (mono_class_enum_basetype (this->vtable->klass));
3029 res = mono_object_new (mono_object_domain (this), enumc);
3030 dst = (char *)res + sizeof (MonoObject);
3031 src = (char *)this + sizeof (MonoObject);
3032 size = mono_class_value_size (enumc, NULL);
3034 memcpy (dst, src, size);
3039 ICALL_EXPORT MonoReflectionType *
3040 ves_icall_System_Enum_get_underlying_type (MonoReflectionType *type)
3045 klass = mono_class_from_mono_type (type->type);
3046 mono_class_init_or_throw (klass);
3048 etype = mono_class_enum_basetype (klass);
3050 /* MS throws this for typebuilders */
3051 mono_raise_exception (mono_get_exception_argument ("Type must be a type provided by the runtime.", "enumType"));
3053 return mono_type_get_object (mono_object_domain (type), etype);
3057 ves_icall_System_Enum_compare_value_to (MonoObject *this, MonoObject *other)
3059 gpointer tdata = (char *)this + sizeof (MonoObject);
3060 gpointer odata = (char *)other + sizeof (MonoObject);
3061 MonoType *basetype = mono_class_enum_basetype (this->vtable->klass);
3062 g_assert (basetype);
3064 #define COMPARE_ENUM_VALUES(ENUM_TYPE) do { \
3065 ENUM_TYPE me = *((ENUM_TYPE*)tdata); \
3066 ENUM_TYPE other = *((ENUM_TYPE*)odata); \
3069 return me > other ? 1 : -1; \
3072 switch (basetype->type) {
3074 COMPARE_ENUM_VALUES (guint8);
3076 COMPARE_ENUM_VALUES (gint8);
3077 case MONO_TYPE_CHAR:
3079 COMPARE_ENUM_VALUES (guint16);
3081 COMPARE_ENUM_VALUES (gint16);
3083 COMPARE_ENUM_VALUES (guint32);
3085 COMPARE_ENUM_VALUES (gint32);
3087 COMPARE_ENUM_VALUES (guint64);
3089 COMPARE_ENUM_VALUES (gint64);
3091 g_error ("Implement type 0x%02x in get_hashcode", basetype->type);
3093 #undef COMPARE_ENUM_VALUES
3098 ves_icall_System_Enum_get_hashcode (MonoObject *this)
3100 gpointer data = (char *)this + sizeof (MonoObject);
3101 MonoType *basetype = mono_class_enum_basetype (this->vtable->klass);
3102 g_assert (basetype);
3104 switch (basetype->type) {
3106 return *((gint8*)data);
3108 return *((guint8*)data);
3109 case MONO_TYPE_CHAR:
3111 return *((guint16*)data);
3114 return *((gint16*)data);
3116 return *((guint32*)data);
3118 return *((gint32*)data);
3120 case MONO_TYPE_I8: {
3121 gint64 value = *((gint64*)data);
3122 return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
3125 g_error ("Implement type 0x%02x in get_hashcode", basetype->type);
3131 ves_icall_get_enum_info (MonoReflectionType *type, MonoEnumInfo *info)
3133 MonoDomain *domain = mono_object_domain (type);
3134 MonoClass *enumc = mono_class_from_mono_type (type->type);
3135 guint j = 0, nvalues, crow;
3137 MonoClassField *field;
3139 mono_class_init_or_throw (enumc);
3141 MONO_STRUCT_SETREF (info, utype, mono_type_get_object (domain, mono_class_enum_basetype (enumc)));
3142 nvalues = mono_class_num_fields (enumc) ? mono_class_num_fields (enumc) - 1 : 0;
3143 MONO_STRUCT_SETREF (info, names, mono_array_new (domain, mono_defaults.string_class, nvalues));
3144 MONO_STRUCT_SETREF (info, values, mono_array_new (domain, enumc, nvalues));
3148 while ((field = mono_class_get_fields (enumc, &iter))) {
3151 MonoTypeEnum def_type;
3153 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3155 if (strcmp ("value__", mono_field_get_name (field)) == 0)
3157 if (mono_field_is_deleted (field))
3159 mono_array_setref (info->names, j, mono_string_new (domain, mono_field_get_name (field)));
3161 p = mono_class_get_field_default_value (field, &def_type);
3162 len = mono_metadata_decode_blob_size (p, &p);
3163 switch (mono_class_enum_basetype (enumc)->type) {
3166 mono_array_set (info->values, gchar, j, *p);
3168 case MONO_TYPE_CHAR:
3171 mono_array_set (info->values, gint16, j, read16 (p));
3175 mono_array_set (info->values, gint32, j, read32 (p));
3179 mono_array_set (info->values, gint64, j, read64 (p));
3182 g_error ("Implement type 0x%02x in get_enum_info", mono_class_enum_basetype (enumc)->type);
3189 BFLAGS_IgnoreCase = 1,
3190 BFLAGS_DeclaredOnly = 2,
3191 BFLAGS_Instance = 4,
3193 BFLAGS_Public = 0x10,
3194 BFLAGS_NonPublic = 0x20,
3195 BFLAGS_FlattenHierarchy = 0x40,
3196 BFLAGS_InvokeMethod = 0x100,
3197 BFLAGS_CreateInstance = 0x200,
3198 BFLAGS_GetField = 0x400,
3199 BFLAGS_SetField = 0x800,
3200 BFLAGS_GetProperty = 0x1000,
3201 BFLAGS_SetProperty = 0x2000,
3202 BFLAGS_ExactBinding = 0x10000,
3203 BFLAGS_SuppressChangeType = 0x20000,
3204 BFLAGS_OptionalParamBinding = 0x40000
3207 ICALL_EXPORT MonoReflectionField *
3208 ves_icall_Type_GetField (MonoReflectionType *type, MonoString *name, guint32 bflags)
3211 MonoClass *startklass, *klass;
3213 MonoClassField *field;
3216 int (*compare_func) (const char *s1, const char *s2) = NULL;
3217 domain = ((MonoObject *)type)->vtable->domain;
3218 klass = startklass = mono_class_from_mono_type (type->type);
3221 mono_raise_exception (mono_get_exception_argument_null ("name"));
3222 if (type->type->byref)
3225 compare_func = (bflags & BFLAGS_IgnoreCase) ? mono_utf8_strcasecmp : strcmp;
3228 if (klass->exception_type != MONO_EXCEPTION_NONE)
3229 mono_raise_exception (mono_class_get_exception_for_failure (klass));
3232 while ((field = mono_class_get_fields_lazy (klass, &iter))) {
3233 guint32 flags = mono_field_get_flags (field);
3236 if (mono_field_is_deleted_with_flags (field, flags))
3238 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
3239 if (bflags & BFLAGS_Public)
3241 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
3242 if (bflags & BFLAGS_NonPublic) {
3249 if (flags & FIELD_ATTRIBUTE_STATIC) {
3250 if (bflags & BFLAGS_Static)
3251 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3254 if (bflags & BFLAGS_Instance)
3261 utf8_name = mono_string_to_utf8 (name);
3263 if (compare_func (mono_field_get_name (field), utf8_name)) {
3269 return mono_field_get_object (domain, klass, field);
3271 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3277 ICALL_EXPORT MonoArray*
3278 ves_icall_Type_GetFields_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
3281 MonoClass *startklass, *klass, *refklass;
3286 MonoClassField *field;
3287 MonoPtrArray tmp_array;
3289 domain = ((MonoObject *)type)->vtable->domain;
3290 if (type->type->byref)
3291 return mono_array_new (domain, mono_defaults.field_info_class, 0);
3292 klass = startklass = mono_class_from_mono_type (type->type);
3293 refklass = mono_class_from_mono_type (reftype->type);
3295 mono_ptr_array_init (tmp_array, 2);
3298 if (klass->exception_type != MONO_EXCEPTION_NONE) {
3299 mono_ptr_array_destroy (tmp_array);
3300 mono_raise_exception (mono_class_get_exception_for_failure (klass));
3304 while ((field = mono_class_get_fields_lazy (klass, &iter))) {
3305 guint32 flags = mono_field_get_flags (field);
3307 if (mono_field_is_deleted_with_flags (field, flags))
3309 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
3310 if (bflags & BFLAGS_Public)
3312 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
3313 if (bflags & BFLAGS_NonPublic) {
3320 if (flags & FIELD_ATTRIBUTE_STATIC) {
3321 if (bflags & BFLAGS_Static)
3322 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3325 if (bflags & BFLAGS_Instance)
3331 member = (MonoObject*)mono_field_get_object (domain, refklass, field);
3332 mono_ptr_array_append (tmp_array, member);
3334 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3337 res = mono_array_new_cached (domain, mono_defaults.field_info_class, mono_ptr_array_size (tmp_array));
3339 for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3340 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3342 mono_ptr_array_destroy (tmp_array);
3348 method_nonpublic (MonoMethod* method, gboolean start_klass)
3350 switch (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) {
3351 case METHOD_ATTRIBUTE_ASSEM:
3352 return (start_klass || mono_defaults.generic_ilist_class);
3353 case METHOD_ATTRIBUTE_PRIVATE:
3355 case METHOD_ATTRIBUTE_PUBLIC:
3363 mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, gboolean ignore_case, gboolean allow_ctors, MonoException **ex)
3366 MonoClass *startklass;
3369 int len, match, nslots;
3370 /*FIXME, use MonoBitSet*/
3371 guint32 method_slots_default [8];
3372 guint32 *method_slots = NULL;
3373 int (*compare_func) (const char *s1, const char *s2) = NULL;
3375 array = g_ptr_array_new ();
3381 compare_func = (ignore_case) ? mono_utf8_strcasecmp : strcmp;
3383 /* An optimization for calls made from Delegate:CreateDelegate () */
3384 if (klass->delegate && name && !strcmp (name, "Invoke") && (bflags == (BFLAGS_Public | BFLAGS_Static | BFLAGS_Instance))) {
3385 method = mono_get_delegate_invoke (klass);
3386 if (mono_loader_get_last_error ())
3389 g_ptr_array_add (array, method);
3393 mono_class_setup_methods (klass);
3394 mono_class_setup_vtable (klass);
3395 if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3398 if (is_generic_parameter (&klass->byval_arg))
3399 nslots = mono_class_get_vtable_size (klass->parent);
3401 nslots = MONO_CLASS_IS_INTERFACE (klass) ? mono_class_num_methods (klass) : mono_class_get_vtable_size (klass);
3402 if (nslots >= sizeof (method_slots_default) * 8) {
3403 method_slots = g_new0 (guint32, nslots / 32 + 1);
3405 method_slots = method_slots_default;
3406 memset (method_slots, 0, sizeof (method_slots_default));
3409 mono_class_setup_methods (klass);
3410 mono_class_setup_vtable (klass);
3411 if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3415 while ((method = mono_class_get_methods (klass, &iter))) {
3417 if (method->slot != -1) {
3418 g_assert (method->slot < nslots);
3419 if (method_slots [method->slot >> 5] & (1 << (method->slot & 0x1f)))
3421 if (!(method->flags & METHOD_ATTRIBUTE_NEW_SLOT))
3422 method_slots [method->slot >> 5] |= 1 << (method->slot & 0x1f);
3425 if (!allow_ctors && method->name [0] == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0))
3427 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3428 if (bflags & BFLAGS_Public)
3430 } else if ((bflags & BFLAGS_NonPublic) && method_nonpublic (method, (klass == startklass))) {
3436 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3437 if (bflags & BFLAGS_Static)
3438 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3441 if (bflags & BFLAGS_Instance)
3449 if (compare_func (name, method->name))
3454 g_ptr_array_add (array, method);
3456 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3458 if (method_slots != method_slots_default)
3459 g_free (method_slots);
3464 if (method_slots != method_slots_default)
3465 g_free (method_slots);
3466 g_ptr_array_free (array, TRUE);
3468 if (klass->exception_type != MONO_EXCEPTION_NONE) {
3469 *ex = mono_class_get_exception_for_failure (klass);
3471 *ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3472 mono_loader_clear_error ();
3477 ICALL_EXPORT MonoArray*
3478 ves_icall_Type_GetMethodsByName (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoBoolean ignore_case, MonoReflectionType *reftype)
3480 static MonoClass *MethodInfo_array;
3483 MonoVTable *array_vtable;
3484 MonoException *ex = NULL;
3485 const char *mname = NULL;
3486 GPtrArray *method_array;
3487 MonoClass *klass, *refklass;
3490 if (!MethodInfo_array) {
3491 MonoClass *klass = mono_array_class_get (mono_defaults.method_info_class, 1);
3492 mono_memory_barrier ();
3493 MethodInfo_array = klass;
3496 klass = mono_class_from_mono_type (type->type);
3497 refklass = mono_class_from_mono_type (reftype->type);
3498 domain = ((MonoObject *)type)->vtable->domain;
3499 array_vtable = mono_class_vtable_full (domain, MethodInfo_array, TRUE);
3500 if (type->type->byref)
3501 return mono_array_new_specific (array_vtable, 0);
3504 mname = mono_string_to_utf8 (name);
3506 method_array = mono_class_get_methods_by_name (klass, mname, bflags, ignore_case, FALSE, &ex);
3507 g_free ((char*)mname);
3509 mono_raise_exception (ex);
3511 res = mono_array_new_specific (array_vtable, method_array->len);
3514 for (i = 0; i < method_array->len; ++i) {
3515 MonoMethod *method = g_ptr_array_index (method_array, i);
3516 mono_array_setref (res, i, mono_method_get_object (domain, method, refklass));
3519 g_ptr_array_free (method_array, TRUE);
3523 ICALL_EXPORT MonoArray*
3524 ves_icall_Type_GetConstructors_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
3527 static MonoClass *System_Reflection_ConstructorInfo;
3528 MonoClass *startklass, *klass, *refklass;
3533 gpointer iter = NULL;
3534 MonoPtrArray tmp_array;
3536 mono_ptr_array_init (tmp_array, 4); /*FIXME, guestimating*/
3538 domain = ((MonoObject *)type)->vtable->domain;
3539 if (type->type->byref)
3540 return mono_array_new_cached (domain, mono_defaults.method_info_class, 0);
3541 klass = startklass = mono_class_from_mono_type (type->type);
3542 refklass = mono_class_from_mono_type (reftype->type);
3544 if (!System_Reflection_ConstructorInfo)
3545 System_Reflection_ConstructorInfo = mono_class_from_name (
3546 mono_defaults.corlib, "System.Reflection", "ConstructorInfo");
3548 mono_class_setup_methods (klass);
3549 if (klass->exception_type != MONO_EXCEPTION_NONE)
3550 mono_raise_exception (mono_class_get_exception_for_failure (klass));
3554 while ((method = mono_class_get_methods (klass, &iter))) {
3556 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
3558 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3559 if (bflags & BFLAGS_Public)
3562 if (bflags & BFLAGS_NonPublic)
3568 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3569 if (bflags & BFLAGS_Static)
3570 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3573 if (bflags & BFLAGS_Instance)
3579 member = (MonoObject*)mono_method_get_object (domain, method, refklass);
3581 mono_ptr_array_append (tmp_array, member);
3584 res = mono_array_new_cached (domain, System_Reflection_ConstructorInfo, mono_ptr_array_size (tmp_array));
3586 for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3587 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3589 mono_ptr_array_destroy (tmp_array);
3595 property_hash (gconstpointer data)
3597 MonoProperty *prop = (MonoProperty*)data;
3599 return g_str_hash (prop->name);
3603 property_equal (MonoProperty *prop1, MonoProperty *prop2)
3605 // Properties are hide-by-name-and-signature
3606 if (!g_str_equal (prop1->name, prop2->name))
3609 if (prop1->get && prop2->get && !mono_metadata_signature_equal (mono_method_signature (prop1->get), mono_method_signature (prop2->get)))
3611 if (prop1->set && prop2->set && !mono_metadata_signature_equal (mono_method_signature (prop1->set), mono_method_signature (prop2->set)))
3617 property_accessor_nonpublic (MonoMethod* accessor, gboolean start_klass)
3622 return method_nonpublic (accessor, start_klass);
3625 ICALL_EXPORT MonoArray*
3626 ves_icall_Type_GetPropertiesByName (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoBoolean ignore_case, MonoReflectionType *reftype)
3630 static MonoClass *System_Reflection_PropertyInfo;
3631 MonoClass *startklass, *klass;
3637 gchar *propname = NULL;
3638 int (*compare_func) (const char *s1, const char *s2) = NULL;
3640 GHashTable *properties = NULL;
3641 MonoPtrArray tmp_array;
3643 mono_ptr_array_init (tmp_array, 8); /*This the average for ASP.NET types*/
3645 if (!System_Reflection_PropertyInfo)
3646 System_Reflection_PropertyInfo = mono_class_from_name (
3647 mono_defaults.corlib, "System.Reflection", "PropertyInfo");
3649 domain = ((MonoObject *)type)->vtable->domain;
3650 if (type->type->byref)
3651 return mono_array_new_cached (domain, System_Reflection_PropertyInfo, 0);
3652 klass = startklass = mono_class_from_mono_type (type->type);
3655 propname = mono_string_to_utf8 (name);
3656 compare_func = (ignore_case) ? mono_utf8_strcasecmp : strcmp;
3659 properties = g_hash_table_new (property_hash, (GEqualFunc)property_equal);
3661 mono_class_setup_methods (klass);
3662 mono_class_setup_vtable (klass);
3663 if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3667 while ((prop = mono_class_get_properties (klass, &iter))) {
3673 flags = method->flags;
3676 if ((prop->get && ((prop->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)) ||
3677 (prop->set && ((prop->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC))) {
3678 if (bflags & BFLAGS_Public)
3680 } else if (bflags & BFLAGS_NonPublic) {
3681 if (property_accessor_nonpublic(prop->get, startklass == klass) ||
3682 property_accessor_nonpublic(prop->set, startklass == klass)) {
3689 if (flags & METHOD_ATTRIBUTE_STATIC) {
3690 if (bflags & BFLAGS_Static)
3691 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3694 if (bflags & BFLAGS_Instance)
3703 if (compare_func (propname, prop->name))
3707 if (g_hash_table_lookup (properties, prop))
3710 mono_ptr_array_append (tmp_array, mono_property_get_object (domain, startklass, prop));
3712 g_hash_table_insert (properties, prop, prop);
3714 if ((!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent)))
3717 g_hash_table_destroy (properties);
3720 res = mono_array_new_cached (domain, System_Reflection_PropertyInfo, mono_ptr_array_size (tmp_array));
3721 for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3722 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3724 mono_ptr_array_destroy (tmp_array);
3730 g_hash_table_destroy (properties);
3733 mono_ptr_array_destroy (tmp_array);
3735 if (klass->exception_type != MONO_EXCEPTION_NONE) {
3736 ex = mono_class_get_exception_for_failure (klass);
3738 ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3739 mono_loader_clear_error ();
3741 mono_raise_exception (ex);
3745 ICALL_EXPORT MonoReflectionEvent *
3746 ves_icall_MonoType_GetEvent (MonoReflectionType *type, MonoString *name, guint32 bflags)
3749 MonoClass *klass, *startklass;
3754 int (*compare_func) (const char *s1, const char *s2);
3756 event_name = mono_string_to_utf8 (name);
3757 if (type->type->byref)
3759 klass = startklass = mono_class_from_mono_type (type->type);
3760 domain = mono_object_domain (type);
3762 mono_class_init_or_throw (klass);
3764 compare_func = (bflags & BFLAGS_IgnoreCase) ? mono_utf8_strcasecmp : strcmp;
3766 if (klass->exception_type != MONO_EXCEPTION_NONE)
3767 mono_raise_exception (mono_class_get_exception_for_failure (klass));
3770 while ((event = mono_class_get_events (klass, &iter))) {
3771 if (compare_func (event->name, event_name))
3774 method = event->add;
3776 method = event->remove;
3778 method = event->raise;
3780 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3781 if (!(bflags & BFLAGS_Public))
3784 if (!(bflags & BFLAGS_NonPublic))
3786 if ((klass != startklass) && (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PRIVATE)
3790 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3791 if (!(bflags & BFLAGS_Static))
3793 if (!(bflags & BFLAGS_FlattenHierarchy) && (klass != startklass))
3796 if (!(bflags & BFLAGS_Instance))
3800 if (!(bflags & BFLAGS_NonPublic))
3803 g_free (event_name);
3804 return mono_event_get_object (domain, startklass, event);
3807 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3810 g_free (event_name);
3815 event_hash (gconstpointer data)
3817 MonoEvent *event = (MonoEvent*)data;
3819 return g_str_hash (event->name);
3823 event_equal (MonoEvent *event1, MonoEvent *event2)
3825 // Events are hide-by-name
3826 return g_str_equal (event1->name, event2->name);
3829 ICALL_EXPORT MonoArray*
3830 ves_icall_Type_GetEvents_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
3834 static MonoClass *System_Reflection_EventInfo;
3835 MonoClass *startklass, *klass;
3841 GHashTable *events = NULL;
3842 MonoPtrArray tmp_array;
3844 mono_ptr_array_init (tmp_array, 4);
3846 if (!System_Reflection_EventInfo)
3847 System_Reflection_EventInfo = mono_class_from_name (
3848 mono_defaults.corlib, "System.Reflection", "EventInfo");
3850 domain = mono_object_domain (type);
3851 if (type->type->byref)
3852 return mono_array_new_cached (domain, System_Reflection_EventInfo, 0);
3853 klass = startklass = mono_class_from_mono_type (type->type);
3855 events = g_hash_table_new (event_hash, (GEqualFunc)event_equal);
3857 mono_class_setup_methods (klass);
3858 mono_class_setup_vtable (klass);
3859 if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3863 while ((event = mono_class_get_events (klass, &iter))) {
3865 method = event->add;
3867 method = event->remove;
3869 method = event->raise;
3871 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3872 if (bflags & BFLAGS_Public)
3874 } else if ((klass == startklass) || (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) {
3875 if (bflags & BFLAGS_NonPublic)
3880 if (bflags & BFLAGS_NonPublic)
3886 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3887 if (bflags & BFLAGS_Static)
3888 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3891 if (bflags & BFLAGS_Instance)
3896 if (bflags & BFLAGS_Instance)
3901 if (g_hash_table_lookup (events, event))
3904 mono_ptr_array_append (tmp_array, mono_event_get_object (domain, startklass, event));
3906 g_hash_table_insert (events, event, event);
3908 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3911 g_hash_table_destroy (events);
3913 res = mono_array_new_cached (domain, System_Reflection_EventInfo, mono_ptr_array_size (tmp_array));
3915 for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3916 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3918 mono_ptr_array_destroy (tmp_array);
3923 mono_ptr_array_destroy (tmp_array);
3924 if (klass->exception_type != MONO_EXCEPTION_NONE) {
3925 ex = mono_class_get_exception_for_failure (klass);
3927 ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3928 mono_loader_clear_error ();
3930 mono_raise_exception (ex);
3934 ICALL_EXPORT MonoReflectionType *
3935 ves_icall_Type_GetNestedType (MonoReflectionType *type, MonoString *name, guint32 bflags)
3944 mono_raise_exception (mono_get_exception_argument_null ("name"));
3946 domain = ((MonoObject *)type)->vtable->domain;
3947 if (type->type->byref)
3949 klass = mono_class_from_mono_type (type->type);
3951 str = mono_string_to_utf8 (name);
3954 if (klass->exception_type != MONO_EXCEPTION_NONE)
3955 mono_raise_exception (mono_class_get_exception_for_failure (klass));
3958 * If a nested type is generic, return its generic type definition.
3959 * Note that this means that the return value is essentially a
3960 * nested type of the generic type definition of @klass.
3962 * A note in MSDN claims that a generic type definition can have
3963 * nested types that aren't generic. In any case, the container of that
3964 * nested type would be the generic type definition.
3966 if (klass->generic_class)
3967 klass = klass->generic_class->container_class;
3970 while ((nested = mono_class_get_nested_types (klass, &iter))) {
3972 if ((nested->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
3973 if (bflags & BFLAGS_Public)
3976 if (bflags & BFLAGS_NonPublic)
3981 if (strcmp (nested->name, str) == 0){
3983 return mono_type_get_object (domain, &nested->byval_arg);
3986 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3992 ICALL_EXPORT MonoArray*
3993 ves_icall_Type_GetNestedTypes (MonoReflectionType *type, guint32 bflags)
4002 MonoPtrArray tmp_array;
4004 domain = ((MonoObject *)type)->vtable->domain;
4005 if (type->type->byref)
4006 return mono_array_new (domain, mono_defaults.monotype_class, 0);
4007 klass = mono_class_from_mono_type (type->type);
4010 * If a nested type is generic, return its generic type definition.
4011 * Note that this means that the return value is essentially the set
4012 * of nested types of the generic type definition of @klass.
4014 * A note in MSDN claims that a generic type definition can have
4015 * nested types that aren't generic. In any case, the container of that
4016 * nested type would be the generic type definition.
4018 if (klass->generic_class)
4019 klass = klass->generic_class->container_class;
4021 mono_ptr_array_init (tmp_array, 1);
4023 while ((nested = mono_class_get_nested_types (klass, &iter))) {
4025 if ((nested->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
4026 if (bflags & BFLAGS_Public)
4029 if (bflags & BFLAGS_NonPublic)
4034 member = (MonoObject*)mono_type_get_object (domain, &nested->byval_arg);
4035 mono_ptr_array_append (tmp_array, member);
4038 res = mono_array_new_cached (domain, mono_defaults.monotype_class, mono_ptr_array_size (tmp_array));
4040 for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
4041 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
4043 mono_ptr_array_destroy (tmp_array);
4048 ICALL_EXPORT MonoReflectionType*
4049 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssembly *assembly, MonoReflectionModule *module, MonoString *name, MonoBoolean throwOnError, MonoBoolean ignoreCase)
4052 MonoType *type = NULL;
4053 MonoTypeNameParse info;
4054 gboolean type_resolve;
4056 /* On MS.NET, this does not fire a TypeResolve event */
4057 type_resolve = TRUE;
4058 str = mono_string_to_utf8 (name);
4059 /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
4060 if (!mono_reflection_parse_type (str, &info)) {
4062 mono_reflection_free_type_info (&info);
4063 if (throwOnError) /* uhm: this is a parse error, though... */
4064 mono_raise_exception (mono_get_exception_type_load (name, NULL));
4065 /*g_print ("failed parse\n");*/
4069 if (info.assembly.name) {
4071 mono_reflection_free_type_info (&info);
4073 /* 1.0 and 2.0 throw different exceptions */
4074 if (mono_defaults.generic_ilist_class)
4075 mono_raise_exception (mono_get_exception_argument (NULL, "Type names passed to Assembly.GetType() must not specify an assembly."));
4077 mono_raise_exception (mono_get_exception_type_load (name, NULL));
4082 if (module != NULL) {
4084 type = mono_reflection_get_type (module->image, &info, ignoreCase, &type_resolve);
4089 if (assembly_is_dynamic (assembly->assembly)) {
4090 /* Enumerate all modules */
4091 MonoReflectionAssemblyBuilder *abuilder = (MonoReflectionAssemblyBuilder*)assembly;
4095 if (abuilder->modules) {
4096 for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
4097 MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
4098 type = mono_reflection_get_type (&mb->dynamic_image->image, &info, ignoreCase, &type_resolve);
4104 if (!type && abuilder->loaded_modules) {
4105 for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
4106 MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
4107 type = mono_reflection_get_type (mod->image, &info, ignoreCase, &type_resolve);
4114 type = mono_reflection_get_type (assembly->assembly->image, &info, ignoreCase, &type_resolve);
4116 mono_reflection_free_type_info (&info);
4118 MonoException *e = NULL;
4121 e = mono_get_exception_type_load (name, NULL);
4123 if (mono_loader_get_last_error () && mono_defaults.generic_ilist_class)
4124 e = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
4126 mono_loader_clear_error ();
4129 mono_raise_exception (e);
4132 } else if (mono_loader_get_last_error ()) {
4134 mono_raise_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
4135 mono_loader_clear_error ();
4138 if (type->type == MONO_TYPE_CLASS) {
4139 MonoClass *klass = mono_type_get_class (type);
4141 if (mono_security_enabled () && !klass->exception_type)
4142 /* Some security problems are detected during generic vtable construction */
4143 mono_class_setup_vtable (klass);
4145 /* need to report exceptions ? */
4146 if (throwOnError && klass->exception_type) {
4147 /* report SecurityException (or others) that occured when loading the assembly */
4148 MonoException *exc = mono_class_get_exception_for_failure (klass);
4149 mono_loader_clear_error ();
4150 mono_raise_exception (exc);
4151 } else if (mono_security_enabled () && klass->exception_type == MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND) {
4156 /* g_print ("got it\n"); */
4157 return mono_type_get_object (mono_object_domain (assembly), type);
4161 replace_shadow_path (MonoDomain *domain, gchar *dirname, gchar **filename)
4164 gchar *shadow_ini_file;
4167 /* Check for shadow-copied assembly */
4168 if (mono_is_shadow_copy_enabled (domain, dirname)) {
4169 shadow_ini_file = g_build_filename (dirname, "__AssemblyInfo__.ini", NULL);
4171 if (!g_file_get_contents (shadow_ini_file, &content, &len, NULL) ||
4172 !g_file_test (content, G_FILE_TEST_IS_REGULAR)) {
4178 g_free (shadow_ini_file);
4179 if (content != NULL) {
4182 *filename = content;
4189 ICALL_EXPORT MonoString *
4190 ves_icall_System_Reflection_Assembly_get_code_base (MonoReflectionAssembly *assembly, MonoBoolean escaped)
4192 MonoDomain *domain = mono_object_domain (assembly);
4193 MonoAssembly *mass = assembly->assembly;
4194 MonoString *res = NULL;
4199 if (g_path_is_absolute (mass->image->name)) {
4200 absolute = g_strdup (mass->image->name);
4201 dirname = g_path_get_dirname (absolute);
4203 absolute = g_build_filename (mass->basedir, mass->image->name, NULL);
4204 dirname = g_strdup (mass->basedir);
4207 replace_shadow_path (domain, dirname, &absolute);
4212 for (i = strlen (absolute) - 1; i >= 0; i--)
4213 if (absolute [i] == '\\')
4218 uri = g_filename_to_uri (absolute, NULL, NULL);
4220 const char *prepend = "file://";
4222 if (*absolute == '/' && *(absolute + 1) == '/') {
4225 prepend = "file:///";
4228 uri = g_strconcat (prepend, absolute, NULL);
4232 res = mono_string_new (domain, uri);
4239 ICALL_EXPORT MonoBoolean
4240 ves_icall_System_Reflection_Assembly_get_global_assembly_cache (MonoReflectionAssembly *assembly)
4242 MonoAssembly *mass = assembly->assembly;
4244 return mass->in_gac;
4247 ICALL_EXPORT MonoReflectionAssembly*
4248 ves_icall_System_Reflection_Assembly_load_with_partial_name (MonoString *mname, MonoObject *evidence)
4252 MonoImageOpenStatus status;
4254 name = mono_string_to_utf8 (mname);
4255 res = mono_assembly_load_with_partial_name (name, &status);
4261 return mono_assembly_get_object (mono_domain_get (), res);
4264 ICALL_EXPORT MonoString *
4265 ves_icall_System_Reflection_Assembly_get_location (MonoReflectionAssembly *assembly)
4267 MonoDomain *domain = mono_object_domain (assembly);
4270 res = mono_string_new (domain, mono_image_get_filename (assembly->assembly->image));
4275 ICALL_EXPORT MonoBoolean
4276 ves_icall_System_Reflection_Assembly_get_ReflectionOnly (MonoReflectionAssembly *assembly)
4278 return assembly->assembly->ref_only;
4281 ICALL_EXPORT MonoString *
4282 ves_icall_System_Reflection_Assembly_InternalImageRuntimeVersion (MonoReflectionAssembly *assembly)
4284 MonoDomain *domain = mono_object_domain (assembly);
4286 return mono_string_new (domain, assembly->assembly->image->version);
4289 ICALL_EXPORT MonoReflectionMethod*
4290 ves_icall_System_Reflection_Assembly_get_EntryPoint (MonoReflectionAssembly *assembly)
4294 guint32 token = mono_image_get_entry_point (assembly->assembly->image);
4298 method = mono_get_method_checked (assembly->assembly->image, token, NULL, NULL, &error);
4299 mono_error_raise_exception (&error);
4301 return mono_method_get_object (mono_object_domain (assembly), method, NULL);
4304 ICALL_EXPORT MonoReflectionModule*
4305 ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAssembly *assembly)
4307 return mono_module_get_object (mono_object_domain (assembly), assembly->assembly->image);
4310 ICALL_EXPORT MonoArray*
4311 ves_icall_System_Reflection_Assembly_GetManifestResourceNames (MonoReflectionAssembly *assembly)
4313 MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4314 MonoArray *result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, table->rows);
4318 for (i = 0; i < table->rows; ++i) {
4319 val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
4320 mono_array_setref (result, i, mono_string_new (mono_object_domain (assembly), val));
4326 create_version (MonoDomain *domain, guint32 major, guint32 minor, guint32 build, guint32 revision)
4328 static MonoClass *System_Version = NULL;
4329 static MonoMethod *create_version = NULL;
4333 if (!System_Version) {
4334 System_Version = mono_class_from_name (mono_defaults.corlib, "System", "Version");
4335 g_assert (System_Version);
4338 if (!create_version) {
4339 MonoMethodDesc *desc = mono_method_desc_new (":.ctor(int,int,int,int)", FALSE);
4340 create_version = mono_method_desc_search_in_class (desc, System_Version);
4341 g_assert (create_version);
4342 mono_method_desc_free (desc);
4348 args [3] = &revision;
4349 result = mono_object_new (domain, System_Version);
4350 mono_runtime_invoke (create_version, result, args, NULL);
4355 ICALL_EXPORT MonoArray*
4356 ves_icall_System_Reflection_Assembly_GetReferencedAssemblies (MonoReflectionAssembly *assembly)
4358 static MonoClass *System_Reflection_AssemblyName;
4360 MonoDomain *domain = mono_object_domain (assembly);
4362 static MonoMethod *create_culture = NULL;
4363 MonoImage *image = assembly->assembly->image;
4366 if (!System_Reflection_AssemblyName)
4367 System_Reflection_AssemblyName = mono_class_from_name (
4368 mono_defaults.corlib, "System.Reflection", "AssemblyName");
4370 t = &assembly->assembly->image->tables [MONO_TABLE_ASSEMBLYREF];
4373 result = mono_array_new (domain, System_Reflection_AssemblyName, count);
4375 if (count > 0 && !create_culture) {
4376 MonoMethodDesc *desc = mono_method_desc_new (
4377 "System.Globalization.CultureInfo:CreateCulture(string,bool)", TRUE);
4378 create_culture = mono_method_desc_search_in_image (desc, mono_defaults.corlib);
4379 g_assert (create_culture);
4380 mono_method_desc_free (desc);
4383 for (i = 0; i < count; i++) {
4384 MonoReflectionAssemblyName *aname;
4385 guint32 cols [MONO_ASSEMBLYREF_SIZE];
4387 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
4389 aname = (MonoReflectionAssemblyName *) mono_object_new (
4390 domain, System_Reflection_AssemblyName);
4392 MONO_OBJECT_SETREF (aname, name, mono_string_new (domain, mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_NAME])));
4394 aname->major = cols [MONO_ASSEMBLYREF_MAJOR_VERSION];
4395 aname->minor = cols [MONO_ASSEMBLYREF_MINOR_VERSION];
4396 aname->build = cols [MONO_ASSEMBLYREF_BUILD_NUMBER];
4397 aname->revision = cols [MONO_ASSEMBLYREF_REV_NUMBER];
4398 aname->flags = cols [MONO_ASSEMBLYREF_FLAGS];
4399 aname->versioncompat = 1; /* SameMachine (default) */
4400 aname->hashalg = ASSEMBLY_HASH_SHA1; /* SHA1 (default) */
4401 MONO_OBJECT_SETREF (aname, version, create_version (domain, aname->major, aname->minor, aname->build, aname->revision));
4403 if (create_culture) {
4405 MonoBoolean assembly_ref = 1;
4406 args [0] = mono_string_new (domain, mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_CULTURE]));
4407 args [1] = &assembly_ref;
4408 MONO_OBJECT_SETREF (aname, cultureInfo, mono_runtime_invoke (create_culture, NULL, args, NULL));
4411 if (cols [MONO_ASSEMBLYREF_PUBLIC_KEY]) {
4412 const gchar *pkey_ptr = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY]);
4413 guint32 pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
4415 if ((cols [MONO_ASSEMBLYREF_FLAGS] & ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG)) {
4416 /* public key token isn't copied - the class library will
4417 automatically generate it from the public key if required */
4418 MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
4419 memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
4421 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
4422 memcpy (mono_array_addr (aname->keyToken, guint8, 0), pkey_ptr, pkey_len);
4425 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 0));
4428 /* note: this function doesn't return the codebase on purpose (i.e. it can
4429 be used under partial trust as path information isn't present). */
4431 mono_array_setref (result, i, aname);
4436 /* move this in some file in mono/util/ */
4438 g_concat_dir_and_file (const char *dir, const char *file)
4440 g_return_val_if_fail (dir != NULL, NULL);
4441 g_return_val_if_fail (file != NULL, NULL);
4444 * If the directory name doesn't have a / on the end, we need
4445 * to add one so we get a proper path to the file
4447 if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
4448 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
4450 return g_strconcat (dir, file, NULL);
4454 ves_icall_System_Reflection_Assembly_GetManifestResourceInternal (MonoReflectionAssembly *assembly, MonoString *name, gint32 *size, MonoReflectionModule **ref_module)
4456 char *n = mono_string_to_utf8 (name);
4457 MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4459 guint32 cols [MONO_MANIFEST_SIZE];
4460 guint32 impl, file_idx;
4464 for (i = 0; i < table->rows; ++i) {
4465 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4466 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
4467 if (strcmp (val, n) == 0)
4471 if (i == table->rows)
4474 impl = cols [MONO_MANIFEST_IMPLEMENTATION];
4477 * this code should only be called after obtaining the
4478 * ResourceInfo and handling the other cases.
4480 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
4481 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
4483 module = mono_image_load_file_for_image (assembly->assembly->image, file_idx);
4488 module = assembly->assembly->image;
4490 mono_gc_wbarrier_generic_store (ref_module, (MonoObject*) mono_module_get_object (mono_domain_get (), module));
4492 return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
4495 ICALL_EXPORT gboolean
4496 ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoManifestResourceInfo *info)
4498 MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4500 guint32 cols [MONO_MANIFEST_SIZE];
4501 guint32 file_cols [MONO_FILE_SIZE];
4505 n = mono_string_to_utf8 (name);
4506 for (i = 0; i < table->rows; ++i) {
4507 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4508 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
4509 if (strcmp (val, n) == 0)
4513 if (i == table->rows)
4516 if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
4517 info->location = RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST;
4520 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
4521 case MONO_IMPLEMENTATION_FILE:
4522 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4523 table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
4524 mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
4525 val = mono_metadata_string_heap (assembly->assembly->image, file_cols [MONO_FILE_NAME]);
4526 MONO_OBJECT_SETREF (info, filename, mono_string_new (mono_object_domain (assembly), val));
4527 if (file_cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA)
4530 info->location = RESOURCE_LOCATION_EMBEDDED;
4533 case MONO_IMPLEMENTATION_ASSEMBLYREF:
4534 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4535 mono_assembly_load_reference (assembly->assembly->image, i - 1);
4536 if (assembly->assembly->image->references [i - 1] == (gpointer)-1) {
4537 char *msg = g_strdup_printf ("Assembly %d referenced from assembly %s not found ", i - 1, assembly->assembly->image->name);
4538 MonoException *ex = mono_get_exception_file_not_found2 (msg, NULL);
4540 mono_raise_exception (ex);
4542 MONO_OBJECT_SETREF (info, assembly, mono_assembly_get_object (mono_domain_get (), assembly->assembly->image->references [i - 1]));
4544 /* Obtain info recursively */
4545 ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (info->assembly, name, info);
4546 info->location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
4549 case MONO_IMPLEMENTATION_EXP_TYPE:
4550 g_assert_not_reached ();
4558 ICALL_EXPORT MonoObject*
4559 ves_icall_System_Reflection_Assembly_GetFilesInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoBoolean resource_modules)
4561 MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
4562 MonoArray *result = NULL;
4567 /* check hash if needed */
4569 n = mono_string_to_utf8 (name);
4570 for (i = 0; i < table->rows; ++i) {
4571 val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
4572 if (strcmp (val, n) == 0) {
4575 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
4576 fn = mono_string_new (mono_object_domain (assembly), n);
4578 return (MonoObject*)fn;
4586 for (i = 0; i < table->rows; ++i) {
4587 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA))
4591 result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, count);
4594 for (i = 0; i < table->rows; ++i) {
4595 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
4596 val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
4597 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
4598 mono_array_setref (result, count, mono_string_new (mono_object_domain (assembly), n));
4603 return (MonoObject*)result;
4606 ICALL_EXPORT MonoArray*
4607 ves_icall_System_Reflection_Assembly_GetModulesInternal (MonoReflectionAssembly *assembly)
4609 MonoDomain *domain = mono_domain_get();
4612 int i, j, file_count = 0;
4613 MonoImage **modules;
4614 guint32 module_count, real_module_count;
4615 MonoTableInfo *table;
4616 guint32 cols [MONO_FILE_SIZE];
4617 MonoImage *image = assembly->assembly->image;
4619 g_assert (image != NULL);
4620 g_assert (!assembly_is_dynamic (assembly->assembly));
4622 table = &image->tables [MONO_TABLE_FILE];
4623 file_count = table->rows;
4625 modules = image->modules;
4626 module_count = image->module_count;
4628 real_module_count = 0;
4629 for (i = 0; i < module_count; ++i)
4631 real_module_count ++;
4633 klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
4634 res = mono_array_new (domain, klass, 1 + real_module_count + file_count);
4636 mono_array_setref (res, 0, mono_module_get_object (domain, image));
4638 for (i = 0; i < module_count; ++i)
4640 mono_array_setref (res, j, mono_module_get_object (domain, modules[i]));
4644 for (i = 0; i < file_count; ++i, ++j) {
4645 mono_metadata_decode_row (table, i, cols, MONO_FILE_SIZE);
4646 if (cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA)
4647 mono_array_setref (res, j, mono_module_file_get_object (domain, image, i));
4649 MonoImage *m = mono_image_load_file_for_image (image, i + 1);
4651 MonoString *fname = mono_string_new (mono_domain_get (), mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
4652 mono_raise_exception (mono_get_exception_file_not_found2 (NULL, fname));
4654 mono_array_setref (res, j, mono_module_get_object (domain, m));
4661 ICALL_EXPORT MonoReflectionMethod*
4662 ves_icall_GetCurrentMethod (void)
4664 MonoMethod *m = mono_method_get_last_managed ();
4666 while (m->is_inflated)
4667 m = ((MonoMethodInflated*)m)->declaring;
4669 return mono_method_get_object (mono_domain_get (), m, NULL);
4674 mono_method_get_equivalent_method (MonoMethod *method, MonoClass *klass)
4677 if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) {
4680 MonoMethodInflated *inflated = (MonoMethodInflated*)method;
4681 //method is inflated, we should inflate it on the other class
4682 MonoGenericContext ctx;
4683 ctx.method_inst = inflated->context.method_inst;
4684 ctx.class_inst = inflated->context.class_inst;
4685 if (klass->generic_class)
4686 ctx.class_inst = klass->generic_class->context.class_inst;
4687 else if (klass->generic_container)
4688 ctx.class_inst = klass->generic_container->context.class_inst;
4689 result = mono_class_inflate_generic_method_full_checked (inflated->declaring, klass, &ctx, &error);
4690 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4694 mono_class_setup_methods (method->klass);
4695 if (method->klass->exception_type)
4697 for (i = 0; i < method->klass->method.count; ++i) {
4698 if (method->klass->methods [i] == method) {
4703 mono_class_setup_methods (klass);
4704 if (klass->exception_type)
4706 g_assert (offset >= 0 && offset < klass->method.count);
4707 return klass->methods [offset];
4710 ICALL_EXPORT MonoReflectionMethod*
4711 ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternalType (MonoMethod *method, MonoType *type)
4715 klass = mono_class_from_mono_type (type);
4716 if (mono_class_get_generic_type_definition (method->klass) != mono_class_get_generic_type_definition (klass))
4718 if (method->klass != klass) {
4719 method = mono_method_get_equivalent_method (method, klass);
4724 klass = method->klass;
4725 return mono_method_get_object (mono_domain_get (), method, klass);
4728 ICALL_EXPORT MonoReflectionMethod*
4729 ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternal (MonoMethod *method)
4731 return mono_method_get_object (mono_domain_get (), method, NULL);
4734 ICALL_EXPORT MonoReflectionMethodBody*
4735 ves_icall_System_Reflection_MethodBase_GetMethodBodyInternal (MonoMethod *method)
4737 return mono_method_body_get_object (mono_domain_get (), method);
4740 ICALL_EXPORT MonoReflectionAssembly*
4741 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (void)
4743 MonoMethod *dest = NULL;
4745 mono_stack_walk_no_il (get_executing, &dest);
4747 return mono_assembly_get_object (mono_domain_get (), dest->klass->image->assembly);
4751 ICALL_EXPORT MonoReflectionAssembly*
4752 ves_icall_System_Reflection_Assembly_GetEntryAssembly (void)
4754 MonoDomain* domain = mono_domain_get ();
4756 if (!domain->entry_assembly)
4759 return mono_assembly_get_object (domain, domain->entry_assembly);
4762 ICALL_EXPORT MonoReflectionAssembly*
4763 ves_icall_System_Reflection_Assembly_GetCallingAssembly (void)
4769 mono_stack_walk_no_il (get_executing, &dest);
4771 mono_stack_walk_no_il (get_caller, &dest);
4774 return mono_assembly_get_object (mono_domain_get (), dest->klass->image->assembly);
4777 ICALL_EXPORT MonoString *
4778 ves_icall_System_MonoType_getFullName (MonoReflectionType *object, gboolean full_name,
4779 gboolean assembly_qualified)
4781 MonoDomain *domain = mono_object_domain (object);
4782 MonoTypeNameFormat format;
4787 format = assembly_qualified ?
4788 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED :
4789 MONO_TYPE_NAME_FORMAT_FULL_NAME;
4791 format = MONO_TYPE_NAME_FORMAT_REFLECTION;
4793 name = mono_type_get_name_full (object->type, format);
4797 if (full_name && (object->type->type == MONO_TYPE_VAR || object->type->type == MONO_TYPE_MVAR)) {
4802 res = mono_string_new (domain, name);
4809 vell_icall_MonoType_get_core_clr_security_level (MonoReflectionType *this)
4811 MonoClass *klass = mono_class_from_mono_type (this->type);
4812 mono_class_init_or_throw (klass);
4813 return mono_security_core_clr_class_level (klass);
4817 fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *aname, MonoAssemblyName *name, const char *absolute, gboolean by_default_version, gboolean default_publickey, gboolean default_token)
4819 static MonoMethod *create_culture = NULL;
4822 const char *pkey_ptr;
4824 MonoBoolean assembly_ref = 0;
4826 MONO_OBJECT_SETREF (aname, name, mono_string_new (domain, name->name));
4827 aname->major = name->major;
4828 aname->minor = name->minor;
4829 aname->build = name->build;
4830 aname->flags = name->flags;
4831 aname->revision = name->revision;
4832 aname->hashalg = name->hash_alg;
4833 aname->versioncompat = 1; /* SameMachine (default) */
4834 aname->processor_architecture = name->arch;
4836 if (by_default_version)
4837 MONO_OBJECT_SETREF (aname, version, create_version (domain, name->major, name->minor, name->build, name->revision));
4840 if (absolute != NULL && *absolute != '\0') {
4841 const gchar *prepend = "file://";
4844 codebase = g_strdup (absolute);
4849 for (i = strlen (codebase) - 1; i >= 0; i--)
4850 if (codebase [i] == '\\')
4853 if (*codebase == '/' && *(codebase + 1) == '/') {
4856 prepend = "file:///";
4860 result = g_strconcat (prepend, codebase, NULL);
4866 MONO_OBJECT_SETREF (aname, codebase, mono_string_new (domain, codebase));
4870 if (!create_culture) {
4871 MonoMethodDesc *desc = mono_method_desc_new ("System.Globalization.CultureInfo:CreateCulture(string,bool)", TRUE);
4872 create_culture = mono_method_desc_search_in_image (desc, mono_defaults.corlib);
4873 g_assert (create_culture);
4874 mono_method_desc_free (desc);
4877 if (name->culture) {
4878 args [0] = mono_string_new (domain, name->culture);
4879 args [1] = &assembly_ref;
4880 MONO_OBJECT_SETREF (aname, cultureInfo, mono_runtime_invoke (create_culture, NULL, args, NULL));
4883 if (name->public_key) {
4884 pkey_ptr = (char*)name->public_key;
4885 pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
4887 MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
4888 memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
4889 aname->flags |= ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG;
4890 } else if (default_publickey) {
4891 MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, 0));
4892 aname->flags |= ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG;
4895 /* MonoAssemblyName keeps the public key token as an hexadecimal string */
4896 if (name->public_key_token [0]) {
4900 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 8));
4901 p = mono_array_addr (aname->keyToken, char, 0);
4903 for (i = 0, j = 0; i < 8; i++) {
4904 *p = g_ascii_xdigit_value (name->public_key_token [j++]) << 4;
4905 *p |= g_ascii_xdigit_value (name->public_key_token [j++]);
4908 } else if (default_token) {
4909 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 0));
4913 ICALL_EXPORT MonoString *
4914 ves_icall_System_Reflection_Assembly_get_fullName (MonoReflectionAssembly *assembly)
4916 MonoDomain *domain = mono_object_domain (assembly);
4917 MonoAssembly *mass = assembly->assembly;
4921 name = mono_stringify_assembly_name (&mass->aname);
4922 res = mono_string_new (domain, name);
4929 ves_icall_System_Reflection_Assembly_FillName (MonoReflectionAssembly *assembly, MonoReflectionAssemblyName *aname)
4932 MonoAssembly *mass = assembly->assembly;
4934 if (g_path_is_absolute (mass->image->name)) {
4935 fill_reflection_assembly_name (mono_object_domain (assembly),
4936 aname, &mass->aname, mass->image->name, TRUE,
4940 absolute = g_build_filename (mass->basedir, mass->image->name, NULL);
4942 fill_reflection_assembly_name (mono_object_domain (assembly),
4943 aname, &mass->aname, absolute, TRUE, TRUE,
4950 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoString *fname, MonoReflectionAssemblyName *aname)
4953 MonoImageOpenStatus status = MONO_IMAGE_OK;
4956 MonoAssemblyName name;
4959 filename = mono_string_to_utf8 (fname);
4961 dirname = g_path_get_dirname (filename);
4962 replace_shadow_path (mono_domain_get (), dirname, &filename);
4965 image = mono_image_open (filename, &status);
4971 if (status == MONO_IMAGE_IMAGE_INVALID)
4972 exc = mono_get_exception_bad_image_format2 (NULL, fname);
4974 exc = mono_get_exception_file_not_found2 (NULL, fname);
4975 mono_raise_exception (exc);
4978 res = mono_assembly_fill_assembly_name (image, &name);
4980 mono_image_close (image);
4982 mono_raise_exception (mono_get_exception_argument ("assemblyFile", "The file does not contain a manifest"));
4985 fill_reflection_assembly_name (mono_domain_get (), aname, &name, filename,
4989 mono_image_close (image);
4992 ICALL_EXPORT MonoBoolean
4993 ves_icall_System_Reflection_Assembly_LoadPermissions (MonoReflectionAssembly *assembly,
4994 char **minimum, guint32 *minLength, char **optional, guint32 *optLength, char **refused, guint32 *refLength)
4996 MonoBoolean result = FALSE;
4997 MonoDeclSecurityEntry entry;
4999 /* SecurityAction.RequestMinimum */
5000 if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQMIN, &entry)) {
5001 *minimum = entry.blob;
5002 *minLength = entry.size;
5005 /* SecurityAction.RequestOptional */
5006 if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQOPT, &entry)) {
5007 *optional = entry.blob;
5008 *optLength = entry.size;
5011 /* SecurityAction.RequestRefuse */
5012 if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQREFUSE, &entry)) {
5013 *refused = entry.blob;
5014 *refLength = entry.size;
5022 mono_module_get_types (MonoDomain *domain, MonoImage *image, MonoArray **exceptions, MonoBoolean exportedOnly)
5026 MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
5028 guint32 attrs, visibility;
5030 /* we start the count from 1 because we skip the special type <Module> */
5033 for (i = 1; i < tdef->rows; ++i) {
5034 attrs = mono_metadata_decode_row_col (tdef, i, MONO_TYPEDEF_FLAGS);
5035 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5036 if (visibility == TYPE_ATTRIBUTE_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_PUBLIC)
5040 count = tdef->rows - 1;
5042 res = mono_array_new (domain, mono_defaults.monotype_class, count);
5043 *exceptions = mono_array_new (domain, mono_defaults.exception_class, count);
5045 for (i = 1; i < tdef->rows; ++i) {
5046 attrs = mono_metadata_decode_row_col (tdef, i, MONO_TYPEDEF_FLAGS);
5047 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5048 if (!exportedOnly || (visibility == TYPE_ATTRIBUTE_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_PUBLIC)) {
5050 klass = mono_class_get_checked (image, (i + 1) | MONO_TOKEN_TYPE_DEF, &error);
5051 g_assert (!mono_loader_get_last_error ()); /* Plug any leaks */
5054 mono_array_setref (res, count, mono_type_get_object (domain, &klass->byval_arg));
5056 MonoException *ex = mono_error_convert_to_exception (&error);
5057 mono_array_setref (*exceptions, count, ex);
5066 ICALL_EXPORT MonoArray*
5067 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssembly *assembly, MonoBoolean exportedOnly)
5069 MonoArray *res = NULL;
5070 MonoArray *exceptions = NULL;
5071 MonoImage *image = NULL;
5072 MonoTableInfo *table = NULL;
5075 int i, len, ex_count;
5077 domain = mono_object_domain (assembly);
5079 g_assert (!assembly_is_dynamic (assembly->assembly));
5080 image = assembly->assembly->image;
5081 table = &image->tables [MONO_TABLE_FILE];
5082 res = mono_module_get_types (domain, image, &exceptions, exportedOnly);
5084 /* Append data from all modules in the assembly */
5085 for (i = 0; i < table->rows; ++i) {
5086 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
5087 MonoImage *loaded_image = mono_assembly_load_module (image->assembly, i + 1);
5090 MonoArray *res2 = mono_module_get_types (domain, loaded_image, &ex2, exportedOnly);
5091 /* Append the new types to the end of the array */
5092 if (mono_array_length (res2) > 0) {
5094 MonoArray *res3, *ex3;
5096 len1 = mono_array_length (res);
5097 len2 = mono_array_length (res2);
5099 res3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
5100 mono_array_memcpy_refs (res3, 0, res, 0, len1);
5101 mono_array_memcpy_refs (res3, len1, res2, 0, len2);
5104 ex3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
5105 mono_array_memcpy_refs (ex3, 0, exceptions, 0, len1);
5106 mono_array_memcpy_refs (ex3, len1, ex2, 0, len2);
5113 /* the ReflectionTypeLoadException must have all the types (Types property),
5114 * NULL replacing types which throws an exception. The LoaderException must
5115 * contain all exceptions for NULL items.
5118 len = mono_array_length (res);
5121 for (i = 0; i < len; i++) {
5122 MonoReflectionType *t = mono_array_get (res, gpointer, i);
5126 klass = mono_type_get_class (t->type);
5127 if ((klass != NULL) && klass->exception_type) {
5128 /* keep the class in the list */
5129 list = g_list_append (list, klass);
5130 /* and replace Type with NULL */
5131 mono_array_setref (res, i, NULL);
5138 if (list || ex_count) {
5140 MonoException *exc = NULL;
5141 MonoArray *exl = NULL;
5142 int j, length = g_list_length (list) + ex_count;
5144 mono_loader_clear_error ();
5146 exl = mono_array_new (domain, mono_defaults.exception_class, length);
5147 /* Types for which mono_class_get_checked () succeeded */
5148 for (i = 0, tmp = list; tmp; i++, tmp = tmp->next) {
5149 MonoException *exc = mono_class_get_exception_for_failure (tmp->data);
5150 mono_array_setref (exl, i, exc);
5152 /* Types for which it don't */
5153 for (j = 0; j < mono_array_length (exceptions); ++j) {
5154 MonoException *exc = mono_array_get (exceptions, MonoException*, j);
5156 g_assert (i < length);
5157 mono_array_setref (exl, i, exc);
5164 exc = mono_get_exception_reflection_type_load (res, exl);
5165 mono_loader_clear_error ();
5166 mono_raise_exception (exc);
5172 ICALL_EXPORT gboolean
5173 ves_icall_System_Reflection_AssemblyName_ParseName (MonoReflectionAssemblyName *name, MonoString *assname)
5175 MonoAssemblyName aname;
5176 MonoDomain *domain = mono_object_domain (name);
5178 gboolean is_version_defined;
5179 gboolean is_token_defined;
5181 aname.public_key = NULL;
5182 val = mono_string_to_utf8 (assname);
5183 if (!mono_assembly_name_parse_full (val, &aname, TRUE, &is_version_defined, &is_token_defined)) {
5184 g_free ((guint8*) aname.public_key);
5189 fill_reflection_assembly_name (domain, name, &aname, "", is_version_defined,
5190 FALSE, is_token_defined);
5192 mono_assembly_name_free (&aname);
5193 g_free ((guint8*) aname.public_key);
5199 ICALL_EXPORT MonoReflectionType*
5200 ves_icall_System_Reflection_Module_GetGlobalType (MonoReflectionModule *module)
5203 MonoDomain *domain = mono_object_domain (module);
5206 g_assert (module->image);
5208 if (image_is_dynamic (module->image) && ((MonoDynamicImage*)(module->image))->initial_image)
5209 /* These images do not have a global type */
5212 klass = mono_class_get_checked (module->image, 1 | MONO_TOKEN_TYPE_DEF, &error);
5213 mono_error_raise_exception (&error);
5214 return mono_type_get_object (domain, &klass->byval_arg);
5218 ves_icall_System_Reflection_Module_Close (MonoReflectionModule *module)
5220 /*if (module->image)
5221 mono_image_close (module->image);*/
5224 ICALL_EXPORT MonoString*
5225 ves_icall_System_Reflection_Module_GetGuidInternal (MonoReflectionModule *module)
5227 MonoDomain *domain = mono_object_domain (module);
5229 g_assert (module->image);
5230 return mono_string_new (domain, module->image->guid);
5233 ICALL_EXPORT gpointer
5234 ves_icall_System_Reflection_Module_GetHINSTANCE (MonoReflectionModule *module)
5237 if (module->image && module->image->is_module_handle)
5238 return module->image->raw_data;
5241 return (gpointer) (-1);
5245 ves_icall_System_Reflection_Module_GetPEKind (MonoImage *image, gint32 *pe_kind, gint32 *machine)
5247 if (image_is_dynamic (image)) {
5248 MonoDynamicImage *dyn = (MonoDynamicImage*)image;
5249 *pe_kind = dyn->pe_kind;
5250 *machine = dyn->machine;
5253 *pe_kind = ((MonoCLIImageInfo*)(image->image_info))->cli_cli_header.ch_flags & 0x3;
5254 *machine = ((MonoCLIImageInfo*)(image->image_info))->cli_header.coff.coff_machine;
5259 ves_icall_System_Reflection_Module_GetMDStreamVersion (MonoImage *image)
5261 return (image->md_version_major << 16) | (image->md_version_minor);
5264 ICALL_EXPORT MonoArray*
5265 ves_icall_System_Reflection_Module_InternalGetTypes (MonoReflectionModule *module)
5267 MonoArray *exceptions;
5271 return mono_array_new (mono_object_domain (module), mono_defaults.monotype_class, 0);
5273 MonoArray *res = mono_module_get_types (mono_object_domain (module), module->image, &exceptions, FALSE);
5274 for (i = 0; i < mono_array_length (exceptions); ++i) {
5275 MonoException *ex = mono_array_get (exceptions, MonoException *, i);
5277 mono_raise_exception (ex);
5284 mono_memberref_is_method (MonoImage *image, guint32 token)
5286 if (!image_is_dynamic (image)) {
5287 guint32 cols [MONO_MEMBERREF_SIZE];
5289 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
5290 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
5291 mono_metadata_decode_blob_size (sig, &sig);
5292 return (*sig != 0x6);
5294 MonoClass *handle_class;
5296 if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL))
5299 return mono_defaults.methodhandle_class == handle_class;
5304 init_generic_context_from_args (MonoGenericContext *context, MonoArray *type_args, MonoArray *method_args)
5307 context->class_inst = mono_metadata_get_generic_inst (mono_array_length (type_args),
5308 mono_array_addr (type_args, MonoType*, 0));
5310 context->class_inst = NULL;
5312 context->method_inst = mono_metadata_get_generic_inst (mono_array_length (method_args),
5313 mono_array_addr (method_args, MonoType*, 0));
5315 context->method_inst = NULL;
5318 ICALL_EXPORT MonoType*
5319 ves_icall_System_Reflection_Module_ResolveTypeToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *resolve_error)
5322 int table = mono_metadata_token_table (token);
5323 int index = mono_metadata_token_index (token);
5324 MonoGenericContext context;
5327 *resolve_error = ResolveTokenError_Other;
5329 /* Validate token */
5330 if ((table != MONO_TABLE_TYPEDEF) && (table != MONO_TABLE_TYPEREF) &&
5331 (table != MONO_TABLE_TYPESPEC)) {
5332 *resolve_error = ResolveTokenError_BadTable;
5336 if (image_is_dynamic (image)) {
5337 if ((table == MONO_TABLE_TYPEDEF) || (table == MONO_TABLE_TYPEREF)) {
5338 klass = mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5339 return klass ? &klass->byval_arg : NULL;
5342 init_generic_context_from_args (&context, type_args, method_args);
5343 klass = mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
5344 return klass ? &klass->byval_arg : NULL;
5347 if ((index <= 0) || (index > image->tables [table].rows)) {
5348 *resolve_error = ResolveTokenError_OutOfRange;
5352 init_generic_context_from_args (&context, type_args, method_args);
5353 klass = mono_class_get_checked (image, token, &error);
5355 klass = mono_class_inflate_generic_class_checked (klass, &context, &error);
5356 mono_error_raise_exception (&error);
5359 return &klass->byval_arg;
5364 ICALL_EXPORT MonoMethod*
5365 ves_icall_System_Reflection_Module_ResolveMethodToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *resolve_error)
5368 int table = mono_metadata_token_table (token);
5369 int index = mono_metadata_token_index (token);
5370 MonoGenericContext context;
5373 *resolve_error = ResolveTokenError_Other;
5375 /* Validate token */
5376 if ((table != MONO_TABLE_METHOD) && (table != MONO_TABLE_METHODSPEC) &&
5377 (table != MONO_TABLE_MEMBERREF)) {
5378 *resolve_error = ResolveTokenError_BadTable;
5382 if (image_is_dynamic (image)) {
5383 if (table == MONO_TABLE_METHOD)
5384 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5386 if ((table == MONO_TABLE_MEMBERREF) && !(mono_memberref_is_method (image, token))) {
5387 *resolve_error = ResolveTokenError_BadTable;
5391 init_generic_context_from_args (&context, type_args, method_args);
5392 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
5395 if ((index <= 0) || (index > image->tables [table].rows)) {
5396 *resolve_error = ResolveTokenError_OutOfRange;
5399 if ((table == MONO_TABLE_MEMBERREF) && (!mono_memberref_is_method (image, token))) {
5400 *resolve_error = ResolveTokenError_BadTable;
5404 init_generic_context_from_args (&context, type_args, method_args);
5405 method = mono_get_method_checked (image, token, NULL, &context, &error);
5406 mono_error_raise_exception (&error);
5411 ICALL_EXPORT MonoString*
5412 ves_icall_System_Reflection_Module_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *error)
5414 int index = mono_metadata_token_index (token);
5416 *error = ResolveTokenError_Other;
5418 /* Validate token */
5419 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
5420 *error = ResolveTokenError_BadTable;
5424 if (image_is_dynamic (image))
5425 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5427 if ((index <= 0) || (index >= image->heap_us.size)) {
5428 *error = ResolveTokenError_OutOfRange;
5432 /* FIXME: What to do if the index points into the middle of a string ? */
5434 return mono_ldstr (mono_domain_get (), image, index);
5437 ICALL_EXPORT MonoClassField*
5438 ves_icall_System_Reflection_Module_ResolveFieldToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *resolve_error)
5442 int table = mono_metadata_token_table (token);
5443 int index = mono_metadata_token_index (token);
5444 MonoGenericContext context;
5445 MonoClassField *field;
5447 *resolve_error = ResolveTokenError_Other;
5449 /* Validate token */
5450 if ((table != MONO_TABLE_FIELD) && (table != MONO_TABLE_MEMBERREF)) {
5451 *resolve_error = ResolveTokenError_BadTable;
5455 if (image_is_dynamic (image)) {
5456 if (table == MONO_TABLE_FIELD)
5457 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5459 if (mono_memberref_is_method (image, token)) {
5460 *resolve_error = ResolveTokenError_BadTable;
5464 init_generic_context_from_args (&context, type_args, method_args);
5465 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
5468 if ((index <= 0) || (index > image->tables [table].rows)) {
5469 *resolve_error = ResolveTokenError_OutOfRange;
5472 if ((table == MONO_TABLE_MEMBERREF) && (mono_memberref_is_method (image, token))) {
5473 *resolve_error = ResolveTokenError_BadTable;
5477 init_generic_context_from_args (&context, type_args, method_args);
5478 field = mono_field_from_token_checked (image, token, &klass, &context, &error);
5479 mono_error_raise_exception (&error);
5485 ICALL_EXPORT MonoObject*
5486 ves_icall_System_Reflection_Module_ResolveMemberToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *error)
5488 int table = mono_metadata_token_table (token);
5490 *error = ResolveTokenError_Other;
5493 case MONO_TABLE_TYPEDEF:
5494 case MONO_TABLE_TYPEREF:
5495 case MONO_TABLE_TYPESPEC: {
5496 MonoType *t = ves_icall_System_Reflection_Module_ResolveTypeToken (image, token, type_args, method_args, error);
5498 return (MonoObject*)mono_type_get_object (mono_domain_get (), t);
5502 case MONO_TABLE_METHOD:
5503 case MONO_TABLE_METHODSPEC: {
5504 MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, type_args, method_args, error);
5506 return (MonoObject*)mono_method_get_object (mono_domain_get (), m, m->klass);
5510 case MONO_TABLE_FIELD: {
5511 MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, type_args, method_args, error);
5513 return (MonoObject*)mono_field_get_object (mono_domain_get (), f->parent, f);
5517 case MONO_TABLE_MEMBERREF:
5518 if (mono_memberref_is_method (image, token)) {
5519 MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, type_args, method_args, error);
5521 return (MonoObject*)mono_method_get_object (mono_domain_get (), m, m->klass);
5526 MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, type_args, method_args, error);
5528 return (MonoObject*)mono_field_get_object (mono_domain_get (), f->parent, f);
5535 *error = ResolveTokenError_BadTable;
5541 ICALL_EXPORT MonoArray*
5542 ves_icall_System_Reflection_Module_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *error)
5544 int table = mono_metadata_token_table (token);
5545 int idx = mono_metadata_token_index (token);
5546 MonoTableInfo *tables = image->tables;
5551 *error = ResolveTokenError_OutOfRange;
5553 /* FIXME: Support other tables ? */
5554 if (table != MONO_TABLE_STANDALONESIG)
5557 if (image_is_dynamic (image))
5560 if ((idx == 0) || (idx > tables [MONO_TABLE_STANDALONESIG].rows))
5563 sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
5565 ptr = mono_metadata_blob_heap (image, sig);
5566 len = mono_metadata_decode_blob_size (ptr, &ptr);
5568 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, len);
5569 memcpy (mono_array_addr (res, guint8, 0), ptr, len);
5573 ICALL_EXPORT MonoReflectionType*
5574 ves_icall_ModuleBuilder_create_modified_type (MonoReflectionTypeBuilder *tb, MonoString *smodifiers)
5577 int isbyref = 0, rank;
5578 char *str = mono_string_to_utf8 (smodifiers);
5581 klass = mono_class_from_mono_type (tb->type.type);
5583 /* logic taken from mono_reflection_parse_type(): keep in sync */
5587 if (isbyref) { /* only one level allowed by the spec */
5594 return mono_type_get_object (mono_object_domain (tb), &klass->this_arg);
5597 klass = mono_ptr_class_get (&klass->byval_arg);
5598 mono_class_init (klass);
5609 else if (*p != '*') { /* '*' means unknown lower bound */
5620 klass = mono_array_class_get (klass, rank);
5621 mono_class_init (klass);
5628 return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
5631 ICALL_EXPORT MonoBoolean
5632 ves_icall_Type_IsArrayImpl (MonoReflectionType *t)
5638 res = !type->byref && (type->type == MONO_TYPE_ARRAY || type->type == MONO_TYPE_SZARRAY);
5644 check_for_invalid_type (MonoClass *klass)
5648 if (klass->byval_arg.type != MONO_TYPE_TYPEDBYREF)
5651 name = mono_type_get_full_name (klass);
5652 str = mono_string_new (mono_domain_get (), name);
5654 mono_raise_exception ((MonoException*)mono_get_exception_type_load (str, NULL));
5657 ICALL_EXPORT MonoReflectionType *
5658 ves_icall_Type_make_array_type (MonoReflectionType *type, int rank)
5660 MonoClass *klass, *aklass;
5662 klass = mono_class_from_mono_type (type->type);
5663 check_for_invalid_type (klass);
5665 if (rank == 0) //single dimentional array
5666 aklass = mono_array_class_get (klass, 1);
5668 aklass = mono_bounded_array_class_get (klass, rank, TRUE);
5670 return mono_type_get_object (mono_object_domain (type), &aklass->byval_arg);
5673 ICALL_EXPORT MonoReflectionType *
5674 ves_icall_Type_make_byref_type (MonoReflectionType *type)
5678 klass = mono_class_from_mono_type (type->type);
5679 mono_class_init_or_throw (klass);
5680 check_for_invalid_type (klass);
5682 return mono_type_get_object (mono_object_domain (type), &klass->this_arg);
5685 ICALL_EXPORT MonoReflectionType *
5686 ves_icall_Type_MakePointerType (MonoReflectionType *type)
5688 MonoClass *klass, *pklass;
5690 klass = mono_class_from_mono_type (type->type);
5691 mono_class_init_or_throw (klass);
5692 check_for_invalid_type (klass);
5694 pklass = mono_ptr_class_get (type->type);
5696 return mono_type_get_object (mono_object_domain (type), &pklass->byval_arg);
5699 ICALL_EXPORT MonoObject *
5700 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionType *type, MonoObject *target,
5701 MonoReflectionMethod *info, MonoBoolean throwOnBindFailure)
5703 MonoClass *delegate_class = mono_class_from_mono_type (type->type);
5704 MonoObject *delegate;
5706 MonoMethod *method = info->method;
5708 mono_class_init_or_throw (delegate_class);
5710 mono_assert (delegate_class->parent == mono_defaults.multicastdelegate_class);
5712 if (mono_security_core_clr_enabled ()) {
5713 if (!mono_security_core_clr_ensure_delegate_creation (method, throwOnBindFailure))
5717 delegate = mono_object_new (mono_object_domain (type), delegate_class);
5719 if (method_is_dynamic (method)) {
5720 /* Creating a trampoline would leak memory */
5721 func = mono_compile_method (method);
5723 if (target && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass != mono_object_class (target))
5724 method = mono_object_get_virtual_method (target, method);
5725 func = mono_create_ftnptr (mono_domain_get (),
5726 mono_runtime_create_jump_trampoline (mono_domain_get (), method, TRUE));
5729 mono_delegate_ctor_with_method (delegate, target, func, method);
5735 ves_icall_System_Delegate_SetMulticastInvoke (MonoDelegate *this)
5737 /* Reset the invoke impl to the default one */
5738 this->invoke_impl = mono_runtime_create_delegate_trampoline (this->object.vtable->klass);
5742 * Magic number to convert a time which is relative to
5743 * Jan 1, 1970 into a value which is relative to Jan 1, 0001.
5745 #define EPOCH_ADJUST ((guint64)62135596800LL)
5748 * Magic number to convert FILETIME base Jan 1, 1601 to DateTime - base Jan, 1, 0001
5750 #define FILETIME_ADJUST ((guint64)504911232000000000LL)
5753 /* convert a SYSTEMTIME which is of the form "last thursday in october" to a real date */
5755 convert_to_absolute_date(SYSTEMTIME *date)
5757 #define IS_LEAP(y) ((y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0))
5758 static int days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
5759 static int leap_days_in_month[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
5760 /* from the calendar FAQ */
5761 int a = (14 - date->wMonth) / 12;
5762 int y = date->wYear - a;
5763 int m = date->wMonth + 12 * a - 2;
5764 int d = (1 + y + y/4 - y/100 + y/400 + (31*m)/12) % 7;
5766 /* d is now the day of the week for the first of the month (0 == Sunday) */
5768 int day_of_week = date->wDayOfWeek;
5770 /* set day_in_month to the first day in the month which falls on day_of_week */
5771 int day_in_month = 1 + (day_of_week - d);
5772 if (day_in_month <= 0)
5775 /* wDay is 1 for first weekday in month, 2 for 2nd ... 5 means last - so work that out allowing for days in the month */
5776 date->wDay = day_in_month + (date->wDay - 1) * 7;
5777 if (date->wDay > (IS_LEAP(date->wYear) ? leap_days_in_month[date->wMonth - 1] : days_in_month[date->wMonth - 1]))
5784 * Return's the offset from GMT of a local time.
5786 * tm is a local time
5787 * t is the same local time as seconds.
5790 gmt_offset(struct tm *tm, time_t t)
5792 #if defined (HAVE_TM_GMTOFF)
5793 return tm->tm_gmtoff;
5798 g.tm_isdst = tm->tm_isdst;
5800 return (int)difftime(t, t2);
5805 * This is heavily based on zdump.c from glibc 2.2.
5807 * * data[0]: start of daylight saving time (in DateTime ticks).
5808 * * data[1]: end of daylight saving time (in DateTime ticks).
5809 * * data[2]: utcoffset (in TimeSpan ticks).
5810 * * data[3]: additional offset when daylight saving (in TimeSpan ticks).
5811 * * name[0]: name of this timezone when not daylight saving.
5812 * * name[1]: name of this timezone when daylight saving.
5814 * FIXME: This only works with "standard" Unix dates (years between 1900 and 2100) while
5815 * the class library allows years between 1 and 9999.
5817 * Returns true on success and zero on failure.
5819 ICALL_EXPORT guint32
5820 ves_icall_System_CurrentSystemTimeZone_GetTimeZoneData (guint32 year, MonoArray **data, MonoArray **names)
5823 MonoDomain *domain = mono_domain_get ();
5824 struct tm start, tt;
5827 long int gmtoff, gmtoff_after, gmtoff_st, gmtoff_ds;
5828 int day, transitioned;
5831 gmtoff_st = gmtoff_ds = transitioned = 0;
5833 MONO_CHECK_ARG_NULL (data);
5834 MONO_CHECK_ARG_NULL (names);
5836 mono_gc_wbarrier_generic_store (data, (MonoObject*) mono_array_new (domain, mono_defaults.int64_class, 4));
5837 mono_gc_wbarrier_generic_store (names, (MonoObject*) mono_array_new (domain, mono_defaults.string_class, 2));
5840 * no info is better than crashing: we'll need our own tz data
5841 * to make this work properly, anyway. The range is probably
5842 * reduced to 1970 .. 2037 because that is what mktime is
5843 * guaranteed to support (we get into an infinite loop
5847 memset (&start, 0, sizeof (start));
5850 start.tm_year = year-1900;
5852 t = mktime (&start);
5854 if ((year < 1970) || (year > 2037) || (t == -1)) {
5856 tt = *localtime (&t);
5857 strftime (tzone, sizeof (tzone), "%Z", &tt);
5858 mono_array_setref ((*names), 0, mono_string_new (domain, tzone));
5859 mono_array_setref ((*names), 1, mono_string_new (domain, tzone));
5863 gmtoff = gmt_offset (&start, t);
5865 /* For each day of the year, calculate the tm_gmtoff. */
5866 for (day = 0; day < 365 && transitioned < 2; day++) {
5869 tt = *localtime (&t);
5871 gmtoff_after = gmt_offset(&tt, t);
5873 /* Daylight saving starts or ends here. */
5874 if (gmtoff_after != gmtoff) {
5878 /* Try to find the exact hour when daylight saving starts/ends. */
5882 tt1 = *localtime (&t1);
5883 } while (gmt_offset (&tt1, t1) != gmtoff);
5885 /* Try to find the exact minute when daylight saving starts/ends. */
5888 tt1 = *localtime (&t1);
5889 } while (gmt_offset (&tt1, t1) == gmtoff);
5891 strftime (tzone, sizeof (tzone), "%Z", &tt);
5893 /* Write data, if we're already in daylight saving, we're done. */
5895 mono_array_setref ((*names), 1, mono_string_new (domain, tzone));
5896 mono_array_set ((*data), gint64, 0, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
5897 if (gmtoff_ds == 0) {
5899 gmtoff_ds = gmtoff_after;
5906 mono_array_setref ((*names), 0, mono_string_new (domain, tzone));
5907 mono_array_set ((*data), gint64, 1, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
5908 if (gmtoff_ds == 0) {
5909 gmtoff_st = gmtoff_after;
5915 /* This is only set once when we enter daylight saving. */
5917 mono_array_set ((*data), gint64, 2, (gint64)gmtoff_st * 10000000L);
5918 mono_array_set ((*data), gint64, 3, (gint64)(gmtoff_ds - gmtoff_st) * 10000000L);
5920 gmtoff = gmt_offset (&tt, t);
5924 if (transitioned < 2) {
5925 strftime (tzone, sizeof (tzone), "%Z", &tt);
5926 mono_array_setref ((*names), 0, mono_string_new (domain, tzone));
5927 mono_array_setref ((*names), 1, mono_string_new (domain, tzone));
5928 mono_array_set ((*data), gint64, 0, 0);
5929 mono_array_set ((*data), gint64, 1, 0);
5930 mono_array_set ((*data), gint64, 2, (gint64) gmtoff * 10000000L);
5931 mono_array_set ((*data), gint64, 3, 0);
5936 MonoDomain *domain = mono_domain_get ();
5937 TIME_ZONE_INFORMATION tz_info;
5942 tz_id = GetTimeZoneInformation (&tz_info);
5943 if (tz_id == TIME_ZONE_ID_INVALID)
5946 MONO_CHECK_ARG_NULL (data);
5947 MONO_CHECK_ARG_NULL (names);
5949 mono_gc_wbarrier_generic_store (data, mono_array_new (domain, mono_defaults.int64_class, 4));
5950 mono_gc_wbarrier_generic_store (names, mono_array_new (domain, mono_defaults.string_class, 2));
5952 for (i = 0; i < 32; ++i)
5953 if (!tz_info.DaylightName [i])
5955 mono_array_setref ((*names), 1, mono_string_new_utf16 (domain, tz_info.DaylightName, i));
5956 for (i = 0; i < 32; ++i)
5957 if (!tz_info.StandardName [i])
5959 mono_array_setref ((*names), 0, mono_string_new_utf16 (domain, tz_info.StandardName, i));
5961 if ((year <= 1601) || (year > 30827)) {
5963 * According to MSDN, the MS time functions can't handle dates outside
5969 /* even if the timezone has no daylight savings it may have Bias (e.g. GMT+13 it seems) */
5970 if (tz_id != TIME_ZONE_ID_UNKNOWN) {
5971 tz_info.StandardDate.wYear = year;
5972 convert_to_absolute_date(&tz_info.StandardDate);
5973 err = SystemTimeToFileTime (&tz_info.StandardDate, &ft);
5978 mono_array_set ((*data), gint64, 1, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
5979 tz_info.DaylightDate.wYear = year;
5980 convert_to_absolute_date(&tz_info.DaylightDate);
5981 err = SystemTimeToFileTime (&tz_info.DaylightDate, &ft);
5986 mono_array_set ((*data), gint64, 0, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
5988 mono_array_set ((*data), gint64, 2, (tz_info.Bias + tz_info.StandardBias) * -600000000LL);
5989 mono_array_set ((*data), gint64, 3, (tz_info.DaylightBias - tz_info.StandardBias) * -600000000LL);
5997 static inline gint32
5998 mono_array_get_byte_length (MonoArray *array)
6004 klass = array->obj.vtable->klass;
6006 if (array->bounds == NULL)
6007 length = array->max_length;
6010 for (i = 0; i < klass->rank; ++ i)
6011 length *= array->bounds [i].length;
6014 switch (klass->element_class->byval_arg.type) {
6017 case MONO_TYPE_BOOLEAN:
6021 case MONO_TYPE_CHAR:
6029 return length * sizeof (gpointer);
6040 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array)
6042 return mono_array_get_byte_length (array);
6046 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx)
6048 return mono_array_get (array, gint8, idx);
6052 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value)
6054 mono_array_set (array, gint8, idx, value);
6057 ICALL_EXPORT MonoBoolean
6058 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count)
6060 guint8 *src_buf, *dest_buf;
6062 /* This is called directly from the class libraries without going through the managed wrapper */
6063 MONO_CHECK_ARG_NULL (src);
6064 MONO_CHECK_ARG_NULL (dest);
6066 /* watch out for integer overflow */
6067 if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
6070 src_buf = (guint8 *)src->vector + src_offset;
6071 dest_buf = (guint8 *)dest->vector + dest_offset;
6074 memcpy (dest_buf, src_buf, count);
6076 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
6081 #ifndef DISABLE_REMOTING
6082 ICALL_EXPORT MonoObject *
6083 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObject *this, MonoString *class_name)
6085 MonoDomain *domain = mono_object_domain (this);
6087 MonoRealProxy *rp = ((MonoRealProxy *)this);
6088 MonoTransparentProxy *tp;
6092 res = mono_object_new (domain, mono_defaults.transparent_proxy_class);
6093 tp = (MonoTransparentProxy*) res;
6095 MONO_OBJECT_SETREF (tp, rp, rp);
6096 type = ((MonoReflectionType *)rp->class_to_proxy)->type;
6097 klass = mono_class_from_mono_type (type);
6099 tp->custom_type_info = (mono_object_isinst (this, mono_defaults.iremotingtypeinfo_class) != NULL);
6100 tp->remote_class = mono_remote_class (domain, class_name, klass);
6102 res->vtable = mono_remote_class_vtable (domain, tp->remote_class, rp);
6106 ICALL_EXPORT MonoReflectionType *
6107 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
6109 return mono_type_get_object (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg);
6113 /* System.Environment */
6116 ves_icall_System_Environment_get_UserName (void)
6118 /* using glib is more portable */
6119 return mono_string_new (mono_domain_get (), g_get_user_name ());
6123 ICALL_EXPORT MonoString *
6124 ves_icall_System_Environment_get_MachineName (void)
6126 #if defined (HOST_WIN32)
6131 len = MAX_COMPUTERNAME_LENGTH + 1;
6132 buf = g_new (gunichar2, len);
6135 if (GetComputerName (buf, (PDWORD) &len))
6136 result = mono_string_new_utf16 (mono_domain_get (), buf, len);
6140 #elif !defined(DISABLE_SOCKETS)
6144 if (gethostname (buf, sizeof (buf)) == 0)
6145 result = mono_string_new (mono_domain_get (), buf);
6151 return mono_string_new (mono_domain_get (), "mono");
6156 ves_icall_System_Environment_get_Platform (void)
6158 #if defined (TARGET_WIN32)
6161 #elif defined(__MACH__)
6164 // Notice that the value is hidden from user code, and only exposed
6165 // to mscorlib. This is due to Mono's Unix/MacOS code predating the
6166 // define and making assumptions based on Unix/128/4 values before there
6167 // was a MacOS define. Lots of code would assume that not-Unix meant
6168 // Windows, but in this case, it would be OSX.
6177 ICALL_EXPORT MonoString *
6178 ves_icall_System_Environment_get_NewLine (void)
6180 #if defined (HOST_WIN32)
6181 return mono_string_new (mono_domain_get (), "\r\n");
6183 return mono_string_new (mono_domain_get (), "\n");
6187 ICALL_EXPORT MonoString *
6188 ves_icall_System_Environment_GetEnvironmentVariable (MonoString *name)
6196 utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
6197 value = g_getenv (utf8_name);
6204 return mono_string_new (mono_domain_get (), value);
6208 * There is no standard way to get at environ.
6211 #ifndef __MINGW32_VERSION
6212 #if defined(__APPLE__) && !defined (__arm__)
6213 /* Apple defines this in crt_externs.h but doesn't provide that header for
6214 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
6215 * in fact exist on all implementations (so far)
6217 gchar ***_NSGetEnviron(void);
6218 #define environ (*_NSGetEnviron())
6226 ICALL_EXPORT MonoArray *
6227 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
6238 env_strings = GetEnvironmentStrings();
6241 env_string = env_strings;
6242 while (*env_string != '\0') {
6243 /* weird case that MS seems to skip */
6244 if (*env_string != '=')
6246 while (*env_string != '\0')
6252 domain = mono_domain_get ();
6253 names = mono_array_new (domain, mono_defaults.string_class, n);
6257 env_string = env_strings;
6258 while (*env_string != '\0') {
6259 /* weird case that MS seems to skip */
6260 if (*env_string != '=') {
6261 equal_str = wcschr(env_string, '=');
6262 g_assert(equal_str);
6263 str = mono_string_new_utf16 (domain, env_string, equal_str-env_string);
6264 mono_array_setref (names, n, str);
6267 while (*env_string != '\0')
6272 FreeEnvironmentStrings (env_strings);
6285 for (e = environ; *e != 0; ++ e)
6288 domain = mono_domain_get ();
6289 names = mono_array_new (domain, mono_defaults.string_class, n);
6292 for (e = environ; *e != 0; ++ e) {
6293 parts = g_strsplit (*e, "=", 2);
6295 str = mono_string_new (domain, *parts);
6296 mono_array_setref (names, n, str);
6309 * If your platform lacks setenv/unsetenv, you must upgrade your glib.
6311 #if !GLIB_CHECK_VERSION(2,4,0)
6312 #define g_setenv(a,b,c) setenv(a,b,c)
6313 #define g_unsetenv(a) unsetenv(a)
6317 ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
6320 gunichar2 *utf16_name, *utf16_value;
6322 gchar *utf8_name, *utf8_value;
6327 utf16_name = mono_string_to_utf16 (name);
6328 if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
6329 SetEnvironmentVariable (utf16_name, NULL);
6330 g_free (utf16_name);
6334 utf16_value = mono_string_to_utf16 (value);
6336 SetEnvironmentVariable (utf16_name, utf16_value);
6338 g_free (utf16_name);
6339 g_free (utf16_value);
6341 utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
6343 if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
6344 g_unsetenv (utf8_name);
6349 utf8_value = mono_string_to_utf8_checked (value, &error);
6350 if (!mono_error_ok (&error)) {
6352 mono_error_raise_exception (&error);
6354 g_setenv (utf8_name, utf8_value, TRUE);
6357 g_free (utf8_value);
6362 ves_icall_System_Environment_Exit (int result)
6364 mono_environment_exitcode_set (result);
6366 /* FIXME: There are some cleanup hangs that should be worked out, but
6367 * if the program is going to exit, everything will be cleaned up when
6368 * NaCl exits anyway.
6370 #ifndef __native_client__
6371 if (!mono_runtime_try_shutdown ())
6372 mono_thread_exit ();
6374 /* Suspend all managed threads since the runtime is going away */
6375 mono_thread_suspend_all_other_threads ();
6377 mono_runtime_quit ();
6380 /* we may need to do some cleanup here... */
6384 ICALL_EXPORT MonoString*
6385 ves_icall_System_Environment_GetGacPath (void)
6387 return mono_string_new (mono_domain_get (), mono_assembly_getrootdir ());
6390 ICALL_EXPORT MonoString*
6391 ves_icall_System_Environment_GetWindowsFolderPath (int folder)
6393 #if defined (HOST_WIN32)
6394 #ifndef CSIDL_FLAG_CREATE
6395 #define CSIDL_FLAG_CREATE 0x8000
6398 WCHAR path [MAX_PATH];
6399 /* Create directory if no existing */
6400 if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
6404 return mono_string_new_utf16 (mono_domain_get (), path, len);
6407 g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
6409 return mono_string_new (mono_domain_get (), "");
6412 ICALL_EXPORT MonoArray *
6413 ves_icall_System_Environment_GetLogicalDrives (void)
6415 gunichar2 buf [256], *ptr, *dname;
6417 guint initial_size = 127, size = 128;
6420 MonoString *drivestr;
6421 MonoDomain *domain = mono_domain_get ();
6427 while (size > initial_size) {
6428 size = (guint) GetLogicalDriveStrings (initial_size, ptr);
6429 if (size > initial_size) {
6432 ptr = g_malloc0 ((size + 1) * sizeof (gunichar2));
6433 initial_size = size;
6447 result = mono_array_new (domain, mono_defaults.string_class, ndrives);
6452 while (*u16) { u16++; len ++; }
6453 drivestr = mono_string_new_utf16 (domain, dname, len);
6454 mono_array_setref (result, ndrives++, drivestr);
6464 ICALL_EXPORT MonoString *
6465 ves_icall_System_IO_DriveInfo_GetDriveFormat (MonoString *path)
6467 gunichar2 volume_name [MAX_PATH + 1];
6469 if (GetVolumeInformation (mono_string_chars (path), NULL, 0, NULL, NULL, NULL, volume_name, MAX_PATH + 1) == FALSE)
6471 return mono_string_from_utf16 (volume_name);
6474 ICALL_EXPORT MonoString *
6475 ves_icall_System_Environment_InternalGetHome (void)
6477 return mono_string_new (mono_domain_get (), g_get_home_dir ());
6480 static const char *encodings [] = {
6482 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
6483 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
6484 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
6486 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
6487 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
6488 "x_unicode_2_0_utf_7",
6490 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
6491 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
6493 "utf_16", "UTF_16LE", "ucs_2", "unicode",
6496 "unicodefffe", "utf_16be",
6503 * Returns the internal codepage, if the value of "int_code_page" is
6504 * 1 at entry, and we can not compute a suitable code page number,
6505 * returns the code page as a string
6507 ICALL_EXPORT MonoString*
6508 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page)
6513 char *codepage = NULL;
6515 int want_name = *int_code_page;
6518 *int_code_page = -1;
6520 g_get_charset (&cset);
6521 c = codepage = strdup (cset);
6522 for (c = codepage; *c; c++){
6523 if (isascii (*c) && isalpha (*c))
6528 /* g_print ("charset: %s\n", cset); */
6530 /* handle some common aliases */
6533 for (i = 0; p != 0; ){
6534 if ((gssize) p < 7){
6536 p = encodings [++i];
6539 if (strcmp (p, codepage) == 0){
6540 *int_code_page = code;
6543 p = encodings [++i];
6546 if (strstr (codepage, "utf_8") != NULL)
6547 *int_code_page |= 0x10000000;
6550 if (want_name && *int_code_page == -1)
6551 return mono_string_new (mono_domain_get (), cset);
6556 ICALL_EXPORT MonoBoolean
6557 ves_icall_System_Environment_get_HasShutdownStarted (void)
6559 if (mono_runtime_is_shutting_down ())
6562 if (mono_domain_is_unloading (mono_domain_get ()))
6569 ves_icall_System_Environment_BroadcastSettingChange (void)
6572 SendMessageTimeout (HWND_BROADCAST, WM_SETTINGCHANGE, (WPARAM)NULL, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 2000, 0);
6577 ves_icall_MonoMethodMessage_InitMessage (MonoMethodMessage *this,
6578 MonoReflectionMethod *method,
6579 MonoArray *out_args)
6581 mono_message_init (mono_object_domain (this), this, method, out_args);
6584 #ifndef DISABLE_REMOTING
6585 ICALL_EXPORT MonoBoolean
6586 ves_icall_IsTransparentProxy (MonoObject *proxy)
6591 if (proxy->vtable->klass == mono_defaults.transparent_proxy_class)
6597 ICALL_EXPORT MonoReflectionMethod *
6598 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
6599 MonoReflectionType *rtype, MonoReflectionMethod *rmethod)
6603 MonoMethod **vtable;
6604 MonoMethod *res = NULL;
6606 MONO_CHECK_ARG_NULL (rtype);
6607 MONO_CHECK_ARG_NULL (rmethod);
6609 method = rmethod->method;
6610 klass = mono_class_from_mono_type (rtype->type);
6611 mono_class_init_or_throw (klass);
6613 if (MONO_CLASS_IS_INTERFACE (klass))
6616 if (method->flags & METHOD_ATTRIBUTE_STATIC)
6619 if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6620 if (klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE))
6626 mono_class_setup_vtable (klass);
6627 vtable = klass->vtable;
6629 if (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6630 gboolean variance_used = FALSE;
6631 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
6632 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
6634 res = vtable [offs + method->slot];
6636 if (!(klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE)))
6639 if (method->slot != -1)
6640 res = vtable [method->slot];
6646 return mono_method_get_object (mono_domain_get (), res, NULL);
6650 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6655 klass = mono_class_from_mono_type (type->type);
6656 vtable = mono_class_vtable_full (mono_domain_get (), klass, TRUE);
6658 mono_vtable_set_is_remote (vtable, enable);
6661 #else /* DISABLE_REMOTING */
6664 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6666 g_assert_not_reached ();
6671 ICALL_EXPORT MonoObject *
6672 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionType *type)
6677 domain = mono_object_domain (type);
6678 klass = mono_class_from_mono_type (type->type);
6679 mono_class_init_or_throw (klass);
6681 if (MONO_CLASS_IS_INTERFACE (klass) || (klass->flags & TYPE_ATTRIBUTE_ABSTRACT))
6682 mono_raise_exception (mono_get_exception_argument ("type", "Type cannot be instantiated"));
6684 if (klass->rank >= 1) {
6685 g_assert (klass->rank == 1);
6686 return (MonoObject *) mono_array_new (domain, klass->element_class, 0);
6688 /* Bypass remoting object creation check */
6689 return mono_object_new_alloc_specific (mono_class_vtable_full (domain, klass, TRUE));
6693 ICALL_EXPORT MonoString *
6694 ves_icall_System_IO_get_temp_path (void)
6696 return mono_string_new (mono_domain_get (), g_get_tmp_dir ());
6699 #ifndef PLATFORM_NO_DRIVEINFO
6700 ICALL_EXPORT MonoBoolean
6701 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (MonoString *path_name, guint64 *free_bytes_avail,
6702 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
6706 ULARGE_INTEGER wapi_free_bytes_avail;
6707 ULARGE_INTEGER wapi_total_number_of_bytes;
6708 ULARGE_INTEGER wapi_total_number_of_free_bytes;
6710 *error = ERROR_SUCCESS;
6711 result = GetDiskFreeSpaceEx (mono_string_chars (path_name), &wapi_free_bytes_avail, &wapi_total_number_of_bytes,
6712 &wapi_total_number_of_free_bytes);
6715 *free_bytes_avail = wapi_free_bytes_avail.QuadPart;
6716 *total_number_of_bytes = wapi_total_number_of_bytes.QuadPart;
6717 *total_number_of_free_bytes = wapi_total_number_of_free_bytes.QuadPart;
6719 *free_bytes_avail = 0;
6720 *total_number_of_bytes = 0;
6721 *total_number_of_free_bytes = 0;
6722 *error = GetLastError ();
6728 ICALL_EXPORT guint32
6729 ves_icall_System_IO_DriveInfo_GetDriveType (MonoString *root_path_name)
6731 return GetDriveType (mono_string_chars (root_path_name));
6735 ICALL_EXPORT gpointer
6736 ves_icall_RuntimeMethod_GetFunctionPointer (MonoMethod *method)
6738 return mono_compile_method (method);
6741 ICALL_EXPORT MonoString *
6742 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
6747 path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
6749 #if defined (HOST_WIN32)
6750 /* Avoid mixing '/' and '\\' */
6753 for (i = strlen (path) - 1; i >= 0; i--)
6754 if (path [i] == '/')
6758 mcpath = mono_string_new (mono_domain_get (), path);
6765 get_bundled_app_config (void)
6767 const gchar *app_config;
6770 gchar *config_file_name, *config_file_path;
6774 domain = mono_domain_get ();
6775 file = domain->setup->configuration_file;
6779 // Retrieve config file and remove the extension
6780 config_file_name = mono_string_to_utf8 (file);
6781 config_file_path = mono_portability_find_file (config_file_name, TRUE);
6782 if (!config_file_path)
6783 config_file_path = config_file_name;
6784 len = strlen (config_file_path) - strlen (".config");
6785 module = g_malloc0 (len + 1);
6786 memcpy (module, config_file_path, len);
6787 // Get the config file from the module name
6788 app_config = mono_config_string_for_assembly_file (module);
6791 if (config_file_name != config_file_path)
6792 g_free (config_file_name);
6793 g_free (config_file_path);
6798 return mono_string_new (mono_domain_get (), app_config);
6802 get_bundled_machine_config (void)
6804 const gchar *machine_config;
6806 machine_config = mono_get_machine_config ();
6808 if (!machine_config)
6811 return mono_string_new (mono_domain_get (), machine_config);
6814 ICALL_EXPORT MonoString *
6815 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
6820 path = g_path_get_dirname (mono_get_config_dir ());
6822 #if defined (HOST_WIN32)
6823 /* Avoid mixing '/' and '\\' */
6826 for (i = strlen (path) - 1; i >= 0; i--)
6827 if (path [i] == '/')
6831 ipath = mono_string_new (mono_domain_get (), path);
6837 ICALL_EXPORT gboolean
6838 ves_icall_get_resources_ptr (MonoReflectionAssembly *assembly, gpointer *result, gint32 *size)
6840 MonoPEResourceDataEntry *entry;
6843 if (!assembly || !result || !size)
6848 image = assembly->assembly->image;
6849 entry = mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
6853 *result = mono_image_rva_map (image, entry->rde_data_offset);
6858 *size = entry->rde_size;
6863 ICALL_EXPORT MonoBoolean
6864 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (void)
6866 return mono_is_debugger_attached ();
6869 ICALL_EXPORT MonoBoolean
6870 ves_icall_System_Diagnostics_Debugger_IsLogging (void)
6872 if (mono_get_runtime_callbacks ()->debug_log_is_enabled)
6873 return mono_get_runtime_callbacks ()->debug_log_is_enabled ();
6879 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoString *category, MonoString *message)
6881 if (mono_get_runtime_callbacks ()->debug_log)
6882 mono_get_runtime_callbacks ()->debug_log (level, category, message);
6886 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
6888 #if defined (HOST_WIN32)
6889 OutputDebugString (mono_string_chars (message));
6891 g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
6895 /* Only used for value types */
6896 ICALL_EXPORT MonoObject *
6897 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionType *type)
6902 domain = mono_object_domain (type);
6903 klass = mono_class_from_mono_type (type->type);
6904 mono_class_init_or_throw (klass);
6906 if (mono_class_is_nullable (klass))
6907 /* No arguments -> null */
6910 return mono_object_new (domain, klass);
6913 ICALL_EXPORT MonoReflectionMethod *
6914 ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definition)
6916 MonoClass *klass, *parent;
6917 MonoMethod *method = m->method;
6918 MonoMethod *result = NULL;
6921 if (method->klass == NULL)
6924 if (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
6925 MONO_CLASS_IS_INTERFACE (method->klass) ||
6926 method->flags & METHOD_ATTRIBUTE_NEW_SLOT)
6929 slot = mono_method_get_vtable_slot (method);
6933 klass = method->klass;
6934 if (klass->generic_class)
6935 klass = klass->generic_class->container_class;
6938 /* At the end of the loop, klass points to the eldest class that has this virtual function slot. */
6939 for (parent = klass->parent; parent != NULL; parent = parent->parent) {
6940 mono_class_setup_vtable (parent);
6941 if (parent->vtable_size <= slot)
6946 klass = klass->parent;
6951 if (klass == method->klass)
6954 /*This is possible if definition == FALSE.
6955 * Do it here to be really sure we don't read invalid memory.
6957 if (slot >= klass->vtable_size)
6960 mono_class_setup_vtable (klass);
6962 result = klass->vtable [slot];
6963 if (result == NULL) {
6964 /* It is an abstract method */
6965 gpointer iter = NULL;
6966 while ((result = mono_class_get_methods (klass, &iter)))
6967 if (result->slot == slot)
6974 return mono_method_get_object (mono_domain_get (), result, NULL);
6977 ICALL_EXPORT MonoString*
6978 ves_icall_MonoMethod_get_name (MonoReflectionMethod *m)
6980 MonoMethod *method = m->method;
6982 MONO_OBJECT_SETREF (m, name, mono_string_new (mono_object_domain (m), method->name));
6987 mono_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
6989 iter->sig = *(MonoMethodSignature**)argsp;
6991 g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
6992 g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
6995 /* FIXME: it's not documented what start is exactly... */
6999 iter->args = argsp + sizeof (gpointer);
7001 iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
7003 /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
7006 ICALL_EXPORT MonoTypedRef
7007 mono_ArgIterator_IntGetNextArg (MonoArgIterator *iter)
7009 guint32 i, arg_size;
7013 i = iter->sig->sentinelpos + iter->next_arg;
7015 g_assert (i < iter->sig->param_count);
7017 res.type = iter->sig->params [i];
7018 res.klass = mono_class_from_mono_type (res.type);
7019 arg_size = mono_type_stack_size (res.type, &align);
7020 #if defined(__arm__) || defined(__mips__)
7021 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7023 res.value = iter->args;
7024 #if defined(__native_client__) && SIZEOF_REGISTER == 8
7025 /* Values are stored as 8 byte register sized objects, but 'value'
7026 * is dereferenced as a pointer in other routines.
7028 res.value = (char*)res.value + 4;
7030 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
7031 if (arg_size <= sizeof (gpointer)) {
7033 int padding = arg_size - mono_type_size (res.type, &dummy);
7034 res.value = (guint8*)res.value + padding;
7037 iter->args = (char*)iter->args + arg_size;
7040 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7045 ICALL_EXPORT MonoTypedRef
7046 mono_ArgIterator_IntGetNextArgT (MonoArgIterator *iter, MonoType *type)
7048 guint32 i, arg_size;
7052 i = iter->sig->sentinelpos + iter->next_arg;
7054 g_assert (i < iter->sig->param_count);
7056 while (i < iter->sig->param_count) {
7057 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
7059 res.type = iter->sig->params [i];
7060 res.klass = mono_class_from_mono_type (res.type);
7061 /* FIXME: endianess issue... */
7062 arg_size = mono_type_stack_size (res.type, &align);
7063 #if defined(__arm__) || defined(__mips__)
7064 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7066 res.value = iter->args;
7067 iter->args = (char*)iter->args + arg_size;
7069 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7072 /* g_print ("arg type 0x%02x not found\n", res.type->type); */
7080 ICALL_EXPORT MonoType*
7081 mono_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
7085 i = iter->sig->sentinelpos + iter->next_arg;
7087 g_assert (i < iter->sig->param_count);
7089 return iter->sig->params [i];
7092 ICALL_EXPORT MonoObject*
7093 mono_TypedReference_ToObject (MonoTypedRef tref)
7095 if (MONO_TYPE_IS_REFERENCE (tref.type)) {
7096 MonoObject** objp = tref.value;
7100 return mono_value_box (mono_domain_get (), tref.klass, tref.value);
7103 ICALL_EXPORT MonoObject*
7104 mono_TypedReference_ToObjectInternal (MonoType *type, gpointer value, MonoClass *klass)
7106 if (MONO_TYPE_IS_REFERENCE (type)) {
7107 MonoObject** objp = value;
7111 return mono_value_box (mono_domain_get (), klass, value);
7115 prelink_method (MonoMethod *method)
7117 const char *exc_class, *exc_arg;
7118 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7120 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7122 mono_raise_exception(
7123 mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg ) );
7125 /* create the wrapper, too? */
7129 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethod *method)
7131 prelink_method (method->method);
7135 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionType *type)
7137 MonoClass *klass = mono_class_from_mono_type (type->type);
7139 gpointer iter = NULL;
7141 mono_class_init_or_throw (klass);
7143 while ((m = mono_class_get_methods (klass, &iter)))
7147 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
7149 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
7150 gint32 const **exponents,
7151 gunichar2 const **digitLowerTable,
7152 gunichar2 const **digitUpperTable,
7153 gint64 const **tenPowersList,
7154 gint32 const **decHexDigits)
7156 *mantissas = Formatter_MantissaBitsTable;
7157 *exponents = Formatter_TensExponentTable;
7158 *digitLowerTable = Formatter_DigitLowerTable;
7159 *digitUpperTable = Formatter_DigitUpperTable;
7160 *tenPowersList = Formatter_TenPowersList;
7161 *decHexDigits = Formatter_DecHexDigits;
7164 /* These parameters are "readonly" in corlib/System/Globalization/TextInfo.cs */
7166 ves_icall_System_Globalization_TextInfo_GetDataTablePointersLite (
7167 guint16 const **to_lower_data_low,
7168 guint16 const **to_lower_data_high,
7169 guint16 const **to_upper_data_low,
7170 guint16 const **to_upper_data_high)
7172 *to_lower_data_low = ToLowerDataLow;
7173 *to_lower_data_high = ToLowerDataHigh;
7174 *to_upper_data_low = ToUpperDataLow;
7175 *to_upper_data_high = ToUpperDataHigh;
7179 * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
7180 * and avoid useless allocations.
7185 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional)
7189 for (i = 0; i < type->num_mods; ++i) {
7190 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required))
7195 res = mono_array_new (mono_domain_get (), mono_defaults.systemtype_class, count);
7197 for (i = 0; i < type->num_mods; ++i) {
7198 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required)) {
7200 MonoClass *klass = mono_class_get_checked (image, type->modifiers [i].token, &error);
7201 mono_error_raise_exception (&error); /* this is safe, no cleanup needed on callers */
7202 mono_array_setref (res, count, mono_type_get_object (mono_domain_get (), &klass->byval_arg));
7209 ICALL_EXPORT MonoArray*
7210 param_info_get_type_modifiers (MonoReflectionParameter *param, MonoBoolean optional)
7212 MonoType *type = param->ClassImpl->type;
7213 MonoClass *member_class = mono_object_class (param->MemberImpl);
7214 MonoMethod *method = NULL;
7217 MonoMethodSignature *sig;
7219 if (mono_class_is_reflection_method_or_constructor (member_class)) {
7220 MonoReflectionMethod *rmethod = (MonoReflectionMethod*)param->MemberImpl;
7221 method = rmethod->method;
7222 } else if (member_class->image == mono_defaults.corlib && !strcmp ("MonoProperty", member_class->name)) {
7223 MonoReflectionProperty *prop = (MonoReflectionProperty *)param->MemberImpl;
7224 if (!(method = prop->property->get))
7225 method = prop->property->set;
7228 char *type_name = mono_type_get_full_name (member_class);
7229 char *msg = g_strdup_printf ("Custom modifiers on a ParamInfo with member %s are not supported", type_name);
7230 MonoException *ex = mono_get_exception_not_supported (msg);
7233 mono_raise_exception (ex);
7236 image = method->klass->image;
7237 pos = param->PositionImpl;
7238 sig = mono_method_signature (method);
7242 type = sig->params [pos];
7244 return type_array_from_modifiers (image, type, optional);
7248 get_property_type (MonoProperty *prop)
7250 MonoMethodSignature *sig;
7252 sig = mono_method_signature (prop->get);
7254 } else if (prop->set) {
7255 sig = mono_method_signature (prop->set);
7256 return sig->params [sig->param_count - 1];
7261 ICALL_EXPORT MonoArray*
7262 property_info_get_type_modifiers (MonoReflectionProperty *property, MonoBoolean optional)
7264 MonoType *type = get_property_type (property->property);
7265 MonoImage *image = property->klass->image;
7269 return type_array_from_modifiers (image, type, optional);
7273 *Construct a MonoType suited to be used to decode a constant blob object.
7275 * @type is the target type which will be constructed
7276 * @blob_type is the blob type, for example, that comes from the constant table
7277 * @real_type is the expected constructed type.
7280 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
7282 type->type = blob_type;
7283 type->data.klass = NULL;
7284 if (blob_type == MONO_TYPE_CLASS)
7285 type->data.klass = mono_defaults.object_class;
7286 else if (real_type->type == MONO_TYPE_VALUETYPE && real_type->data.klass->enumtype) {
7287 /* For enums, we need to use the base type */
7288 type->type = MONO_TYPE_VALUETYPE;
7289 type->data.klass = mono_class_from_mono_type (real_type);
7291 type->data.klass = mono_class_from_mono_type (real_type);
7294 ICALL_EXPORT MonoObject*
7295 property_info_get_default_value (MonoReflectionProperty *property)
7298 MonoProperty *prop = property->property;
7299 MonoType *type = get_property_type (prop);
7300 MonoDomain *domain = mono_object_domain (property);
7301 MonoTypeEnum def_type;
7302 const char *def_value;
7305 mono_class_init (prop->parent);
7307 if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT))
7308 mono_raise_exception (mono_get_exception_invalid_operation (NULL));
7310 def_value = mono_class_get_property_default_value (prop, &def_type);
7312 mono_type_from_blob_type (&blob_type, def_type, type);
7313 o = mono_get_object_from_blob (domain, &blob_type, def_value);
7318 ICALL_EXPORT MonoBoolean
7319 custom_attrs_defined_internal (MonoObject *obj, MonoReflectionType *attr_type)
7321 MonoClass *attr_class = mono_class_from_mono_type (attr_type->type);
7322 MonoCustomAttrInfo *cinfo;
7325 mono_class_init_or_throw (attr_class);
7327 cinfo = mono_reflection_get_custom_attrs_info (obj);
7330 found = mono_custom_attrs_has_attr (cinfo, attr_class);
7332 mono_custom_attrs_free (cinfo);
7336 ICALL_EXPORT MonoArray*
7337 custom_attrs_get_by_type (MonoObject *obj, MonoReflectionType *attr_type)
7339 MonoClass *attr_class = attr_type ? mono_class_from_mono_type (attr_type->type) : NULL;
7344 mono_class_init_or_throw (attr_class);
7346 res = mono_reflection_get_custom_attrs_by_type (obj, attr_class, &error);
7347 mono_error_raise_exception (&error);
7349 if (mono_loader_get_last_error ()) {
7350 mono_raise_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
7351 g_assert_not_reached ();
7359 ICALL_EXPORT MonoString*
7360 ves_icall_Mono_Runtime_GetDisplayName (void)
7363 MonoString *display_name;
7365 info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
7366 display_name = mono_string_new (mono_domain_get (), info);
7368 return display_name;
7371 ICALL_EXPORT MonoString*
7372 ves_icall_System_ComponentModel_Win32Exception_W32ErrorMessage (guint32 code)
7374 MonoString *message;
7378 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7379 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code, 0,
7382 message = mono_string_new (mono_domain_get (), "Error looking up error string");
7384 message = mono_string_new_utf16 (mono_domain_get (), buf, ret);
7390 #ifndef DISABLE_ICALL_TABLES
7392 #define ICALL_TYPE(id,name,first)
7393 #define ICALL(id,name,func) Icall_ ## id,
7396 #include "metadata/icall-def.h"
7402 #define ICALL_TYPE(id,name,first) Icall_type_ ## id,
7403 #define ICALL(id,name,func)
7405 #include "metadata/icall-def.h"
7411 #define ICALL_TYPE(id,name,firstic) {(Icall_ ## firstic)},
7412 #define ICALL(id,name,func)
7414 guint16 first_icall;
7417 static const IcallTypeDesc
7418 icall_type_descs [] = {
7419 #include "metadata/icall-def.h"
7423 #define icall_desc_num_icalls(desc) ((desc) [1].first_icall - (desc) [0].first_icall)
7426 #define ICALL_TYPE(id,name,first)
7429 #ifdef HAVE_ARRAY_ELEM_INIT
7430 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
7431 #define MSGSTRFIELD1(line) str##line
7433 static const struct msgstrtn_t {
7434 #define ICALL(id,name,func)
7436 #define ICALL_TYPE(id,name,first) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7437 #include "metadata/icall-def.h"
7439 } icall_type_names_str = {
7440 #define ICALL_TYPE(id,name,first) (name),
7441 #include "metadata/icall-def.h"
7444 static const guint16 icall_type_names_idx [] = {
7445 #define ICALL_TYPE(id,name,first) [Icall_type_ ## id] = offsetof (struct msgstrtn_t, MSGSTRFIELD(__LINE__)),
7446 #include "metadata/icall-def.h"
7449 #define icall_type_name_get(id) ((const char*)&icall_type_names_str + icall_type_names_idx [(id)])
7451 static const struct msgstr_t {
7453 #define ICALL_TYPE(id,name,first)
7454 #define ICALL(id,name,func) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7455 #include "metadata/icall-def.h"
7457 } icall_names_str = {
7458 #define ICALL(id,name,func) (name),
7459 #include "metadata/icall-def.h"
7462 static const guint16 icall_names_idx [] = {
7463 #define ICALL(id,name,func) [Icall_ ## id] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
7464 #include "metadata/icall-def.h"
7467 #define icall_name_get(id) ((const char*)&icall_names_str + icall_names_idx [(id)])
7473 #define ICALL_TYPE(id,name,first) name,
7474 #define ICALL(id,name,func)
7475 static const char* const
7476 icall_type_names [] = {
7477 #include "metadata/icall-def.h"
7481 #define icall_type_name_get(id) (icall_type_names [(id)])
7485 #define ICALL_TYPE(id,name,first)
7486 #define ICALL(id,name,func) name,
7487 static const char* const
7489 #include "metadata/icall-def.h"
7492 #define icall_name_get(id) icall_names [(id)]
7494 #endif /* !HAVE_ARRAY_ELEM_INIT */
7498 #define ICALL_TYPE(id,name,first)
7499 #define ICALL(id,name,func) func,
7500 static const gconstpointer
7501 icall_functions [] = {
7502 #include "metadata/icall-def.h"
7506 #ifdef ENABLE_ICALL_SYMBOL_MAP
7509 #define ICALL_TYPE(id,name,first)
7510 #define ICALL(id,name,func) #func,
7511 static const gconstpointer
7512 icall_symbols [] = {
7513 #include "metadata/icall-def.h"
7518 #endif /* DISABLE_ICALL_TABLES */
7520 static mono_mutex_t icall_mutex;
7521 static GHashTable *icall_hash = NULL;
7522 static GHashTable *jit_icall_hash_name = NULL;
7523 static GHashTable *jit_icall_hash_addr = NULL;
7526 mono_icall_init (void)
7528 #ifndef DISABLE_ICALL_TABLES
7531 /* check that tables are sorted: disable in release */
7534 const char *prev_class = NULL;
7535 const char *prev_method;
7537 for (i = 0; i < Icall_type_num; ++i) {
7538 const IcallTypeDesc *desc;
7541 if (prev_class && strcmp (prev_class, icall_type_name_get (i)) >= 0)
7542 g_print ("class %s should come before class %s\n", icall_type_name_get (i), prev_class);
7543 prev_class = icall_type_name_get (i);
7544 desc = &icall_type_descs [i];
7545 num_icalls = icall_desc_num_icalls (desc);
7546 /*g_print ("class %s has %d icalls starting at %d\n", prev_class, num_icalls, desc->first_icall);*/
7547 for (j = 0; j < num_icalls; ++j) {
7548 const char *methodn = icall_name_get (desc->first_icall + j);
7549 if (prev_method && strcmp (prev_method, methodn) >= 0)
7550 g_print ("method %s should come before method %s\n", methodn, prev_method);
7551 prev_method = methodn;
7557 icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7558 mono_mutex_init (&icall_mutex);
7562 mono_icall_lock (void)
7564 mono_locks_mutex_acquire (&icall_mutex, IcallLock);
7568 mono_icall_unlock (void)
7570 mono_locks_mutex_release (&icall_mutex, IcallLock);
7574 mono_icall_cleanup (void)
7576 g_hash_table_destroy (icall_hash);
7577 g_hash_table_destroy (jit_icall_hash_name);
7578 g_hash_table_destroy (jit_icall_hash_addr);
7579 mono_mutex_destroy (&icall_mutex);
7583 mono_add_internal_call (const char *name, gconstpointer method)
7587 g_hash_table_insert (icall_hash, g_strdup (name), (gpointer) method);
7589 mono_icall_unlock ();
7592 #ifndef DISABLE_ICALL_TABLES
7594 #ifdef HAVE_ARRAY_ELEM_INIT
7596 compare_method_imap (const void *key, const void *elem)
7598 const char* method_name = (const char*)&icall_names_str + (*(guint16*)elem);
7599 return strcmp (key, method_name);
7603 find_method_icall (const IcallTypeDesc *imap, const char *name)
7605 const guint16 *nameslot = mono_binary_search (name, icall_names_idx + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names_idx [0]), compare_method_imap);
7608 return (gpointer)icall_functions [(nameslot - &icall_names_idx [0])];
7612 compare_class_imap (const void *key, const void *elem)
7614 const char* class_name = (const char*)&icall_type_names_str + (*(guint16*)elem);
7615 return strcmp (key, class_name);
7618 static const IcallTypeDesc*
7619 find_class_icalls (const char *name)
7621 const guint16 *nameslot = mono_binary_search (name, icall_type_names_idx, Icall_type_num, sizeof (icall_type_names_idx [0]), compare_class_imap);
7624 return &icall_type_descs [nameslot - &icall_type_names_idx [0]];
7627 #else /* HAVE_ARRAY_ELEM_INIT */
7630 compare_method_imap (const void *key, const void *elem)
7632 const char** method_name = (const char**)elem;
7633 return strcmp (key, *method_name);
7637 find_method_icall (const IcallTypeDesc *imap, const char *name)
7639 const char **nameslot = mono_binary_search (name, icall_names + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names [0]), compare_method_imap);
7642 return (gpointer)icall_functions [(nameslot - icall_names)];
7646 compare_class_imap (const void *key, const void *elem)
7648 const char** class_name = (const char**)elem;
7649 return strcmp (key, *class_name);
7652 static const IcallTypeDesc*
7653 find_class_icalls (const char *name)
7655 const char **nameslot = mono_binary_search (name, icall_type_names, Icall_type_num, sizeof (icall_type_names [0]), compare_class_imap);
7658 return &icall_type_descs [nameslot - icall_type_names];
7661 #endif /* HAVE_ARRAY_ELEM_INIT */
7663 #endif /* DISABLE_ICALL_TABLES */
7666 * we should probably export this as an helper (handle nested types).
7667 * Returns the number of chars written in buf.
7670 concat_class_name (char *buf, int bufsize, MonoClass *klass)
7672 int nspacelen, cnamelen;
7673 nspacelen = strlen (klass->name_space);
7674 cnamelen = strlen (klass->name);
7675 if (nspacelen + cnamelen + 2 > bufsize)
7678 memcpy (buf, klass->name_space, nspacelen);
7679 buf [nspacelen ++] = '.';
7681 memcpy (buf + nspacelen, klass->name, cnamelen);
7682 buf [nspacelen + cnamelen] = 0;
7683 return nspacelen + cnamelen;
7686 #ifdef DISABLE_ICALL_TABLES
7688 no_icall_table (void)
7690 g_assert_not_reached ();
7695 mono_lookup_internal_call (MonoMethod *method)
7700 int typelen = 0, mlen, siglen;
7702 #ifndef DISABLE_ICALL_TABLES
7703 const IcallTypeDesc *imap = NULL;
7706 g_assert (method != NULL);
7708 if (method->is_inflated)
7709 method = ((MonoMethodInflated *) method)->declaring;
7711 if (method->klass->nested_in) {
7712 int pos = concat_class_name (mname, sizeof (mname)-2, method->klass->nested_in);
7716 mname [pos++] = '/';
7719 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
7725 typelen = concat_class_name (mname, sizeof (mname), method->klass);
7730 #ifndef DISABLE_ICALL_TABLES
7731 imap = find_class_icalls (mname);
7734 mname [typelen] = ':';
7735 mname [typelen + 1] = ':';
7737 mlen = strlen (method->name);
7738 memcpy (mname + typelen + 2, method->name, mlen);
7739 sigstart = mname + typelen + 2 + mlen;
7742 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
7743 siglen = strlen (tmpsig);
7744 if (typelen + mlen + siglen + 6 > sizeof (mname))
7747 memcpy (sigstart + 1, tmpsig, siglen);
7748 sigstart [siglen + 1] = ')';
7749 sigstart [siglen + 2] = 0;
7754 res = g_hash_table_lookup (icall_hash, mname);
7756 mono_icall_unlock ();;
7759 /* try without signature */
7761 res = g_hash_table_lookup (icall_hash, mname);
7763 mono_icall_unlock ();
7767 #ifdef DISABLE_ICALL_TABLES
7768 mono_icall_unlock ();
7769 /* Fail only when the result is actually used */
7770 /* mono_marshal_get_native_wrapper () depends on this */
7771 if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor"))
7772 return ves_icall_System_String_ctor_RedirectToCreateString;
7774 return no_icall_table;
7776 /* it wasn't found in the static call tables */
7778 mono_icall_unlock ();
7781 res = find_method_icall (imap, sigstart - mlen);
7783 mono_icall_unlock ();
7786 /* try _with_ signature */
7788 res = find_method_icall (imap, sigstart - mlen);
7790 mono_icall_unlock ();
7794 g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
7795 g_print ("\nYour mono runtime and class libraries are out of sync.\n");
7796 g_print ("The out of sync library is: %s\n", method->klass->image->name);
7797 g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
7798 g_print ("Do not report this as a bug unless you're sure you have updated correctly:\nyou probably have a broken mono install.\n");
7799 g_print ("If you see other errors or faults after this message they are probably related\n");
7800 g_print ("and you need to fix your mono install first.\n");
7802 mono_icall_unlock ();
7808 #ifdef ENABLE_ICALL_SYMBOL_MAP
7810 func_cmp (gconstpointer key, gconstpointer p)
7812 return (gsize)key - (gsize)*(gsize*)p;
7817 * mono_lookup_icall_symbol:
7819 * Given the icall METHOD, returns its C symbol.
7822 mono_lookup_icall_symbol (MonoMethod *m)
7824 #ifdef DISABLE_ICALL_TABLES
7825 g_assert_not_reached ();
7828 #ifdef ENABLE_ICALL_SYMBOL_MAP
7832 static gconstpointer *functions_sorted;
7833 static const char**symbols_sorted;
7834 static gboolean inited;
7839 functions_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7840 memcpy (functions_sorted, icall_functions, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7841 symbols_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7842 memcpy (symbols_sorted, icall_symbols, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7843 /* Bubble sort the two arrays */
7847 for (i = 0; i < G_N_ELEMENTS (icall_functions) - 1; ++i) {
7848 if (functions_sorted [i] > functions_sorted [i + 1]) {
7851 tmp = functions_sorted [i];
7852 functions_sorted [i] = functions_sorted [i + 1];
7853 functions_sorted [i + 1] = tmp;
7854 tmp = symbols_sorted [i];
7855 symbols_sorted [i] = symbols_sorted [i + 1];
7856 symbols_sorted [i + 1] = tmp;
7863 func = mono_lookup_internal_call (m);
7866 slot = mono_binary_search (func, functions_sorted, G_N_ELEMENTS (icall_functions), sizeof (gpointer), func_cmp);
7870 return symbols_sorted [(gpointer*)slot - (gpointer*)functions_sorted];
7872 fprintf (stderr, "icall symbol maps not enabled, pass --enable-icall-symbol-map to configure.\n");
7873 g_assert_not_reached ();
7880 type_from_typename (char *typename)
7882 MonoClass *klass = NULL; /* assignment to shut GCC warning up */
7884 if (!strcmp (typename, "int"))
7885 klass = mono_defaults.int_class;
7886 else if (!strcmp (typename, "ptr"))
7887 klass = mono_defaults.int_class;
7888 else if (!strcmp (typename, "void"))
7889 klass = mono_defaults.void_class;
7890 else if (!strcmp (typename, "int32"))
7891 klass = mono_defaults.int32_class;
7892 else if (!strcmp (typename, "uint32"))
7893 klass = mono_defaults.uint32_class;
7894 else if (!strcmp (typename, "int8"))
7895 klass = mono_defaults.sbyte_class;
7896 else if (!strcmp (typename, "uint8"))
7897 klass = mono_defaults.byte_class;
7898 else if (!strcmp (typename, "int16"))
7899 klass = mono_defaults.int16_class;
7900 else if (!strcmp (typename, "uint16"))
7901 klass = mono_defaults.uint16_class;
7902 else if (!strcmp (typename, "long"))
7903 klass = mono_defaults.int64_class;
7904 else if (!strcmp (typename, "ulong"))
7905 klass = mono_defaults.uint64_class;
7906 else if (!strcmp (typename, "float"))
7907 klass = mono_defaults.single_class;
7908 else if (!strcmp (typename, "double"))
7909 klass = mono_defaults.double_class;
7910 else if (!strcmp (typename, "object"))
7911 klass = mono_defaults.object_class;
7912 else if (!strcmp (typename, "obj"))
7913 klass = mono_defaults.object_class;
7914 else if (!strcmp (typename, "string"))
7915 klass = mono_defaults.string_class;
7916 else if (!strcmp (typename, "bool"))
7917 klass = mono_defaults.boolean_class;
7918 else if (!strcmp (typename, "boolean"))
7919 klass = mono_defaults.boolean_class;
7921 g_error ("%s", typename);
7922 g_assert_not_reached ();
7924 return &klass->byval_arg;
7928 * LOCKING: Take the corlib image lock.
7930 MonoMethodSignature*
7931 mono_create_icall_signature (const char *sigstr)
7936 MonoMethodSignature *res, *res2;
7937 MonoImage *corlib = mono_defaults.corlib;
7939 mono_image_lock (corlib);
7940 res = g_hash_table_lookup (corlib->helper_signatures, sigstr);
7941 mono_image_unlock (corlib);
7946 parts = g_strsplit (sigstr, " ", 256);
7955 res = mono_metadata_signature_alloc (corlib, len - 1);
7960 * Under windows, the default pinvoke calling convention is STDCALL but
7963 res->call_convention = MONO_CALL_C;
7966 res->ret = type_from_typename (parts [0]);
7967 for (i = 1; i < len; ++i) {
7968 res->params [i - 1] = type_from_typename (parts [i]);
7973 mono_image_lock (corlib);
7974 res2 = g_hash_table_lookup (corlib->helper_signatures, sigstr);
7976 res = res2; /*Value is allocated in the image pool*/
7978 g_hash_table_insert (corlib->helper_signatures, (gpointer)sigstr, res);
7979 mono_image_unlock (corlib);
7985 mono_find_jit_icall_by_name (const char *name)
7987 MonoJitICallInfo *info;
7988 g_assert (jit_icall_hash_name);
7991 info = g_hash_table_lookup (jit_icall_hash_name, name);
7992 mono_icall_unlock ();
7997 mono_find_jit_icall_by_addr (gconstpointer addr)
7999 MonoJitICallInfo *info;
8000 g_assert (jit_icall_hash_addr);
8003 info = g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
8004 mono_icall_unlock ();
8010 * mono_get_jit_icall_info:
8012 * Return the hashtable mapping JIT icall names to MonoJitICallInfo structures. The
8013 * caller should access it while holding the icall lock.
8016 mono_get_jit_icall_info (void)
8018 return jit_icall_hash_name;
8022 * mono_lookup_jit_icall_symbol:
8024 * Given the jit icall NAME, returns its C symbol if possible, or NULL.
8027 mono_lookup_jit_icall_symbol (const char *name)
8029 MonoJitICallInfo *info;
8030 const char *res = NULL;
8033 info = g_hash_table_lookup (jit_icall_hash_name, name);
8035 res = info->c_symbol;
8036 mono_icall_unlock ();
8041 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
8044 g_hash_table_insert (jit_icall_hash_addr, (gpointer)wrapper, info);
8045 mono_icall_unlock ();
8049 mono_register_jit_icall_full (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save, const char *c_symbol)
8051 MonoJitICallInfo *info;
8058 if (!jit_icall_hash_name) {
8059 jit_icall_hash_name = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
8060 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
8063 if (g_hash_table_lookup (jit_icall_hash_name, name)) {
8064 g_warning ("jit icall already defined \"%s\"\n", name);
8065 g_assert_not_reached ();
8068 info = g_new0 (MonoJitICallInfo, 1);
8073 info->c_symbol = c_symbol;
8076 info->wrapper = func;
8078 info->wrapper = NULL;
8081 g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
8082 g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
8084 mono_icall_unlock ();
8089 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
8091 return mono_register_jit_icall_full (func, name, sig, is_save, NULL);