[2019-12] [merp] Capture Environment.FailFast message in crash report (#18921)
[mono-project.git] / mono / metadata / icall.c
blob4ee6e9958e79e42d6724acd025ee2e93303c95e4
1 /**
2 * \file
4 * Authors:
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)
9 * Aleksey Kliger (aleksey@xamarin.com)
11 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
12 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
13 * Copyright 2011-2015 Xamarin Inc (http://www.xamarin.com).
14 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
17 #include <config.h>
19 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
20 /* Needed for _ecvt_s */
21 #define MINGW_HAS_SECURE_API 1
22 #include <stdio.h>
23 #endif
25 #include <glib.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <ctype.h>
29 #ifdef HAVE_ALLOCA_H
30 #include <alloca.h>
31 #endif
32 #ifdef HAVE_SYS_TIME_H
33 #include <sys/time.h>
34 #endif
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #if defined (HAVE_WCHAR_H)
39 #include <wchar.h>
40 #endif
42 #include "mono/metadata/icall-internals.h"
43 #include "mono/utils/mono-membar.h"
44 #include <mono/metadata/object.h>
45 #include <mono/metadata/threads.h>
46 #include <mono/metadata/threads-types.h>
47 #include <mono/metadata/threadpool.h>
48 #include <mono/metadata/threadpool-io.h>
49 #include <mono/metadata/monitor.h>
50 #include <mono/metadata/reflection.h>
51 #include <mono/metadata/image-internals.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/assembly-internals.h>
54 #include <mono/metadata/tabledefs.h>
55 #include <mono/metadata/exception.h>
56 #include <mono/metadata/exception-internals.h>
57 #include <mono/metadata/w32file.h>
58 #include <mono/metadata/console-io.h>
59 #include <mono/metadata/w32socket.h>
60 #include <mono/metadata/mono-endian.h>
61 #include <mono/metadata/tokentype.h>
62 #include <mono/metadata/metadata-internals.h>
63 #include <mono/metadata/class-internals.h>
64 #include <mono/metadata/class-init.h>
65 #include <mono/metadata/reflection-internals.h>
66 #include <mono/metadata/marshal.h>
67 #include <mono/metadata/gc-internals.h>
68 #include <mono/metadata/mono-gc.h>
69 #include <mono/metadata/rand.h>
70 #include <mono/metadata/appdomain-icalls.h>
71 #include <mono/metadata/string-icalls.h>
72 #include <mono/metadata/debug-helpers.h>
73 #include <mono/metadata/w32process.h>
74 #include <mono/metadata/environment.h>
75 #include <mono/metadata/profiler-private.h>
76 #include <mono/metadata/locales.h>
77 #include <mono/metadata/filewatcher.h>
78 #include <mono/metadata/security.h>
79 #include <mono/metadata/mono-config.h>
80 #include <mono/metadata/cil-coff.h>
81 #include <mono/metadata/number-formatter.h>
82 #include <mono/metadata/security-manager.h>
83 #include <mono/metadata/security-core-clr.h>
84 #include <mono/metadata/mono-perfcounters.h>
85 #include <mono/metadata/mono-debug.h>
86 #include <mono/metadata/mono-ptr-array.h>
87 #include <mono/metadata/verify-internals.h>
88 #include <mono/metadata/runtime.h>
89 #include <mono/metadata/file-mmap.h>
90 #include <mono/metadata/seq-points-data.h>
91 #include <mono/metadata/icall-table.h>
92 #include <mono/metadata/handle.h>
93 #include <mono/metadata/w32mutex.h>
94 #include <mono/metadata/w32semaphore.h>
95 #include <mono/metadata/w32event.h>
96 #include <mono/metadata/abi-details.h>
97 #include <mono/metadata/loader-internals.h>
98 #include <mono/utils/monobitset.h>
99 #include <mono/utils/mono-time.h>
100 #include <mono/utils/mono-proclib.h>
101 #include <mono/utils/mono-string.h>
102 #include <mono/utils/mono-error-internals.h>
103 #include <mono/utils/mono-mmap.h>
104 #include <mono/utils/mono-io-portability.h>
105 #include <mono/utils/mono-digest.h>
106 #include <mono/utils/bsearch.h>
107 #include <mono/utils/mono-os-mutex.h>
108 #include <mono/utils/mono-threads.h>
109 #include <mono/metadata/w32error.h>
110 #include <mono/utils/w32api.h>
111 #include <mono/utils/mono-merp.h>
112 #include <mono/utils/mono-state.h>
113 #include <mono/utils/mono-logger-internals.h>
114 #include <mono/utils/mono-math.h>
115 #if !defined(HOST_WIN32) && defined(HAVE_SYS_UTSNAME_H)
116 #include <sys/utsname.h>
117 #endif
118 #include "icall-decl.h"
119 #include "mono/utils/mono-threads-coop.h"
120 #include "mono/metadata/icall-signatures.h"
122 //#define MONO_DEBUG_ICALLARRAY
124 #ifdef MONO_DEBUG_ICALLARRAY
126 static char debug_icallarray; // 0:uninitialized 1:true 2:false
128 static gboolean
129 icallarray_print_enabled (void)
131 if (!debug_icallarray)
132 debug_icallarray = MONO_TRACE_IS_TRACED (G_LOG_LEVEL_DEBUG, MONO_TRACE_ICALLARRAY) ? 1 : 2;
133 return debug_icallarray == 1;
136 static void
137 icallarray_print (const char *format, ...)
139 if (!icallarray_print_enabled ())
140 return;
141 va_list args;
142 va_start (args, format);
143 g_printv (format, args);
144 va_end (args);
147 #else
148 #define icallarray_print_enabled() (FALSE)
149 #define icallarray_print(...) /* nothing */
150 #endif
152 /* Lazy class loading functions */
153 static GENERATE_GET_CLASS_WITH_CACHE (module, "System.Reflection", "Module")
155 static void
156 array_set_value_impl (MonoArrayHandle arr, MonoObjectHandle value, guint32 pos, gboolean strict_enums, gboolean strict_signs, MonoError *error);
158 static MonoArrayHandle
159 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error);
161 static inline MonoBoolean
162 is_generic_parameter (MonoType *type)
164 return !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR);
167 #ifndef HOST_WIN32
168 static inline void
169 mono_icall_make_platform_path (gchar *path)
171 return;
174 static inline const gchar *
175 mono_icall_get_file_path_prefix (const gchar *path)
177 return "file://";
179 #endif /* HOST_WIN32 */
181 #if MONO_LLVM_LOADED
183 static
184 MonoJitICallInfos mono_jit_icall_info;
186 MonoJitICallInfos*
187 mono_get_jit_icall_info (void)
189 return &mono_jit_icall_info;
192 #else
194 MonoJitICallInfos mono_jit_icall_info;
196 #endif
198 MonoObjectHandle
199 ves_icall_System_Array_GetValueImpl (MonoArrayHandle array, guint32 pos, MonoError *error)
201 MonoClass * const array_class = mono_handle_class (array);
202 MonoClass * const element_class = m_class_get_element_class (array_class);
204 #ifdef ENABLE_NETCORE
205 if (m_class_is_native_pointer (element_class)) {
206 mono_error_set_not_supported (error, NULL);
207 return NULL_HANDLE;
209 #endif
211 if (m_class_is_valuetype (element_class)) {
212 gsize element_size = mono_array_element_size (array_class);
213 gpointer element_address = mono_array_addr_with_size_fast (MONO_HANDLE_RAW (array), element_size, (gsize)pos);
214 return mono_value_box_handle (MONO_HANDLE_DOMAIN (array), element_class, element_address, error);
216 MonoObjectHandle result = mono_new_null ();
217 mono_handle_array_getref (result, array, pos);
218 return result;
221 MonoObjectHandle
222 ves_icall_System_Array_GetValue (MonoArrayHandle arr, MonoArrayHandle indices, MonoError *error)
224 MONO_CHECK_ARG_NULL_HANDLE (indices, NULL_HANDLE);
226 MonoClass * const indices_class = mono_handle_class (indices);
227 MonoClass * const array_class = mono_handle_class (arr);
229 g_assert (m_class_get_rank (indices_class) == 1);
231 if (MONO_HANDLE_GETVAL (indices, bounds) || MONO_HANDLE_GETVAL (indices, max_length) != m_class_get_rank (array_class)) {
232 mono_error_set_argument (error, NULL, NULL);
233 return NULL_HANDLE;
236 gint32 index = 0;
238 if (!MONO_HANDLE_GETVAL (arr, bounds)) {
239 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, 0);
240 if (index < 0 || index >= MONO_HANDLE_GETVAL (arr, max_length)) {
241 mono_error_set_index_out_of_range (error);
242 return NULL_HANDLE;
245 return ves_icall_System_Array_GetValueImpl (arr, index, error);
248 for (gint32 i = 0; i < m_class_get_rank (array_class); i++) {
249 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, i);
250 if ((index < MONO_HANDLE_GETVAL (arr, bounds [i].lower_bound)) ||
251 (index >= (mono_array_lower_bound_t)MONO_HANDLE_GETVAL (arr, bounds [i].length) + MONO_HANDLE_GETVAL (arr, bounds [i].lower_bound))) {
252 mono_error_set_index_out_of_range (error);
253 return NULL_HANDLE;
257 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, 0);
258 gint32 pos = index - MONO_HANDLE_GETVAL (arr, bounds [0].lower_bound);
259 for (gint32 i = 1; i < m_class_get_rank (array_class); i++) {
260 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, i);
261 pos = pos * MONO_HANDLE_GETVAL (arr, bounds [i].length) + index -
262 MONO_HANDLE_GETVAL (arr, bounds [i].lower_bound);
265 return ves_icall_System_Array_GetValueImpl (arr, pos, error);
268 void
269 ves_icall_System_Array_SetValueImpl (MonoArrayHandle arr, MonoObjectHandle value, guint32 pos, MonoError *error)
271 array_set_value_impl (arr, value, pos, FALSE, TRUE, error);
274 static inline void
275 set_invalid_cast (MonoError *error, MonoClass *src_class, MonoClass *dst_class)
277 mono_get_runtime_callbacks ()->set_cast_details (src_class, dst_class);
278 mono_error_set_invalid_cast (error);
281 #if ENABLE_NETCORE
282 void
283 ves_icall_System_Array_SetValueRelaxedImpl (MonoArrayHandle arr, MonoObjectHandle value, guint32 pos, MonoError *error)
285 array_set_value_impl (arr, value, pos, FALSE, FALSE, error);
288 // Copied from CoreCLR: https://github.com/dotnet/coreclr/blob/d3e39bc2f81e3dbf9e4b96347f62b49d8700336c/src/vm/invokeutil.cpp#L33
289 #define PT_Primitive 0x01000000
291 static const guint32 primitive_conversions [] = {
292 0x00, // MONO_TYPE_END
293 0x00, // MONO_TYPE_VOID
294 PT_Primitive | 0x0004, // MONO_TYPE_BOOLEAN
295 PT_Primitive | 0x3F88, // MONO_TYPE_CHAR (W = U2, CHAR, I4, U4, I8, U8, R4, R8)
296 PT_Primitive | 0x3550, // MONO_TYPE_I1 (W = I1, I2, I4, I8, R4, R8)
297 PT_Primitive | 0x3FE8, // MONO_TYPE_U1 (W = CHAR, U1, I2, U2, I4, U4, I8, U8, R4, R8)
298 PT_Primitive | 0x3540, // MONO_TYPE_I2 (W = I2, I4, I8, R4, R8)
299 PT_Primitive | 0x3F88, // MONO_TYPE_U2 (W = U2, CHAR, I4, U4, I8, U8, R4, R8)
300 PT_Primitive | 0x3500, // MONO_TYPE_I4 (W = I4, I8, R4, R8)
301 PT_Primitive | 0x3E00, // MONO_TYPE_U4 (W = U4, I8, R4, R8)
302 PT_Primitive | 0x3400, // MONO_TYPE_I8 (W = I8, R4, R8)
303 PT_Primitive | 0x3800, // MONO_TYPE_U8 (W = U8, R4, R8)
304 PT_Primitive | 0x3000, // MONO_TYPE_R4 (W = R4, R8)
305 PT_Primitive | 0x2000, // MONO_TYPE_R8 (W = R8)
308 // Copied from CoreCLR: https://github.com/dotnet/coreclr/blob/030a3ea9b8dbeae89c90d34441d4d9a1cf4a7de6/src/vm/invokeutil.h#L176
309 static
310 gboolean can_primitive_widen (MonoTypeEnum src_type, MonoTypeEnum dest_type)
312 if (dest_type > MONO_TYPE_R8 || src_type > MONO_TYPE_R8) {
313 return (MONO_TYPE_I == dest_type && MONO_TYPE_I == src_type) || (MONO_TYPE_U == dest_type && MONO_TYPE_U == src_type);
315 return ((1 << dest_type) & primitive_conversions [src_type]) != 0;
318 // Copied from CoreCLR: https://github.com/dotnet/coreclr/blob/eafa8648ebee92de1380278b15cd5c2b6ef11218/src/vm/array.cpp#L1406
319 static MonoTypeEnum
320 get_normalized_integral_array_element_type (MonoTypeEnum elementType)
322 // Array Primitive types such as E_T_I4 and E_T_U4 are interchangeable
323 // Enums with interchangeable underlying types are interchangable
324 // BOOL is NOT interchangeable with I1/U1, neither CHAR -- with I2/U2
326 switch (elementType) {
327 case MONO_TYPE_U1:
328 case MONO_TYPE_U2:
329 case MONO_TYPE_U4:
330 case MONO_TYPE_U8:
331 case MONO_TYPE_U:
332 return (MonoTypeEnum) (elementType - 1); // normalize to signed type
335 return elementType;
338 MonoBoolean
339 ves_icall_System_Array_CanChangePrimitive (MonoReflectionType *volatile* ref_src_type_handle, MonoReflectionType *volatile* ref_dst_type_handle, MonoBoolean reliable)
341 MonoReflectionType* const ref_src_type = *ref_src_type_handle;
342 MonoReflectionType* const ref_dst_type = *ref_dst_type_handle;
344 MonoType *src_type = ref_src_type->type;
345 MonoType *dst_type = ref_dst_type->type;
347 g_assert (mono_type_is_primitive (src_type));
348 g_assert (mono_type_is_primitive (dst_type));
350 MonoTypeEnum normalized_src_type = get_normalized_integral_array_element_type (src_type->type);
351 MonoTypeEnum normalized_dst_type = get_normalized_integral_array_element_type (dst_type->type);
353 // Allow conversions like int <-> uint
354 if (normalized_src_type == normalized_dst_type) {
355 return TRUE;
358 // Widening is not allowed if reliable is true.
359 if (reliable) {
360 return FALSE;
363 // NOTE we don't use normalized types here so int -> ulong will be false
364 // see https://github.com/dotnet/coreclr/pull/25209#issuecomment-505952295
365 return can_primitive_widen (src_type->type, dst_type->type);
367 #endif
369 static void
370 array_set_value_impl (MonoArrayHandle arr_handle, MonoObjectHandle value_handle, guint32 pos, gboolean strict_enums, gboolean strict_signs, MonoError *error)
372 MonoClass *ac, *vc, *ec;
373 gint32 esize, vsize;
374 gpointer *ea = NULL, *va = NULL;
376 guint64 u64 = 0;
377 gint64 i64 = 0;
378 gdouble r64 = 0;
379 gboolean castOk = FALSE;
380 gboolean et_isenum = FALSE;
381 gboolean vt_isenum = FALSE;
383 error_init (error);
385 if (!MONO_HANDLE_IS_NULL (value_handle))
386 vc = mono_handle_class (value_handle);
387 else
388 vc = NULL;
390 ac = mono_handle_class (arr_handle);
391 ec = m_class_get_element_class (ac);
392 esize = mono_array_element_size (ac);
394 if (mono_class_is_nullable (ec)) {
395 #ifdef ENABLE_NETCORE
396 if (vc && m_class_is_primitive (vc) && vc != m_class_get_nullable_elem_class (ec)) {
397 // T -> Nullable<T> T must be exact
398 set_invalid_cast (error, vc, ec);
399 goto leave;
401 #endif
402 MONO_ENTER_NO_SAFEPOINTS;
403 ea = (gpointer*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (arr_handle), esize, pos);
404 if (!MONO_HANDLE_IS_NULL (value_handle))
405 va = (gpointer*) mono_object_unbox_internal (MONO_HANDLE_RAW (value_handle));
406 mono_nullable_init_unboxed ((guint8*)ea, va, ec);
407 MONO_EXIT_NO_SAFEPOINTS;
408 goto leave;
411 if (MONO_HANDLE_IS_NULL (value_handle)) {
412 MONO_ENTER_NO_SAFEPOINTS;
413 ea = (gpointer*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (arr_handle), esize, pos);
414 mono_gc_bzero_atomic (ea, esize);
415 MONO_EXIT_NO_SAFEPOINTS;
416 goto leave;
419 #ifdef ENABLE_NETCORE
420 #define WIDENING_MSG NULL
421 #define WIDENING_ARG NULL
422 #else
423 #define WIDENING_MSG "not a widening conversion"
424 #define WIDENING_ARG "value"
425 #endif
427 #define NO_WIDENING_CONVERSION G_STMT_START{ \
428 mono_error_set_argument (error, WIDENING_ARG, WIDENING_MSG); \
429 break; \
430 }G_STMT_END
432 #define CHECK_WIDENING_CONVERSION(extra) G_STMT_START{ \
433 if (esize < vsize + (extra)) { \
434 mono_error_set_argument (error, WIDENING_ARG, WIDENING_MSG); \
435 break; \
437 }G_STMT_END
439 #define INVALID_CAST G_STMT_START{ \
440 mono_get_runtime_callbacks ()->set_cast_details (vc, ec); \
441 mono_error_set_invalid_cast (error); \
442 break; \
443 }G_STMT_END
445 MonoTypeEnum et;
446 et = m_class_get_byval_arg (ec)->type;
447 MonoTypeEnum vt;
448 vt = m_class_get_byval_arg (vc)->type;
450 /* Check element (destination) type. */
451 switch (et) {
452 case MONO_TYPE_STRING:
453 switch (vt) {
454 case MONO_TYPE_STRING:
455 break;
456 default:
457 INVALID_CAST;
459 break;
460 case MONO_TYPE_BOOLEAN:
461 switch (vt) {
462 case MONO_TYPE_BOOLEAN:
463 break;
464 case MONO_TYPE_CHAR:
465 case MONO_TYPE_U1:
466 case MONO_TYPE_U2:
467 case MONO_TYPE_U4:
468 case MONO_TYPE_U8:
469 case MONO_TYPE_I1:
470 case MONO_TYPE_I2:
471 case MONO_TYPE_I4:
472 case MONO_TYPE_I8:
473 case MONO_TYPE_R4:
474 case MONO_TYPE_R8:
475 NO_WIDENING_CONVERSION;
476 break;
477 default:
478 INVALID_CAST;
480 break;
481 default:
482 break;
484 if (!is_ok (error))
485 goto leave;
487 castOk = mono_object_handle_isinst_mbyref_raw (value_handle, ec, error);
488 if (!is_ok (error))
489 goto leave;
491 if (!m_class_is_valuetype (ec)) {
492 if (!castOk)
493 INVALID_CAST;
494 if (is_ok (error))
495 MONO_HANDLE_ARRAY_SETREF (arr_handle, pos, value_handle);
496 goto leave;
499 if (castOk) {
500 MONO_ENTER_NO_SAFEPOINTS;
501 ea = (gpointer*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (arr_handle), esize, pos);
502 va = (gpointer*) mono_object_unbox_internal (MONO_HANDLE_RAW (value_handle));
503 if (m_class_has_references (ec))
504 mono_value_copy_internal (ea, va, ec);
505 else
506 mono_gc_memmove_atomic (ea, va, esize);
507 MONO_EXIT_NO_SAFEPOINTS;
509 goto leave;
512 if (!m_class_is_valuetype (vc))
513 INVALID_CAST;
515 if (!is_ok (error))
516 goto leave;
518 vsize = mono_class_value_size (vc, NULL);
520 et_isenum = et == MONO_TYPE_VALUETYPE && m_class_is_enumtype (m_class_get_byval_arg (ec)->data.klass);
521 vt_isenum = vt == MONO_TYPE_VALUETYPE && m_class_is_enumtype (m_class_get_byval_arg (vc)->data.klass);
523 #if ENABLE_NETCORE
524 if (strict_enums && et_isenum && !vt_isenum) {
525 INVALID_CAST;
526 goto leave;
528 #endif
530 if (et_isenum)
531 et = mono_class_enum_basetype_internal (m_class_get_byval_arg (ec)->data.klass)->type;
533 if (vt_isenum)
534 vt = mono_class_enum_basetype_internal (m_class_get_byval_arg (vc)->data.klass)->type;
536 #if ENABLE_NETCORE
537 // Treat MONO_TYPE_U/I as MONO_TYPE_U8/I8/U4/I4
538 #if SIZEOF_VOID_P == 8
539 vt = vt == MONO_TYPE_U ? MONO_TYPE_U8 : (vt == MONO_TYPE_I ? MONO_TYPE_I8 : vt);
540 et = et == MONO_TYPE_U ? MONO_TYPE_U8 : (et == MONO_TYPE_I ? MONO_TYPE_I8 : et);
541 #else
542 vt = vt == MONO_TYPE_U ? MONO_TYPE_U4 : (vt == MONO_TYPE_I ? MONO_TYPE_I4 : vt);
543 et = et == MONO_TYPE_U ? MONO_TYPE_U4 : (et == MONO_TYPE_I ? MONO_TYPE_I4 : et);
544 #endif
545 #endif
547 #define ASSIGN_UNSIGNED(etype) G_STMT_START{\
548 switch (vt) { \
549 case MONO_TYPE_U1: \
550 case MONO_TYPE_U2: \
551 case MONO_TYPE_U4: \
552 case MONO_TYPE_U8: \
553 case MONO_TYPE_CHAR: \
554 CHECK_WIDENING_CONVERSION(0); \
555 *(etype *) ea = (etype) u64; \
556 break; \
557 /* You can't assign a signed value to an unsigned array. */ \
558 case MONO_TYPE_I1: \
559 case MONO_TYPE_I2: \
560 case MONO_TYPE_I4: \
561 case MONO_TYPE_I8: \
562 if (!strict_signs) { \
563 CHECK_WIDENING_CONVERSION(0); \
564 *(etype *) ea = (etype) i64; \
565 break; \
567 /* You can't assign a floating point number to an integer array. */ \
568 case MONO_TYPE_R4: \
569 case MONO_TYPE_R8: \
570 NO_WIDENING_CONVERSION; \
571 break; \
572 default: \
573 INVALID_CAST; \
574 break; \
576 }G_STMT_END
578 #define ASSIGN_SIGNED(etype) G_STMT_START{\
579 switch (vt) { \
580 case MONO_TYPE_I1: \
581 case MONO_TYPE_I2: \
582 case MONO_TYPE_I4: \
583 case MONO_TYPE_I8: \
584 CHECK_WIDENING_CONVERSION(0); \
585 *(etype *) ea = (etype) i64; \
586 break; \
587 /* You can assign an unsigned value to a signed array if the array's */ \
588 /* element size is larger than the value size. */ \
589 case MONO_TYPE_U1: \
590 case MONO_TYPE_U2: \
591 case MONO_TYPE_U4: \
592 case MONO_TYPE_U8: \
593 case MONO_TYPE_CHAR: \
594 CHECK_WIDENING_CONVERSION(strict_signs ? 1 : 0); \
595 *(etype *) ea = (etype) u64; \
596 break; \
597 /* You can't assign a floating point number to an integer array. */ \
598 case MONO_TYPE_R4: \
599 case MONO_TYPE_R8: \
600 NO_WIDENING_CONVERSION; \
601 break; \
602 default: \
603 INVALID_CAST; \
604 break; \
606 }G_STMT_END
608 #define ASSIGN_REAL(etype) G_STMT_START{\
609 switch (vt) { \
610 case MONO_TYPE_R4: \
611 case MONO_TYPE_R8: \
612 CHECK_WIDENING_CONVERSION(0); \
613 *(etype *) ea = (etype) r64; \
614 break; \
615 /* All integer values fit into a floating point array, so we don't */ \
616 /* need to CHECK_WIDENING_CONVERSION here. */ \
617 case MONO_TYPE_I1: \
618 case MONO_TYPE_I2: \
619 case MONO_TYPE_I4: \
620 case MONO_TYPE_I8: \
621 *(etype *) ea = (etype) i64; \
622 break; \
623 case MONO_TYPE_U1: \
624 case MONO_TYPE_U2: \
625 case MONO_TYPE_U4: \
626 case MONO_TYPE_U8: \
627 case MONO_TYPE_CHAR: \
628 *(etype *) ea = (etype) u64; \
629 break; \
630 default: \
631 INVALID_CAST; \
632 break; \
634 }G_STMT_END
636 MONO_ENTER_NO_SAFEPOINTS;
637 g_assert (!MONO_HANDLE_IS_NULL (value_handle));
638 g_assert (m_class_is_valuetype (vc));
639 va = (gpointer*) mono_object_unbox_internal (MONO_HANDLE_RAW (value_handle));
640 ea = (gpointer*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (arr_handle), esize, pos);
642 switch (vt) {
643 case MONO_TYPE_U1:
644 u64 = *(guint8 *) va;
645 break;
646 case MONO_TYPE_U2:
647 u64 = *(guint16 *) va;
648 break;
649 case MONO_TYPE_U4:
650 u64 = *(guint32 *) va;
651 break;
652 case MONO_TYPE_U8:
653 u64 = *(guint64 *) va;
654 break;
655 case MONO_TYPE_I1:
656 i64 = *(gint8 *) va;
657 break;
658 case MONO_TYPE_I2:
659 i64 = *(gint16 *) va;
660 break;
661 case MONO_TYPE_I4:
662 i64 = *(gint32 *) va;
663 break;
664 case MONO_TYPE_I8:
665 i64 = *(gint64 *) va;
666 break;
667 case MONO_TYPE_R4:
668 r64 = *(gfloat *) va;
669 break;
670 case MONO_TYPE_R8:
671 r64 = *(gdouble *) va;
672 break;
673 case MONO_TYPE_CHAR:
674 u64 = *(guint16 *) va;
675 break;
676 case MONO_TYPE_BOOLEAN:
677 /* Boolean is only compatible with itself. */
678 switch (et) {
679 case MONO_TYPE_CHAR:
680 case MONO_TYPE_U1:
681 case MONO_TYPE_U2:
682 case MONO_TYPE_U4:
683 case MONO_TYPE_U8:
684 case MONO_TYPE_I1:
685 case MONO_TYPE_I2:
686 case MONO_TYPE_I4:
687 case MONO_TYPE_I8:
688 case MONO_TYPE_R4:
689 case MONO_TYPE_R8:
690 NO_WIDENING_CONVERSION;
691 break;
692 default:
693 INVALID_CAST;
695 break;
696 default:
697 break;
699 /* If we can't do a direct copy, let's try a widening conversion. */
701 if (is_ok (error)) {
702 switch (et) {
703 case MONO_TYPE_CHAR:
704 ASSIGN_UNSIGNED (guint16);
705 break;
706 case MONO_TYPE_U1:
707 ASSIGN_UNSIGNED (guint8);
708 break;
709 case MONO_TYPE_U2:
710 ASSIGN_UNSIGNED (guint16);
711 break;
712 case MONO_TYPE_U4:
713 ASSIGN_UNSIGNED (guint32);
714 break;
715 case MONO_TYPE_U8:
716 ASSIGN_UNSIGNED (guint64);
717 break;
718 case MONO_TYPE_I1:
719 ASSIGN_SIGNED (gint8);
720 break;
721 case MONO_TYPE_I2:
722 ASSIGN_SIGNED (gint16);
723 break;
724 case MONO_TYPE_I4:
725 ASSIGN_SIGNED (gint32);
726 break;
727 case MONO_TYPE_I8:
728 ASSIGN_SIGNED (gint64);
729 break;
730 case MONO_TYPE_R4:
731 ASSIGN_REAL (gfloat);
732 break;
733 case MONO_TYPE_R8:
734 ASSIGN_REAL (gdouble);
735 break;
736 default:
737 INVALID_CAST;
741 MONO_EXIT_NO_SAFEPOINTS;
743 #undef INVALID_CAST
744 #undef NO_WIDENING_CONVERSION
745 #undef CHECK_WIDENING_CONVERSION
746 #undef ASSIGN_UNSIGNED
747 #undef ASSIGN_SIGNED
748 #undef ASSIGN_REAL
750 leave:
751 return;
754 void
755 ves_icall_System_Array_SetValue (MonoArrayHandle arr, MonoObjectHandle value,
756 MonoArrayHandle idxs, MonoError *error)
758 icallarray_print ("%s\n", __func__);
760 MonoArrayBounds dim;
761 MonoClass *ac, *ic;
762 gint32 idx;
763 gint32 i, pos;
765 error_init (error);
767 if (MONO_HANDLE_IS_NULL (idxs)) {
768 #ifdef ENABLE_NETCORE
769 mono_error_set_argument_null (error, "indices", "");
770 #else
771 mono_error_set_argument_null (error, "idxs", "");
772 #endif
773 return;
776 ic = mono_handle_class (idxs);
777 ac = mono_handle_class (arr);
779 g_assert (m_class_get_rank (ic) == 1);
780 if (mono_handle_array_has_bounds (idxs) || MONO_HANDLE_GETVAL (idxs, max_length) != m_class_get_rank (ac)) {
781 #ifdef ENABLE_NETCORE
782 mono_error_set_argument (error, NULL, "");
783 #else
784 mono_error_set_argument (error, "idxs", "");
785 #endif
786 return;
789 if (!mono_handle_array_has_bounds (arr)) {
790 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, 0);
791 if (idx < 0 || idx >= MONO_HANDLE_GETVAL (arr, max_length)) {
792 mono_error_set_exception_instance (error, mono_get_exception_index_out_of_range ());
793 return;
796 array_set_value_impl (arr, value, idx, TRUE, TRUE, error);
797 return;
800 gint32 ac_rank = m_class_get_rank (ac);
801 for (i = 0; i < ac_rank; i++) {
802 mono_handle_array_get_bounds_dim (arr, i, &dim);
803 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, i);
804 if ((idx < dim.lower_bound) ||
805 (idx >= (mono_array_lower_bound_t)dim.length + dim.lower_bound)) {
806 mono_error_set_exception_instance (error, mono_get_exception_index_out_of_range ());
807 return;
811 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, 0);
812 mono_handle_array_get_bounds_dim (arr, 0, &dim);
813 pos = idx - dim.lower_bound;
814 for (i = 1; i < ac_rank; i++) {
815 mono_handle_array_get_bounds_dim (arr, i, &dim);
816 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, i);
817 pos = pos * dim.length + idx - dim.lower_bound;
820 array_set_value_impl (arr, value, pos, TRUE, TRUE, error);
823 #ifdef ENABLE_NETCORE
825 void
826 ves_icall_System_Array_InternalCreate (MonoArray *volatile* result, MonoType* type, gint32 rank, gint32* pLengths, gint32* pLowerBounds)
828 ERROR_DECL (error);
830 MonoClass* klass = mono_class_from_mono_type_internal (type);
831 if (!mono_class_init_checked (klass, error))
832 goto exit;
834 if (m_class_get_byval_arg (m_class_get_element_class (klass))->type == MONO_TYPE_VOID) {
835 mono_error_set_not_supported (error, "Arrays of System.Void are not supported.");
836 goto exit;
839 if (type->byref || m_class_is_byreflike (klass)) {
840 mono_error_set_not_supported (error, NULL);
841 goto exit;
844 MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
845 if (is_generic_parameter (type) || mono_class_is_gtd (klass) || (gklass && gklass->context.class_inst->is_open)) {
846 mono_error_set_not_supported (error, NULL);
847 goto exit;
850 /* vectors are not the same as one dimensional arrays with non-zero bounds */
851 gboolean bounded;
852 bounded = pLowerBounds != NULL && rank == 1 && pLowerBounds [0] != 0;
854 MonoClass* aklass;
855 aklass = mono_class_create_bounded_array (klass, rank, bounded);
857 uintptr_t aklass_rank;
858 aklass_rank = m_class_get_rank (aklass);
860 uintptr_t* sizes;
861 sizes = g_newa (uintptr_t, aklass_rank * 2);
863 intptr_t* lower_bounds;
864 lower_bounds = (intptr_t*)(sizes + aklass_rank);
866 // Copy lengths and lower_bounds from gint32 to [u]intptr_t.
867 for (uintptr_t i = 0; i < aklass_rank; ++i) {
868 if (pLowerBounds != NULL) {
869 lower_bounds [i] = pLowerBounds [i];
870 if ((gint64) pLowerBounds [i] + (gint64) pLengths [i] > G_MAXINT32) {
871 mono_error_set_argument_out_of_range (error, NULL, "Length + bound must not exceed Int32.MaxValue.");
872 goto exit;
874 } else {
875 lower_bounds [i] = 0;
877 sizes [i] = pLengths [i];
880 *result = mono_array_new_full_checked (mono_domain_get (), aklass, sizes, lower_bounds, error);
882 exit:
883 mono_error_set_pending_exception (error);
886 #endif
888 #ifndef ENABLE_NETCORE
889 MonoArrayHandle
890 ves_icall_System_Array_CreateInstanceImpl (MonoReflectionTypeHandle type, MonoArrayHandle lengths, MonoArrayHandle bounds, MonoError *error)
892 // FIXME? fixed could be used for lengths, bounds.
894 icallarray_print ("%s type:%p length:%p bounds:%p\n", __func__, type, lengths, bounds);
896 MONO_CHECK_ARG_NULL_HANDLE (type, NULL_HANDLE_ARRAY);
897 MONO_CHECK_ARG_NULL_HANDLE (lengths, NULL_HANDLE_ARRAY);
899 MONO_CHECK_ARG (lengths, mono_array_handle_length (lengths) > 0, NULL_HANDLE_ARRAY);
900 if (!MONO_HANDLE_IS_NULL (bounds))
901 MONO_CHECK_ARG (bounds, mono_array_handle_length (lengths) == mono_array_handle_length (bounds), NULL_HANDLE_ARRAY);
903 for (uintptr_t i = 0; i < mono_array_handle_length (lengths); ++i) {
904 gint32 length = 0;
905 MONO_HANDLE_ARRAY_GETVAL (length, lengths, gint32, i);
906 if (length < 0) {
907 mono_error_set_argument_out_of_range (error, NULL, "MonoArgumentException:NULL");
908 return NULL_HANDLE_ARRAY;
912 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
913 if (!mono_class_init_checked (klass, error))
914 return NULL_HANDLE_ARRAY;
916 if (m_class_get_byval_arg (m_class_get_element_class (klass))->type == MONO_TYPE_VOID) {
917 mono_error_set_not_supported (error, "Arrays of System.Void are not supported.");
918 return NULL_HANDLE_ARRAY;
921 /* vectors are not the same as one dimensional arrays with non-zero bounds */
922 gboolean bounded = FALSE;
923 if (!MONO_HANDLE_IS_NULL (bounds) && mono_array_handle_length (bounds) == 1) {
924 gint32 bound0 = 0;
925 MONO_HANDLE_ARRAY_GETVAL (bound0, bounds, gint32, 0);
926 bounded = bound0 != 0;
929 MonoClass * const aklass = mono_class_create_bounded_array (klass, mono_array_handle_length (lengths), bounded);
930 uintptr_t const aklass_rank = m_class_get_rank (aklass);
931 uintptr_t * const sizes = g_newa (uintptr_t, aklass_rank);
932 intptr_t * const lower_bounds = g_newa (intptr_t, aklass_rank);
934 // Copy lengths and lower_bounds from gint32 to [u]intptr_t.
936 for (uintptr_t i = 0; i < aklass_rank; ++i) {
937 MONO_HANDLE_ARRAY_GETVAL (sizes [i], lengths, gint32, i);
938 if (!MONO_HANDLE_IS_NULL (bounds))
939 MONO_HANDLE_ARRAY_GETVAL (lower_bounds [i], bounds, gint32, i);
940 else
941 lower_bounds [i] = 0;
944 return mono_array_new_full_handle (MONO_HANDLE_DOMAIN (type), aklass, sizes, lower_bounds, error);
946 #endif
948 gint32
949 ves_icall_System_Array_GetRank (MonoObjectHandle arr, MonoError *error)
951 gint32 const result = m_class_get_rank (mono_handle_class (arr));
953 icallarray_print ("%s arr:%p res:%d\n", __func__, MONO_HANDLE_RAW (arr), result);
955 return result;
958 #ifdef ENABLE_NETCORE
959 gint32
960 ves_icall_System_Array_GetCorElementTypeOfElementType (MonoArrayHandle arr, MonoError *error)
962 MonoType *type = mono_type_get_underlying_type (m_class_get_byval_arg (m_class_get_element_class (mono_handle_class (arr))));
963 return type->type;
966 gint32
967 ves_icall_System_Array_IsValueOfElementType (MonoArrayHandle arr, MonoObjectHandle obj, MonoError *error)
969 return m_class_get_element_class (mono_handle_class (arr)) == mono_handle_class (obj);
971 #endif
973 static mono_array_size_t
974 mono_array_get_length (MonoArrayHandle arr, gint32 dimension, MonoError *error)
976 if (dimension < 0 || dimension >= m_class_get_rank (mono_handle_class (arr))) {
977 mono_error_set_index_out_of_range (error);
978 return 0;
981 return MONO_HANDLE_GETVAL (arr, bounds) ? MONO_HANDLE_GETVAL (arr, bounds [dimension].length)
982 : MONO_HANDLE_GETVAL (arr, max_length);
985 gint32
986 ves_icall_System_Array_GetLength (MonoArrayHandle arr, gint32 dimension, MonoError *error)
988 icallarray_print ("%s arr:%p dimension:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)dimension);
990 mono_array_size_t const length = mono_array_get_length (arr, dimension, error);
991 if (length > G_MAXINT32) {
992 mono_error_set_overflow (error);
993 return 0;
995 return (gint32)length;
998 gint64
999 ves_icall_System_Array_GetLongLength (MonoArrayHandle arr, gint32 dimension, MonoError *error)
1001 icallarray_print ("%s arr:%p dimension:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)dimension);
1003 return (gint64)mono_array_get_length (arr, dimension, error);
1006 gint32
1007 ves_icall_System_Array_GetLowerBound (MonoArrayHandle arr, gint32 dimension, MonoError *error)
1009 icallarray_print ("%s arr:%p dimension:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)dimension);
1011 if (dimension < 0 || dimension >= m_class_get_rank (mono_handle_class (arr))) {
1012 mono_error_set_index_out_of_range (error);
1013 return 0;
1016 return MONO_HANDLE_GETVAL (arr, bounds) ? MONO_HANDLE_GETVAL (arr, bounds [dimension].lower_bound)
1017 : 0;
1020 #ifndef ENABLE_NETCORE
1021 void
1022 ves_icall_System_Array_ClearInternal (MonoArrayHandle arr, int idx, int length, MonoError *error)
1024 icallarray_print ("%s arr:%p idx:%d len:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)idx, (int)length);
1026 int sz = mono_array_element_size (mono_handle_class (arr));
1027 mono_gc_bzero_atomic (mono_array_addr_with_size_fast (MONO_HANDLE_RAW (arr), sz, idx), length * sz);
1029 #endif
1031 MonoBoolean
1032 ves_icall_System_Array_FastCopy (MonoArrayHandle source, int source_idx, MonoArrayHandle dest, int dest_idx, int length, MonoError *error)
1034 MonoVTable * const src_vtable = MONO_HANDLE_GETVAL (source, obj.vtable);
1035 MonoVTable * const dest_vtable = MONO_HANDLE_GETVAL (dest, obj.vtable);
1037 if (src_vtable->rank != dest_vtable->rank)
1038 return FALSE;
1040 MonoArrayBounds *source_bounds = MONO_HANDLE_GETVAL (source, bounds);
1041 MonoArrayBounds *dest_bounds = MONO_HANDLE_GETVAL (dest, bounds);
1043 for (int i = 0; i < src_vtable->rank; i++) {
1044 if ((source_bounds && source_bounds [i].lower_bound > 0) ||
1045 (dest_bounds && dest_bounds [i].lower_bound > 0))
1046 return FALSE;
1049 /* there's no integer overflow since mono_array_length_internal returns an unsigned integer */
1050 if ((dest_idx + length > mono_array_handle_length (dest)) ||
1051 (source_idx + length > mono_array_handle_length (source)))
1052 return FALSE;
1054 MonoClass * const src_class = m_class_get_element_class (src_vtable->klass);
1055 MonoClass * const dest_class = m_class_get_element_class (dest_vtable->klass);
1058 * Handle common cases.
1061 /* Case1: object[] -> valuetype[] (ArrayList::ToArray)
1062 We fallback to managed here since we need to typecheck each boxed valuetype before storing them in the dest array.
1064 if (src_class == mono_defaults.object_class && m_class_is_valuetype (dest_class))
1065 return FALSE;
1067 /* Check if we're copying a char[] <==> (u)short[] */
1068 if (src_class != dest_class) {
1069 if (m_class_is_valuetype (dest_class) || m_class_is_enumtype (dest_class) ||
1070 m_class_is_valuetype (src_class) || m_class_is_valuetype (src_class))
1071 return FALSE;
1073 /* 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. */
1074 if (!mono_class_is_subclass_of_internal (src_class, dest_class, FALSE))
1075 return FALSE;
1077 if (m_class_is_native_pointer (src_class) || m_class_is_native_pointer (dest_class))
1078 return FALSE;
1081 if (m_class_is_valuetype (dest_class)) {
1082 gsize const element_size = mono_array_element_size (MONO_HANDLE_GETVAL (source, obj.vtable->klass));
1084 MONO_ENTER_NO_SAFEPOINTS; // gchandle would also work here, is slow, breaks profiler tests.
1086 gconstpointer const source_addr =
1087 mono_array_addr_with_size_fast (MONO_HANDLE_RAW (source), element_size, source_idx);
1088 if (m_class_has_references (dest_class)) {
1089 mono_value_copy_array_handle (dest, dest_idx, source_addr, length);
1090 } else {
1091 gpointer const dest_addr =
1092 mono_array_addr_with_size_fast (MONO_HANDLE_RAW (dest), element_size, dest_idx);
1093 mono_gc_memmove_atomic (dest_addr, source_addr, element_size * length);
1096 MONO_EXIT_NO_SAFEPOINTS;
1097 } else {
1098 mono_array_handle_memcpy_refs (dest, dest_idx, source, source_idx, length);
1101 return TRUE;
1104 void
1105 ves_icall_System_Array_GetGenericValue_icall (MonoArray **arr, guint32 pos, gpointer value)
1107 icallarray_print ("%s arr:%p pos:%u value:%p\n", __func__, *arr, pos, value);
1109 MONO_REQ_GC_UNSAFE_MODE; // because of gpointer value
1111 MonoClass * const ac = mono_object_class (*arr);
1112 gsize const esize = mono_array_element_size (ac);
1113 gconstpointer * const ea = (gconstpointer*)((char*)(*arr)->vector + (pos * esize));
1115 mono_gc_memmove_atomic (value, ea, esize);
1118 void
1119 ves_icall_System_Array_SetGenericValue_icall (MonoArray **arr, guint32 pos, gpointer value)
1121 icallarray_print ("%s arr:%p pos:%u value:%p\n", __func__, *arr, pos, value);
1123 MONO_REQ_GC_UNSAFE_MODE; // because of gpointer value
1125 MonoClass * const ac = mono_object_class (*arr);
1126 MonoClass * const ec = m_class_get_element_class (ac);
1128 gsize const esize = mono_array_element_size (ac);
1129 gpointer * const ea = (gpointer*)((char*)(*arr)->vector + (pos * esize));
1131 if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (ec))) {
1132 g_assert (esize == sizeof (gpointer));
1133 mono_gc_wbarrier_generic_store_internal (ea, *(MonoObject **)value);
1134 } else {
1135 g_assert (m_class_is_inited (ec));
1136 g_assert (esize == mono_class_value_size (ec, NULL));
1137 if (m_class_has_references (ec))
1138 mono_gc_wbarrier_value_copy_internal (ea, value, 1, ec);
1139 else
1140 mono_gc_memmove_atomic (ea, value, esize);
1144 void
1145 #if ENABLE_NETCORE
1146 ves_icall_System_Runtime_RuntimeImports_Memmove (guint8 *destination, guint8 *source, size_t byte_count)
1147 #else
1148 ves_icall_System_Runtime_RuntimeImports_Memmove (guint8 *destination, guint8 *source, guint byte_count)
1149 #endif
1151 mono_gc_memmove_atomic (destination, source, byte_count);
1154 #if ENABLE_NETCORE
1155 void
1156 ves_icall_System_Runtime_RuntimeImports_RhBulkMoveWithWriteBarrier (guint8 *destination, guint8 *source, size_t byte_count)
1158 mono_gc_wbarrier_range_copy (destination, source, byte_count);
1160 #else
1161 void
1162 ves_icall_System_Runtime_RuntimeImports_Memmove_wbarrier (guint8 *destination, guint8 *source, guint len, MonoType *type)
1164 if (MONO_TYPE_IS_REFERENCE (type))
1165 mono_gc_wbarrier_arrayref_copy_internal (destination, source, len);
1166 else
1167 mono_gc_wbarrier_value_copy_internal (destination, source, len, mono_class_from_mono_type_internal (type));
1169 #endif
1171 void
1172 #if ENABLE_NETCORE
1173 ves_icall_System_Runtime_RuntimeImports_ZeroMemory (guint8 *p, size_t byte_length)
1174 #else
1175 ves_icall_System_Runtime_RuntimeImports_ZeroMemory (guint8 *p, guint byte_length)
1176 #endif
1178 memset (p, 0, byte_length);
1181 void
1182 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArrayHandle array, MonoClassField *field_handle, MonoError *error)
1184 MonoClass *klass = mono_handle_class (array);
1185 guint32 size = mono_array_element_size (klass);
1186 MonoType *type = mono_type_get_underlying_type (m_class_get_byval_arg (m_class_get_element_class (klass)));
1187 int align;
1188 const char *field_data;
1190 if (MONO_TYPE_IS_REFERENCE (type) || type->type == MONO_TYPE_VALUETYPE) {
1191 mono_error_set_argument (error, "array", "Cannot initialize array of non-primitive type");
1192 return;
1195 MonoType *field_type = mono_field_get_type_checked (field_handle, error);
1196 if (!field_type)
1197 return;
1199 if (!(field_type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
1200 mono_error_set_argument_format (error, "field_handle", "Field '%s' doesn't have an RVA", mono_field_get_name (field_handle));
1201 return;
1204 size *= MONO_HANDLE_GETVAL(array, max_length);
1205 field_data = mono_field_get_data (field_handle);
1207 if (size > mono_type_size (field_handle->type, &align)) {
1208 mono_error_set_argument (error, "field_handle", "Field not large enough to fill array");
1209 return;
1212 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1213 #define SWAP(n) { \
1214 guint ## n *data = (guint ## n *) mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0); \
1215 guint ## n *src = (guint ## n *) field_data; \
1216 int i, \
1217 nEnt = (size / sizeof(guint ## n)); \
1219 for (i = 0; i < nEnt; i++) { \
1220 data[i] = read ## n (&src[i]); \
1224 /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
1226 switch (type->type) {
1227 case MONO_TYPE_CHAR:
1228 case MONO_TYPE_I2:
1229 case MONO_TYPE_U2:
1230 SWAP (16);
1231 break;
1232 case MONO_TYPE_I4:
1233 case MONO_TYPE_U4:
1234 case MONO_TYPE_R4:
1235 SWAP (32);
1236 break;
1237 case MONO_TYPE_I8:
1238 case MONO_TYPE_U8:
1239 case MONO_TYPE_R8:
1240 SWAP (64);
1241 break;
1242 default:
1243 memcpy (mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0), field_data, size);
1244 break;
1246 #else
1247 memcpy (mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0), field_data, size);
1248 #endif
1251 gint
1252 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
1254 return offsetof (MonoString, chars);
1257 MonoObjectHandle
1258 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObjectHandle obj, MonoError *error)
1260 if (MONO_HANDLE_IS_NULL (obj) || !m_class_is_valuetype (mono_handle_class (obj)))
1261 return obj;
1263 return mono_object_clone_handle (obj, error);
1266 void
1267 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle, MonoError *error)
1269 MonoClass *klass;
1270 MonoVTable *vtable;
1272 MONO_CHECK_ARG_NULL (handle,);
1274 klass = mono_class_from_mono_type_internal (handle);
1275 MONO_CHECK_ARG (handle, klass,);
1277 if (mono_class_is_gtd (klass))
1278 return;
1280 vtable = mono_class_vtable_checked (mono_domain_get (), klass, error);
1281 return_if_nok (error);
1283 /* This will call the type constructor */
1284 mono_runtime_class_init_full (vtable, error);
1287 void
1288 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (MonoImage *image, MonoError *error)
1290 mono_image_check_for_module_cctor (image);
1291 if (!image->has_module_cctor)
1292 return;
1294 MonoClass *module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, error);
1295 return_if_nok (error);
1297 MonoVTable * vtable = mono_class_vtable_checked (mono_domain_get (), module_klass, error);
1298 return_if_nok (error);
1300 mono_runtime_class_init_full (vtable, error);
1303 MonoBoolean
1304 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
1306 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
1307 // It does not work on win32
1308 #elif defined(TARGET_ANDROID) || defined(__linux__)
1309 // No need for now
1310 #else
1311 guint8 *stack_addr;
1312 guint8 *current;
1313 size_t stack_size;
1314 int min_size;
1315 MonoInternalThread *thread;
1317 mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
1318 /* if we have no info we are optimistic and assume there is enough room */
1319 if (!stack_addr)
1320 return TRUE;
1322 thread = mono_thread_internal_current ();
1323 // .net seems to check that at least 50% of stack is available
1324 min_size = thread->stack_size / 2;
1326 // TODO: It's not always set
1327 if (!min_size)
1328 return TRUE;
1330 current = (guint8 *)&stack_addr;
1331 if (current > stack_addr) {
1332 if ((current - stack_addr) < min_size)
1333 return FALSE;
1334 } else {
1335 if (current - (stack_addr - stack_size) < min_size)
1336 return FALSE;
1338 #endif
1339 return TRUE;
1342 #ifdef ENABLE_NETCORE
1343 MonoObjectHandle
1344 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetUninitializedObjectInternal (MonoType *handle, MonoError *error)
1346 MonoClass *klass;
1348 g_assert (handle);
1350 klass = mono_class_from_mono_type_internal (handle);
1351 if (m_class_is_string (klass)) {
1352 mono_error_set_argument (error, NULL, NULL);
1353 return NULL_HANDLE;
1356 if (m_class_is_abstract (klass) || m_class_is_interface (klass) || m_class_is_gtd (klass)) {
1357 mono_error_set_member_access (error, NULL, NULL);
1358 return NULL_HANDLE;
1361 if (m_class_is_byreflike (klass)) {
1362 mono_error_set_not_supported (error, NULL, NULL);
1363 return NULL_HANDLE;
1366 if (m_class_is_nullable (klass))
1367 return mono_object_new_handle (mono_domain_get (), m_class_get_nullable_elem_class (klass), error);
1368 else
1369 return mono_object_new_handle (mono_domain_get (), klass, error);
1372 void
1373 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_PrepareMethod (MonoMethod *method, gpointer inst_types, int n_inst_types, MonoError *error)
1375 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT) {
1376 mono_error_set_argument (error, NULL, NULL);
1377 return;
1380 MonoGenericContainer *container = NULL;
1381 if (method->is_generic)
1382 container = mono_method_get_generic_container (method);
1383 else if (m_class_is_gtd (method->klass))
1384 container = mono_class_get_generic_container (method->klass);
1385 if (container) {
1386 int nparams = container->type_argc + (container->parent ? container->parent->type_argc : 0);
1387 if (nparams != n_inst_types) {
1388 mono_error_set_argument (error, NULL, NULL);
1389 return;
1393 // FIXME: Implement
1395 #endif
1397 MonoObjectHandle
1398 ves_icall_System_Object_MemberwiseClone (MonoObjectHandle this_obj, MonoError *error)
1400 return mono_object_clone_handle (this_obj, error);
1403 gint32
1404 ves_icall_System_ValueType_InternalGetHashCode (MonoObjectHandle this_obj, MonoArrayHandleOut fields, MonoError *error)
1406 MonoClass *klass;
1407 MonoClassField **unhandled = NULL;
1408 int count = 0;
1409 gint32 result = (int)(gsize)mono_defaults.int32_class;
1410 MonoClassField* field;
1411 gpointer iter;
1413 klass = mono_handle_class (this_obj);
1415 if (mono_class_num_fields (klass) == 0)
1416 return result;
1419 * Compute the starting value of the hashcode for fields of primitive
1420 * types, and return the remaining fields in an array to the managed side.
1421 * This way, we can avoid costly reflection operations in managed code.
1423 iter = NULL;
1424 while ((field = mono_class_get_fields_internal (klass, &iter))) {
1425 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1426 continue;
1427 if (mono_field_is_deleted (field))
1428 continue;
1429 gpointer addr = (guint8*)MONO_HANDLE_RAW (this_obj) + field->offset;
1430 /* FIXME: Add more types */
1431 switch (field->type->type) {
1432 case MONO_TYPE_I4:
1433 result ^= *(gint32*)addr;
1434 break;
1435 case MONO_TYPE_PTR:
1436 result ^= mono_aligned_addr_hash (*(gpointer*)addr);
1437 break;
1438 case MONO_TYPE_STRING: {
1439 MonoString *s;
1440 s = *(MonoString**)addr;
1441 if (s != NULL)
1442 result ^= mono_string_hash_internal (s);
1443 break;
1445 default:
1446 if (!unhandled)
1447 unhandled = g_newa (MonoClassField*, mono_class_num_fields (klass));
1448 unhandled [count ++] = field;
1452 if (unhandled) {
1453 MonoArrayHandle fields_arr = mono_array_new_handle (mono_domain_get (), mono_defaults.object_class, count, error);
1454 return_val_if_nok (error, 0);
1455 MONO_HANDLE_ASSIGN (fields, fields_arr);
1456 MonoObjectHandle h = MONO_HANDLE_NEW (MonoObject, NULL);
1457 for (int i = 0; i < count; ++i) {
1458 MonoObject *o = mono_field_get_value_object_checked (mono_handle_domain (this_obj), unhandled [i], MONO_HANDLE_RAW (this_obj), error);
1459 return_val_if_nok (error, 0);
1460 MONO_HANDLE_ASSIGN_RAW (h, o);
1461 mono_array_handle_setref (fields_arr, i, h);
1463 } else {
1464 MONO_HANDLE_ASSIGN (fields, NULL_HANDLE);
1466 return result;
1469 MonoBoolean
1470 ves_icall_System_ValueType_Equals (MonoObjectHandle this_obj, MonoObjectHandle that, MonoArrayHandleOut fields, MonoError *error)
1472 MonoClass *klass;
1473 MonoClassField **unhandled = NULL;
1474 MonoClassField* field;
1475 gpointer iter;
1476 int count = 0;
1478 MONO_CHECK_ARG_NULL_HANDLE (that, FALSE);
1480 MONO_HANDLE_ASSIGN (fields, NULL_HANDLE);
1482 if (mono_handle_vtable (this_obj) != mono_handle_vtable (that))
1483 return FALSE;
1485 klass = mono_handle_class (this_obj);
1487 if (m_class_is_enumtype (klass) && mono_class_enum_basetype_internal (klass) && mono_class_enum_basetype_internal (klass)->type == MONO_TYPE_I4)
1488 return *(gint32*)mono_handle_get_data_unsafe (this_obj) == *(gint32*)mono_handle_get_data_unsafe (that);
1491 * Do the comparison for fields of primitive type and return a result if
1492 * possible. Otherwise, return the remaining fields in an array to the
1493 * managed side. This way, we can avoid costly reflection operations in
1494 * managed code.
1496 iter = NULL;
1497 while ((field = mono_class_get_fields_internal (klass, &iter))) {
1498 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1499 continue;
1500 if (mono_field_is_deleted (field))
1501 continue;
1502 guint8 *this_field = (guint8 *)MONO_HANDLE_RAW (this_obj) + field->offset;
1503 guint8 *that_field = (guint8 *)MONO_HANDLE_RAW (that) + field->offset;
1505 #define UNALIGNED_COMPARE(type) \
1506 do { \
1507 type left, right; \
1508 memcpy (&left, this_field, sizeof (type)); \
1509 memcpy (&right, that_field, sizeof (type)); \
1510 if (left != right) \
1511 return FALSE; \
1512 } while (0)
1514 /* FIXME: Add more types */
1515 switch (field->type->type) {
1516 case MONO_TYPE_U1:
1517 case MONO_TYPE_I1:
1518 case MONO_TYPE_BOOLEAN:
1519 if (*this_field != *that_field)
1520 return FALSE;
1521 break;
1522 case MONO_TYPE_U2:
1523 case MONO_TYPE_I2:
1524 case MONO_TYPE_CHAR:
1525 #ifdef NO_UNALIGNED_ACCESS
1526 if (G_UNLIKELY ((intptr_t) this_field & 1 || (intptr_t) that_field & 1))
1527 UNALIGNED_COMPARE (gint16);
1528 else
1529 #endif
1530 if (*(gint16 *) this_field != *(gint16 *) that_field)
1531 return FALSE;
1532 break;
1533 case MONO_TYPE_U4:
1534 case MONO_TYPE_I4:
1535 #ifdef NO_UNALIGNED_ACCESS
1536 if (G_UNLIKELY ((intptr_t) this_field & 3 || (intptr_t) that_field & 3))
1537 UNALIGNED_COMPARE (gint32);
1538 else
1539 #endif
1540 if (*(gint32 *) this_field != *(gint32 *) that_field)
1541 return FALSE;
1542 break;
1543 case MONO_TYPE_U8:
1544 case MONO_TYPE_I8:
1545 #ifdef NO_UNALIGNED_ACCESS
1546 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1547 UNALIGNED_COMPARE (gint64);
1548 else
1549 #endif
1550 if (*(gint64 *) this_field != *(gint64 *) that_field)
1551 return FALSE;
1552 break;
1554 case MONO_TYPE_R4: {
1555 float d1, d2;
1556 #ifdef NO_UNALIGNED_ACCESS
1557 memcpy (&d1, this_field, sizeof (float));
1558 memcpy (&d2, that_field, sizeof (float));
1559 #else
1560 d1 = *(float *) this_field;
1561 d2 = *(float *) that_field;
1562 #endif
1563 if (d1 != d2 && !(mono_isnan (d1) && mono_isnan (d2)))
1564 return FALSE;
1565 break;
1567 case MONO_TYPE_R8: {
1568 double d1, d2;
1569 #ifdef NO_UNALIGNED_ACCESS
1570 memcpy (&d1, this_field, sizeof (double));
1571 memcpy (&d2, that_field, sizeof (double));
1572 #else
1573 d1 = *(double *) this_field;
1574 d2 = *(double *) that_field;
1575 #endif
1576 if (d1 != d2 && !(mono_isnan (d1) && mono_isnan (d2)))
1577 return FALSE;
1578 break;
1580 case MONO_TYPE_PTR:
1581 #ifdef NO_UNALIGNED_ACCESS
1582 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1583 UNALIGNED_COMPARE (gpointer);
1584 else
1585 #endif
1586 if (*(gpointer *) this_field != *(gpointer *) that_field)
1587 return FALSE;
1588 break;
1589 case MONO_TYPE_STRING: {
1590 MonoString *s1, *s2;
1591 guint32 s1len, s2len;
1592 s1 = *(MonoString**)this_field;
1593 s2 = *(MonoString**)that_field;
1594 if (s1 == s2)
1595 break;
1596 if ((s1 == NULL) || (s2 == NULL))
1597 return FALSE;
1598 s1len = mono_string_length_internal (s1);
1599 s2len = mono_string_length_internal (s2);
1600 if (s1len != s2len)
1601 return FALSE;
1603 if (memcmp (mono_string_chars_internal (s1), mono_string_chars_internal (s2), s1len * sizeof (gunichar2)) != 0)
1604 return FALSE;
1605 break;
1607 default:
1608 if (!unhandled)
1609 unhandled = g_newa (MonoClassField*, mono_class_num_fields (klass));
1610 unhandled [count ++] = field;
1613 #undef UNALIGNED_COMPARE
1615 if (m_class_is_enumtype (klass))
1616 /* enums only have one non-static field */
1617 break;
1620 if (unhandled) {
1621 MonoArrayHandle fields_arr = mono_array_new_handle (mono_domain_get (), mono_defaults.object_class, count * 2, error);
1622 return_val_if_nok (error, 0);
1623 MONO_HANDLE_ASSIGN (fields, fields_arr);
1624 MonoObjectHandle h = MONO_HANDLE_NEW (MonoObject, NULL);
1625 for (int i = 0; i < count; ++i) {
1626 MonoObject *o = mono_field_get_value_object_checked (mono_handle_domain (this_obj), unhandled [i], MONO_HANDLE_RAW (this_obj), error);
1627 return_val_if_nok (error, FALSE);
1628 MONO_HANDLE_ASSIGN_RAW (h, o);
1629 mono_array_handle_setref (fields_arr, i * 2, h);
1631 o = mono_field_get_value_object_checked (mono_handle_domain (this_obj), unhandled [i], MONO_HANDLE_RAW (that), error);
1632 return_val_if_nok (error, FALSE);
1633 MONO_HANDLE_ASSIGN_RAW (h, o);
1634 mono_array_handle_setref (fields_arr, (i * 2) + 1, h);
1636 return FALSE;
1637 } else {
1638 return TRUE;
1642 MonoReflectionTypeHandle
1643 ves_icall_System_Object_GetType (MonoObjectHandle obj, MonoError *error)
1645 MonoDomain *domain = MONO_HANDLE_DOMAIN (obj);
1646 MonoClass *klass = mono_handle_class (obj);
1647 #ifndef DISABLE_REMOTING
1648 if (mono_class_is_transparent_proxy (klass)) {
1649 MonoTransparentProxyHandle proxy_obj = MONO_HANDLE_CAST (MonoTransparentProxy, obj);
1650 MonoRemoteClass *remote_class = MONO_HANDLE_GETVAL (proxy_obj, remote_class);
1651 /* If it's a transparent proxy for an interface, return the
1652 * interface type, not the unhelpful proxy_class class (which
1653 * is just MarshalByRefObject). */
1654 MonoType *proxy_type =
1655 mono_remote_class_is_interface_proxy (remote_class) ?
1656 m_class_get_byval_arg (remote_class->interfaces[0]) :
1657 m_class_get_byval_arg (remote_class->proxy_class);
1658 return mono_type_get_object_handle (domain, proxy_type, error);
1659 } else
1660 #endif
1661 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
1664 static gboolean
1665 get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1667 MonoMethod **dest = (MonoMethod **)data;
1669 /* skip unmanaged frames */
1670 if (!managed)
1671 return FALSE;
1673 if (!(*dest)) {
1674 if (!strcmp (m_class_get_name_space (m->klass), "System.Reflection"))
1675 return FALSE;
1676 *dest = m;
1677 return TRUE;
1679 return FALSE;
1682 static gboolean
1683 in_corlib_name_space (MonoClass *klass, const char *name_space)
1685 return m_class_get_image (klass) == mono_defaults.corlib &&
1686 !strcmp (m_class_get_name_space (klass), name_space);
1689 static gboolean
1690 get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1692 MonoMethod **dest = (MonoMethod **)data;
1694 /* skip unmanaged frames */
1695 if (!managed)
1696 return FALSE;
1698 if (m->wrapper_type != MONO_WRAPPER_NONE)
1699 return FALSE;
1701 if (m == *dest) {
1702 *dest = NULL;
1703 return FALSE;
1706 if (in_corlib_name_space (m->klass, "System.Reflection"))
1707 return FALSE;
1709 if (!(*dest)) {
1710 *dest = m;
1711 return TRUE;
1713 return FALSE;
1716 static gboolean
1717 get_caller_no_system_or_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1719 MonoMethod **dest = (MonoMethod **)data;
1721 /* skip unmanaged frames */
1722 if (!managed)
1723 return FALSE;
1725 if (m->wrapper_type != MONO_WRAPPER_NONE)
1726 return FALSE;
1728 if (m == *dest) {
1729 *dest = NULL;
1730 return FALSE;
1733 if (in_corlib_name_space (m->klass, "System.Reflection") || in_corlib_name_space (m->klass, "System"))
1734 return FALSE;
1736 if (!(*dest)) {
1737 *dest = m;
1738 return TRUE;
1740 return FALSE;
1744 * mono_runtime_get_caller_no_system_or_reflection:
1746 * Walk the stack of the current thread and find the first managed method that
1747 * is not in the mscorlib System or System.Reflection namespace. This skips
1748 * unmanaged callers and wrapper methods.
1750 * \returns a pointer to the \c MonoMethod or NULL if we walked past all the
1751 * callers.
1753 MonoMethod*
1754 mono_runtime_get_caller_no_system_or_reflection (void)
1756 MonoMethod *dest = NULL;
1757 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1758 return dest;
1762 * mono_runtime_get_caller_from_stack_mark:
1764 * Walk the stack and return the assembly of the method referenced
1765 * by the stack mark STACK_MARK.
1767 MonoAssembly*
1768 mono_runtime_get_caller_from_stack_mark (MonoStackCrawlMark *stack_mark)
1770 // FIXME: Use the stack mark
1771 MonoMethod *dest = NULL;
1772 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1773 if (dest)
1774 return m_class_get_image (dest->klass)->assembly;
1775 else
1776 return NULL;
1779 static MonoReflectionTypeHandle
1780 type_from_parsed_name (MonoTypeNameParse *info, MonoStackCrawlMark *stack_mark, MonoBoolean ignoreCase, MonoAssembly **caller_assembly, MonoError *error)
1782 MonoMethod *m;
1783 MonoType *type = NULL;
1784 MonoAssembly *assembly = NULL;
1785 gboolean type_resolve = FALSE;
1786 MonoImage *rootimage = NULL;
1787 MonoAssemblyLoadContext *alc = mono_domain_ambient_alc (mono_domain_get ());
1789 error_init (error);
1792 * We must compute the calling assembly as type loading must happen under a metadata context.
1793 * For example. The main assembly is a.exe and Type.GetType is called from dir/b.dll. Without
1794 * the metadata context (basedir currently) set to dir/b.dll we won't be able to load a dir/c.dll.
1796 m = mono_method_get_last_managed ();
1797 if (m && m_class_get_image (m->klass) != mono_defaults.corlib) {
1798 /* Happens with inlining */
1799 assembly = m_class_get_image (m->klass)->assembly;
1800 } else {
1801 assembly = mono_runtime_get_caller_from_stack_mark (stack_mark);
1804 if (assembly) {
1805 type_resolve = TRUE;
1806 rootimage = assembly->image;
1807 } else {
1808 // FIXME: once wasm can use stack marks, consider turning all this into an assert
1809 g_warning (G_STRLOC);
1812 *caller_assembly = assembly;
1814 if (info->assembly.name) {
1815 MonoAssemblyByNameRequest req;
1816 mono_assembly_request_prepare_byname (&req, MONO_ASMCTX_DEFAULT, alc);
1817 req.requesting_assembly = assembly;
1818 req.basedir = assembly ? assembly->basedir : NULL;
1819 assembly = mono_assembly_request_byname (&info->assembly, &req, NULL);
1822 if (assembly) {
1823 /* When loading from the current assembly, AppDomain.TypeResolve will not be called yet */
1824 type = mono_reflection_get_type_checked (alc, rootimage, assembly->image, info, ignoreCase, TRUE, &type_resolve, error);
1825 goto_if_nok (error, fail);
1828 // XXXX - aleksey -
1829 // Say we're looking for System.Generic.Dict<int, Local>
1830 // we FAIL the get type above, because S.G.Dict isn't in assembly->image. So we drop down here.
1831 // but then we FAIL AGAIN because now we pass null as the image and the rootimage and everything
1832 // is messed up when we go to construct the Local as the type arg...
1834 // By contrast, if we started with Mine<System.Generic.Dict<int, Local>> we'd go in with assembly->image
1835 // as the root and then even the detour into generics would still not screw us when we went to load Local.
1836 if (!info->assembly.name && !type) {
1837 /* try mscorlib */
1838 type = mono_reflection_get_type_checked (alc, rootimage, NULL, info, ignoreCase, TRUE, &type_resolve, error);
1839 goto_if_nok (error, fail);
1841 if (assembly && !type && type_resolve) {
1842 type_resolve = FALSE; /* This will invoke TypeResolve if not done in the first 'if' */
1843 type = mono_reflection_get_type_checked (alc, rootimage, assembly->image, info, ignoreCase, TRUE, &type_resolve, error);
1844 goto_if_nok (error, fail);
1847 if (!type)
1848 goto fail;
1850 return mono_type_get_object_handle (mono_domain_get (), type, error);
1851 fail:
1852 return MONO_HANDLE_NEW (MonoReflectionType, NULL);
1855 MonoReflectionTypeHandle
1856 ves_icall_System_RuntimeTypeHandle_internal_from_name (MonoStringHandle name,
1857 MonoStackCrawlMark *stack_mark,
1858 MonoReflectionAssemblyHandle callerAssembly,
1859 MonoBoolean throwOnError,
1860 MonoBoolean ignoreCase,
1861 MonoBoolean reflectionOnly,
1862 MonoError *error)
1864 MonoTypeNameParse info;
1865 gboolean free_info = FALSE;
1866 MonoAssembly *caller_assembly;
1867 MonoReflectionTypeHandle type = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1869 /* The callerAssembly argument is unused for now */
1871 char *str = mono_string_handle_to_utf8 (name, error);
1872 goto_if_nok (error, leave);
1874 free_info = TRUE;
1875 if (!mono_reflection_parse_type_checked (str, &info, error))
1876 goto leave;
1878 /* mono_reflection_parse_type() mangles the string */
1880 MONO_HANDLE_ASSIGN (type, type_from_parsed_name (&info, (MonoStackCrawlMark*)stack_mark, ignoreCase, &caller_assembly, error));
1882 goto_if_nok (error, leave);
1884 if (MONO_HANDLE_IS_NULL (type)) {
1885 if (throwOnError) {
1886 char *tname = info.name_space ? g_strdup_printf ("%s.%s", info.name_space, info.name) : g_strdup (info.name);
1887 char *aname;
1888 if (info.assembly.name)
1889 aname = mono_stringify_assembly_name (&info.assembly);
1890 else if (caller_assembly)
1891 aname = mono_stringify_assembly_name (mono_assembly_get_name_internal (caller_assembly));
1892 else
1893 aname = g_strdup ("");
1894 mono_error_set_type_load_name (error, tname, aname, "");
1896 goto leave;
1899 leave:
1900 if (free_info)
1901 mono_reflection_free_type_info (&info);
1902 g_free (str);
1903 if (!is_ok (error)) {
1904 if (!throwOnError) {
1905 mono_error_cleanup (error);
1906 error_init (error);
1908 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
1909 } else
1910 return type;
1914 MonoReflectionTypeHandle
1915 ves_icall_System_Type_internal_from_handle (MonoType *handle, MonoError *error)
1917 MonoDomain *domain = mono_domain_get ();
1919 return mono_type_get_object_handle (domain, handle, error);
1922 MonoType*
1923 ves_icall_Mono_RuntimeClassHandle_GetTypeFromClass (MonoClass *klass, MonoError *error)
1925 return m_class_get_byval_arg (klass);
1928 void
1929 ves_icall_Mono_RuntimeGPtrArrayHandle_GPtrArrayFree (GPtrArray *ptr_array)
1931 g_ptr_array_free (ptr_array, TRUE);
1934 void
1935 ves_icall_Mono_SafeStringMarshal_GFree (void *c_str)
1937 g_free (c_str);
1940 char*
1941 ves_icall_Mono_SafeStringMarshal_StringToUtf8 (MonoString *volatile* s)
1943 ERROR_DECL (error);
1944 char *result = mono_string_to_utf8_checked_internal (*s, error);
1945 mono_error_set_pending_exception (error);
1946 return result;
1949 /* System.TypeCode */
1950 typedef enum {
1951 TYPECODE_EMPTY,
1952 TYPECODE_OBJECT,
1953 TYPECODE_DBNULL,
1954 TYPECODE_BOOLEAN,
1955 TYPECODE_CHAR,
1956 TYPECODE_SBYTE,
1957 TYPECODE_BYTE,
1958 TYPECODE_INT16,
1959 TYPECODE_UINT16,
1960 TYPECODE_INT32,
1961 TYPECODE_UINT32,
1962 TYPECODE_INT64,
1963 TYPECODE_UINT64,
1964 TYPECODE_SINGLE,
1965 TYPECODE_DOUBLE,
1966 TYPECODE_DECIMAL,
1967 TYPECODE_DATETIME,
1968 TYPECODE_STRING = 18
1969 } TypeCode;
1971 #ifndef ENABLE_NETCORE
1972 guint32
1973 ves_icall_type_GetTypeCodeInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
1975 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1976 int t = type->type;
1978 if (type->byref)
1979 return TYPECODE_OBJECT;
1981 handle_enum:
1982 switch (t) {
1983 case MONO_TYPE_VOID:
1984 return TYPECODE_OBJECT;
1985 case MONO_TYPE_BOOLEAN:
1986 return TYPECODE_BOOLEAN;
1987 case MONO_TYPE_U1:
1988 return TYPECODE_BYTE;
1989 case MONO_TYPE_I1:
1990 return TYPECODE_SBYTE;
1991 case MONO_TYPE_U2:
1992 return TYPECODE_UINT16;
1993 case MONO_TYPE_I2:
1994 return TYPECODE_INT16;
1995 case MONO_TYPE_CHAR:
1996 return TYPECODE_CHAR;
1997 case MONO_TYPE_PTR:
1998 case MONO_TYPE_U:
1999 case MONO_TYPE_I:
2000 return TYPECODE_OBJECT;
2001 case MONO_TYPE_U4:
2002 return TYPECODE_UINT32;
2003 case MONO_TYPE_I4:
2004 return TYPECODE_INT32;
2005 case MONO_TYPE_U8:
2006 return TYPECODE_UINT64;
2007 case MONO_TYPE_I8:
2008 return TYPECODE_INT64;
2009 case MONO_TYPE_R4:
2010 return TYPECODE_SINGLE;
2011 case MONO_TYPE_R8:
2012 return TYPECODE_DOUBLE;
2013 case MONO_TYPE_VALUETYPE: {
2014 MonoClass *klass = type->data.klass;
2016 if (m_class_is_enumtype (klass)) {
2017 t = mono_class_enum_basetype_internal (klass)->type;
2018 goto handle_enum;
2019 } else if (mono_is_corlib_image (m_class_get_image (klass))) {
2020 if (strcmp (m_class_get_name_space (klass), "System") == 0) {
2021 if (strcmp (m_class_get_name (klass), "Decimal") == 0)
2022 return TYPECODE_DECIMAL;
2023 else if (strcmp (m_class_get_name (klass), "DateTime") == 0)
2024 return TYPECODE_DATETIME;
2027 return TYPECODE_OBJECT;
2029 case MONO_TYPE_STRING:
2030 return TYPECODE_STRING;
2031 case MONO_TYPE_SZARRAY:
2032 case MONO_TYPE_ARRAY:
2033 case MONO_TYPE_OBJECT:
2034 case MONO_TYPE_VAR:
2035 case MONO_TYPE_MVAR:
2036 case MONO_TYPE_TYPEDBYREF:
2037 return TYPECODE_OBJECT;
2038 case MONO_TYPE_CLASS:
2040 MonoClass *klass = type->data.klass;
2041 if (m_class_get_image (klass) == mono_defaults.corlib && strcmp (m_class_get_name_space (klass), "System") == 0) {
2042 if (strcmp (m_class_get_name (klass), "DBNull") == 0)
2043 return TYPECODE_DBNULL;
2046 return TYPECODE_OBJECT;
2047 case MONO_TYPE_GENERICINST:
2048 return TYPECODE_OBJECT;
2049 default:
2050 g_error ("type 0x%02x not handled in GetTypeCode()", t);
2052 return 0;
2054 #endif
2056 static MonoType*
2057 mono_type_get_underlying_type_ignore_byref (MonoType *type)
2059 if (type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (type->data.klass))
2060 return mono_class_enum_basetype_internal (type->data.klass);
2061 if (type->type == MONO_TYPE_GENERICINST && m_class_is_enumtype (type->data.generic_class->container_class))
2062 return mono_class_enum_basetype_internal (type->data.generic_class->container_class);
2063 return type;
2066 guint32
2067 ves_icall_RuntimeTypeHandle_type_is_assignable_from (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_c, MonoError *error)
2069 g_assert (!MONO_HANDLE_IS_NULL (ref_type));
2071 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2072 MonoClass *klass = mono_class_from_mono_type_internal (type);
2073 MonoType *ctype = MONO_HANDLE_GETVAL (ref_c, type);
2074 MonoClass *klassc = mono_class_from_mono_type_internal (ctype);
2076 if (type->byref ^ ctype->byref)
2077 return FALSE;
2079 if (type->byref) {
2080 MonoType *t = mono_type_get_underlying_type_ignore_byref (type);
2081 MonoType *ot = mono_type_get_underlying_type_ignore_byref (ctype);
2083 klass = mono_class_from_mono_type_internal (t);
2084 klassc = mono_class_from_mono_type_internal (ot);
2086 if (mono_type_is_primitive (t)) {
2087 return mono_type_is_primitive (ot) && m_class_get_instance_size (klass) == m_class_get_instance_size (klassc);
2088 } else if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) {
2089 return t->type == ot->type && t->data.generic_param->num == ot->data.generic_param->num;
2090 } else if (t->type == MONO_TYPE_PTR || t->type == MONO_TYPE_FNPTR) {
2091 return t->type == ot->type;
2092 } else {
2093 if (ot->type == MONO_TYPE_VAR || ot->type == MONO_TYPE_MVAR)
2094 return FALSE;
2096 if (m_class_is_valuetype (klass))
2097 return klass == klassc;
2098 return m_class_is_valuetype (klass) == m_class_is_valuetype (klassc);
2102 gboolean result;
2103 mono_class_is_assignable_from_checked (klass, klassc, &result, error);
2104 return (guint32)result;
2107 MonoBoolean
2108 ves_icall_RuntimeTypeHandle_is_subclass_of (MonoType *childType, MonoType *baseType)
2110 ERROR_DECL (error);
2111 mono_bool result = FALSE;
2112 MonoClass *childClass;
2113 MonoClass *baseClass;
2115 childClass = mono_class_from_mono_type_internal (childType);
2116 baseClass = mono_class_from_mono_type_internal (baseType);
2118 if (G_UNLIKELY (childType->byref)) {
2119 result = !baseType->byref && baseClass == mono_defaults.object_class;
2120 goto done;
2123 if (G_UNLIKELY (baseType->byref)) {
2124 result = FALSE;
2125 goto done;
2128 if (childType == baseType) {
2129 /* .NET IsSubclassOf is not reflexive */
2130 result = FALSE;
2131 goto done;
2134 if (G_UNLIKELY (is_generic_parameter (childType))) {
2135 /* slow path: walk the type hierarchy looking at base types
2136 * until we see baseType. If the current type is not a gparam,
2137 * break out of the loop and use is_subclass_of.
2139 MonoClass *c = mono_generic_param_get_base_type (childClass);
2141 result = FALSE;
2142 while (c != NULL) {
2143 if (c == baseClass) {
2144 result = TRUE;
2145 break;
2147 if (!is_generic_parameter (m_class_get_byval_arg (c))) {
2148 result = mono_class_is_subclass_of_internal (c, baseClass, FALSE);
2149 break;
2150 } else
2151 c = mono_generic_param_get_base_type (c);
2153 } else {
2154 result = mono_class_is_subclass_of_internal (childClass, baseClass, FALSE);
2156 done:
2157 mono_error_set_pending_exception (error);
2158 return result;
2161 guint32
2162 ves_icall_RuntimeTypeHandle_IsInstanceOfType (MonoReflectionTypeHandle ref_type, MonoObjectHandle obj, MonoError *error)
2164 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2165 MonoClass *klass = mono_class_from_mono_type_internal (type);
2166 mono_class_init_checked (klass, error);
2167 return_val_if_nok (error, FALSE);
2168 MonoObjectHandle inst = mono_object_handle_isinst (obj, klass, error);
2169 return_val_if_nok (error, FALSE);
2170 return !MONO_HANDLE_IS_NULL (inst);
2173 guint32
2174 ves_icall_RuntimeTypeHandle_GetAttributes (MonoReflectionTypeHandle ref_type, MonoError *error)
2176 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2178 #ifdef ENABLE_NETCORE
2179 if (type->byref || type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR)
2180 return TYPE_ATTRIBUTE_NOT_PUBLIC;
2181 #endif
2183 MonoClass *klass = mono_class_from_mono_type_internal (type);
2184 return mono_class_get_flags (klass);
2187 MonoReflectionMarshalAsAttributeHandle
2188 ves_icall_System_Reflection_FieldInfo_get_marshal_info (MonoReflectionFieldHandle field_h, MonoError *error)
2190 MonoDomain *domain = MONO_HANDLE_DOMAIN (field_h);
2191 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
2192 MonoClass *klass = field->parent;
2194 MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
2195 if (mono_class_is_gtd (klass) ||
2196 (gklass && gklass->context.class_inst->is_open))
2197 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
2199 MonoType *ftype = mono_field_get_type_internal (field);
2200 if (ftype && !(ftype->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL))
2201 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
2203 MonoMarshalType *info = mono_marshal_load_type_info (klass);
2205 for (int i = 0; i < info->num_fields; ++i) {
2206 if (info->fields [i].field == field) {
2207 if (!info->fields [i].mspec)
2208 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
2209 else {
2210 return mono_reflection_marshal_as_attribute_from_marshal_spec (domain, klass, info->fields [i].mspec, error);
2215 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
2218 MonoReflectionFieldHandle
2219 ves_icall_System_Reflection_FieldInfo_internal_from_handle_type (MonoClassField *handle, MonoType *type, MonoError *error)
2221 MonoClass *klass;
2223 g_assert (handle);
2225 if (!type) {
2226 klass = handle->parent;
2227 } else {
2228 klass = mono_class_from_mono_type_internal (type);
2230 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
2232 if (!found)
2233 /* The managed code will throw the exception */
2234 return MONO_HANDLE_CAST (MonoReflectionField, NULL_HANDLE);
2237 return mono_field_get_object_handle (mono_domain_get (), klass, handle, error);
2240 MonoReflectionEventHandle
2241 ves_icall_System_Reflection_EventInfo_internal_from_handle_type (MonoEvent *handle, MonoType *type, MonoError *error)
2243 MonoClass *klass;
2245 g_assert (handle);
2247 if (!type) {
2248 klass = handle->parent;
2249 } else {
2250 klass = mono_class_from_mono_type_internal (type);
2252 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
2253 if (!found)
2254 /* Managed code will throw an exception */
2255 return MONO_HANDLE_CAST (MonoReflectionEvent, NULL_HANDLE);
2258 return mono_event_get_object_handle (mono_domain_get (), klass, handle, error);
2261 MonoReflectionPropertyHandle
2262 ves_icall_System_Reflection_RuntimePropertyInfo_internal_from_handle_type (MonoProperty *handle, MonoType *type, MonoError *error)
2264 MonoClass *klass;
2266 g_assert (handle);
2268 if (!type) {
2269 klass = handle->parent;
2270 } else {
2271 klass = mono_class_from_mono_type_internal (type);
2273 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
2274 if (!found)
2275 /* Managed code will throw an exception */
2276 return MONO_HANDLE_CAST (MonoReflectionProperty, NULL_HANDLE);
2279 return mono_property_get_object_handle (mono_domain_get (), klass, handle, error);
2282 MonoArrayHandle
2283 ves_icall_System_Reflection_FieldInfo_GetTypeModifiers (MonoReflectionFieldHandle field_h, MonoBoolean optional, MonoError *error)
2285 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
2287 MonoType *type = mono_field_get_type_checked (field, error);
2288 return_val_if_nok (error, NULL_HANDLE_ARRAY);
2290 return type_array_from_modifiers (m_class_get_image (field->parent), type, optional, error);
2294 ves_icall_get_method_attributes (MonoMethod *method)
2296 return method->flags;
2299 void
2300 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info, MonoError *error)
2302 MonoDomain *domain = mono_domain_get ();
2304 MonoMethodSignature* sig = mono_method_signature_checked (method, error);
2305 return_if_nok (error);
2307 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (method->klass), error);
2308 return_if_nok (error);
2310 MONO_STRUCT_SETREF_INTERNAL (info, parent, MONO_HANDLE_RAW (rt));
2312 MONO_HANDLE_ASSIGN (rt, mono_type_get_object_handle (domain, sig->ret, error));
2313 return_if_nok (error);
2315 MONO_STRUCT_SETREF_INTERNAL (info, ret, MONO_HANDLE_RAW (rt));
2317 info->attrs = method->flags;
2318 info->implattrs = method->iflags;
2319 guint32 callconv;
2320 if (sig->call_convention == MONO_CALL_DEFAULT)
2321 callconv = sig->sentinelpos >= 0 ? 2 : 1;
2322 else {
2323 if (sig->call_convention == MONO_CALL_VARARG || sig->sentinelpos >= 0)
2324 callconv = 2;
2325 else
2326 callconv = 1;
2328 callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6);
2329 info->callconv = callconv;
2332 MonoArrayHandle
2333 ves_icall_System_Reflection_MonoMethodInfo_get_parameter_info (MonoMethod *method, MonoReflectionMethodHandle member, MonoError *error)
2335 MonoDomain *domain = mono_domain_get ();
2337 MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
2338 MONO_HANDLE_GET (reftype, member, reftype);
2339 MonoClass *klass = NULL;
2340 if (!MONO_HANDLE_IS_NULL (reftype))
2341 klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (reftype, type));
2342 return mono_param_get_objects_internal (domain, method, klass, error);
2345 MonoReflectionMarshalAsAttributeHandle
2346 ves_icall_System_MonoMethodInfo_get_retval_marshal (MonoMethod *method, MonoError *error)
2348 MonoDomain *domain = mono_domain_get ();
2349 MonoReflectionMarshalAsAttributeHandle res = MONO_HANDLE_NEW (MonoReflectionMarshalAsAttribute, NULL);
2351 MonoMarshalSpec **mspecs = g_new (MonoMarshalSpec*, mono_method_signature_internal (method)->param_count + 1);
2352 mono_method_get_marshal_info (method, mspecs);
2354 if (mspecs [0]) {
2355 MONO_HANDLE_ASSIGN (res, mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [0], error));
2356 goto_if_nok (error, leave);
2359 leave:
2360 for (int i = mono_method_signature_internal (method)->param_count; i >= 0; i--)
2361 if (mspecs [i])
2362 mono_metadata_free_marshal_spec (mspecs [i]);
2363 g_free (mspecs);
2365 return res;
2368 gint32
2369 ves_icall_RuntimeFieldInfo_GetFieldOffset (MonoReflectionFieldHandle field, MonoError *error)
2371 MonoClassField *class_field = MONO_HANDLE_GETVAL (field, field);
2372 mono_class_setup_fields (class_field->parent);
2374 return class_field->offset - MONO_ABI_SIZEOF (MonoObject);
2377 MonoReflectionTypeHandle
2378 ves_icall_RuntimeFieldInfo_GetParentType (MonoReflectionFieldHandle field, MonoBoolean declaring, MonoError *error)
2380 MonoDomain *domain = MONO_HANDLE_DOMAIN (field);
2381 MonoClass *parent;
2383 if (declaring) {
2384 MonoClassField *f = MONO_HANDLE_GETVAL (field, field);
2385 parent = f->parent;
2386 } else {
2387 parent = MONO_HANDLE_GETVAL (field, klass);
2390 return mono_type_get_object_handle (domain, m_class_get_byval_arg (parent), error);
2393 MonoObjectHandle
2394 ves_icall_RuntimeFieldInfo_GetValueInternal (MonoReflectionFieldHandle field_handle, MonoObjectHandle obj_handle, MonoError *error)
2396 MonoReflectionField * const field = MONO_HANDLE_RAW (field_handle);
2397 MonoClass *fklass = field->klass;
2398 MonoClassField *cf = field->field;
2400 if (mono_asmctx_get_kind (&m_class_get_image (fklass)->assembly->context) == MONO_ASMCTX_REFONLY) {
2401 mono_error_set_invalid_operation (error,
2402 "It is illegal to get the value on a field on a type loaded using the ReflectionOnly methods.");
2403 return NULL_HANDLE;
2406 if (mono_security_core_clr_enabled () &&
2407 !mono_security_core_clr_ensure_reflection_access_field (cf, error)) {
2408 return NULL_HANDLE;
2411 MonoObject * const obj = MONO_HANDLE_RAW (obj_handle);
2412 MonoObject *result;
2414 #ifndef DISABLE_REMOTING
2415 if (G_UNLIKELY (obj != NULL && mono_class_is_transparent_proxy (mono_object_class (obj)))) {
2416 /* We get here if someone used a
2417 * System.Reflection.FieldInfo:GetValue on a
2418 * ContextBoundObject's or cross-domain MarshalByRefObject's
2419 * transparent proxy. */
2420 result = mono_load_remote_field_new_checked (obj, fklass, cf, error);
2421 } else
2422 #endif
2423 result = mono_field_get_value_object_checked (mono_object_domain (field), cf, obj, error);
2425 return MONO_HANDLE_NEW (MonoObject, result);
2428 void
2429 ves_icall_RuntimeFieldInfo_SetValueInternal (MonoReflectionFieldHandle field, MonoObjectHandle obj, MonoObjectHandle value, MonoError *error)
2431 MonoClassField *cf = MONO_HANDLE_GETVAL (field, field);
2433 MonoClass *field_klass = MONO_HANDLE_GETVAL (field, klass);
2434 if (mono_asmctx_get_kind (&m_class_get_image (field_klass)->assembly->context) == MONO_ASMCTX_REFONLY) {
2435 mono_error_set_invalid_operation (error, "It is illegal to set the value on a field on a type loaded using the ReflectionOnly methods.");
2436 return;
2439 if (mono_security_core_clr_enabled () &&
2440 !mono_security_core_clr_ensure_reflection_access_field (cf, error)) {
2441 return;
2444 #ifndef DISABLE_REMOTING
2445 if (G_UNLIKELY (!MONO_HANDLE_IS_NULL (obj) && mono_class_is_transparent_proxy (mono_handle_class (obj)))) {
2446 /* We get here if someone used a
2447 * System.Reflection.FieldInfo:SetValue on a
2448 * ContextBoundObject's or cross-domain MarshalByRefObject's
2449 * transparent proxy. */
2450 /* FIXME: use handles for mono_store_remote_field_new_checked */
2451 MonoObject *v = MONO_HANDLE_RAW (value);
2452 MonoObject *o = MONO_HANDLE_RAW (obj);
2453 mono_store_remote_field_new_checked (o, field_klass, cf, v, error);
2454 return;
2456 #endif
2458 MonoType *type = mono_field_get_type_checked (cf, error);
2459 return_if_nok (error);
2461 gboolean isref = FALSE;
2462 uint32_t value_gchandle = 0;
2463 gchar *v = NULL;
2464 if (!type->byref) {
2465 switch (type->type) {
2466 case MONO_TYPE_U1:
2467 case MONO_TYPE_I1:
2468 case MONO_TYPE_BOOLEAN:
2469 case MONO_TYPE_U2:
2470 case MONO_TYPE_I2:
2471 case MONO_TYPE_CHAR:
2472 case MONO_TYPE_U:
2473 case MONO_TYPE_I:
2474 case MONO_TYPE_U4:
2475 case MONO_TYPE_I4:
2476 case MONO_TYPE_R4:
2477 case MONO_TYPE_U8:
2478 case MONO_TYPE_I8:
2479 case MONO_TYPE_R8:
2480 case MONO_TYPE_VALUETYPE:
2481 case MONO_TYPE_PTR:
2482 isref = FALSE;
2483 if (!MONO_HANDLE_IS_NULL (value))
2484 v = (char*)mono_object_handle_pin_unbox (value, &value_gchandle);
2485 break;
2486 case MONO_TYPE_STRING:
2487 case MONO_TYPE_OBJECT:
2488 case MONO_TYPE_CLASS:
2489 case MONO_TYPE_ARRAY:
2490 case MONO_TYPE_SZARRAY:
2491 /* Do nothing */
2492 isref = TRUE;
2493 break;
2494 case MONO_TYPE_GENERICINST: {
2495 MonoGenericClass *gclass = type->data.generic_class;
2496 g_assert (!gclass->context.class_inst->is_open);
2498 if (mono_class_is_nullable (mono_class_from_mono_type_internal (type))) {
2499 MonoClass *nklass = mono_class_from_mono_type_internal (type);
2502 * Convert the boxed vtype into a Nullable structure.
2503 * This is complicated by the fact that Nullables have
2504 * a variable structure.
2506 MonoObjectHandle nullable = mono_object_new_handle (mono_domain_get (), nklass, error);
2507 return_if_nok (error);
2509 uint32_t nullable_gchandle = 0;
2510 guint8 *nval = (guint8*)mono_object_handle_pin_unbox (nullable, &nullable_gchandle);
2511 mono_nullable_init_from_handle (nval, value, nklass);
2513 isref = FALSE;
2514 value_gchandle = nullable_gchandle;
2515 v = (gchar*)nval;
2517 else {
2518 isref = !m_class_is_valuetype (gclass->container_class);
2519 if (!isref && !MONO_HANDLE_IS_NULL (value)) {
2520 v = (char*)mono_object_handle_pin_unbox (value, &value_gchandle);
2523 break;
2525 default:
2526 g_error ("type 0x%x not handled in "
2527 "ves_icall_FieldInfo_SetValueInternal", type->type);
2528 return;
2532 /* either value is a reference type, or it's a value type and we pinned
2533 * it and v points to the payload. */
2534 g_assert ((isref && v == NULL && value_gchandle == 0) ||
2535 (!isref && v != NULL && value_gchandle != 0) ||
2536 (!isref && v == NULL && value_gchandle == 0));
2538 if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
2539 MonoVTable *vtable = mono_class_vtable_checked (MONO_HANDLE_DOMAIN (field), cf->parent, error);
2540 goto_if_nok (error, leave);
2542 if (!vtable->initialized) {
2543 if (!mono_runtime_class_init_full (vtable, error))
2544 goto leave;
2546 if (isref)
2547 mono_field_static_set_value_internal (vtable, cf, MONO_HANDLE_RAW (value)); /* FIXME make mono_field_static_set_value work with handles for value */
2548 else
2549 mono_field_static_set_value_internal (vtable, cf, v);
2550 } else {
2552 if (isref)
2553 MONO_HANDLE_SET_FIELD_REF (obj, cf, value);
2554 else
2555 mono_field_set_value_internal (MONO_HANDLE_RAW (obj), cf, v); /* FIXME: make mono_field_set_value take a handle for obj */
2557 leave:
2558 if (value_gchandle)
2559 mono_gchandle_free_internal (value_gchandle);
2562 static MonoObjectHandle
2563 typed_reference_to_object (MonoTypedRef *tref, MonoError *error)
2565 HANDLE_FUNCTION_ENTER ();
2566 MonoObjectHandle result;
2567 if (MONO_TYPE_IS_REFERENCE (tref->type)) {
2568 MonoObject** objp = (MonoObject **)tref->value;
2569 result = MONO_HANDLE_NEW (MonoObject, *objp);
2570 } else if (mono_type_is_pointer (tref->type)) {
2571 /* Boxed as UIntPtr */
2572 result = mono_value_box_handle (mono_domain_get (), mono_get_uintptr_class (), tref->value, error);
2573 } else {
2574 result = mono_value_box_handle (mono_domain_get (), tref->klass, tref->value, error);
2576 HANDLE_FUNCTION_RETURN_REF (MonoObject, result);
2579 MonoObjectHandle
2580 ves_icall_System_RuntimeFieldHandle_GetValueDirect (MonoReflectionFieldHandle field_h, MonoReflectionTypeHandle field_type_h, MonoTypedRef *obj, MonoReflectionTypeHandle context_type_h, MonoError *error)
2582 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
2583 MonoClass *klass = mono_class_from_mono_type_internal (field->type);
2585 if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (field->parent))) {
2586 mono_error_set_not_implemented (error, "");
2587 return MONO_HANDLE_NEW (MonoObject, NULL);
2588 } else if (MONO_TYPE_IS_REFERENCE (field->type)) {
2589 return MONO_HANDLE_NEW (MonoObject, *(MonoObject**)((guint8*)obj->value + field->offset - sizeof (MonoObject)));
2590 } else {
2591 return mono_value_box_handle (mono_domain_get (), klass, (guint8*)obj->value + field->offset - sizeof (MonoObject), error);
2595 void
2596 ves_icall_System_RuntimeFieldHandle_SetValueDirect (MonoReflectionFieldHandle field_h, MonoReflectionTypeHandle field_type_h, MonoTypedRef *obj, MonoObjectHandle value_h, MonoReflectionTypeHandle context_type_h, MonoError *error)
2598 MonoClassField *f = MONO_HANDLE_GETVAL (field_h, field);
2600 g_assert (obj);
2602 if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (f->parent))) {
2603 MonoObjectHandle objHandle = typed_reference_to_object (obj, error);
2604 return_if_nok (error);
2605 ves_icall_RuntimeFieldInfo_SetValueInternal (field_h, objHandle, value_h, error);
2606 } else if (MONO_TYPE_IS_REFERENCE (f->type)) {
2607 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), MONO_HANDLE_RAW (value_h), FALSE);
2608 } else {
2609 guint gchandle = 0;
2610 g_assert (MONO_HANDLE_RAW (value_h));
2611 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), mono_object_handle_pin_unbox (value_h, &gchandle), FALSE);
2612 mono_gchandle_free_internal (gchandle);
2616 MonoObjectHandle
2617 ves_icall_RuntimeFieldInfo_GetRawConstantValue (MonoReflectionFieldHandle rfield, MonoError* error)
2619 MonoObjectHandle o_handle = NULL_HANDLE_INIT;
2621 MonoObject *o = NULL;
2622 MonoClassField *field = MONO_HANDLE_GETVAL (rfield, field);
2623 MonoClass *klass;
2624 MonoDomain *domain = MONO_HANDLE_DOMAIN (rfield);
2625 gchar *v;
2626 MonoTypeEnum def_type;
2627 const char *def_value;
2628 MonoType *t;
2629 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
2631 mono_class_init_internal (field->parent);
2633 t = mono_field_get_type_checked (field, error);
2634 goto_if_nok (error, return_null);
2636 if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT))
2637 goto invalid_operation;
2639 if (image_is_dynamic (m_class_get_image (field->parent))) {
2640 MonoClass *klass = field->parent;
2641 int fidx = field - m_class_get_fields (klass);
2642 MonoFieldDefaultValue *def_values = mono_class_get_field_def_values (klass);
2644 g_assert (def_values);
2645 def_type = def_values [fidx].def_type;
2646 def_value = def_values [fidx].data;
2648 if (def_type == MONO_TYPE_END)
2649 goto invalid_operation;
2650 } else {
2651 def_value = mono_class_get_field_default_value (field, &def_type);
2652 /* FIXME, maybe we should try to raise TLE if field->parent is broken */
2653 if (!def_value)
2654 goto invalid_operation;
2657 /*FIXME unify this with reflection.c:mono_get_object_from_blob*/
2658 switch (def_type) {
2659 case MONO_TYPE_U1:
2660 case MONO_TYPE_I1:
2661 case MONO_TYPE_BOOLEAN:
2662 case MONO_TYPE_U2:
2663 case MONO_TYPE_I2:
2664 case MONO_TYPE_CHAR:
2665 case MONO_TYPE_U:
2666 case MONO_TYPE_I:
2667 case MONO_TYPE_U4:
2668 case MONO_TYPE_I4:
2669 case MONO_TYPE_R4:
2670 case MONO_TYPE_U8:
2671 case MONO_TYPE_I8:
2672 case MONO_TYPE_R8: {
2673 MonoType *t;
2675 /* boxed value type */
2676 t = g_new0 (MonoType, 1);
2677 t->type = def_type;
2678 klass = mono_class_from_mono_type_internal (t);
2679 g_free (t);
2680 o = mono_object_new_checked (domain, klass, error);
2681 goto_if_nok (error, return_null);
2682 o_handle = MONO_HANDLE_NEW (MonoObject, o);
2683 v = ((gchar *) o) + sizeof (MonoObject);
2684 (void)mono_get_constant_value_from_blob (domain, def_type, def_value, v, string_handle, error);
2685 goto_if_nok (error, return_null);
2686 break;
2688 case MONO_TYPE_STRING:
2689 case MONO_TYPE_CLASS:
2690 (void)mono_get_constant_value_from_blob (domain, def_type, def_value, &o, string_handle, error);
2691 goto_if_nok (error, return_null);
2692 o_handle = MONO_HANDLE_NEW (MonoObject, o);
2693 break;
2694 default:
2695 g_assert_not_reached ();
2698 goto exit;
2699 invalid_operation:
2700 mono_error_set_invalid_operation (error, NULL);
2701 // fall through
2702 return_null:
2703 o_handle = NULL_HANDLE;
2704 // fall through
2705 exit:
2706 return o_handle;
2709 MonoReflectionTypeHandle
2710 ves_icall_RuntimeFieldInfo_ResolveType (MonoReflectionFieldHandle ref_field, MonoError *error)
2712 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_field);
2713 MonoClassField *field = MONO_HANDLE_GETVAL (ref_field, field);
2714 MonoType *type = mono_field_get_type_checked (field, error);
2715 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
2716 return mono_type_get_object_handle (domain, type, error);
2719 void
2720 ves_icall_RuntimePropertyInfo_get_property_info (MonoReflectionPropertyHandle property, MonoPropertyInfo *info, PInfo req_info, MonoError *error)
2722 MonoDomain *domain = MONO_HANDLE_DOMAIN (property);
2723 const MonoProperty *pproperty = MONO_HANDLE_GETVAL (property, property);
2725 if ((req_info & PInfo_ReflectedType) != 0) {
2726 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
2727 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2728 return_if_nok (error);
2730 MONO_STRUCT_SETREF_INTERNAL (info, parent, MONO_HANDLE_RAW (rt));
2732 if ((req_info & PInfo_DeclaringType) != 0) {
2733 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (pproperty->parent), error);
2734 return_if_nok (error);
2736 MONO_STRUCT_SETREF_INTERNAL (info, declaring_type, MONO_HANDLE_RAW (rt));
2739 if ((req_info & PInfo_Name) != 0) {
2740 MonoStringHandle name = mono_string_new_handle (domain, pproperty->name, error);
2741 return_if_nok (error);
2743 MONO_STRUCT_SETREF_INTERNAL (info, name, MONO_HANDLE_RAW (name));
2746 if ((req_info & PInfo_Attributes) != 0)
2747 info->attrs = pproperty->attrs;
2749 if ((req_info & PInfo_GetMethod) != 0) {
2750 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2751 MonoReflectionMethodHandle rm;
2752 if (pproperty->get &&
2753 (((pproperty->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2754 pproperty->get->klass == property_klass)) {
2755 rm = mono_method_get_object_handle (domain, pproperty->get, property_klass, error);
2756 return_if_nok (error);
2757 } else {
2758 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2761 MONO_STRUCT_SETREF_INTERNAL (info, get, MONO_HANDLE_RAW (rm));
2763 if ((req_info & PInfo_SetMethod) != 0) {
2764 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2765 MonoReflectionMethodHandle rm;
2766 if (pproperty->set &&
2767 (((pproperty->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2768 pproperty->set->klass == property_klass)) {
2769 rm = mono_method_get_object_handle (domain, pproperty->set, property_klass, error);
2770 return_if_nok (error);
2771 } else {
2772 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2775 MONO_STRUCT_SETREF_INTERNAL (info, set, MONO_HANDLE_RAW (rm));
2778 * There may be other methods defined for properties, though, it seems they are not exposed
2779 * in the reflection API
2783 static gboolean
2784 add_event_other_methods_to_array (MonoDomain *domain, MonoMethod *m, MonoArrayHandle dest, int i, MonoError *error)
2786 HANDLE_FUNCTION_ENTER ();
2787 error_init (error);
2788 MonoReflectionMethodHandle rm = mono_method_get_object_handle (domain, m, NULL, error);
2789 goto_if_nok (error, leave);
2790 MONO_HANDLE_ARRAY_SETREF (dest, i, rm);
2791 leave:
2792 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2795 void
2796 ves_icall_RuntimeEventInfo_get_event_info (MonoReflectionMonoEventHandle ref_event, MonoEventInfo *info, MonoError *error)
2798 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_event);
2800 MonoClass *klass = MONO_HANDLE_GETVAL (ref_event, klass);
2801 MonoEvent *event = MONO_HANDLE_GETVAL (ref_event, event);
2803 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2804 return_if_nok (error);
2805 MONO_STRUCT_SETREF_INTERNAL (info, reflected_type, MONO_HANDLE_RAW (rt));
2807 rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (event->parent), error);
2808 return_if_nok (error);
2809 MONO_STRUCT_SETREF_INTERNAL (info, declaring_type, MONO_HANDLE_RAW (rt));
2811 MonoStringHandle ev_name = mono_string_new_handle (domain, event->name, error);
2812 return_if_nok (error);
2813 MONO_STRUCT_SETREF_INTERNAL (info, name, MONO_HANDLE_RAW (ev_name));
2815 info->attrs = event->attrs;
2817 MonoReflectionMethodHandle rm;
2818 if (event->add) {
2819 rm = mono_method_get_object_handle (domain, event->add, klass, error);
2820 return_if_nok (error);
2821 } else {
2822 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2825 MONO_STRUCT_SETREF_INTERNAL (info, add_method, MONO_HANDLE_RAW (rm));
2827 if (event->remove) {
2828 rm = mono_method_get_object_handle (domain, event->remove, klass, error);
2829 return_if_nok (error);
2830 } else {
2831 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2834 MONO_STRUCT_SETREF_INTERNAL (info, remove_method, MONO_HANDLE_RAW (rm));
2836 if (event->raise) {
2837 rm = mono_method_get_object_handle (domain, event->raise, klass, error);
2838 return_if_nok (error);
2839 } else {
2840 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2843 MONO_STRUCT_SETREF_INTERNAL (info, raise_method, MONO_HANDLE_RAW (rm));
2845 #ifndef MONO_SMALL_CONFIG
2846 if (event->other) {
2847 int i, n = 0;
2848 while (event->other [n])
2849 n++;
2850 MonoArrayHandle info_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, n, error);
2851 return_if_nok (error);
2853 MONO_STRUCT_SETREF_INTERNAL (info, other_methods, MONO_HANDLE_RAW (info_arr));
2855 for (i = 0; i < n; i++)
2856 if (!add_event_other_methods_to_array (domain, event->other [i], info_arr, i, error))
2857 return;
2859 #endif
2862 static void
2863 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
2865 int i;
2866 MonoClass *ic;
2868 mono_class_setup_interfaces (klass, error);
2869 return_if_nok (error);
2871 int klass_interface_count = m_class_get_interface_count (klass);
2872 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
2873 for (i = 0; i < klass_interface_count; i++) {
2874 ic = klass_interfaces [i];
2875 g_hash_table_insert (ifaces, ic, ic);
2877 collect_interfaces (ic, ifaces, error);
2878 return_if_nok (error);
2882 typedef struct {
2883 MonoArrayHandle iface_array;
2884 MonoGenericContext *context;
2885 MonoError *error;
2886 MonoDomain *domain;
2887 int next_idx;
2888 } FillIfaceArrayData;
2890 static void
2891 fill_iface_array (gpointer key, gpointer value, gpointer user_data)
2893 HANDLE_FUNCTION_ENTER ();
2894 FillIfaceArrayData *data = (FillIfaceArrayData *)user_data;
2895 MonoClass *ic = (MonoClass *)key;
2896 MonoType *ret = m_class_get_byval_arg (ic), *inflated = NULL;
2897 MonoError *error = data->error;
2899 goto_if_nok (error, leave);
2901 if (data->context && mono_class_is_ginst (ic) && mono_class_get_generic_class (ic)->context.class_inst->is_open) {
2902 inflated = ret = mono_class_inflate_generic_type_checked (ret, data->context, error);
2903 goto_if_nok (error, leave);
2906 MonoReflectionTypeHandle rt;
2907 rt = mono_type_get_object_handle (data->domain, ret, error);
2908 goto_if_nok (error, leave);
2910 MONO_HANDLE_ARRAY_SETREF (data->iface_array, data->next_idx, rt);
2911 data->next_idx++;
2913 if (inflated)
2914 mono_metadata_free_type (inflated);
2915 leave:
2916 HANDLE_FUNCTION_RETURN ();
2919 static guint
2920 get_interfaces_hash (gconstpointer v1)
2922 MonoClass *k = (MonoClass*)v1;
2924 return m_class_get_type_token (k);
2927 MonoArrayHandle
2928 ves_icall_RuntimeType_GetInterfaces (MonoReflectionTypeHandle ref_type, MonoError *error)
2930 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2931 MonoClass *klass = mono_class_from_mono_type_internal (type);
2933 GHashTable *iface_hash = g_hash_table_new (get_interfaces_hash, NULL);
2935 MonoGenericContext *context = NULL;
2936 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open) {
2937 context = mono_class_get_context (klass);
2938 klass = mono_class_get_generic_class (klass)->container_class;
2941 for (MonoClass *parent = klass; parent; parent = m_class_get_parent (parent)) {
2942 mono_class_setup_interfaces (parent, error);
2943 goto_if_nok (error, fail);
2944 collect_interfaces (parent, iface_hash, error);
2945 goto_if_nok (error, fail);
2948 MonoDomain *domain;
2949 domain = MONO_HANDLE_DOMAIN (ref_type);
2951 int len;
2952 len = g_hash_table_size (iface_hash);
2953 if (len == 0) {
2954 g_hash_table_destroy (iface_hash);
2955 if (!domain->empty_types) {
2956 domain->empty_types = mono_array_new_cached (domain, mono_defaults.runtimetype_class, 0, error);
2957 goto_if_nok (error, fail);
2959 return MONO_HANDLE_NEW (MonoArray, domain->empty_types);
2962 FillIfaceArrayData data;
2963 data.iface_array = MONO_HANDLE_NEW (MonoArray, mono_array_new_cached (domain, mono_defaults.runtimetype_class, len, error));
2964 goto_if_nok (error, fail);
2965 data.context = context;
2966 data.error = error;
2967 data.domain = domain;
2968 data.next_idx = 0;
2970 g_hash_table_foreach (iface_hash, fill_iface_array, &data);
2972 goto_if_nok (error, fail);
2974 g_hash_table_destroy (iface_hash);
2975 return data.iface_array;
2977 fail:
2978 g_hash_table_destroy (iface_hash);
2979 return NULL_HANDLE_ARRAY;
2982 static gboolean
2983 set_interface_map_data_method_object (MonoDomain *domain, MonoMethod *method, MonoClass *iclass, int ioffset, MonoClass *klass, MonoArrayHandle targets, MonoArrayHandle methods, int i, MonoError *error)
2985 HANDLE_FUNCTION_ENTER ();
2986 error_init (error);
2987 MonoReflectionMethodHandle member = mono_method_get_object_handle (domain, method, iclass, error);
2988 goto_if_nok (error, leave);
2990 MONO_HANDLE_ARRAY_SETREF (methods, i, member);
2992 MONO_HANDLE_ASSIGN (member, mono_method_get_object_handle (domain, m_class_get_vtable (klass) [i + ioffset], klass, error));
2993 goto_if_nok (error, leave);
2995 MONO_HANDLE_ARRAY_SETREF (targets, i, member);
2997 leave:
2998 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3001 void
3002 ves_icall_RuntimeType_GetInterfaceMapData (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_iface, MonoArrayHandleOut targets, MonoArrayHandleOut methods, MonoError *error)
3004 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3005 MonoClass *klass = mono_class_from_mono_type_internal (type);
3006 MonoType *iface = MONO_HANDLE_GETVAL (ref_iface, type);
3007 MonoClass *iclass = mono_class_from_mono_type_internal (iface);
3009 mono_class_init_checked (klass, error);
3010 return_if_nok (error);
3011 mono_class_init_checked (iclass, error);
3012 return_if_nok (error);
3014 mono_class_setup_vtable (klass);
3016 gboolean variance_used;
3017 int ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
3018 if (ioffset == -1)
3019 return;
3021 int len = mono_class_num_methods (iclass);
3022 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3023 MonoArrayHandle targets_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
3024 return_if_nok (error);
3025 MONO_HANDLE_ASSIGN (targets, targets_arr);
3027 MonoArrayHandle methods_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
3028 return_if_nok (error);
3029 MONO_HANDLE_ASSIGN (methods, methods_arr);
3031 MonoMethod* method;
3032 int i = 0;
3033 gpointer iter = NULL;
3034 while ((method = mono_class_get_methods (iclass, &iter))) {
3035 if (!set_interface_map_data_method_object (domain, method, iclass, ioffset, klass, targets, methods, i, error))
3036 return;
3037 i ++;
3041 void
3042 ves_icall_RuntimeType_GetPacking (MonoReflectionTypeHandle ref_type, guint32 *packing, guint32 *size, MonoError *error)
3044 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3045 MonoClass *klass = mono_class_from_mono_type_internal (type);
3047 mono_class_init_checked (klass, error);
3048 return_if_nok (error);
3050 if (image_is_dynamic (m_class_get_image (klass))) {
3051 MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, ref_type);
3052 *packing = MONO_HANDLE_GETVAL (tb, packing_size);
3053 *size = MONO_HANDLE_GETVAL (tb, class_size);
3054 } else {
3055 mono_metadata_packing_from_typedef (m_class_get_image (klass), m_class_get_type_token (klass), packing, size);
3059 MonoReflectionTypeHandle
3060 ves_icall_RuntimeTypeHandle_GetElementType (MonoReflectionTypeHandle ref_type, MonoError *error)
3062 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3063 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3065 if (!type->byref && type->type == MONO_TYPE_SZARRAY) {
3066 return mono_type_get_object_handle (domain, m_class_get_byval_arg (type->data.klass), error);
3069 MonoClass *klass = mono_class_from_mono_type_internal (type);
3070 mono_class_init_checked (klass, error);
3071 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
3073 // GetElementType should only return a type for:
3074 // Array Pointer PassedByRef
3075 if (type->byref)
3076 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
3077 else if (m_class_get_element_class (klass) && MONO_CLASS_IS_ARRAY (klass))
3078 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_element_class (klass)), error);
3079 else if (m_class_get_element_class (klass) && type->type == MONO_TYPE_PTR)
3080 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_element_class (klass)), error);
3081 else
3082 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3085 MonoReflectionTypeHandle
3086 ves_icall_RuntimeTypeHandle_GetBaseType (MonoReflectionTypeHandle ref_type, MonoError *error)
3088 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3089 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3091 if (type->byref)
3092 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3094 MonoClass *klass = mono_class_from_mono_type_internal (type);
3095 if (!m_class_get_parent (klass))
3096 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3098 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_parent (klass)), error);
3101 guint32
3102 ves_icall_RuntimeTypeHandle_GetCorElementType (MonoReflectionTypeHandle ref_type, MonoError *error)
3104 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3106 if (type->byref)
3107 return MONO_TYPE_BYREF;
3108 else
3109 return (guint32)type->type;
3112 MonoBoolean
3113 ves_icall_RuntimeTypeHandle_HasReferences (MonoReflectionTypeHandle ref_type, MonoError *error)
3115 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3116 MonoClass *klass;
3118 klass = mono_class_from_mono_type_internal (type);
3119 mono_class_init_internal (klass);
3120 return m_class_has_references (klass);
3123 MonoBoolean
3124 ves_icall_RuntimeTypeHandle_IsByRefLike (MonoReflectionTypeHandle ref_type, MonoError *error)
3126 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3127 /* .NET Core says byref types are not IsByRefLike */
3128 if (type->byref)
3129 return FALSE;
3130 MonoClass *klass = mono_class_from_mono_type_internal (type);
3131 return m_class_is_byreflike (klass);
3134 MonoBoolean
3135 ves_icall_RuntimeTypeHandle_IsComObject (MonoReflectionTypeHandle ref_type, MonoError *error)
3137 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3138 MonoClass *klass = mono_class_from_mono_type_internal (type);
3139 mono_class_init_checked (klass, error);
3140 return_val_if_nok (error, FALSE);
3142 return mono_class_is_com_object (klass);
3145 guint32
3146 ves_icall_reflection_get_token (MonoObjectHandle obj, MonoError *error)
3148 error_init (error);
3149 return mono_reflection_get_token_checked (obj, error);
3152 MonoReflectionModuleHandle
3153 ves_icall_RuntimeTypeHandle_GetModule (MonoReflectionTypeHandle type, MonoError *error)
3155 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
3156 MonoType *t = MONO_HANDLE_GETVAL (type, type);
3157 MonoClass *klass = mono_class_from_mono_type_internal (t);
3158 return mono_module_get_object_handle (domain, m_class_get_image (klass), error);
3161 MonoReflectionAssemblyHandle
3162 ves_icall_RuntimeTypeHandle_GetAssembly (MonoReflectionTypeHandle type, MonoError *error)
3164 MonoDomain *domain = mono_domain_get ();
3165 MonoType *t = MONO_HANDLE_GETVAL (type, type);
3166 MonoClass *klass = mono_class_from_mono_type_internal (t);
3167 return mono_assembly_get_object_handle (domain, m_class_get_image (klass)->assembly, error);
3170 MonoReflectionTypeHandle
3171 ves_icall_RuntimeType_get_DeclaringType (MonoReflectionTypeHandle ref_type, MonoError *error)
3173 MonoDomain *domain = mono_domain_get ();
3174 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3175 MonoClass *klass;
3177 if (type->byref)
3178 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3179 if (type->type == MONO_TYPE_VAR) {
3180 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
3181 klass = param ? param->owner.klass : NULL;
3182 } else if (type->type == MONO_TYPE_MVAR) {
3183 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
3184 klass = param ? param->owner.method->klass : NULL;
3185 } else {
3186 klass = m_class_get_nested_in (mono_class_from_mono_type_internal (type));
3189 if (!klass)
3190 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3192 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
3195 MonoStringHandle
3196 ves_icall_RuntimeType_get_Name (MonoReflectionTypeHandle reftype, MonoError *error)
3198 MonoDomain *domain = mono_domain_get ();
3199 MonoType *type = MONO_HANDLE_RAW(reftype)->type;
3200 MonoClass *klass = mono_class_from_mono_type_internal (type);
3201 // FIXME: this should be escaped in some scenarios with mono_identifier_escape_type_name_chars
3202 // Determining exactly when to do so is fairly difficult, so for now we don't bother to avoid regressions
3203 const char *klass_name = m_class_get_name (klass);
3205 if (type->byref) {
3206 char *n = g_strdup_printf ("%s&", klass_name);
3207 MonoStringHandle res = mono_string_new_handle (domain, n, error);
3209 g_free (n);
3211 return res;
3212 } else {
3213 return mono_string_new_handle (domain, klass_name, error);
3217 MonoStringHandle
3218 ves_icall_RuntimeType_get_Namespace (MonoReflectionTypeHandle type, MonoError *error)
3220 MonoDomain *domain = mono_domain_get ();
3221 MonoClass *klass = mono_class_from_mono_type_handle (type);
3223 MonoClass *klass_nested_in;
3224 while ((klass_nested_in = m_class_get_nested_in (klass)))
3225 klass = klass_nested_in;
3227 if (m_class_get_name_space (klass) [0] == '\0')
3228 return NULL_HANDLE_STRING;
3230 char *escaped = mono_identifier_escape_type_name_chars (m_class_get_name_space (klass));
3231 MonoStringHandle res = mono_string_new_handle (domain, escaped, error);
3232 g_free (escaped);
3233 return res;
3236 gint32
3237 ves_icall_RuntimeTypeHandle_GetArrayRank (MonoReflectionTypeHandle ref_type, MonoError *error)
3239 error_init (error);
3240 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3242 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
3243 mono_error_set_argument (error, "type", "Type must be an array type");
3244 return 0;
3247 MonoClass *klass = mono_class_from_mono_type_internal (type);
3249 return m_class_get_rank (klass);
3252 static MonoArrayHandle
3253 create_type_array (MonoDomain *domain, MonoBoolean runtimeTypeArray, int count, MonoError *error)
3255 return mono_array_new_handle (domain, runtimeTypeArray ? mono_defaults.runtimetype_class : mono_defaults.systemtype_class, count, error);
3258 static gboolean
3259 set_type_object_in_array (MonoDomain *domain, MonoType *type, MonoArrayHandle dest, int i, MonoError *error)
3261 HANDLE_FUNCTION_ENTER();
3262 error_init (error);
3263 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, type, error);
3264 goto_if_nok (error, leave);
3266 MONO_HANDLE_ARRAY_SETREF (dest, i, rt);
3268 leave:
3269 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3272 MonoArrayHandle
3273 ves_icall_RuntimeType_GetGenericArguments (MonoReflectionTypeHandle ref_type, MonoBoolean runtimeTypeArray, MonoError *error)
3275 error_init (error);
3276 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3278 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3279 MonoClass *klass = mono_class_from_mono_type_internal (type);
3281 MonoArrayHandle res = MONO_HANDLE_NEW (MonoArray, NULL);
3282 if (mono_class_is_gtd (klass)) {
3283 MonoGenericContainer *container = mono_class_get_generic_container (klass);
3284 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, container->type_argc, error));
3285 goto_if_nok (error, leave);
3286 for (int i = 0; i < container->type_argc; ++i) {
3287 MonoClass *pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
3289 if (!set_type_object_in_array (domain, m_class_get_byval_arg (pklass), res, i, error))
3290 goto leave;
3293 } else if (mono_class_is_ginst (klass)) {
3294 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
3295 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, inst->type_argc, error));
3296 goto_if_nok (error, leave);
3297 for (int i = 0; i < inst->type_argc; ++i) {
3298 if (!set_type_object_in_array (domain, inst->type_argv [i], res, i, error))
3299 goto leave;
3303 leave:
3304 return res;
3307 MonoBoolean
3308 ves_icall_RuntimeTypeHandle_IsGenericTypeDefinition (MonoReflectionTypeHandle ref_type, MonoError *error)
3310 error_init (error);
3312 if (!IS_MONOTYPE (MONO_HANDLE_RAW(ref_type)))
3313 return FALSE;
3315 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3316 if (type->byref)
3317 return FALSE;
3319 MonoClass *klass = mono_class_from_mono_type_internal (type);
3320 return mono_class_is_gtd (klass);
3323 MonoReflectionTypeHandle
3324 ves_icall_RuntimeTypeHandle_GetGenericTypeDefinition_impl (MonoReflectionTypeHandle ref_type, MonoError *error)
3326 error_init (error);
3327 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3329 MonoReflectionTypeHandle ret = MONO_HANDLE_NEW (MonoReflectionType, NULL);
3331 if (type->byref)
3332 goto leave;
3334 MonoClass *klass;
3335 klass = mono_class_from_mono_type_internal (type);
3337 if (mono_class_is_gtd (klass)) {
3338 /* check this one */
3339 MONO_HANDLE_ASSIGN (ret, ref_type);
3340 goto leave;
3342 if (mono_class_is_ginst (klass)) {
3343 MonoClass *generic_class = mono_class_get_generic_class (klass)->container_class;
3345 guint32 ref_info_handle = mono_class_get_ref_info_handle (generic_class);
3347 if (m_class_was_typebuilder (generic_class) && ref_info_handle) {
3348 MonoObjectHandle tb = mono_gchandle_get_target_handle (ref_info_handle);
3349 g_assert (!MONO_HANDLE_IS_NULL (tb));
3350 MONO_HANDLE_ASSIGN (ret, tb);
3351 } else {
3352 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3353 MONO_HANDLE_ASSIGN (ret, mono_type_get_object_handle (domain, m_class_get_byval_arg (generic_class), error));
3356 leave:
3357 return ret;
3360 MonoReflectionTypeHandle
3361 ves_icall_RuntimeType_MakeGenericType (MonoReflectionTypeHandle reftype, MonoArrayHandle type_array, MonoError *error)
3363 error_init (error);
3364 MonoDomain *domain = MONO_HANDLE_DOMAIN (reftype);
3366 g_assert (IS_MONOTYPE_HANDLE (reftype));
3367 MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
3368 mono_class_init_checked (mono_class_from_mono_type_internal (type), error);
3369 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
3371 int count = mono_array_handle_length (type_array);
3372 MonoType **types = g_new0 (MonoType *, count);
3374 MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
3375 for (int i = 0; i < count; i++) {
3376 MONO_HANDLE_ARRAY_GETREF (t, type_array, i);
3377 types [i] = MONO_HANDLE_GETVAL (t, type);
3380 MonoType *geninst = mono_reflection_bind_generic_parameters (reftype, count, types, error);
3381 g_free (types);
3382 if (!geninst) {
3383 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3386 MonoClass *klass = mono_class_from_mono_type_internal (geninst);
3388 /*we might inflate to the GTD*/
3389 if (mono_class_is_ginst (klass) && !mono_verifier_class_is_valid_generic_instantiation (klass)) {
3390 mono_error_set_argument (error, "typeArguments", "Invalid generic arguments");
3391 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3394 return mono_type_get_object_handle (domain, geninst, error);
3397 MonoBoolean
3398 ves_icall_RuntimeTypeHandle_HasInstantiation (MonoReflectionTypeHandle ref_type, MonoError *error)
3400 error_init (error);
3401 MonoClass *klass;
3403 if (!IS_MONOTYPE (MONO_HANDLE_RAW (ref_type)))
3404 return FALSE;
3406 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3407 if (type->byref)
3408 return FALSE;
3410 klass = mono_class_from_mono_type_internal (type);
3411 return mono_class_is_ginst (klass) || mono_class_is_gtd (klass);
3414 gint32
3415 ves_icall_RuntimeType_GetGenericParameterPosition (MonoReflectionTypeHandle ref_type, MonoError *error)
3417 error_init (error);
3418 if (!IS_MONOTYPE_HANDLE (ref_type))
3419 return -1;
3420 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3422 if (is_generic_parameter (type))
3423 return mono_type_get_generic_param_num (type);
3424 return -1;
3427 MonoGenericParamInfo *
3428 ves_icall_RuntimeTypeHandle_GetGenericParameterInfo (MonoReflectionTypeHandle ref_type, MonoError *error)
3430 error_init (error);
3431 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3432 return mono_generic_param_info (type->data.generic_param);
3435 MonoBoolean
3436 ves_icall_RuntimeTypeHandle_IsGenericVariable (MonoReflectionTypeHandle ref_type, MonoError *error)
3438 MonoType *type = MONO_HANDLE_GETVAL(ref_type, type);
3439 return is_generic_parameter (type);
3442 MonoReflectionMethodHandle
3443 ves_icall_RuntimeType_GetCorrespondingInflatedMethod (MonoReflectionTypeHandle ref_type,
3444 MonoReflectionMethodHandle generic,
3445 MonoError *error)
3447 error_init (error);
3448 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3449 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3450 MonoClass *klass = mono_class_from_mono_type_internal (type);
3452 mono_class_init_checked (klass, error);
3453 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3455 MonoMethod *generic_method = MONO_HANDLE_GETVAL (generic, method);
3457 MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3458 MonoMethod *method;
3459 gpointer iter = NULL;
3460 while ((method = mono_class_get_methods (klass, &iter))) {
3461 if (method->token == generic_method->token) {
3462 ret = mono_method_get_object_handle (domain, method, klass, error);
3463 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3467 return ret;
3470 MonoReflectionMethodHandle
3471 ves_icall_RuntimeType_get_DeclaringMethod (MonoReflectionTypeHandle ref_type, MonoError *error)
3473 error_init (error);
3474 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3475 MonoReflectionMethodHandle ret = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
3477 if (type->byref || (type->type != MONO_TYPE_MVAR && type->type != MONO_TYPE_VAR)) {
3478 mono_error_set_invalid_operation (error, "DeclaringMethod can only be used on generic arguments");
3479 goto leave;
3481 if (type->type == MONO_TYPE_VAR)
3482 goto leave;
3484 MonoMethod *method;
3485 method = mono_type_get_generic_param_owner (type)->owner.method;
3486 g_assert (method);
3488 MonoDomain *domain;
3489 domain = MONO_HANDLE_DOMAIN (ref_type);
3491 MONO_HANDLE_ASSIGN (ret, mono_method_get_object_handle (domain, method, method->klass, error));
3492 leave:
3493 return ret;
3496 #ifndef ENABLE_NETCORE
3497 MonoBoolean
3498 ves_icall_System_RuntimeType_IsTypeExportedToWindowsRuntime (MonoError *error)
3500 error_init (error);
3501 mono_error_set_not_implemented (error, "%s", "System.RuntimeType.IsTypeExportedToWindowsRuntime");
3502 return FALSE;
3505 MonoBoolean
3506 ves_icall_System_RuntimeType_IsWindowsRuntimeObjectType (MonoError *error)
3508 error_init (error);
3509 mono_error_set_not_implemented (error, "%s", "System.RuntimeType.IsWindowsRuntimeObjectType");
3510 return FALSE;
3512 #endif /* ENABLE_NETCORE */
3514 void
3515 ves_icall_RuntimeMethodInfo_GetPInvoke (MonoReflectionMethodHandle ref_method, int* flags, MonoStringHandleOut entry_point, MonoStringHandleOut dll_name, MonoError *error)
3517 MonoDomain *domain = mono_domain_get ();
3518 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3519 MonoImage *image = m_class_get_image (method->klass);
3520 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
3521 MonoTableInfo *tables = image->tables;
3522 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3523 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3524 guint32 im_cols [MONO_IMPLMAP_SIZE];
3525 guint32 scope_token;
3526 const char *import = NULL;
3527 const char *scope = NULL;
3529 error_init (error);
3531 if (image_is_dynamic (image)) {
3532 MonoReflectionMethodAux *method_aux =
3533 (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)image)->method_aux_hash, method);
3534 if (method_aux) {
3535 import = method_aux->dllentry;
3536 scope = method_aux->dll;
3539 if (!import || !scope) {
3540 mono_error_set_argument (error, "method", "System.Refleciton.Emit method with invalid pinvoke information");
3541 return;
3544 else {
3545 if (piinfo->implmap_idx) {
3546 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3548 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
3549 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
3550 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
3551 scope = mono_metadata_string_heap (image, scope_token);
3555 *flags = piinfo->piflags;
3556 MONO_HANDLE_ASSIGN (entry_point, mono_string_new_handle (domain, import, error));
3557 return_if_nok (error);
3558 MONO_HANDLE_ASSIGN (dll_name, mono_string_new_handle (domain, scope, error));
3561 MonoReflectionMethodHandle
3562 ves_icall_RuntimeMethodInfo_GetGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *error)
3564 error_init (error);
3565 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3567 if (method->is_generic)
3568 return ref_method;
3570 if (!method->is_inflated)
3571 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3573 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
3575 MonoMethod *result = imethod->declaring;
3576 /* Not a generic method. */
3577 if (!result->is_generic)
3578 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3580 if (image_is_dynamic (m_class_get_image (method->klass))) {
3581 MonoDynamicImage *image = (MonoDynamicImage*)m_class_get_image (method->klass);
3584 * FIXME: Why is this stuff needed at all ? Why can't the code below work for
3585 * the dynamic case as well ?
3587 mono_image_lock ((MonoImage*)image);
3588 MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, (MonoReflectionMethod*)mono_g_hash_table_lookup (image->generic_def_objects, imethod));
3589 mono_image_unlock ((MonoImage*)image);
3591 if (!MONO_HANDLE_IS_NULL (res))
3592 return res;
3595 if (imethod->context.class_inst) {
3596 MonoClass *klass = ((MonoMethod *) imethod)->klass;
3597 /*Generic methods gets the context of the GTD.*/
3598 if (mono_class_get_context (klass)) {
3599 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
3600 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3604 return mono_method_get_object_handle (MONO_HANDLE_DOMAIN (ref_method), result, NULL, error);
3607 #ifdef ENABLE_NETCORE
3608 static GENERATE_TRY_GET_CLASS_WITH_CACHE (stream, "System.IO", "Stream")
3609 static int io_stream_begin_read_slot = -1;
3610 static int io_stream_begin_write_slot = -1;
3611 static int io_stream_end_read_slot = -1;
3612 static int io_stream_end_write_slot = -1;
3613 static gboolean io_stream_slots_set = FALSE;
3615 static void
3616 init_io_stream_slots (void)
3618 MonoClass* klass = mono_class_try_get_stream_class ();
3619 mono_class_setup_vtable (klass);
3620 MonoMethod **klass_methods = m_class_get_methods (klass);
3621 if (!klass_methods) {
3622 mono_class_setup_methods (klass);
3623 klass_methods = m_class_get_methods (klass);
3625 int method_count = mono_class_get_method_count (klass);
3626 int methods_found = 0;
3627 for (int i = 0; i < method_count; i++) {
3628 // find slots for Begin(End)Read and Begin(End)Write
3629 MonoMethod* m = klass->methods [i];
3630 if (m->slot == -1)
3631 continue;
3633 if (!strcmp (m->name, "BeginRead")) {
3634 methods_found++;
3635 io_stream_begin_read_slot = m->slot;
3636 } else if (!strcmp (m->name, "BeginWrite")) {
3637 methods_found++;
3638 io_stream_begin_write_slot = m->slot;
3639 } else if (!strcmp (m->name, "EndRead")) {
3640 methods_found++;
3641 io_stream_end_read_slot = m->slot;
3642 } else if (!strcmp (m->name, "EndWrite")) {
3643 methods_found++;
3644 io_stream_end_write_slot = m->slot;
3647 g_assert (methods_found <= 4); // some of them can be linked out
3648 io_stream_slots_set = TRUE;
3651 MonoBoolean
3652 ves_icall_System_IO_Stream_HasOverriddenBeginEndRead (MonoObjectHandle stream, MonoError *error)
3654 MonoClass* curr_klass = MONO_HANDLE_GET_CLASS (stream);
3655 MonoClass* base_klass = mono_class_try_get_stream_class ();
3657 if (!io_stream_slots_set)
3658 init_io_stream_slots ();
3660 // slots can still be -1 and it means Linker removed the methods from the base class (Stream)
3661 // in this case we can safely assume the methods are not overridden
3662 // otherwise - check vtable
3663 gboolean begin_read_is_overriden = io_stream_begin_read_slot != -1 && curr_klass->vtable [io_stream_begin_read_slot]->klass != base_klass;
3664 gboolean end_read_is_overriden = io_stream_end_read_slot != -1 && curr_klass->vtable [io_stream_end_read_slot]->klass != base_klass;
3666 // return true if BeginRead or EndRead were overriden
3667 return begin_read_is_overriden || end_read_is_overriden;
3670 MonoBoolean
3671 ves_icall_System_IO_Stream_HasOverriddenBeginEndWrite (MonoObjectHandle stream, MonoError *error)
3673 MonoClass* curr_klass = MONO_HANDLE_GETVAL (stream, vtable)->klass;
3674 MonoClass* base_klass = mono_class_try_get_stream_class ();
3676 if (!io_stream_slots_set)
3677 init_io_stream_slots ();
3679 gboolean begin_write_is_overriden = curr_klass->vtable [io_stream_begin_write_slot]->klass != base_klass;
3680 gboolean end_write_is_overriden = curr_klass->vtable [io_stream_end_write_slot]->klass != base_klass;
3682 // return true if BeginWrite or EndWrite were overriden
3683 return begin_write_is_overriden || end_write_is_overriden;
3685 #endif
3687 MonoBoolean
3688 ves_icall_RuntimeMethodInfo_get_IsGenericMethod (MonoReflectionMethodHandle ref_method, MonoError *erro)
3690 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3691 return mono_method_signature_internal (method)->generic_param_count != 0;
3694 MonoBoolean
3695 ves_icall_RuntimeMethodInfo_get_IsGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *Error)
3697 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3698 return method->is_generic;
3701 static gboolean
3702 set_array_generic_argument_handle_inflated (MonoDomain *domain, MonoGenericInst *inst, int i, MonoArrayHandle arr, MonoError *error)
3704 HANDLE_FUNCTION_ENTER ();
3705 error_init (error);
3706 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, inst->type_argv [i], error);
3707 goto_if_nok (error, leave);
3708 MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3709 leave:
3710 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3713 static gboolean
3714 set_array_generic_argument_handle_gparam (MonoDomain *domain, MonoGenericContainer *container, int i, MonoArrayHandle arr, MonoError *error)
3716 HANDLE_FUNCTION_ENTER ();
3717 error_init (error);
3718 MonoGenericParam *param = mono_generic_container_get_param (container, i);
3719 MonoClass *pklass = mono_class_create_generic_parameter (param);
3720 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (pklass), error);
3721 goto_if_nok (error, leave);
3722 MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3723 leave:
3724 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3727 MonoArrayHandle
3728 ves_icall_RuntimeMethodInfo_GetGenericArguments (MonoReflectionMethodHandle ref_method, MonoError *error)
3730 error_init (error);
3731 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_method);
3732 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3734 if (method->is_inflated) {
3735 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
3737 if (inst) {
3738 int count = inst->type_argc;
3739 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3740 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3742 for (int i = 0; i < count; i++) {
3743 if (!set_array_generic_argument_handle_inflated (domain, inst, i, res, error))
3744 break;
3746 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3747 return res;
3751 int count = mono_method_signature_internal (method)->generic_param_count;
3752 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3753 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3755 MonoGenericContainer *container = mono_method_get_generic_container (method);
3756 for (int i = 0; i < count; i++) {
3757 if (!set_array_generic_argument_handle_gparam (domain, container, i, res, error))
3758 break;
3760 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3761 return res;
3764 MonoObjectHandle
3765 ves_icall_InternalInvoke (MonoReflectionMethodHandle method_handle, MonoObjectHandle this_arg_handle,
3766 MonoArrayHandle params_handle, MonoExceptionHandleOut exception_out, MonoError *error)
3768 MonoReflectionMethod* const method = MONO_HANDLE_RAW (method_handle);
3769 MonoObject* const this_arg = MONO_HANDLE_RAW (this_arg_handle);
3770 MonoArray* const params = MONO_HANDLE_RAW (params_handle);
3773 * Invoke from reflection is supposed to always be a virtual call (the API
3774 * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
3775 * greater flexibility.
3777 MonoMethod *m = method->method;
3778 MonoMethodSignature* const sig = mono_method_signature_internal (m);
3779 MonoImage *image = NULL;
3780 int pcount = 0;
3781 void *obj = this_arg;
3782 char *this_name = NULL;
3783 char *target_name = NULL;
3784 char *msg = NULL;
3785 MonoObject *result = NULL;
3786 MonoArray *arr = NULL;
3787 MonoException *exception = NULL;
3789 *MONO_HANDLE_REF (exception_out) = NULL;
3791 if (mono_security_core_clr_enabled () &&
3792 !mono_security_core_clr_ensure_reflection_access_method (m, error)) {
3793 goto return_null;
3796 if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
3797 if (!mono_class_vtable_checked (mono_object_domain (method), m->klass, error)) {
3798 mono_error_cleanup (error); /* FIXME does this make sense? */
3799 error_init_reuse (error);
3800 exception = mono_class_get_exception_for_failure (m->klass);
3801 goto return_null;
3804 if (this_arg) {
3805 if (!mono_object_isinst_checked (this_arg, m->klass, error)) {
3806 if (!is_ok (error)) {
3807 exception = mono_error_convert_to_exception (error);
3808 goto return_null;
3810 this_name = mono_type_get_full_name (mono_object_class (this_arg));
3811 target_name = mono_type_get_full_name (m->klass);
3812 msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
3813 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", msg);
3814 goto return_null;
3816 m = mono_object_get_virtual_method_internal (this_arg, m);
3817 /* must pass the pointer to the value for valuetype methods */
3818 if (m_class_is_valuetype (m->klass)) {
3819 obj = mono_object_unbox_internal (this_arg);
3820 // FIXMEcoop? Does obj need to be put into a handle?
3822 } else if (strcmp (m->name, ".ctor") && !m->wrapper_type) {
3823 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Non-static method requires a target.");
3824 goto return_null;
3828 if ((m->klass != NULL && m_class_is_byreflike (m->klass)) || m_class_is_byreflike (mono_class_from_mono_type_internal (sig->ret))) {
3829 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method with stack pointers via reflection");
3830 goto return_null;
3832 #if ENABLE_NETCORE
3833 if (sig->ret->byref) {
3834 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
3835 if (ret_byval->type == MONO_TYPE_VOID) {
3836 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "ByRef to void return values are not supported in reflection invocation");
3837 goto return_null;
3839 if (m_class_is_byreflike (mono_class_from_mono_type_internal (ret_byval))) {
3840 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method returning ByRef to ByRefLike type via reflection");
3841 goto return_null;
3844 #else
3845 if (sig->ret->byref) {
3846 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method returning ByRef type via reflection");
3847 goto return_null;
3849 #endif
3851 pcount = params? mono_array_length_internal (params): 0;
3852 if (pcount != sig->param_count) {
3853 exception = mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetParameterCountException");
3854 goto return_null;
3857 if (mono_class_is_abstract (m->klass) && !strcmp (m->name, ".ctor") && !this_arg) {
3858 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Cannot invoke constructor of an abstract class.");
3859 goto return_null;
3862 image = m_class_get_image (m->klass);
3863 if (mono_asmctx_get_kind (&image->assembly->context) == MONO_ASMCTX_REFONLY) {
3864 exception = mono_get_exception_invalid_operation ("It is illegal to invoke a method on a type loaded using the ReflectionOnly api.");
3865 goto return_null;
3868 if (image_is_dynamic (image) && !((MonoDynamicImage*)image)->run) {
3869 exception = mono_get_exception_not_supported ("Cannot invoke a method in a dynamic assembly without run access.");
3870 goto return_null;
3873 if (m_class_get_rank (m->klass) && !strcmp (m->name, ".ctor")) {
3874 int i;
3875 pcount = mono_array_length_internal (params);
3876 uintptr_t * const lengths = g_newa (uintptr_t, pcount);
3877 /* Note: the synthetized array .ctors have int32 as argument type */
3878 for (i = 0; i < pcount; ++i)
3879 lengths [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, i) + sizeof (MonoObject));
3881 if (m_class_get_rank (m->klass) == 1 && sig->param_count == 2 && m_class_get_rank (m_class_get_element_class (m->klass))) {
3882 /* This is a ctor for jagged arrays. MS creates an array of arrays. */
3883 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, error);
3884 goto_if_nok (error, return_null);
3886 MonoArrayHandle subarray_handle = MONO_HANDLE_NEW (MonoArray, NULL);
3888 for (i = 0; i < mono_array_length_internal (arr); ++i) {
3889 MonoArray *subarray = mono_array_new_full_checked (mono_object_domain (params), m_class_get_element_class (m->klass), &lengths [1], NULL, error);
3890 goto_if_nok (error, return_null);
3891 MONO_HANDLE_ASSIGN_RAW (subarray_handle, subarray); // FIXME? Overkill?
3892 mono_array_setref_fast (arr, i, subarray);
3894 goto exit;
3897 if (m_class_get_rank (m->klass) == pcount) {
3898 /* Only lengths provided. */
3899 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, error);
3900 goto_if_nok (error, return_null);
3901 goto exit;
3902 } else {
3903 g_assert (pcount == (m_class_get_rank (m->klass) * 2));
3904 /* The arguments are lower-bound-length pairs */
3905 intptr_t * const lower_bounds = (intptr_t *)g_alloca (sizeof (intptr_t) * pcount);
3907 for (i = 0; i < pcount / 2; ++i) {
3908 lower_bounds [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, (i * 2)) + sizeof (MonoObject));
3909 lengths [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, (i * 2) + 1) + sizeof (MonoObject));
3912 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, lower_bounds, error);
3913 goto_if_nok (error, return_null);
3914 goto exit;
3917 result = mono_runtime_invoke_array_checked (m, obj, params, error);
3918 goto exit;
3919 return_null:
3920 result = NULL;
3921 arr = NULL;
3922 exit:
3923 if (exception) {
3924 MONO_HANDLE_NEW (MonoException, exception); // FIXME? overkill?
3925 mono_gc_wbarrier_generic_store_internal (MONO_HANDLE_REF (exception_out), (MonoObject*)exception);
3927 g_free (target_name);
3928 g_free (this_name);
3929 g_free (msg);
3930 g_assert (!result || !arr); // only one, or neither, should be set
3931 return result ? MONO_HANDLE_NEW (MonoObject, result) : arr ? MONO_HANDLE_NEW (MonoObject, (MonoObject*)arr) : NULL_HANDLE;
3934 #ifndef DISABLE_REMOTING
3935 static void
3936 internal_execute_field_getter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArrayHandleOut outArgs, MonoError *error)
3938 MonoArray *out_args;
3939 MonoClass *k = mono_object_class (this_arg);
3940 MonoString *name;
3941 char *str;
3943 // FIXME Refactor/inline internal_execute_field_setter and internal_execute_field_getter.
3945 /* If this is a proxy, then it must be a CBO */
3946 if (mono_class_is_transparent_proxy (k)) {
3947 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
3948 this_arg = tp->rp->unwrapped_server;
3949 MONO_HANDLE_NEW (MonoObject, this_arg);
3950 g_assert (this_arg);
3951 k = mono_object_class (this_arg);
3954 name = mono_array_get_internal (params, MonoString *, 1);
3955 MONO_HANDLE_NEW (MonoString, name);
3957 str = mono_string_to_utf8_checked_internal (name, error);
3958 return_if_nok (error);
3960 do {
3961 MonoClassField* field = mono_class_get_field_from_name_full (k, str, NULL);
3962 if (field) {
3963 g_free (str);
3964 MonoClass *field_klass = mono_class_from_mono_type_internal (field->type);
3965 MonoObject *result;
3966 if (m_class_is_valuetype (field_klass)) {
3967 result = mono_value_box_checked (domain, field_klass, (char *)this_arg + field->offset, error);
3968 return_if_nok (error);
3969 } else
3970 result = (MonoObject *)*((gpointer *)((char *)this_arg + field->offset));
3972 MONO_HANDLE_NEW (MonoObject, result);
3974 out_args = mono_array_new_checked (domain, mono_defaults.object_class, 1, error);
3975 return_if_nok (error);
3976 MONO_HANDLE_NEW (MonoArray, out_args); // FIXME? overkill?
3977 mono_gc_wbarrier_generic_store_internal (MONO_HANDLE_REF (outArgs), (MonoObject*) out_args);
3978 mono_array_setref_internal (out_args, 0, result);
3979 return;
3981 k = m_class_get_parent (k);
3982 } while (k);
3984 g_free (str);
3985 g_assert_not_reached ();
3988 static void
3989 internal_execute_field_setter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArrayHandleOut outArgs, MonoError *error)
3991 MonoArray *out_args;
3992 MonoClass *k = mono_object_class (this_arg);
3993 MonoString *name;
3994 guint32 size;
3995 gint32 align;
3996 char *str;
3998 /* If this is a proxy, then it must be a CBO */
3999 if (mono_class_is_transparent_proxy (k)) {
4000 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
4001 this_arg = tp->rp->unwrapped_server;
4002 MONO_HANDLE_NEW (MonoObject, this_arg);
4003 g_assert (this_arg);
4004 k = mono_object_class (this_arg);
4007 name = mono_array_get_internal (params, MonoString *, 1);
4008 MONO_HANDLE_NEW (MonoString, name);
4010 str = mono_string_to_utf8_checked_internal (name, error);
4011 return_if_nok (error);
4013 do {
4014 MonoClassField* field = mono_class_get_field_from_name_full (k, str, NULL);
4015 if (field) {
4016 g_free (str);
4017 MonoClass *field_klass = mono_class_from_mono_type_internal (field->type);
4018 MonoObject *val = (MonoObject *)mono_array_get_internal (params, gpointer, 2);
4019 MONO_HANDLE_NEW (MonoObject, val);
4021 if (m_class_is_valuetype (field_klass)) {
4022 size = mono_type_size (field->type, &align);
4023 g_assert (size == mono_class_value_size (field_klass, NULL));
4024 mono_gc_wbarrier_value_copy_internal ((char *)this_arg + field->offset, (char*)val + sizeof (MonoObject), 1, field_klass);
4025 } else {
4026 mono_gc_wbarrier_set_field_internal (this_arg, (char*)this_arg + field->offset, val);
4029 out_args = mono_array_new_checked (domain, mono_defaults.object_class, 0, error);
4030 return_if_nok (error);
4031 MONO_HANDLE_NEW (MonoArray, out_args); // FIXME? overkill?
4032 mono_gc_wbarrier_generic_store_internal (MONO_HANDLE_REF (outArgs), (MonoObject*) out_args);
4033 return;
4036 k = m_class_get_parent (k);
4037 } while (k);
4039 g_free (str);
4040 g_assert_not_reached ();
4043 MonoObjectHandle
4044 ves_icall_InternalExecute (MonoReflectionMethodHandle method_handle, MonoObjectHandle this_arg_handle, MonoArrayHandle params_handle, MonoArrayHandleOut outArgs, MonoError* error)
4046 MONO_HANDLE_ASSIGN_RAW (outArgs, NULL);
4048 MonoReflectionMethod* const method = MONO_HANDLE_RAW (method_handle);
4049 MonoObject* const this_arg = MONO_HANDLE_RAW (this_arg_handle);
4050 MonoArray* const params = MONO_HANDLE_RAW (params_handle);
4051 MonoObjectHandle null_handle = NULL_HANDLE_INIT;
4053 MonoDomain *domain = mono_object_domain (method);
4054 MonoMethod *m = method->method;
4055 MonoMethodSignature *sig = mono_method_signature_internal (m);
4056 MonoArray *out_args;
4057 MonoObject *result;
4058 int i, j, outarg_count = 0;
4060 if (m->klass == mono_defaults.object_class) {
4062 if (!strcmp (m->name, "FieldGetter")) {
4063 internal_execute_field_getter (domain, this_arg, params, outArgs, error);
4064 return null_handle;
4065 } else if (!strcmp (m->name, "FieldSetter")) {
4066 internal_execute_field_setter (domain, this_arg, params, outArgs, error);
4067 return null_handle;
4071 for (i = 0; i < mono_array_length_internal (params); i++) {
4072 if (sig->params [i]->byref)
4073 outarg_count++;
4076 out_args = mono_array_new_checked (domain, mono_defaults.object_class, outarg_count, error);
4077 return_val_if_nok (error, null_handle);
4078 MONO_HANDLE_NEW (MonoArray, out_args);
4080 /* handle constructors only for objects already allocated */
4081 if (!strcmp (method->method->name, ".ctor"))
4082 g_assert (this_arg);
4084 /* This can be called only on MBR objects, so no need to unbox for valuetypes. */
4085 g_assert (!m_class_is_valuetype (method->method->klass));
4086 result = mono_runtime_invoke_array_checked (method->method, this_arg, params, error);
4087 return_val_if_nok (error, null_handle);
4089 MonoObjectHandle result_handle = MONO_HANDLE_NEW (MonoObject, result);
4090 MonoObjectHandle arg_handle = MONO_HANDLE_NEW (MonoObject, NULL);
4092 for (i = 0, j = 0; i < mono_array_length_internal (params); i++) {
4093 if (sig->params [i]->byref) {
4094 gpointer arg;
4095 arg = mono_array_get_internal (params, gpointer, i);
4096 MONO_HANDLE_ASSIGN_RAW (arg_handle, arg); // FIXME? overkill?
4097 mono_array_setref_internal (out_args, j, arg);
4098 j++;
4102 mono_gc_wbarrier_generic_store_internal (MONO_HANDLE_REF (outArgs), (MonoObject*)out_args);
4104 return result_handle;
4106 #endif
4108 static guint64
4109 read_enum_value (const char *mem, int type)
4111 switch (type) {
4112 case MONO_TYPE_BOOLEAN:
4113 case MONO_TYPE_U1:
4114 return *(guint8*)mem;
4115 case MONO_TYPE_I1:
4116 return *(gint8*)mem;
4117 case MONO_TYPE_CHAR:
4118 case MONO_TYPE_U2:
4119 return read16 (mem);
4120 case MONO_TYPE_I2:
4121 return (gint16) read16 (mem);
4122 case MONO_TYPE_U4:
4123 case MONO_TYPE_R4:
4124 return read32 (mem);
4125 case MONO_TYPE_I4:
4126 return (gint32) read32 (mem);
4127 case MONO_TYPE_U8:
4128 case MONO_TYPE_I8:
4129 case MONO_TYPE_R8:
4130 return read64 (mem);
4131 case MONO_TYPE_U:
4132 case MONO_TYPE_I:
4133 #if SIZEOF_REGISTER == 8
4134 return read64 (mem);
4135 #else
4136 return read32 (mem);
4137 #endif
4138 default:
4139 g_assert_not_reached ();
4141 return 0;
4144 static void
4145 write_enum_value (void *mem, int type, guint64 value)
4147 switch (type) {
4148 case MONO_TYPE_U1:
4149 case MONO_TYPE_I1:
4150 case MONO_TYPE_BOOLEAN: {
4151 guint8 *p = (guint8*)mem;
4152 *p = value;
4153 break;
4155 case MONO_TYPE_U2:
4156 case MONO_TYPE_I2:
4157 case MONO_TYPE_CHAR: {
4158 guint16 *p = (guint16 *)mem;
4159 *p = value;
4160 break;
4162 case MONO_TYPE_U4:
4163 case MONO_TYPE_I4:
4164 case MONO_TYPE_R4: {
4165 guint32 *p = (guint32 *)mem;
4166 *p = value;
4167 break;
4169 case MONO_TYPE_U8:
4170 case MONO_TYPE_I8:
4171 case MONO_TYPE_R8: {
4172 guint64 *p = (guint64 *)mem;
4173 *p = value;
4174 break;
4176 case MONO_TYPE_U:
4177 case MONO_TYPE_I: {
4178 #if SIZEOF_REGISTER == 8
4179 guint64 *p = (guint64 *)mem;
4180 *p = value;
4181 #else
4182 guint32 *p = (guint32 *)mem;
4183 *p = value;
4184 break;
4185 #endif
4186 break;
4188 default:
4189 g_assert_not_reached ();
4191 return;
4194 MonoObjectHandle
4195 ves_icall_System_Enum_ToObject (MonoReflectionTypeHandle enumType, guint64 value, MonoError *error)
4197 MonoDomain *domain;
4198 MonoClass *enumc;
4199 MonoObjectHandle resultHandle;
4200 MonoType *etype;
4202 domain = MONO_HANDLE_DOMAIN (enumType);
4203 enumc = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (enumType, type));
4205 mono_class_init_checked (enumc, error);
4206 goto_if_nok (error, return_null);
4208 etype = mono_class_enum_basetype_internal (enumc);
4210 resultHandle = mono_object_new_handle (domain, enumc, error);
4211 goto_if_nok (error, return_null);
4213 write_enum_value (mono_handle_unbox_unsafe (resultHandle), etype->type, value);
4215 return resultHandle;
4217 return_null:
4218 return MONO_HANDLE_NEW (MonoObject, NULL);
4221 MonoBoolean
4222 ves_icall_System_Enum_InternalHasFlag (MonoObjectHandle a, MonoObjectHandle b, MonoError *error)
4224 int size = mono_class_value_size (mono_handle_class (a), NULL);
4225 guint64 a_val = 0, b_val = 0;
4227 memcpy (&a_val, mono_handle_unbox_unsafe (a), size);
4228 memcpy (&b_val, mono_handle_unbox_unsafe (b), size);
4230 return (a_val & b_val) == b_val;
4233 #ifndef ENABLE_NETCORE
4234 MonoObjectHandle
4235 ves_icall_System_Enum_get_value (MonoObjectHandle ehandle, MonoError *error)
4237 MonoObjectHandle resultHandle;
4238 MonoClass *enumc;
4239 int size;
4241 goto_if (MONO_HANDLE_IS_NULL (ehandle), return_null);
4243 g_assert (m_class_is_enumtype (mono_handle_class (ehandle)));
4245 enumc = mono_class_from_mono_type_internal (mono_class_enum_basetype_internal (mono_handle_class (ehandle)));
4247 resultHandle = mono_object_new_handle (MONO_HANDLE_DOMAIN (ehandle), enumc, error);
4248 goto_if_nok (error, return_null);
4249 size = mono_class_value_size (enumc, NULL);
4251 memcpy (mono_handle_unbox_unsafe (resultHandle), mono_handle_unbox_unsafe (ehandle), size);
4253 return resultHandle;
4254 return_null:
4255 return MONO_HANDLE_NEW (MonoObject, NULL);
4257 #endif
4259 MonoReflectionTypeHandle
4260 ves_icall_System_Enum_get_underlying_type (MonoReflectionTypeHandle type, MonoError *error)
4262 MonoType *etype;
4263 MonoClass *klass;
4265 klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
4266 mono_class_init_checked (klass, error);
4267 goto_if_nok (error, return_null);
4269 etype = mono_class_enum_basetype_internal (klass);
4270 if (!etype) {
4271 mono_error_set_argument (error, "enumType", "Type provided must be an Enum.");
4272 goto return_null;
4275 return mono_type_get_object_handle (MONO_HANDLE_DOMAIN (type), etype, error);
4277 return_null:
4278 return MONO_HANDLE_NEW (MonoReflectionType, NULL);
4282 ves_icall_System_Enum_InternalGetCorElementType (MonoObjectHandle this_handle, MonoError *error)
4284 MonoClass *klass = MONO_HANDLE_GETVAL (this_handle, vtable)->klass;
4286 return (int)m_class_get_byval_arg (m_class_get_element_class (klass))->type;
4289 #ifndef ENABLE_NETCORE
4291 ves_icall_System_Enum_compare_value_to (MonoObjectHandle enumHandle, MonoObjectHandle otherHandle, MonoError *error)
4293 if (MONO_HANDLE_IS_NULL (otherHandle))
4294 return 1;
4296 if (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass != MONO_HANDLE_GETVAL (otherHandle, vtable)->klass)
4297 return 2;
4299 gpointer tdata = mono_handle_unbox_unsafe (enumHandle);
4300 gpointer odata = mono_handle_unbox_unsafe (otherHandle);
4301 MonoType *basetype = mono_class_enum_basetype_internal (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass);
4302 g_assert (basetype);
4304 #define COMPARE_ENUM_VALUES(ENUM_TYPE) do { \
4305 ENUM_TYPE me = *((ENUM_TYPE*)tdata); \
4306 ENUM_TYPE other = *((ENUM_TYPE*)odata); \
4307 if (me == other) \
4308 return 0; \
4309 return me > other ? 1 : -1; \
4310 } while (0)
4312 switch (basetype->type) {
4313 case MONO_TYPE_BOOLEAN:
4314 case MONO_TYPE_U1:
4315 COMPARE_ENUM_VALUES (guint8);
4316 case MONO_TYPE_I1:
4317 COMPARE_ENUM_VALUES (gint8);
4318 case MONO_TYPE_CHAR:
4319 case MONO_TYPE_U2:
4320 COMPARE_ENUM_VALUES (guint16);
4321 case MONO_TYPE_I2:
4322 COMPARE_ENUM_VALUES (gint16);
4323 case MONO_TYPE_U4:
4324 COMPARE_ENUM_VALUES (guint32);
4325 case MONO_TYPE_I4:
4326 COMPARE_ENUM_VALUES (gint32);
4327 case MONO_TYPE_R4:
4328 COMPARE_ENUM_VALUES (gfloat);
4329 case MONO_TYPE_U8:
4330 COMPARE_ENUM_VALUES (guint64);
4331 case MONO_TYPE_I8:
4332 COMPARE_ENUM_VALUES (gint64);
4333 case MONO_TYPE_R8:
4334 COMPARE_ENUM_VALUES (gdouble);
4335 case MONO_TYPE_U:
4336 #if SIZEOF_REGISTER == 8
4337 COMPARE_ENUM_VALUES (guint64);
4338 #else
4339 COMPARE_ENUM_VALUES (guint32);
4340 #endif
4341 case MONO_TYPE_I:
4342 #if SIZEOF_REGISTER == 8
4343 COMPARE_ENUM_VALUES (gint64);
4344 #else
4345 COMPARE_ENUM_VALUES (gint32);
4346 #endif
4347 default:
4348 break;
4350 #undef COMPARE_ENUM_VALUES
4351 /* indicates that the enum was of an unsupported underlying type */
4352 return 3;
4354 #endif
4356 #ifndef ENABLE_NETCORE
4358 ves_icall_System_Enum_get_hashcode (MonoObjectHandle enumHandle, MonoError *error)
4360 gpointer data = mono_handle_unbox_unsafe (enumHandle);
4361 MonoType *basetype = mono_class_enum_basetype_internal (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass);
4362 g_assert (basetype);
4364 switch (basetype->type) {
4365 case MONO_TYPE_I1: {
4366 gint8 value = *((gint8*)data);
4367 return ((int)value ^ (int)value << 8);
4369 case MONO_TYPE_U1:
4370 return *((guint8*)data);
4371 case MONO_TYPE_CHAR:
4372 case MONO_TYPE_U2:
4373 return *((guint16*)data);
4375 case MONO_TYPE_I2: {
4376 gint16 value = *((gint16*)data);
4377 return ((int)(guint16)value | (((int)value) << 16));
4379 case MONO_TYPE_U4:
4380 case MONO_TYPE_R4:
4381 return *((guint32*)data);
4382 case MONO_TYPE_I4:
4383 return *((gint32*)data);
4384 case MONO_TYPE_U8:
4385 case MONO_TYPE_I8:
4386 case MONO_TYPE_R8: {
4387 gint64 value = *((gint64*)data);
4388 return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
4390 case MONO_TYPE_I:
4391 case MONO_TYPE_U: {
4392 #if SIZEOF_REGISTER == 8
4393 gint64 value = *((gint64*)data);
4394 return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
4395 #else
4396 return *((guint32*)data);
4397 #endif
4399 default:
4400 g_error ("Implement type 0x%02x in get_hashcode", basetype->type);
4402 return 0;
4404 #endif
4406 static void
4407 get_enum_field (MonoDomain *domain, MonoArrayHandle names, MonoArrayHandle values, int base_type, MonoClassField *field, guint* j, guint64 *previous_value, gboolean *sorted, MonoError *error)
4409 error_init (error);
4410 HANDLE_FUNCTION_ENTER();
4411 guint64 field_value;
4412 const char *p;
4413 MonoTypeEnum def_type;
4415 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
4416 goto leave;
4417 if (strcmp ("value__", mono_field_get_name (field)) == 0)
4418 goto leave;
4419 if (mono_field_is_deleted (field))
4420 goto leave;
4421 MonoStringHandle name;
4422 name = mono_string_new_handle (domain, mono_field_get_name (field), error);
4423 goto_if_nok (error, leave);
4424 MONO_HANDLE_ARRAY_SETREF (names, *j, name);
4426 p = mono_class_get_field_default_value (field, &def_type);
4427 /* len = */ mono_metadata_decode_blob_size (p, &p);
4429 field_value = read_enum_value (p, base_type);
4430 MONO_HANDLE_ARRAY_SETVAL (values, guint64, *j, field_value);
4432 if (*previous_value > field_value)
4433 *sorted = FALSE;
4435 *previous_value = field_value;
4436 (*j)++;
4437 leave:
4438 HANDLE_FUNCTION_RETURN();
4441 MonoBoolean
4442 ves_icall_System_Enum_GetEnumValuesAndNames (MonoReflectionTypeHandle type, MonoArrayHandleOut values, MonoArrayHandleOut names, MonoError *error)
4444 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
4445 MonoClass *enumc = mono_class_from_mono_type_internal (MONO_HANDLE_RAW(type)->type);
4446 guint j = 0, nvalues;
4447 gpointer iter;
4448 MonoClassField *field;
4449 int base_type;
4450 guint64 previous_value = 0;
4451 gboolean sorted = TRUE;
4453 error_init (error);
4454 mono_class_init_checked (enumc, error);
4455 return_val_if_nok (error, FALSE);
4457 if (!m_class_is_enumtype (enumc)) {
4458 #if ENABLE_NETCORE
4459 mono_error_set_argument (error, NULL, "Type provided must be an Enum.");
4460 #else
4461 mono_error_set_argument (error, "enumType", "Type provided must be an Enum.");
4462 #endif
4463 return TRUE;
4466 base_type = mono_class_enum_basetype_internal (enumc)->type;
4468 nvalues = mono_class_num_fields (enumc) > 0 ? mono_class_num_fields (enumc) - 1 : 0;
4469 MONO_HANDLE_ASSIGN(names, mono_array_new_handle (domain, mono_defaults.string_class, nvalues, error));
4470 return_val_if_nok (error, FALSE);
4471 MONO_HANDLE_ASSIGN(values, mono_array_new_handle (domain, mono_defaults.uint64_class, nvalues, error));
4472 return_val_if_nok (error, FALSE);
4474 iter = NULL;
4475 while ((field = mono_class_get_fields_internal (enumc, &iter))) {
4476 get_enum_field(domain, names, values, base_type, field, &j, &previous_value, &sorted, error);
4477 if (!is_ok (error))
4478 break;
4480 return_val_if_nok (error, FALSE);
4482 return sorted || base_type == MONO_TYPE_R4 || base_type == MONO_TYPE_R8;
4485 enum {
4486 BFLAGS_IgnoreCase = 1,
4487 BFLAGS_DeclaredOnly = 2,
4488 BFLAGS_Instance = 4,
4489 BFLAGS_Static = 8,
4490 BFLAGS_Public = 0x10,
4491 BFLAGS_NonPublic = 0x20,
4492 BFLAGS_FlattenHierarchy = 0x40,
4493 BFLAGS_InvokeMethod = 0x100,
4494 BFLAGS_CreateInstance = 0x200,
4495 BFLAGS_GetField = 0x400,
4496 BFLAGS_SetField = 0x800,
4497 BFLAGS_GetProperty = 0x1000,
4498 BFLAGS_SetProperty = 0x2000,
4499 BFLAGS_ExactBinding = 0x10000,
4500 BFLAGS_SuppressChangeType = 0x20000,
4501 BFLAGS_OptionalParamBinding = 0x40000
4504 enum {
4505 MLISTTYPE_All = 0,
4506 MLISTTYPE_CaseSensitive = 1,
4507 MLISTTYPE_CaseInsensitive = 2,
4508 MLISTTYPE_HandleToInfo = 3
4511 GPtrArray*
4512 ves_icall_RuntimeType_GetFields_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 bflags, guint32 mlisttype, MonoError *error)
4514 error_init (error);
4515 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4517 if (type->byref) {
4518 return g_ptr_array_new ();
4521 int (*compare_func) (const char *s1, const char *s2) = NULL;
4522 compare_func = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
4524 MonoClass *startklass, *klass;
4525 klass = startklass = mono_class_from_mono_type_internal (type);
4527 GPtrArray *ptr_array = g_ptr_array_sized_new (16);
4529 handle_parent:
4530 if (mono_class_has_failure (klass)) {
4531 mono_error_set_for_class_failure (error, klass);
4532 goto fail;
4535 MonoClassField *field;
4536 gpointer iter;
4537 iter = NULL;
4538 while ((field = mono_class_get_fields_lazy (klass, &iter))) {
4539 guint32 flags = mono_field_get_flags (field);
4540 int match = 0;
4541 if (mono_field_is_deleted_with_flags (field, flags))
4542 continue;
4543 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
4544 if (bflags & BFLAGS_Public)
4545 match++;
4546 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
4547 if (bflags & BFLAGS_NonPublic) {
4548 match++;
4551 if (!match)
4552 continue;
4553 match = 0;
4554 if (flags & FIELD_ATTRIBUTE_STATIC) {
4555 if (bflags & BFLAGS_Static)
4556 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4557 match++;
4558 } else {
4559 if (bflags & BFLAGS_Instance)
4560 match++;
4563 if (!match)
4564 continue;
4566 if (((mlisttype != MLISTTYPE_All) && (utf8_name != NULL)) && compare_func (mono_field_get_name (field), utf8_name))
4567 continue;
4569 g_ptr_array_add (ptr_array, field);
4571 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
4572 goto handle_parent;
4574 return ptr_array;
4576 fail:
4577 g_ptr_array_free (ptr_array, TRUE);
4578 return NULL;
4581 static gboolean
4582 method_nonpublic (MonoMethod* method, gboolean start_klass)
4584 switch (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) {
4585 case METHOD_ATTRIBUTE_ASSEM:
4586 return (start_klass || mono_defaults.generic_ilist_class);
4587 case METHOD_ATTRIBUTE_PRIVATE:
4588 return start_klass;
4589 case METHOD_ATTRIBUTE_PUBLIC:
4590 return FALSE;
4591 default:
4592 return TRUE;
4596 GPtrArray*
4597 mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, guint32 mlisttype, gboolean allow_ctors, MonoError *error)
4599 GPtrArray *array;
4600 MonoClass *startklass;
4601 MonoMethod *method;
4602 gpointer iter;
4603 int match, nslots;
4604 /*FIXME, use MonoBitSet*/
4605 guint32 method_slots_default [8];
4606 guint32 *method_slots = NULL;
4607 int (*compare_func) (const char *s1, const char *s2) = NULL;
4609 array = g_ptr_array_new ();
4610 startklass = klass;
4611 error_init (error);
4613 compare_func = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
4615 /* An optimization for calls made from Delegate:CreateDelegate () */
4616 if (m_class_is_delegate (klass) && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && name && !strcmp (name, "Invoke") && (bflags == (BFLAGS_Public | BFLAGS_Static | BFLAGS_Instance))) {
4617 method = mono_get_delegate_invoke_internal (klass);
4618 g_assert (method);
4620 g_ptr_array_add (array, method);
4621 return array;
4624 mono_class_setup_methods (klass);
4625 mono_class_setup_vtable (klass);
4626 if (mono_class_has_failure (klass))
4627 goto loader_error;
4629 if (is_generic_parameter (m_class_get_byval_arg (klass)))
4630 nslots = mono_class_get_vtable_size (m_class_get_parent (klass));
4631 else
4632 nslots = MONO_CLASS_IS_INTERFACE_INTERNAL (klass) ? mono_class_num_methods (klass) : mono_class_get_vtable_size (klass);
4633 if (nslots >= sizeof (method_slots_default) * 8) {
4634 method_slots = g_new0 (guint32, nslots / 32 + 1);
4635 } else {
4636 method_slots = method_slots_default;
4637 memset (method_slots, 0, sizeof (method_slots_default));
4639 handle_parent:
4640 mono_class_setup_methods (klass);
4641 mono_class_setup_vtable (klass);
4642 if (mono_class_has_failure (klass))
4643 goto loader_error;
4645 iter = NULL;
4646 while ((method = mono_class_get_methods (klass, &iter))) {
4647 match = 0;
4648 if (method->slot != -1) {
4649 g_assert (method->slot < nslots);
4650 if (method_slots [method->slot >> 5] & (1 << (method->slot & 0x1f)))
4651 continue;
4652 if (!(method->flags & METHOD_ATTRIBUTE_NEW_SLOT))
4653 method_slots [method->slot >> 5] |= 1 << (method->slot & 0x1f);
4656 if (!allow_ctors && method->name [0] == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0))
4657 continue;
4658 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4659 if (bflags & BFLAGS_Public)
4660 match++;
4661 } else if ((bflags & BFLAGS_NonPublic) && method_nonpublic (method, (klass == startklass))) {
4662 match++;
4664 if (!match)
4665 continue;
4666 match = 0;
4667 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4668 if (bflags & BFLAGS_Static)
4669 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4670 match++;
4671 } else {
4672 if (bflags & BFLAGS_Instance)
4673 match++;
4676 if (!match)
4677 continue;
4679 if ((mlisttype != MLISTTYPE_All) && (name != NULL)) {
4680 if (compare_func (name, method->name))
4681 continue;
4684 match = 0;
4685 g_ptr_array_add (array, method);
4687 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
4688 goto handle_parent;
4689 if (method_slots != method_slots_default)
4690 g_free (method_slots);
4692 return array;
4694 loader_error:
4695 if (method_slots != method_slots_default)
4696 g_free (method_slots);
4697 g_ptr_array_free (array, TRUE);
4699 g_assert (mono_class_has_failure (klass));
4700 mono_error_set_for_class_failure (error, klass);
4701 return NULL;
4704 GPtrArray*
4705 ves_icall_RuntimeType_GetMethodsByName_native (MonoReflectionTypeHandle ref_type, const char *mname, guint32 bflags, guint32 mlisttype, MonoError *error)
4707 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4709 MonoClass *klass = mono_class_from_mono_type_internal (type);
4710 if (type->byref) {
4711 return g_ptr_array_new ();
4714 return mono_class_get_methods_by_name (klass, mname, bflags, mlisttype, FALSE, error);
4717 GPtrArray*
4718 ves_icall_RuntimeType_GetConstructors_native (MonoReflectionTypeHandle ref_type, guint32 bflags, MonoError *error)
4720 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4721 if (type->byref) {
4722 return g_ptr_array_new ();
4725 MonoClass *startklass, *klass;
4726 klass = startklass = mono_class_from_mono_type_internal (type);
4728 mono_class_setup_methods (klass);
4729 if (mono_class_has_failure (klass)) {
4730 mono_error_set_for_class_failure (error, klass);
4731 return NULL;
4735 GPtrArray *res_array = g_ptr_array_sized_new (4); /* FIXME, guestimating */
4737 MonoMethod *method;
4738 gpointer iter = NULL;
4739 while ((method = mono_class_get_methods (klass, &iter))) {
4740 int match = 0;
4741 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
4742 continue;
4743 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4744 if (bflags & BFLAGS_Public)
4745 match++;
4746 } else {
4747 if (bflags & BFLAGS_NonPublic)
4748 match++;
4750 if (!match)
4751 continue;
4752 match = 0;
4753 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4754 if (bflags & BFLAGS_Static)
4755 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4756 match++;
4757 } else {
4758 if (bflags & BFLAGS_Instance)
4759 match++;
4762 if (!match)
4763 continue;
4764 g_ptr_array_add (res_array, method);
4767 return res_array;
4770 static guint
4771 property_hash (gconstpointer data)
4773 MonoProperty *prop = (MonoProperty*)data;
4775 return g_str_hash (prop->name);
4778 static gboolean
4779 property_accessor_override (MonoMethod *method1, MonoMethod *method2)
4781 if (method1->slot != -1 && method1->slot == method2->slot)
4782 return TRUE;
4784 if (mono_class_get_generic_type_definition (method1->klass) == mono_class_get_generic_type_definition (method2->klass)) {
4785 if (method1->is_inflated)
4786 method1 = ((MonoMethodInflated*) method1)->declaring;
4787 if (method2->is_inflated)
4788 method2 = ((MonoMethodInflated*) method2)->declaring;
4791 return mono_metadata_signature_equal (mono_method_signature_internal (method1), mono_method_signature_internal (method2));
4794 static gboolean
4795 property_equal (MonoProperty *prop1, MonoProperty *prop2)
4797 // Properties are hide-by-name-and-signature
4798 if (!g_str_equal (prop1->name, prop2->name))
4799 return FALSE;
4801 /* If we see a property in a generic method, we want to
4802 compare the generic signatures, not the inflated signatures
4803 because we might conflate two properties that were
4804 distinct:
4806 class Foo<T,U> {
4807 public T this[T t] { getter { return t; } } // method 1
4808 public U this[U u] { getter { return u; } } // method 2
4811 If we see int Foo<int,int>::Item[int] we need to know if
4812 the indexer came from method 1 or from method 2, and we
4813 shouldn't conflate them. (Bugzilla 36283)
4815 if (prop1->get && prop2->get && !property_accessor_override (prop1->get, prop2->get))
4816 return FALSE;
4818 if (prop1->set && prop2->set && !property_accessor_override (prop1->set, prop2->set))
4819 return FALSE;
4821 return TRUE;
4824 static gboolean
4825 property_accessor_nonpublic (MonoMethod* accessor, gboolean start_klass)
4827 if (!accessor)
4828 return FALSE;
4830 return method_nonpublic (accessor, start_klass);
4833 GPtrArray*
4834 ves_icall_RuntimeType_GetPropertiesByName_native (MonoReflectionTypeHandle ref_type, gchar *propname, guint32 bflags, guint32 mlisttype, MonoError *error)
4836 #if ENABLE_NETCORE
4837 // Fetch non-public properties as well because they can hide public properties with the same name in base classes
4838 bflags |= BFLAGS_NonPublic;
4839 #endif
4840 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4842 if (type->byref) {
4843 return g_ptr_array_new ();
4847 MonoClass *startklass, *klass;
4848 klass = startklass = mono_class_from_mono_type_internal (type);
4850 int (*compare_func) (const char *s1, const char *s2) = (mlisttype == MLISTTYPE_CaseInsensitive) ? mono_utf8_strcasecmp : strcmp;
4852 GPtrArray *res_array = g_ptr_array_sized_new (8); /*This the average for ASP.NET types*/
4854 GHashTable *properties = g_hash_table_new (property_hash, (GEqualFunc)property_equal);
4856 handle_parent:
4857 mono_class_setup_methods (klass);
4858 mono_class_setup_vtable (klass);
4859 if (mono_class_has_failure (klass)) {
4860 mono_error_set_for_class_failure (error, klass);
4861 goto loader_error;
4864 MonoProperty *prop;
4865 gpointer iter;
4866 iter = NULL;
4867 while ((prop = mono_class_get_properties (klass, &iter))) {
4868 int match = 0;
4869 MonoMethod *method = prop->get;
4870 if (!method)
4871 method = prop->set;
4872 guint32 flags = 0;
4873 if (method)
4874 flags = method->flags;
4876 if ((prop->get && ((prop->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)) ||
4877 (prop->set && ((prop->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC))) {
4878 if (bflags & BFLAGS_Public)
4879 match++;
4880 } else if (bflags & BFLAGS_NonPublic) {
4881 if (property_accessor_nonpublic(prop->get, startklass == klass) ||
4882 property_accessor_nonpublic(prop->set, startklass == klass)) {
4883 match++;
4886 if (!match)
4887 continue;
4889 match = 0;
4890 if (flags & METHOD_ATTRIBUTE_STATIC) {
4891 if (bflags & BFLAGS_Static)
4892 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4893 match++;
4894 } else {
4895 if (bflags & BFLAGS_Instance)
4896 match++;
4899 if (!match)
4900 continue;
4901 match = 0;
4903 if ((mlisttype != MLISTTYPE_All) && (propname != NULL) && compare_func (propname, prop->name))
4904 continue;
4906 if (g_hash_table_lookup (properties, prop))
4907 continue;
4909 g_ptr_array_add (res_array, prop);
4911 g_hash_table_insert (properties, prop, prop);
4913 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass))) {
4914 #if ENABLE_NETCORE
4915 // BFLAGS_NonPublic should be excluded for base classes
4916 bflags &= ~BFLAGS_NonPublic;
4917 #endif
4918 goto handle_parent;
4921 g_hash_table_destroy (properties);
4923 return res_array;
4926 loader_error:
4927 if (properties)
4928 g_hash_table_destroy (properties);
4929 g_ptr_array_free (res_array, TRUE);
4931 return NULL;
4934 static guint
4935 event_hash (gconstpointer data)
4937 MonoEvent *event = (MonoEvent*)data;
4939 return g_str_hash (event->name);
4942 static gboolean
4943 event_equal (MonoEvent *event1, MonoEvent *event2)
4945 // Events are hide-by-name
4946 return g_str_equal (event1->name, event2->name);
4949 GPtrArray*
4950 ves_icall_RuntimeType_GetEvents_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 mlisttype, MonoError *error)
4952 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4954 if (type->byref) {
4955 return g_ptr_array_new ();
4958 int (*compare_func) (const char *s1, const char *s2) = (mlisttype == MLISTTYPE_CaseInsensitive) ? mono_utf8_strcasecmp : strcmp;
4960 GPtrArray *res_array = g_ptr_array_sized_new (4);
4962 MonoClass *startklass, *klass;
4963 klass = startklass = mono_class_from_mono_type_internal (type);
4965 GHashTable *events = g_hash_table_new (event_hash, (GEqualFunc)event_equal);
4966 handle_parent:
4967 mono_class_setup_methods (klass);
4968 mono_class_setup_vtable (klass);
4969 if (mono_class_has_failure (klass)) {
4970 mono_error_set_for_class_failure (error, klass);
4971 goto failure;
4974 MonoEvent *event;
4975 gpointer iter;
4976 iter = NULL;
4977 while ((event = mono_class_get_events (klass, &iter))) {
4979 // Remove inherited privates and inherited
4980 // without add/remove/raise methods
4981 if (klass != startklass)
4983 MonoMethod *method = event->add;
4984 if (!method)
4985 method = event->remove;
4986 if (!method)
4987 method = event->raise;
4988 if (!method)
4989 continue;
4990 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PRIVATE)
4991 continue;
4994 if ((mlisttype != MLISTTYPE_All) && (utf8_name != NULL) && compare_func (event->name, utf8_name))
4995 continue;
4997 if (g_hash_table_lookup (events, event))
4998 continue;
5000 g_ptr_array_add (res_array, event);
5002 g_hash_table_insert (events, event, event);
5004 if ((klass = m_class_get_parent (klass)))
5005 goto handle_parent;
5007 g_hash_table_destroy (events);
5009 return res_array;
5011 failure:
5012 if (events != NULL)
5013 g_hash_table_destroy (events);
5015 g_ptr_array_free (res_array, TRUE);
5017 return NULL;
5020 GPtrArray *
5021 ves_icall_RuntimeType_GetNestedTypes_native (MonoReflectionTypeHandle ref_type, char *str, guint32 bflags, guint32 mlisttype, MonoError *error)
5023 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
5025 if (type->byref) {
5026 return g_ptr_array_new ();
5029 int (*compare_func) (const char *s1, const char *s2) = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
5031 MonoClass *klass = mono_class_from_mono_type_internal (type);
5034 * If a nested type is generic, return its generic type definition.
5035 * Note that this means that the return value is essentially the set
5036 * of nested types of the generic type definition of @klass.
5038 * A note in MSDN claims that a generic type definition can have
5039 * nested types that aren't generic. In any case, the container of that
5040 * nested type would be the generic type definition.
5042 if (mono_class_is_ginst (klass))
5043 klass = mono_class_get_generic_class (klass)->container_class;
5045 GPtrArray *res_array = g_ptr_array_new ();
5047 MonoClass *nested;
5048 gpointer iter = NULL;
5049 while ((nested = mono_class_get_nested_types (klass, &iter))) {
5050 int match = 0;
5051 if ((mono_class_get_flags (nested) & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
5052 if (bflags & BFLAGS_Public)
5053 match++;
5054 } else {
5055 if (bflags & BFLAGS_NonPublic)
5056 match++;
5058 if (!match)
5059 continue;
5061 if ((mlisttype != MLISTTYPE_All) && (str != NULL) && compare_func (m_class_get_name (nested), str))
5062 continue;
5064 g_ptr_array_add (res_array, m_class_get_byval_arg (nested));
5067 return res_array;
5070 static MonoType*
5071 get_type_from_module_builder_module (MonoAssemblyLoadContext *alc, MonoArrayHandle modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
5073 HANDLE_FUNCTION_ENTER ();
5074 MonoType *type = NULL;
5075 MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW (MonoReflectionModuleBuilder, NULL);
5076 MONO_HANDLE_ARRAY_GETREF (mb, modules, i);
5077 MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
5078 type = mono_reflection_get_type_checked (alc, &dynamic_image->image, &dynamic_image->image, info, ignoreCase, FALSE, type_resolve, error);
5079 HANDLE_FUNCTION_RETURN_VAL (type);
5082 static MonoType*
5083 get_type_from_module_builder_loaded_modules (MonoAssemblyLoadContext *alc, MonoArrayHandle loaded_modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
5085 HANDLE_FUNCTION_ENTER ();
5086 MonoType *type = NULL;
5087 MonoReflectionModuleHandle mod = MONO_HANDLE_NEW (MonoReflectionModule, NULL);
5088 MONO_HANDLE_ARRAY_GETREF (mod, loaded_modules, i);
5089 MonoImage *image = MONO_HANDLE_GETVAL (mod, image);
5090 type = mono_reflection_get_type_checked (alc, image, image, info, ignoreCase, FALSE, type_resolve, error);
5091 HANDLE_FUNCTION_RETURN_VAL (type);
5094 MonoReflectionTypeHandle
5095 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssemblyHandle assembly_h, MonoReflectionModuleHandle module, MonoStringHandle name, MonoBoolean throwOnError, MonoBoolean ignoreCase, MonoError *error)
5097 ERROR_DECL (parse_error);
5099 MonoTypeNameParse info;
5100 gboolean type_resolve;
5101 MonoAssemblyLoadContext *alc = mono_domain_ambient_alc (mono_domain_get ());
5103 /* On MS.NET, this does not fire a TypeResolve event */
5104 type_resolve = TRUE;
5105 char *str = mono_string_handle_to_utf8 (name, error);
5106 goto_if_nok (error, fail);
5108 /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
5109 if (!mono_reflection_parse_type_checked (str, &info, parse_error)) {
5110 g_free (str);
5111 mono_reflection_free_type_info (&info);
5112 mono_error_cleanup (parse_error);
5113 if (throwOnError) {
5114 #if ENABLE_NETCORE
5115 mono_error_set_argument (error, "typeName@0", "failed to parse the type");
5116 #else
5117 mono_error_set_argument (error, "typeName", "failed to parse the type");
5118 #endif
5119 goto fail;
5121 /*g_print ("failed parse\n");*/
5122 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
5125 if (info.assembly.name) {
5126 g_free (str);
5127 mono_reflection_free_type_info (&info);
5128 if (throwOnError) {
5129 /* 1.0 and 2.0 throw different exceptions */
5130 if (mono_defaults.generic_ilist_class)
5131 mono_error_set_argument (error, NULL, "Type names passed to Assembly.GetType() must not specify an assembly.");
5132 else
5133 mono_error_set_type_load_name (error, g_strdup (""), g_strdup (""), "Type names passed to Assembly.GetType() must not specify an assembly.");
5134 goto fail;
5136 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
5139 MonoType *type;
5140 type = NULL;
5141 if (!MONO_HANDLE_IS_NULL (module)) {
5142 MonoImage *image = MONO_HANDLE_GETVAL (module, image);
5143 if (image) {
5144 type = mono_reflection_get_type_checked (alc, image, image, &info, ignoreCase, FALSE, &type_resolve, error);
5145 if (!is_ok (error)) {
5146 g_free (str);
5147 mono_reflection_free_type_info (&info);
5148 goto fail;
5152 else {
5153 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5154 if (assembly_is_dynamic (assembly)) {
5155 /* Enumerate all modules */
5156 MonoReflectionAssemblyBuilderHandle abuilder = MONO_HANDLE_NEW (MonoReflectionAssemblyBuilder, NULL);
5157 MONO_HANDLE_ASSIGN (abuilder, assembly_h);
5158 int i;
5160 MonoArrayHandle modules = MONO_HANDLE_NEW (MonoArray, NULL);
5161 MONO_HANDLE_GET (modules, abuilder, modules);
5162 if (!MONO_HANDLE_IS_NULL (modules)) {
5163 int n = mono_array_handle_length (modules);
5164 for (i = 0; i < n; ++i) {
5165 type = get_type_from_module_builder_module (alc, modules, i, &info, ignoreCase, &type_resolve, error);
5166 if (!is_ok (error)) {
5167 g_free (str);
5168 mono_reflection_free_type_info (&info);
5169 goto fail;
5171 if (type)
5172 break;
5176 MonoArrayHandle loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL);
5177 MONO_HANDLE_GET (loaded_modules, abuilder, loaded_modules);
5178 if (!type && !MONO_HANDLE_IS_NULL (loaded_modules)) {
5179 int n = mono_array_handle_length (loaded_modules);
5180 for (i = 0; i < n; ++i) {
5181 type = get_type_from_module_builder_loaded_modules (alc, loaded_modules, i, &info, ignoreCase, &type_resolve, error);
5183 if (!is_ok (error)) {
5184 g_free (str);
5185 mono_reflection_free_type_info (&info);
5186 goto fail;
5188 if (type)
5189 break;
5193 else {
5194 type = mono_reflection_get_type_checked (alc, assembly->image, assembly->image, &info, ignoreCase, FALSE, &type_resolve, error);
5195 if (!is_ok (error)) {
5196 g_free (str);
5197 mono_reflection_free_type_info (&info);
5198 goto fail;
5202 g_free (str);
5203 mono_reflection_free_type_info (&info);
5205 if (!type) {
5206 if (throwOnError) {
5207 ERROR_DECL (inner_error);
5208 char *type_name = mono_string_handle_to_utf8 (name, inner_error);
5209 mono_error_assert_ok (inner_error);
5210 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5211 char *assmname = mono_stringify_assembly_name (&assembly->aname);
5212 mono_error_set_type_load_name (error, type_name, assmname, "%s", "");
5213 goto fail;
5216 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
5219 if (type->type == MONO_TYPE_CLASS) {
5220 MonoClass *klass = mono_type_get_class_internal (type);
5222 /* need to report exceptions ? */
5223 if (throwOnError && mono_class_has_failure (klass)) {
5224 /* report SecurityException (or others) that occured when loading the assembly */
5225 mono_error_set_for_class_failure (error, klass);
5226 goto fail;
5230 /* g_print ("got it\n"); */
5231 return mono_type_get_object_handle (MONO_HANDLE_DOMAIN (assembly_h), type, error);
5232 fail:
5233 g_assert (!is_ok (error));
5234 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
5237 static gboolean
5238 replace_shadow_path (MonoDomain *domain, gchar *dirname, gchar **filename)
5240 gchar *content;
5241 gchar *shadow_ini_file;
5242 gsize len;
5244 /* Check for shadow-copied assembly */
5245 if (mono_is_shadow_copy_enabled (domain, dirname)) {
5246 shadow_ini_file = g_build_filename (dirname, "__AssemblyInfo__.ini", (const char*)NULL);
5247 content = NULL;
5248 if (!g_file_get_contents (shadow_ini_file, &content, &len, NULL) ||
5249 !g_file_test (content, G_FILE_TEST_IS_REGULAR)) {
5250 g_free (content);
5251 content = NULL;
5253 g_free (shadow_ini_file);
5254 if (content != NULL) {
5255 g_free (*filename);
5256 *filename = content;
5257 return TRUE;
5260 return FALSE;
5263 MonoStringHandle
5264 ves_icall_System_Reflection_RuntimeAssembly_get_code_base (MonoReflectionAssemblyHandle assembly, MonoBoolean escaped, MonoError *error)
5266 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5267 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
5268 gchar *absolute;
5269 gchar *dirname;
5271 if (g_path_is_absolute (mass->image->name)) {
5272 absolute = g_strdup (mass->image->name);
5273 dirname = g_path_get_dirname (absolute);
5274 } else {
5275 absolute = g_build_filename (mass->basedir, mass->image->name, (const char*)NULL);
5276 dirname = g_strdup (mass->basedir);
5279 replace_shadow_path (domain, dirname, &absolute);
5280 g_free (dirname);
5282 mono_icall_make_platform_path (absolute);
5284 gchar *uri;
5285 if (escaped) {
5286 uri = g_filename_to_uri (absolute, NULL, NULL);
5287 } else {
5288 const gchar *prepend = mono_icall_get_file_path_prefix (absolute);
5289 uri = g_strconcat (prepend, absolute, (const char*)NULL);
5292 g_free (absolute);
5294 MonoStringHandle res;
5295 if (uri) {
5296 res = mono_string_new_handle (domain, uri, error);
5297 g_free (uri);
5298 } else {
5299 res = MONO_HANDLE_NEW (MonoString, NULL);
5301 return res;
5304 #ifndef ENABLE_NETCORE
5305 MonoBoolean
5306 ves_icall_System_Reflection_RuntimeAssembly_get_global_assembly_cache (MonoReflectionAssemblyHandle assembly, MonoError *error)
5308 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly,assembly);
5310 return mass->in_gac;
5313 MonoReflectionAssemblyHandle
5314 ves_icall_System_Reflection_Assembly_load_with_partial_name (MonoStringHandle mname, MonoObjectHandle evidence, MonoError *error)
5316 gchar *name;
5317 MonoImageOpenStatus status;
5318 MonoReflectionAssemblyHandle result = MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5320 name = mono_string_handle_to_utf8 (mname, error);
5321 goto_if_nok (error, leave);
5322 MonoAssembly *res;
5323 res = mono_assembly_load_with_partial_name_internal (name, mono_domain_default_alc (mono_domain_get ()), &status);
5325 g_free (name);
5327 if (res == NULL)
5328 goto leave;
5329 result = mono_assembly_get_object_handle (mono_domain_get (), res, error);
5330 leave:
5331 return result;
5333 #endif
5335 MonoStringHandle
5336 ves_icall_System_Reflection_RuntimeAssembly_get_location (MonoReflectionAssemblyHandle refassembly, MonoError *error)
5338 MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
5339 MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
5340 const char *image_name = m_image_get_filename (assembly->image);
5341 return mono_string_new_handle (domain, image_name != NULL ? image_name : "", error);
5344 #ifndef ENABLE_NETCORE
5345 MonoBoolean
5346 ves_icall_System_Reflection_RuntimeAssembly_get_ReflectionOnly (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5348 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5349 return mono_asmctx_get_kind (&assembly->context) == MONO_ASMCTX_REFONLY;
5351 #endif
5353 MonoStringHandle
5354 ves_icall_System_Reflection_RuntimeAssembly_InternalImageRuntimeVersion (MonoReflectionAssemblyHandle refassembly, MonoError *error)
5356 MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
5357 MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
5359 return mono_string_new_handle (domain, assembly->image->version, error);
5362 MonoReflectionMethodHandle
5363 ves_icall_System_Reflection_RuntimeAssembly_get_EntryPoint (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5365 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5366 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5367 MonoMethod *method;
5369 MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
5370 guint32 token = mono_image_get_entry_point (assembly->image);
5372 if (!token)
5373 goto leave;
5374 method = mono_get_method_checked (assembly->image, token, NULL, NULL, error);
5375 goto_if_nok (error, leave);
5377 MONO_HANDLE_ASSIGN (res, mono_method_get_object_handle (domain, method, NULL, error));
5378 leave:
5379 return res;
5382 MonoReflectionModuleHandle
5383 ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAssemblyHandle assembly, MonoError *error)
5385 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5386 MonoAssembly *a = MONO_HANDLE_GETVAL (assembly, assembly);
5387 return mono_module_get_object_handle (domain, a->image, error);
5390 static gboolean
5391 add_manifest_resource_name_to_array (MonoDomain *domain, MonoImage *image, MonoTableInfo *table, int i, MonoArrayHandle dest, MonoError *error)
5393 HANDLE_FUNCTION_ENTER ();
5394 const char *val = mono_metadata_string_heap (image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
5395 MonoStringHandle str = mono_string_new_handle (domain, val, error);
5396 goto_if_nok (error, leave);
5397 MONO_HANDLE_ARRAY_SETREF (dest, i, str);
5398 leave:
5399 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5402 MonoArrayHandle
5403 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceNames (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5405 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5406 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5407 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
5408 MonoArrayHandle result = mono_array_new_handle (domain, mono_defaults.string_class, table->rows, error);
5409 goto_if_nok (error, fail);
5410 int i;
5412 for (i = 0; i < table->rows; ++i) {
5413 if (!add_manifest_resource_name_to_array (domain, assembly->image, table, i, result, error))
5414 goto fail;
5416 return result;
5417 fail:
5418 return NULL_HANDLE_ARRAY;
5421 #ifndef ENABLE_NETCORE
5422 MonoBoolean
5423 ves_icall_System_Reflection_RuntimeAssembly_GetAotIdInternal (MonoArrayHandle guid_h, MonoError *error)
5425 g_assert (mono_array_handle_length (guid_h) == 16);
5427 guint8 *aotid = mono_runtime_get_aotid_arr ();
5428 if (!aotid) {
5429 return FALSE;
5430 } else {
5431 MONO_ENTER_NO_SAFEPOINTS;
5432 guint8 *data = (guint8*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (guid_h), 1, 0);
5433 memcpy (data, aotid, 16);
5434 MONO_EXIT_NO_SAFEPOINTS;
5435 return TRUE;
5438 #endif
5440 static MonoAssemblyName*
5441 create_referenced_assembly_name (MonoDomain *domain, MonoImage *image, MonoTableInfo *t, int i, MonoError *error)
5443 MonoAssemblyName *aname = g_new0 (MonoAssemblyName, 1);
5445 mono_assembly_get_assemblyref_checked (image, i, aname, error);
5446 return_val_if_nok (error, NULL);
5447 aname->hash_alg = ASSEMBLY_HASH_SHA1 /* SHA1 (default) */;
5448 /* name and culture are pointers into the image tables, but we need
5449 * real malloc'd strings (so that we can g_free() them later from
5450 * Mono.RuntimeMarshal.FreeAssemblyName) */
5451 aname->name = g_strdup (aname->name);
5452 aname->culture = g_strdup (aname->culture);
5453 /* Don't need the hash value in managed */
5454 aname->hash_value = NULL;
5455 aname->hash_len = 0;
5456 g_assert (aname->public_key == NULL);
5458 /* note: this function doesn't return the codebase on purpose (i.e. it can
5459 be used under partial trust as path information isn't present). */
5460 return aname;
5463 GPtrArray*
5464 ves_icall_System_Reflection_Assembly_InternalGetReferencedAssemblies (MonoReflectionAssemblyHandle assembly, MonoError *error)
5466 error_init (error);
5467 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5468 MonoAssembly *ass = MONO_HANDLE_GETVAL(assembly, assembly);
5469 MonoImage *image = ass->image;
5471 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
5472 int count = t->rows;
5474 GPtrArray *result = g_ptr_array_sized_new (count);
5476 for (int i = 0; i < count; i++) {
5477 MonoAssemblyName *aname = create_referenced_assembly_name (domain, image, t, i, error);
5478 if (!is_ok (error))
5479 break;
5480 g_ptr_array_add (result, aname);
5482 return result;
5485 /* move this in some file in mono/util/ */
5486 static char *
5487 g_concat_dir_and_file (const char *dir, const char *file)
5489 g_return_val_if_fail (dir != NULL, NULL);
5490 g_return_val_if_fail (file != NULL, NULL);
5493 * If the directory name doesn't have a / on the end, we need
5494 * to add one so we get a proper path to the file
5496 if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
5497 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, (const char*)NULL);
5498 else
5499 return g_strconcat (dir, file, (const char*)NULL);
5502 void *
5503 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, gint32 *size, MonoReflectionModuleHandleOut ref_module, MonoError *error)
5505 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5506 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5507 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
5508 guint32 i;
5509 guint32 cols [MONO_MANIFEST_SIZE];
5510 guint32 impl, file_idx;
5511 const char *val;
5512 MonoImage *module;
5514 char *n = mono_string_handle_to_utf8 (name, error);
5515 return_val_if_nok (error, NULL);
5517 for (i = 0; i < table->rows; ++i) {
5518 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
5519 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
5520 if (strcmp (val, n) == 0)
5521 break;
5523 g_free (n);
5524 if (i == table->rows)
5525 return NULL;
5526 /* FIXME */
5527 impl = cols [MONO_MANIFEST_IMPLEMENTATION];
5528 if (impl) {
5530 * this code should only be called after obtaining the
5531 * ResourceInfo and handling the other cases.
5533 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
5534 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
5536 module = mono_image_load_file_for_image_checked (assembly->image, file_idx, error);
5537 if (!is_ok (error) || !module)
5538 return NULL;
5540 else
5541 module = assembly->image;
5544 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
5545 return_val_if_nok (error, NULL);
5546 MONO_HANDLE_ASSIGN (ref_module, rm);
5548 return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
5551 static gboolean
5552 get_manifest_resource_info_internal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info, MonoError *error)
5554 HANDLE_FUNCTION_ENTER ();
5555 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5556 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5557 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
5558 int i;
5559 guint32 cols [MONO_MANIFEST_SIZE];
5560 guint32 file_cols [MONO_FILE_SIZE];
5561 const char *val;
5562 char *n;
5564 gboolean result = FALSE;
5566 n = mono_string_handle_to_utf8 (name, error);
5567 goto_if_nok (error, leave);
5569 for (i = 0; i < table->rows; ++i) {
5570 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
5571 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
5572 if (strcmp (val, n) == 0)
5573 break;
5575 g_free (n);
5576 if (i == table->rows)
5577 goto leave;
5579 if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
5580 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST);
5582 else {
5583 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
5584 case MONO_IMPLEMENTATION_FILE:
5585 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
5586 table = &assembly->image->tables [MONO_TABLE_FILE];
5587 mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
5588 val = mono_metadata_string_heap (assembly->image, file_cols [MONO_FILE_NAME]);
5589 MONO_HANDLE_SET (info, filename, mono_string_new_handle (domain, val, error));
5590 if (file_cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA)
5591 MONO_HANDLE_SETVAL (info, location, guint32, 0);
5592 else
5593 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED);
5594 break;
5596 case MONO_IMPLEMENTATION_ASSEMBLYREF:
5597 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
5598 mono_assembly_load_reference (assembly->image, i - 1);
5599 if (assembly->image->references [i - 1] == REFERENCE_MISSING) {
5600 mono_error_set_file_not_found (error, NULL, "Assembly %d referenced from assembly %s not found ", i - 1, assembly->image->name);
5601 goto leave;
5603 MonoReflectionAssemblyHandle assm_obj;
5604 assm_obj = mono_assembly_get_object_handle (mono_domain_get (), assembly->image->references [i - 1], error);
5605 goto_if_nok (error, leave);
5606 MONO_HANDLE_SET (info, assembly, assm_obj);
5608 /* Obtain info recursively */
5609 get_manifest_resource_info_internal (assm_obj, name, info, error);
5610 goto_if_nok (error, leave);
5611 guint32 location;
5612 location = MONO_HANDLE_GETVAL (info, location);
5613 location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
5614 MONO_HANDLE_SETVAL (info, location, guint32, location);
5615 break;
5617 case MONO_IMPLEMENTATION_EXP_TYPE:
5618 g_assert_not_reached ();
5619 break;
5623 result = TRUE;
5624 leave:
5625 HANDLE_FUNCTION_RETURN_VAL (result);
5628 MonoBoolean
5629 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInfoInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info_h, MonoError *error)
5631 return get_manifest_resource_info_internal (assembly_h, name, info_h, error);
5634 static gboolean
5635 add_filename_to_files_array (MonoDomain *domain, MonoAssembly * assembly, MonoTableInfo *table, int i, MonoArrayHandle dest, int dest_idx, MonoError *error)
5637 HANDLE_FUNCTION_ENTER();
5638 const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
5639 char *n = g_concat_dir_and_file (assembly->basedir, val);
5640 MonoStringHandle str = mono_string_new_handle (domain, n, error);
5641 g_free (n);
5642 goto_if_nok (error, leave);
5643 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, str);
5644 leave:
5645 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5648 MonoObjectHandle
5649 ves_icall_System_Reflection_RuntimeAssembly_GetFilesInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoBoolean resource_modules, MonoError *error)
5651 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5652 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5653 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_FILE];
5654 int i, count;
5656 /* check hash if needed */
5657 if (!MONO_HANDLE_IS_NULL(name)) {
5658 char *n = mono_string_handle_to_utf8 (name, error);
5659 goto_if_nok (error, fail);
5661 for (i = 0; i < table->rows; ++i) {
5662 const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
5663 if (strcmp (val, n) == 0) {
5664 g_free (n);
5665 n = g_concat_dir_and_file (assembly->basedir, val);
5666 MonoStringHandle fn = mono_string_new_handle (domain, n, error);
5667 g_free (n);
5668 goto_if_nok (error, fail);
5669 return MONO_HANDLE_CAST (MonoObject, fn);
5672 g_free (n);
5673 return NULL_HANDLE;
5676 count = 0;
5677 for (i = 0; i < table->rows; ++i) {
5678 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA))
5679 count ++;
5682 MonoArrayHandle result;
5683 result = mono_array_new_handle (domain, mono_defaults.string_class, count, error);
5684 goto_if_nok (error, fail);
5686 count = 0;
5687 for (i = 0; i < table->rows; ++i) {
5688 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
5689 if (!add_filename_to_files_array (domain, assembly, table, i, result, count, error))
5690 goto fail;
5691 count++;
5694 return MONO_HANDLE_CAST (MonoObject, result);
5695 fail:
5696 return NULL_HANDLE;
5699 static gboolean
5700 add_module_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int *dest_idx, MonoImage* module, MonoError *error)
5702 HANDLE_FUNCTION_ENTER ();
5703 error_init (error);
5704 if (module) {
5705 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
5706 goto_if_nok (error, leave);
5708 MONO_HANDLE_ARRAY_SETREF (dest, *dest_idx, rm);
5709 ++(*dest_idx);
5712 leave:
5713 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5716 static gboolean
5717 add_file_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int dest_idx, MonoImage *image, MonoTableInfo *table, int table_idx, MonoError *error)
5719 HANDLE_FUNCTION_ENTER ();
5721 guint32 cols [MONO_FILE_SIZE];
5722 mono_metadata_decode_row (table, table_idx, cols, MONO_FILE_SIZE);
5723 if (cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA) {
5724 MonoReflectionModuleHandle rm = mono_module_file_get_object_handle (domain, image, table_idx, error);
5725 goto_if_nok (error, leave);
5726 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5727 } else {
5728 MonoImage *m = mono_image_load_file_for_image_checked (image, table_idx + 1, error);
5729 goto_if_nok (error, leave);
5730 if (!m) {
5731 const char *filename = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
5732 mono_error_set_file_not_found (error, filename, "%s", "");
5733 goto leave;
5735 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, m, error);
5736 goto_if_nok (error, leave);
5737 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5740 leave:
5741 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5744 MonoArrayHandle
5745 ves_icall_System_Reflection_RuntimeAssembly_GetModulesInternal (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5747 error_init (error);
5748 MonoDomain *domain = mono_domain_get();
5749 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5750 MonoClass *klass;
5751 int i, j, file_count = 0;
5752 MonoImage **modules;
5753 guint32 module_count, real_module_count;
5754 MonoTableInfo *table;
5755 MonoImage *image = assembly->image;
5757 g_assert (image != NULL);
5758 g_assert (!assembly_is_dynamic (assembly));
5760 table = &image->tables [MONO_TABLE_FILE];
5761 file_count = table->rows;
5763 modules = image->modules;
5764 module_count = image->module_count;
5766 real_module_count = 0;
5767 for (i = 0; i < module_count; ++i)
5768 if (modules [i])
5769 real_module_count ++;
5771 klass = mono_class_get_module_class ();
5772 MonoArrayHandle res = mono_array_new_handle (domain, klass, 1 + real_module_count + file_count, error);
5773 goto_if_nok (error, fail);
5775 MonoReflectionModuleHandle image_obj;
5776 image_obj = mono_module_get_object_handle (domain, image, error);
5777 goto_if_nok (error, fail);
5779 MONO_HANDLE_ARRAY_SETREF (res, 0, image_obj);
5781 j = 1;
5782 for (i = 0; i < module_count; ++i)
5783 if (!add_module_to_modules_array (domain, res, &j, modules[i], error))
5784 goto fail;
5786 for (i = 0; i < file_count; ++i, ++j) {
5787 if (!add_file_to_modules_array (domain, res, j, image, table, i, error))
5788 goto fail;
5791 return res;
5792 fail:
5793 return NULL_HANDLE_ARRAY;
5796 MonoReflectionMethodHandle
5797 ves_icall_GetCurrentMethod (MonoError *error)
5799 MonoMethod *m = mono_method_get_last_managed ();
5801 if (!m) {
5802 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5803 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5806 while (m->is_inflated)
5807 m = ((MonoMethodInflated*)m)->declaring;
5809 return mono_method_get_object_handle (mono_domain_get (), m, NULL, error);
5812 static MonoMethod*
5813 mono_method_get_equivalent_method (MonoMethod *method, MonoClass *klass)
5815 int offset = -1, i;
5816 if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) {
5817 ERROR_DECL (error);
5818 MonoMethod *result;
5819 MonoMethodInflated *inflated = (MonoMethodInflated*)method;
5820 //method is inflated, we should inflate it on the other class
5821 MonoGenericContext ctx;
5822 ctx.method_inst = inflated->context.method_inst;
5823 ctx.class_inst = inflated->context.class_inst;
5824 if (mono_class_is_ginst (klass))
5825 ctx.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
5826 else if (mono_class_is_gtd (klass))
5827 ctx.class_inst = mono_class_get_generic_container (klass)->context.class_inst;
5828 result = mono_class_inflate_generic_method_full_checked (inflated->declaring, klass, &ctx, error);
5829 g_assert (is_ok (error)); /* FIXME don't swallow the error */
5830 return result;
5833 mono_class_setup_methods (method->klass);
5834 if (mono_class_has_failure (method->klass))
5835 return NULL;
5836 int mcount = mono_class_get_method_count (method->klass);
5837 MonoMethod **method_klass_methods = m_class_get_methods (method->klass);
5838 for (i = 0; i < mcount; ++i) {
5839 if (method_klass_methods [i] == method) {
5840 offset = i;
5841 break;
5844 mono_class_setup_methods (klass);
5845 if (mono_class_has_failure (klass))
5846 return NULL;
5847 g_assert (offset >= 0 && offset < mono_class_get_method_count (klass));
5848 return m_class_get_methods (klass) [offset];
5851 MonoReflectionMethodHandle
5852 ves_icall_System_Reflection_RuntimeMethodInfo_GetMethodFromHandleInternalType_native (MonoMethod *method, MonoType *type, MonoBoolean generic_check, MonoError *error)
5854 MonoClass *klass;
5855 if (type && generic_check) {
5856 klass = mono_class_from_mono_type_internal (type);
5857 if (mono_class_get_generic_type_definition (method->klass) != mono_class_get_generic_type_definition (klass))
5858 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5860 if (method->klass != klass) {
5861 method = mono_method_get_equivalent_method (method, klass);
5862 if (!method)
5863 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5865 } else if (type)
5866 klass = mono_class_from_mono_type_internal (type);
5867 else
5868 klass = method->klass;
5869 return mono_method_get_object_handle (mono_domain_get (), method, klass, error);
5872 MonoReflectionMethodBodyHandle
5873 ves_icall_System_Reflection_RuntimeMethodInfo_GetMethodBodyInternal (MonoMethod *method, MonoError *error)
5875 return mono_method_body_get_object_handle (mono_domain_get (), method, error);
5878 #if ENABLE_NETCORE
5879 MonoReflectionAssemblyHandle
5880 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (MonoStackCrawlMark *stack_mark, MonoError *error)
5882 MonoAssembly *assembly;
5883 assembly = mono_runtime_get_caller_from_stack_mark (stack_mark);
5884 g_assert (assembly);
5885 return mono_assembly_get_object_handle (mono_domain_get (), assembly, error);
5887 #else
5888 MonoReflectionAssemblyHandle
5889 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (MonoError *error)
5891 MonoMethod *dest = NULL;
5892 mono_stack_walk_no_il (get_executing, &dest);
5893 g_assert (dest);
5894 return mono_assembly_get_object_handle (mono_domain_get (), m_class_get_image (dest->klass)->assembly, error);
5896 #endif
5898 MonoReflectionAssemblyHandle
5899 ves_icall_System_Reflection_Assembly_GetEntryAssembly (MonoError *error)
5901 MonoDomain* domain = mono_domain_get ();
5903 if (!domain->entry_assembly)
5904 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5906 return mono_assembly_get_object_handle (domain, domain->entry_assembly, error);
5909 MonoReflectionAssemblyHandle
5910 ves_icall_System_Reflection_Assembly_GetCallingAssembly (MonoError *error)
5912 error_init (error);
5913 MonoMethod *m;
5914 MonoMethod *dest;
5916 dest = NULL;
5917 mono_stack_walk_no_il (get_executing, &dest);
5918 m = dest;
5919 mono_stack_walk_no_il (get_caller_no_reflection, &dest);
5920 if (!dest)
5921 dest = m;
5922 if (!m) {
5923 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5924 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5926 return mono_assembly_get_object_handle (mono_domain_get (), m_class_get_image (dest->klass)->assembly, error);
5929 MonoStringHandle
5930 ves_icall_System_RuntimeType_getFullName (MonoReflectionTypeHandle object, MonoBoolean full_name,
5931 MonoBoolean assembly_qualified, MonoError *error)
5933 MonoDomain *domain = mono_object_domain (MONO_HANDLE_RAW (object));
5934 MonoType *type = MONO_HANDLE_RAW (object)->type;
5935 MonoTypeNameFormat format;
5936 MonoStringHandle res;
5937 gchar *name;
5939 if (full_name)
5940 format = assembly_qualified ?
5941 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED :
5942 MONO_TYPE_NAME_FORMAT_FULL_NAME;
5943 else
5944 format = MONO_TYPE_NAME_FORMAT_REFLECTION;
5946 name = mono_type_get_name_full (type, format);
5947 if (!name)
5948 return NULL_HANDLE_STRING;
5950 if (full_name && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
5951 g_free (name);
5952 return NULL_HANDLE_STRING;
5955 res = mono_string_new_handle (domain, name, error);
5956 g_free (name);
5958 return res;
5961 #ifndef ENABLE_NETCORE
5963 ves_icall_RuntimeType_get_core_clr_security_level (MonoReflectionTypeHandle rfield, MonoError *error)
5965 MonoType *type = MONO_HANDLE_GETVAL (rfield, type);
5966 MonoClass *klass = mono_class_from_mono_type_internal (type);
5968 mono_class_init_checked (klass, error);
5969 return_val_if_nok (error, -1);
5970 return mono_security_core_clr_class_level (klass);
5972 #endif
5975 ves_icall_RuntimeFieldInfo_get_core_clr_security_level (MonoReflectionFieldHandle rfield, MonoError *error)
5977 MonoClassField *field = MONO_HANDLE_GETVAL (rfield, field);
5978 return mono_security_core_clr_field_level (field, TRUE);
5982 ves_icall_RuntimeMethodInfo_get_core_clr_security_level (MonoReflectionMethodHandle rfield, MonoError *error)
5984 MonoMethod *method = MONO_HANDLE_GETVAL (rfield, method);
5985 return mono_security_core_clr_method_level (method, TRUE);
5988 MonoStringHandle
5989 ves_icall_System_Reflection_RuntimeAssembly_get_fullname (MonoReflectionAssemblyHandle assembly, MonoError *error)
5991 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5992 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
5993 gchar *name;
5995 name = mono_stringify_assembly_name (&mass->aname);
5996 MonoStringHandle res = mono_string_new_handle (domain, name, error);
5997 g_free (name);
5998 return res;
6001 MonoAssemblyName *
6002 ves_icall_System_Reflection_AssemblyName_GetNativeName (MonoAssembly *mass)
6004 return &mass->aname;
6007 void
6008 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoStringHandle fname, MonoAssemblyName *name, MonoStringHandleOut normalized_codebase, MonoError *error)
6010 char *filename;
6011 MonoImageOpenStatus status = MONO_IMAGE_OK;
6012 char *codebase = NULL;
6013 gboolean res;
6014 MonoImage *image;
6015 char *dirname;
6017 error_init (error);
6019 MonoDomain *domain = MONO_HANDLE_DOMAIN (fname);
6020 filename = mono_string_handle_to_utf8 (fname, error);
6021 return_if_nok (error);
6023 dirname = g_path_get_dirname (filename);
6024 replace_shadow_path (mono_domain_get (), dirname, &filename);
6025 g_free (dirname);
6027 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "InternalGetAssemblyName (\"%s\")", filename);
6029 MonoAssemblyLoadContext *alc = mono_domain_default_alc (domain);
6030 image = mono_image_open_a_lot (alc, filename, &status, TRUE, FALSE);
6032 if (!image){
6033 if (status == MONO_IMAGE_IMAGE_INVALID)
6034 mono_error_set_bad_image_by_name (error, filename, "Invalid Image");
6035 else
6036 mono_error_set_file_not_found (error, filename, "%s", "");
6037 g_free (filename);
6038 return;
6041 res = mono_assembly_fill_assembly_name_full (image, name, TRUE);
6042 if (!res) {
6043 mono_image_close (image);
6044 g_free (filename);
6045 mono_error_set_argument (error, "assemblyFile", "The file does not contain a manifest");
6046 return;
6049 if (filename != NULL && *filename != '\0') {
6050 gchar *result;
6052 codebase = g_strdup (filename);
6054 mono_icall_make_platform_path (codebase);
6056 const gchar *prepend = mono_icall_get_file_path_prefix (codebase);
6058 result = g_strconcat (prepend, codebase, (const char*)NULL);
6059 g_free (codebase);
6060 codebase = result;
6062 MONO_HANDLE_ASSIGN (normalized_codebase, mono_string_new_handle (mono_domain_get (), codebase, error));
6063 g_free (codebase);
6065 mono_image_close (image);
6066 g_free (filename);
6069 #ifndef ENABLE_NETCORE
6070 MonoBoolean
6071 ves_icall_System_Reflection_RuntimeAssembly_LoadPermissions (MonoReflectionAssemblyHandle assembly_h,
6072 char **minimum, guint32 *minLength, char **optional, guint32 *optLength, char **refused, guint32 *refLength, MonoError *error)
6074 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
6075 MonoBoolean result = FALSE;
6076 MonoDeclSecurityEntry entry;
6078 /* SecurityAction.RequestMinimum */
6079 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQMIN, &entry)) {
6080 *minimum = entry.blob;
6081 *minLength = entry.size;
6082 result = TRUE;
6084 /* SecurityAction.RequestOptional */
6085 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQOPT, &entry)) {
6086 *optional = entry.blob;
6087 *optLength = entry.size;
6088 result = TRUE;
6090 /* SecurityAction.RequestRefuse */
6091 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQREFUSE, &entry)) {
6092 *refused = entry.blob;
6093 *refLength = entry.size;
6094 result = TRUE;
6097 return result;
6099 #endif
6101 static gboolean
6102 mono_module_type_is_visible (MonoTableInfo *tdef, MonoImage *image, int type)
6104 guint32 attrs, visibility;
6105 do {
6106 attrs = mono_metadata_decode_row_col (tdef, type - 1, MONO_TYPEDEF_FLAGS);
6107 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
6108 if (visibility != TYPE_ATTRIBUTE_PUBLIC && visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC)
6109 return FALSE;
6111 } while ((type = mono_metadata_token_index (mono_metadata_nested_in_typedef (image, type))));
6113 return TRUE;
6116 static void
6117 image_get_type (MonoDomain *domain, MonoImage *image, MonoTableInfo *tdef, int table_idx, int count, MonoArrayHandle res, MonoArrayHandle exceptions, MonoBoolean exportedOnly, MonoError *error)
6119 error_init (error);
6120 HANDLE_FUNCTION_ENTER ();
6121 ERROR_DECL (klass_error);
6122 MonoClass *klass = mono_class_get_checked (image, table_idx | MONO_TOKEN_TYPE_DEF, klass_error);
6124 if (klass) {
6125 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
6126 return_if_nok (error);
6128 MONO_HANDLE_ARRAY_SETREF (res, count, rt);
6129 } else {
6130 MonoExceptionHandle ex = mono_error_convert_to_exception_handle (klass_error);
6131 MONO_HANDLE_ARRAY_SETREF (exceptions, count, ex);
6133 HANDLE_FUNCTION_RETURN ();
6136 static MonoArrayHandle
6137 mono_module_get_types (MonoDomain *domain, MonoImage *image, MonoArrayHandleOut exceptions, MonoBoolean exportedOnly, MonoError *error)
6139 MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
6140 int i, count;
6142 error_init (error);
6144 /* we start the count from 1 because we skip the special type <Module> */
6145 if (exportedOnly) {
6146 count = 0;
6147 for (i = 1; i < tdef->rows; ++i) {
6148 if (mono_module_type_is_visible (tdef, image, i + 1))
6149 count++;
6151 } else {
6152 count = tdef->rows - 1;
6154 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.runtimetype_class, count, error);
6155 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6156 MONO_HANDLE_ASSIGN (exceptions, mono_array_new_handle (domain, mono_defaults.exception_class, count, error));
6157 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6158 count = 0;
6159 for (i = 1; i < tdef->rows; ++i) {
6160 if (!exportedOnly || mono_module_type_is_visible (tdef, image, i+1)) {
6161 image_get_type (domain, image, tdef, i + 1, count, res, exceptions, exportedOnly, error);
6162 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6163 count++;
6167 return res;
6170 static void
6171 append_module_types (MonoDomain *domain, MonoArrayHandleOut res, MonoArrayHandleOut exceptions, MonoImage *image, MonoBoolean exportedOnly, MonoError *error)
6173 HANDLE_FUNCTION_ENTER ();
6174 error_init (error);
6175 MonoArrayHandle ex2 = MONO_HANDLE_NEW (MonoArray, NULL);
6176 MonoArrayHandle res2 = mono_module_get_types (domain, image, ex2, exportedOnly, error);
6177 goto_if_nok (error, leave);
6179 /* Append the new types to the end of the array */
6180 if (mono_array_handle_length (res2) > 0) {
6181 guint32 len1, len2;
6183 len1 = mono_array_handle_length (res);
6184 len2 = mono_array_handle_length (res2);
6186 MonoArrayHandle res3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
6187 goto_if_nok (error, leave);
6189 mono_array_handle_memcpy_refs (res3, 0, res, 0, len1);
6190 mono_array_handle_memcpy_refs (res3, len1, res2, 0, len2);
6191 MONO_HANDLE_ASSIGN (res, res3);
6193 MonoArrayHandle ex3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
6194 goto_if_nok (error, leave);
6196 mono_array_handle_memcpy_refs (ex3, 0, exceptions, 0, len1);
6197 mono_array_handle_memcpy_refs (ex3, len1, ex2, 0, len2);
6198 MONO_HANDLE_ASSIGN (exceptions, ex3);
6200 leave:
6201 HANDLE_FUNCTION_RETURN ();
6204 static void
6205 set_class_failure_in_array (MonoArrayHandle exl, int i, MonoClass *klass)
6207 HANDLE_FUNCTION_ENTER ();
6208 ERROR_DECL (unboxed_error);
6209 mono_error_set_for_class_failure (unboxed_error, klass);
6211 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, mono_error_convert_to_exception (unboxed_error));
6212 MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
6213 HANDLE_FUNCTION_RETURN ();
6216 static MonoArrayHandle
6217 assembly_get_types (MonoReflectionAssemblyHandle assembly_handle, MonoBoolean exportedOnly, MonoError *error)
6219 MonoArrayHandle exceptions = MONO_HANDLE_NEW(MonoArray, NULL);
6220 int i;
6222 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_handle);
6223 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_handle, assembly);
6225 g_assert (!assembly_is_dynamic (assembly));
6226 MonoImage *image = assembly->image;
6227 MonoTableInfo *table = &image->tables [MONO_TABLE_FILE];
6228 MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, exportedOnly, error);
6229 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6231 /* Append data from all modules in the assembly */
6232 for (i = 0; i < table->rows; ++i) {
6233 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
6234 MonoImage *loaded_image = mono_assembly_load_module_checked (image->assembly, i + 1, error);
6235 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6237 if (loaded_image) {
6238 append_module_types (domain, res, exceptions, loaded_image, exportedOnly, error);
6239 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6244 /* the ReflectionTypeLoadException must have all the types (Types property),
6245 * NULL replacing types which throws an exception. The LoaderException must
6246 * contain all exceptions for NULL items.
6249 int len = mono_array_handle_length (res);
6251 int ex_count = 0;
6252 GList *list = NULL;
6253 MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
6254 for (i = 0; i < len; i++) {
6255 MONO_HANDLE_ARRAY_GETREF (t, res, i);
6257 if (!MONO_HANDLE_IS_NULL (t)) {
6258 MonoClass *klass = mono_type_get_class_internal (MONO_HANDLE_GETVAL (t, type));
6259 if ((klass != NULL) && mono_class_has_failure (klass)) {
6260 /* keep the class in the list */
6261 list = g_list_append (list, klass);
6262 /* and replace Type with NULL */
6263 MONO_HANDLE_ARRAY_SETREF (res, i, NULL_HANDLE);
6265 } else {
6266 ex_count ++;
6270 if (list || ex_count) {
6271 GList *tmp = NULL;
6272 int j, length = g_list_length (list) + ex_count;
6274 MonoArrayHandle exl = mono_array_new_handle (domain, mono_defaults.exception_class, length, error);
6275 if (!is_ok (error)) {
6276 g_list_free (list);
6277 return NULL_HANDLE_ARRAY;
6279 /* Types for which mono_class_get_checked () succeeded */
6280 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
6281 for (i = 0, tmp = list; tmp; i++, tmp = tmp->next) {
6282 set_class_failure_in_array (exl, i, (MonoClass*)tmp->data);
6284 /* Types for which it don't */
6285 for (j = 0; j < mono_array_handle_length (exceptions); ++j) {
6286 MONO_HANDLE_ARRAY_GETREF (exc, exceptions, j);
6287 if (!MONO_HANDLE_IS_NULL (exc)) {
6288 g_assert (i < length);
6289 MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
6290 i ++;
6293 g_list_free (list);
6294 list = NULL;
6296 MONO_HANDLE_ASSIGN (exc, mono_get_exception_reflection_type_load_checked (res, exl, error));
6297 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6298 mono_error_set_exception_handle (error, exc);
6299 return NULL_HANDLE_ARRAY;
6302 return res;
6305 #ifndef ENABLE_NETCORE
6306 MonoArrayHandle
6307 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssemblyHandle assembly_handle, MonoBoolean exportedOnly, MonoError *error)
6309 return assembly_get_types (assembly_handle, exportedOnly, error);
6311 #endif
6313 #if ENABLE_NETCORE
6314 MonoArrayHandle
6315 ves_icall_System_Reflection_RuntimeAssembly_GetExportedTypes (MonoReflectionAssemblyHandle assembly_handle, MonoError *error)
6317 return assembly_get_types (assembly_handle, TRUE, error);
6320 static void
6321 get_top_level_forwarded_type (MonoImage *image, MonoTableInfo *table, int i, MonoArrayHandle types, MonoArrayHandle exceptions, int *aindex, int *exception_count)
6323 ERROR_DECL (local_error);
6324 guint32 cols [MONO_EXP_TYPE_SIZE];
6325 MonoClass *klass;
6326 MonoReflectionTypeHandle rt;
6328 mono_metadata_decode_row (table, i, cols, MONO_EXP_TYPE_SIZE);
6329 if (!(cols [MONO_EXP_TYPE_FLAGS] & TYPE_ATTRIBUTE_FORWARDER))
6330 return;
6331 guint32 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
6332 const char *name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
6333 const char *nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
6335 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF);
6336 guint32 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
6338 mono_assembly_load_reference (image, assembly_idx - 1);
6339 g_assert (image->references [assembly_idx - 1]);
6341 HANDLE_FUNCTION_ENTER ();
6343 if (image->references [assembly_idx - 1] == REFERENCE_MISSING) {
6344 MonoExceptionHandle ex = MONO_HANDLE_NEW (MonoException, mono_get_exception_bad_image_format ("Invalid image"));
6345 MONO_HANDLE_ARRAY_SETREF (types, *aindex, NULL_HANDLE);
6346 MONO_HANDLE_ARRAY_SETREF (exceptions, *aindex, ex);
6347 (*exception_count)++; (*aindex)++;
6348 goto exit;
6350 klass = mono_class_from_name_checked (image->references [assembly_idx - 1]->image, nspace, name, local_error);
6351 if (!is_ok (local_error)) {
6352 MonoExceptionHandle ex = mono_error_convert_to_exception_handle (local_error);
6353 MONO_HANDLE_ARRAY_SETREF (types, *aindex, NULL_HANDLE);
6354 MONO_HANDLE_ARRAY_SETREF (exceptions, *aindex, ex);
6355 mono_error_cleanup (local_error);
6356 (*exception_count)++; (*aindex)++;
6357 goto exit;
6359 rt = mono_type_get_object_handle (mono_domain_get (), m_class_get_byval_arg (klass), local_error);
6360 if (!is_ok (local_error)) {
6361 MonoExceptionHandle ex = mono_error_convert_to_exception_handle (local_error);
6362 MONO_HANDLE_ARRAY_SETREF (types, *aindex, NULL_HANDLE);
6363 MONO_HANDLE_ARRAY_SETREF (exceptions, *aindex, ex);
6364 mono_error_cleanup (local_error);
6365 (*exception_count)++; (*aindex)++;
6366 goto exit;
6368 MONO_HANDLE_ARRAY_SETREF (types, *aindex, rt);
6369 MONO_HANDLE_ARRAY_SETREF (exceptions, *aindex, NULL_HANDLE);
6370 (*aindex)++;
6372 exit:
6373 HANDLE_FUNCTION_RETURN ();
6376 MonoArrayHandle
6377 ves_icall_System_Reflection_RuntimeAssembly_GetTopLevelForwardedTypes (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
6379 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
6380 MonoImage *image = assembly->image;
6381 int count = 0;
6383 g_assert (!assembly_is_dynamic (assembly));
6384 MonoTableInfo *table = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6385 for (int i = 0; i < table->rows; ++i) {
6386 if (mono_metadata_decode_row_col (table, i, MONO_EXP_TYPE_FLAGS) & TYPE_ATTRIBUTE_FORWARDER)
6387 count ++;
6390 MonoArrayHandle types = mono_array_new_handle (mono_domain_get (), mono_defaults.runtimetype_class, count, error);
6391 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6392 MonoArrayHandle exceptions = mono_array_new_handle (mono_domain_get (), mono_defaults.exception_class, count, error);
6393 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6395 int aindex = 0;
6396 int exception_count = 0;
6397 for (int i = 0; i < table->rows; ++i) {
6398 get_top_level_forwarded_type (image, table, i, types, exceptions, &aindex, &exception_count);
6401 if (exception_count > 0) {
6402 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
6403 MONO_HANDLE_ASSIGN (exc, mono_get_exception_reflection_type_load_checked (types, exceptions, error));
6404 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6405 mono_error_set_exception_handle (error, exc);
6406 return NULL_HANDLE_ARRAY;
6409 return types;
6411 #endif
6413 void
6414 ves_icall_Mono_RuntimeMarshal_FreeAssemblyName (MonoAssemblyName *aname, MonoBoolean free_struct)
6416 mono_assembly_name_free_internal (aname);
6417 if (free_struct)
6418 g_free (aname);
6421 void
6422 ves_icall_Mono_Runtime_DisableMicrosoftTelemetry (void)
6424 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
6425 mono_merp_disable ();
6426 #else
6427 // Icall has platform check in managed too.
6428 g_assert_not_reached ();
6429 #endif
6432 void
6433 ves_icall_Mono_Runtime_AnnotateMicrosoftTelemetry (const char *key, const char *value)
6435 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
6436 if (!mono_merp_enabled ())
6437 g_error ("Cannot add attributes to telemetry without enabling subsystem");
6438 mono_merp_add_annotation (key, value);
6439 #else
6440 // Icall has platform check in managed too.
6441 g_assert_not_reached ();
6442 #endif
6445 void
6446 ves_icall_Mono_Runtime_EnableMicrosoftTelemetry (const char *appBundleID, const char *appSignature, const char *appVersion, const char *merpGUIPath, const char *appPath, const char *configDir, MonoError *error)
6448 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
6449 mono_merp_enable (appBundleID, appSignature, appVersion, merpGUIPath, appPath, configDir);
6451 mono_get_runtime_callbacks ()->install_state_summarizer ();
6452 #else
6453 // Icall has platform check in managed too.
6454 g_assert_not_reached ();
6455 #endif
6458 // Number derived from trials on relevant hardware.
6459 // If it seems large, please confirm it's safe to shrink
6460 // before doing so.
6461 #define MONO_MAX_SUMMARY_LEN_ICALL 500000
6463 MonoStringHandle
6464 ves_icall_Mono_Runtime_ExceptionToState (MonoExceptionHandle exc_handle, guint64 *portable_hash_out, guint64 *unportable_hash_out, MonoError *error)
6466 MonoStringHandle result;
6468 #ifndef DISABLE_CRASH_REPORTING
6469 if (mono_get_eh_callbacks ()->mono_summarize_exception) {
6470 // FIXME: Push handles down into mini/mini-exceptions.c
6471 MonoException *exc = MONO_HANDLE_RAW (exc_handle);
6472 MonoThreadSummary out;
6473 mono_summarize_timeline_start ();
6474 mono_summarize_timeline_phase_log (MonoSummarySuspendHandshake);
6475 mono_summarize_timeline_phase_log (MonoSummaryUnmanagedStacks);
6476 mono_get_eh_callbacks ()->mono_summarize_exception (exc, &out);
6477 mono_summarize_timeline_phase_log (MonoSummaryManagedStacks);
6479 *portable_hash_out = (guint64) out.hashes.offset_free_hash;
6480 *unportable_hash_out = (guint64) out.hashes.offset_rich_hash;
6482 MonoStateWriter writer;
6483 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
6484 mono_state_writer_init (&writer, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
6485 mono_native_state_init (&writer);
6486 mono_summarize_timeline_phase_log (MonoSummaryStateWriter);
6487 gboolean first_thread_added = TRUE;
6488 mono_native_state_add_thread (&writer, &out, NULL, first_thread_added, TRUE);
6489 char *output = mono_native_state_free (&writer, FALSE);
6490 mono_summarize_timeline_phase_log (MonoSummaryStateWriterDone);
6491 result = mono_string_new_handle (mono_domain_get (), output, error);
6492 g_free (output);
6493 g_free (scratch);
6494 return result;
6496 #endif
6498 *portable_hash_out = 0;
6499 *unportable_hash_out = 0;
6500 result = mono_string_new_handle (mono_domain_get (), "", error);
6501 return result;
6504 void
6505 ves_icall_Mono_Runtime_SendMicrosoftTelemetry (const char *payload, guint64 portable_hash, guint64 unportable_hash, MonoError *error)
6507 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
6508 if (!mono_merp_enabled ())
6509 g_error ("Cannot send telemetry without registering parameters first");
6511 pid_t crashed_pid = getpid ();
6513 MonoStackHash hashes;
6514 memset (&hashes, 0, sizeof (MonoStackHash));
6515 hashes.offset_free_hash = portable_hash;
6516 hashes.offset_rich_hash = unportable_hash;
6518 const char *signal = "MANAGED_EXCEPTION";
6520 gboolean success = mono_merp_invoke (crashed_pid, signal, payload, &hashes);
6521 if (!success) {
6522 //g_assert_not_reached ();
6523 mono_error_set_generic_error (error, "System", "Exception", "We were unable to start the Microsoft Error Reporting client.");
6525 #else
6526 // Icall has platform check in managed too.
6527 g_assert_not_reached ();
6528 #endif
6531 void
6532 ves_icall_Mono_Runtime_DumpTelemetry (const char *payload, guint64 portable_hash, guint64 unportable_hash, MonoError *error)
6534 #ifndef DISABLE_CRASH_REPORTING
6535 MonoStackHash hashes;
6536 memset (&hashes, 0, sizeof (MonoStackHash));
6537 hashes.offset_free_hash = portable_hash;
6538 hashes.offset_rich_hash = unportable_hash;
6539 mono_crash_dump (payload, &hashes);
6540 #else
6541 return;
6542 #endif
6545 MonoStringHandle
6546 ves_icall_Mono_Runtime_DumpStateSingle (guint64 *portable_hash, guint64 *unportable_hash, MonoError *error)
6548 MonoStringHandle result;
6550 #ifndef DISABLE_CRASH_REPORTING
6551 MonoStackHash hashes;
6552 memset (&hashes, 0, sizeof (MonoStackHash));
6553 MonoContext *ctx = NULL;
6555 MonoThreadSummary this_thread;
6556 if (!mono_threads_summarize_one (&this_thread, ctx))
6557 return mono_string_new_handle (mono_domain_get (), "", error);
6559 *portable_hash = (guint64) this_thread.hashes.offset_free_hash;
6560 *unportable_hash = (guint64) this_thread.hashes.offset_rich_hash;
6562 MonoStateWriter writer;
6563 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
6564 mono_state_writer_init (&writer, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
6565 mono_native_state_init (&writer);
6566 gboolean first_thread_added = TRUE;
6567 mono_native_state_add_thread (&writer, &this_thread, NULL, first_thread_added, TRUE);
6568 char *output = mono_native_state_free (&writer, FALSE);
6569 result = mono_string_new_handle (mono_domain_get (), output, error);
6570 g_free (output);
6571 g_free (scratch);
6572 #else
6573 *portable_hash = 0;
6574 *unportable_hash = 0;
6575 result = mono_string_new_handle (mono_domain_get (), "", error);
6576 #endif
6578 return result;
6582 void
6583 ves_icall_Mono_Runtime_RegisterReportingForNativeLib (const char *path_suffix, const char *module_name)
6585 #ifndef DISABLE_CRASH_REPORTING
6586 if (mono_get_eh_callbacks ()->mono_register_native_library)
6587 mono_get_eh_callbacks ()->mono_register_native_library (path_suffix, module_name);
6588 #endif
6591 void
6592 ves_icall_Mono_Runtime_RegisterReportingForAllNativeLibs ()
6594 #ifndef DISABLE_CRASH_REPORTING
6595 if (mono_get_eh_callbacks ()->mono_allow_all_native_libraries)
6596 mono_get_eh_callbacks ()->mono_allow_all_native_libraries ();
6597 #endif
6600 void
6601 ves_icall_Mono_Runtime_EnableCrashReportingLog (const char *directory)
6603 #ifndef DISABLE_CRASH_REPORTING
6604 mono_summarize_set_timeline_dir (directory);
6605 #endif
6609 ves_icall_Mono_Runtime_CheckCrashReportingLog (const char *directory, MonoBoolean clear)
6611 int ret = 0;
6612 #ifndef DISABLE_CRASH_REPORTING
6613 ret = (int) mono_summarize_timeline_read_level (directory, clear != 0);
6614 #endif
6615 return ret;
6618 MonoStringHandle
6619 ves_icall_Mono_Runtime_DumpStateTotal (guint64 *portable_hash, guint64 *unportable_hash, MonoError *error)
6621 MonoStringHandle result;
6623 #ifndef DISABLE_CRASH_REPORTING
6624 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
6626 char *out;
6627 MonoStackHash hashes;
6628 memset (&hashes, 0, sizeof (MonoStackHash));
6629 MonoContext *ctx = NULL;
6631 while (!mono_dump_start ())
6632 g_usleep (1000); // wait around for other dump to finish
6634 mono_get_runtime_callbacks ()->install_state_summarizer ();
6636 mono_summarize_timeline_start ();
6638 gboolean success = mono_threads_summarize (ctx, &out, &hashes, TRUE, FALSE, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
6639 mono_summarize_timeline_phase_log (MonoSummaryCleanup);
6641 if (!success)
6642 return mono_string_new_handle (mono_domain_get (), "", error);
6644 *portable_hash = (guint64) hashes.offset_free_hash;
6645 *unportable_hash = (guint64) hashes.offset_rich_hash;
6646 result = mono_string_new_handle (mono_domain_get (), out, error);
6648 // out is now a pointer into garbage memory
6649 g_free (scratch);
6651 mono_summarize_timeline_phase_log (MonoSummaryDone);
6653 mono_dump_complete ();
6654 #else
6655 *portable_hash = 0;
6656 *unportable_hash = 0;
6657 result = mono_string_new_handle (mono_domain_get (), "", error);
6658 #endif
6660 return result;
6663 MonoBoolean
6664 ves_icall_System_Reflection_AssemblyName_ParseAssemblyName (const char *name, MonoAssemblyName *aname, MonoBoolean *is_version_defined_arg, MonoBoolean *is_token_defined_arg)
6666 gboolean is_version_defined = FALSE;
6667 gboolean is_token_defined = FALSE;
6668 gboolean result = FALSE;
6670 result = mono_assembly_name_parse_full (name, aname, TRUE, &is_version_defined, &is_token_defined);
6672 *is_version_defined_arg = (MonoBoolean)is_version_defined;
6673 *is_token_defined_arg = (MonoBoolean)is_token_defined;
6675 return result;
6678 MonoReflectionTypeHandle
6679 ves_icall_System_Reflection_RuntimeModule_GetGlobalType (MonoImage *image, MonoError *error)
6681 MonoDomain *domain = mono_domain_get ();
6682 MonoClass *klass;
6684 g_assert (image);
6686 MonoReflectionTypeHandle ret = MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6688 if (image_is_dynamic (image) && ((MonoDynamicImage*)image)->initial_image)
6689 /* These images do not have a global type */
6690 goto leave;
6692 klass = mono_class_get_checked (image, 1 | MONO_TOKEN_TYPE_DEF, error);
6693 goto_if_nok (error, leave);
6695 ret = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
6696 leave:
6697 return ret;
6700 void
6701 ves_icall_System_Reflection_RuntimeModule_GetGuidInternal (MonoImage *image, MonoArrayHandle guid_h, MonoError *error)
6703 g_assert (mono_array_handle_length (guid_h) == 16);
6705 if (!image->metadata_only) {
6706 g_assert (image->heap_guid.data);
6707 g_assert (image->heap_guid.size >= 16);
6709 MONO_ENTER_NO_SAFEPOINTS;
6710 guint8 *data = (guint8*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (guid_h), 1, 0);
6711 memcpy (data, (guint8*)image->heap_guid.data, 16);
6712 MONO_EXIT_NO_SAFEPOINTS;
6713 } else {
6714 MONO_ENTER_NO_SAFEPOINTS;
6715 guint8 *data = (guint8*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (guid_h), 1, 0);
6716 memset (data, 0, 16);
6717 MONO_EXIT_NO_SAFEPOINTS;
6721 #ifndef HOST_WIN32
6722 static inline gpointer
6723 mono_icall_module_get_hinstance (MonoImage *image)
6725 return (gpointer) (-1);
6727 #endif /* HOST_WIN32 */
6729 gpointer
6730 ves_icall_System_Reflection_RuntimeModule_GetHINSTANCE (MonoImage *image, MonoError *error)
6732 return mono_icall_module_get_hinstance (image);
6735 void
6736 ves_icall_System_Reflection_RuntimeModule_GetPEKind (MonoImage *image, gint32 *pe_kind, gint32 *machine, MonoError *error)
6738 if (image_is_dynamic (image)) {
6739 MonoDynamicImage *dyn = (MonoDynamicImage*)image;
6740 *pe_kind = dyn->pe_kind;
6741 *machine = dyn->machine;
6743 else {
6744 *pe_kind = (image->image_info->cli_cli_header.ch_flags & 0x3);
6745 *machine = image->image_info->cli_header.coff.coff_machine;
6749 gint32
6750 ves_icall_System_Reflection_RuntimeModule_GetMDStreamVersion (MonoImage *image, MonoError *error)
6752 return (image->md_version_major << 16) | (image->md_version_minor);
6755 MonoArrayHandle
6756 ves_icall_System_Reflection_RuntimeModule_InternalGetTypes (MonoImage *image, MonoError *error)
6758 MonoDomain *domain = mono_domain_get ();
6760 if (!image) {
6761 MonoArrayHandle arr = mono_array_new_handle (domain, mono_defaults.runtimetype_class, 0, error);
6762 return arr;
6763 } else {
6764 MonoArrayHandle exceptions = MONO_HANDLE_NEW (MonoArray, NULL);
6765 MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, FALSE, error);
6766 return_val_if_nok (error, MONO_HANDLE_CAST(MonoArray, NULL_HANDLE));
6768 int n = mono_array_handle_length (exceptions);
6769 MonoExceptionHandle ex = MONO_HANDLE_NEW (MonoException, NULL);
6770 for (int i = 0; i < n; ++i) {
6771 MONO_HANDLE_ARRAY_GETREF(ex, exceptions, i);
6772 if (!MONO_HANDLE_IS_NULL (ex)) {
6773 mono_error_set_exception_handle (error, ex);
6774 return MONO_HANDLE_CAST(MonoArray, NULL_HANDLE);
6777 return res;
6781 static gboolean
6782 mono_memberref_is_method (MonoImage *image, guint32 token)
6784 if (!image_is_dynamic (image)) {
6785 guint32 cols [MONO_MEMBERREF_SIZE];
6786 const char *sig;
6787 const MonoTableInfo *table = &image->tables [MONO_TABLE_MEMBERREF];
6788 int idx = mono_metadata_token_index (token) - 1;
6789 if (idx < 0 || table->rows <= idx) {
6790 return FALSE;
6792 mono_metadata_decode_row (table, idx, cols, MONO_MEMBERREF_SIZE);
6793 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6794 mono_metadata_decode_blob_size (sig, &sig);
6795 return (*sig != 0x6);
6796 } else {
6797 ERROR_DECL (error);
6798 MonoClass *handle_class;
6800 if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL, error)) {
6801 mono_error_cleanup (error); /* just probing, ignore error */
6802 return FALSE;
6805 return mono_defaults.methodhandle_class == handle_class;
6809 static MonoGenericInst *
6810 get_generic_inst_from_array_handle (MonoArrayHandle type_args)
6812 int type_argc = mono_array_handle_length (type_args);
6813 int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *);
6815 MonoGenericInst *ginst = (MonoGenericInst *)g_alloca (size);
6816 memset (ginst, 0, sizeof (MonoGenericInst));
6817 ginst->type_argc = type_argc;
6818 for (int i = 0; i < type_argc; i++) {
6819 MONO_HANDLE_ARRAY_GETVAL (ginst->type_argv[i], type_args, MonoType*, i);
6821 ginst->is_open = FALSE;
6822 for (int i = 0; i < type_argc; i++) {
6823 if (mono_class_is_open_constructed_type (ginst->type_argv[i])) {
6824 ginst->is_open = TRUE;
6825 break;
6829 return mono_metadata_get_canonical_generic_inst (ginst);
6832 static void
6833 init_generic_context_from_args_handles (MonoGenericContext *context, MonoArrayHandle type_args, MonoArrayHandle method_args)
6835 if (!MONO_HANDLE_IS_NULL (type_args)) {
6836 context->class_inst = get_generic_inst_from_array_handle (type_args);
6837 } else {
6838 context->class_inst = NULL;
6840 if (!MONO_HANDLE_IS_NULL (method_args)) {
6841 context->method_inst = get_generic_inst_from_array_handle (method_args);
6842 } else {
6843 context->method_inst = NULL;
6848 static MonoType*
6849 module_resolve_type_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6851 HANDLE_FUNCTION_ENTER ();
6852 error_init (error);
6853 MonoType *result = NULL;
6854 MonoClass *klass;
6855 int table = mono_metadata_token_table (token);
6856 int index = mono_metadata_token_index (token);
6857 MonoGenericContext context;
6859 *resolve_error = ResolveTokenError_Other;
6861 /* Validate token */
6862 if ((table != MONO_TABLE_TYPEDEF) && (table != MONO_TABLE_TYPEREF) &&
6863 (table != MONO_TABLE_TYPESPEC)) {
6864 *resolve_error = ResolveTokenError_BadTable;
6865 goto leave;
6868 if (image_is_dynamic (image)) {
6869 if ((table == MONO_TABLE_TYPEDEF) || (table == MONO_TABLE_TYPEREF)) {
6870 ERROR_DECL (inner_error);
6871 klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6872 mono_error_cleanup (inner_error);
6873 result = klass ? m_class_get_byval_arg (klass) : NULL;
6874 goto leave;
6877 init_generic_context_from_args_handles (&context, type_args, method_args);
6878 ERROR_DECL (inner_error);
6879 klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6880 mono_error_cleanup (inner_error);
6881 result = klass ? m_class_get_byval_arg (klass) : NULL;
6882 goto leave;
6885 if ((index <= 0) || (index > image->tables [table].rows)) {
6886 *resolve_error = ResolveTokenError_OutOfRange;
6887 goto leave;
6890 init_generic_context_from_args_handles (&context, type_args, method_args);
6891 klass = mono_class_get_checked (image, token, error);
6892 if (klass)
6893 klass = mono_class_inflate_generic_class_checked (klass, &context, error);
6894 goto_if_nok (error, leave);
6896 if (klass)
6897 result = m_class_get_byval_arg (klass);
6898 leave:
6899 HANDLE_FUNCTION_RETURN_VAL (result);
6902 MonoType*
6903 ves_icall_System_Reflection_RuntimeModule_ResolveTypeToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6905 return module_resolve_type_token (image, token, type_args, method_args, resolve_error, error);
6908 static MonoMethod*
6909 module_resolve_method_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6911 HANDLE_FUNCTION_ENTER ();
6912 error_init (error);
6913 MonoMethod *method = NULL;
6914 int table = mono_metadata_token_table (token);
6915 int index = mono_metadata_token_index (token);
6916 MonoGenericContext context;
6918 *resolve_error = ResolveTokenError_Other;
6920 /* Validate token */
6921 if ((table != MONO_TABLE_METHOD) && (table != MONO_TABLE_METHODSPEC) &&
6922 (table != MONO_TABLE_MEMBERREF)) {
6923 *resolve_error = ResolveTokenError_BadTable;
6924 goto leave;
6927 if (image_is_dynamic (image)) {
6928 if (table == MONO_TABLE_METHOD) {
6929 ERROR_DECL (inner_error);
6930 method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6931 mono_error_cleanup (inner_error);
6932 goto leave;
6935 if ((table == MONO_TABLE_MEMBERREF) && !(mono_memberref_is_method (image, token))) {
6936 *resolve_error = ResolveTokenError_BadTable;
6937 goto leave;
6940 init_generic_context_from_args_handles (&context, type_args, method_args);
6941 ERROR_DECL (inner_error);
6942 method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6943 mono_error_cleanup (inner_error);
6944 goto leave;
6947 if ((index <= 0) || (index > image->tables [table].rows)) {
6948 *resolve_error = ResolveTokenError_OutOfRange;
6949 goto leave;
6951 if ((table == MONO_TABLE_MEMBERREF) && (!mono_memberref_is_method (image, token))) {
6952 *resolve_error = ResolveTokenError_BadTable;
6953 goto leave;
6956 init_generic_context_from_args_handles (&context, type_args, method_args);
6957 method = mono_get_method_checked (image, token, NULL, &context, error);
6959 leave:
6960 HANDLE_FUNCTION_RETURN_VAL (method);
6963 MonoMethod*
6964 ves_icall_System_Reflection_RuntimeModule_ResolveMethodToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6966 return module_resolve_method_token (image, token, type_args, method_args, resolve_error, error);
6969 MonoStringHandle
6970 ves_icall_System_Reflection_RuntimeModule_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error, MonoError *error)
6972 int index = mono_metadata_token_index (token);
6974 *resolve_error = ResolveTokenError_Other;
6976 /* Validate token */
6977 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
6978 *resolve_error = ResolveTokenError_BadTable;
6979 return NULL_HANDLE_STRING;
6982 if (image_is_dynamic (image)) {
6983 ERROR_DECL (ignore_inner_error);
6984 // FIXME ignoring error
6985 // FIXME Push MONO_HANDLE_NEW to lower layers.
6986 MonoStringHandle result = MONO_HANDLE_NEW (MonoString, (MonoString*)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, ignore_inner_error));
6987 mono_error_cleanup (ignore_inner_error);
6988 return result;
6991 if ((index <= 0) || (index >= image->heap_us.size)) {
6992 *resolve_error = ResolveTokenError_OutOfRange;
6993 return NULL_HANDLE_STRING;
6996 /* FIXME: What to do if the index points into the middle of a string ? */
6997 return mono_ldstr_handle (mono_domain_get (), image, index, error);
7000 static MonoClassField*
7001 module_resolve_field_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
7003 HANDLE_FUNCTION_ENTER ();
7004 MonoClass *klass;
7005 int table = mono_metadata_token_table (token);
7006 int index = mono_metadata_token_index (token);
7007 MonoGenericContext context;
7008 MonoClassField *field = NULL;
7010 error_init (error);
7011 *resolve_error = ResolveTokenError_Other;
7013 /* Validate token */
7014 if ((table != MONO_TABLE_FIELD) && (table != MONO_TABLE_MEMBERREF)) {
7015 *resolve_error = ResolveTokenError_BadTable;
7016 goto leave;
7019 if (image_is_dynamic (image)) {
7020 if (table == MONO_TABLE_FIELD) {
7021 ERROR_DECL (inner_error);
7022 field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
7023 mono_error_cleanup (inner_error);
7024 goto leave;
7027 if (mono_memberref_is_method (image, token)) {
7028 *resolve_error = ResolveTokenError_BadTable;
7029 goto leave;
7032 init_generic_context_from_args_handles (&context, type_args, method_args);
7033 ERROR_DECL (inner_error);
7034 field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
7035 mono_error_cleanup (inner_error);
7036 goto leave;
7039 if ((index <= 0) || (index > image->tables [table].rows)) {
7040 *resolve_error = ResolveTokenError_OutOfRange;
7041 goto leave;
7043 if ((table == MONO_TABLE_MEMBERREF) && (mono_memberref_is_method (image, token))) {
7044 *resolve_error = ResolveTokenError_BadTable;
7045 goto leave;
7048 init_generic_context_from_args_handles (&context, type_args, method_args);
7049 field = mono_field_from_token_checked (image, token, &klass, &context, error);
7051 leave:
7052 HANDLE_FUNCTION_RETURN_VAL (field);
7055 MonoClassField*
7056 ves_icall_System_Reflection_RuntimeModule_ResolveFieldToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
7058 return module_resolve_field_token (image, token, type_args, method_args, resolve_error, error);
7061 MonoObjectHandle
7062 ves_icall_System_Reflection_RuntimeModule_ResolveMemberToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *error, MonoError *merror)
7064 int table = mono_metadata_token_table (token);
7066 *error = ResolveTokenError_Other;
7068 switch (table) {
7069 case MONO_TABLE_TYPEDEF:
7070 case MONO_TABLE_TYPEREF:
7071 case MONO_TABLE_TYPESPEC: {
7072 MonoType *t = module_resolve_type_token (image, token, type_args, method_args, error, merror);
7073 if (t) {
7074 return MONO_HANDLE_CAST (MonoObject, mono_type_get_object_handle (mono_domain_get (), t, merror));
7076 else
7077 return NULL_HANDLE;
7079 case MONO_TABLE_METHOD:
7080 case MONO_TABLE_METHODSPEC: {
7081 MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
7082 if (m) {
7083 return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
7084 } else
7085 return NULL_HANDLE;
7087 case MONO_TABLE_FIELD: {
7088 MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
7089 if (f) {
7090 return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
7092 else
7093 return NULL_HANDLE;
7095 case MONO_TABLE_MEMBERREF:
7096 if (mono_memberref_is_method (image, token)) {
7097 MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
7098 if (m) {
7099 return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
7100 } else
7101 return NULL_HANDLE;
7103 else {
7104 MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
7105 if (f) {
7106 return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
7108 else
7109 return NULL_HANDLE;
7111 break;
7113 default:
7114 *error = ResolveTokenError_BadTable;
7117 return NULL_HANDLE;
7120 MonoArrayHandle
7121 ves_icall_System_Reflection_RuntimeModule_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error, MonoError *error)
7123 int table = mono_metadata_token_table (token);
7124 int idx = mono_metadata_token_index (token);
7125 MonoTableInfo *tables = image->tables;
7126 guint32 sig, len;
7127 const char *ptr;
7129 *resolve_error = ResolveTokenError_OutOfRange;
7131 /* FIXME: Support other tables ? */
7132 if (table != MONO_TABLE_STANDALONESIG)
7133 return NULL_HANDLE_ARRAY;
7135 if (image_is_dynamic (image))
7136 return NULL_HANDLE_ARRAY;
7138 if ((idx == 0) || (idx > tables [MONO_TABLE_STANDALONESIG].rows))
7139 return NULL_HANDLE_ARRAY;
7141 sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
7143 ptr = mono_metadata_blob_heap (image, sig);
7144 len = mono_metadata_decode_blob_size (ptr, &ptr);
7146 MonoArrayHandle res = mono_array_new_handle (mono_domain_get (), mono_defaults.byte_class, len, error);
7147 return_val_if_nok (error, NULL_HANDLE_ARRAY);
7149 // FIXME MONO_ENTER_NO_SAFEPOINTS instead of pin/gchandle.
7151 uint32_t h;
7152 gpointer array_base = MONO_ARRAY_HANDLE_PIN (res, guint8, 0, &h);
7153 memcpy (array_base, ptr, len);
7154 mono_gchandle_free_internal (h);
7156 return res;
7159 static void
7160 check_for_invalid_type (MonoClass *klass, MonoError *error)
7162 char *name;
7164 error_init (error);
7166 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_TYPEDBYREF)
7167 return;
7169 name = mono_type_get_full_name (klass);
7170 mono_error_set_type_load_name (error, name, g_strdup (""), "");
7173 MonoReflectionTypeHandle
7174 ves_icall_RuntimeType_make_array_type (MonoReflectionTypeHandle ref_type, int rank, MonoError *error)
7176 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7178 MonoClass *klass = mono_class_from_mono_type_internal (type);
7179 check_for_invalid_type (klass, error);
7180 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
7182 MonoClass *aklass;
7183 if (rank == 0) //single dimension array
7184 aklass = mono_class_create_array (klass, 1);
7185 else
7186 aklass = mono_class_create_bounded_array (klass, rank, TRUE);
7188 if (mono_class_has_failure (aklass)) {
7189 mono_error_set_for_class_failure (error, aklass);
7190 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
7193 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
7194 return mono_type_get_object_handle (domain, m_class_get_byval_arg (aklass), error);
7197 MonoReflectionTypeHandle
7198 ves_icall_RuntimeType_make_byref_type (MonoReflectionTypeHandle ref_type, MonoError *error)
7200 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7202 MonoClass *klass = mono_class_from_mono_type_internal (type);
7203 mono_class_init_checked (klass, error);
7204 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
7206 check_for_invalid_type (klass, error);
7207 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
7209 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
7210 return mono_type_get_object_handle (domain, m_class_get_this_arg (klass), error);
7213 MonoReflectionTypeHandle
7214 ves_icall_RuntimeType_MakePointerType (MonoReflectionTypeHandle ref_type, MonoError *error)
7216 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
7217 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7218 MonoClass *klass = mono_class_from_mono_type_internal (type);
7219 mono_class_init_checked (klass, error);
7220 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
7222 check_for_invalid_type (klass, error);
7223 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
7225 MonoClass *pklass = mono_class_create_ptr (type);
7227 return mono_type_get_object_handle (domain, m_class_get_byval_arg (pklass), error);
7230 MonoObjectHandle
7231 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionTypeHandle ref_type, MonoObjectHandle target,
7232 MonoReflectionMethodHandle info, MonoBoolean throwOnBindFailure, MonoError *error)
7234 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7235 MonoClass *delegate_class = mono_class_from_mono_type_internal (type);
7236 MonoMethod *method = MONO_HANDLE_GETVAL (info, method);
7237 MonoMethodSignature *sig = mono_method_signature_internal (method);
7239 mono_class_init_checked (delegate_class, error);
7240 return_val_if_nok (error, NULL_HANDLE);
7242 if (!(m_class_get_parent (delegate_class) == mono_defaults.multicastdelegate_class)) {
7243 /* FIXME improve this exception message */
7244 mono_error_set_execution_engine (error, "file %s: line %d (%s): assertion failed: (%s)", __FILE__, __LINE__,
7245 __func__,
7246 "delegate_class->parent == mono_defaults.multicastdelegate_class");
7247 return NULL_HANDLE;
7250 if (mono_security_core_clr_enabled ()) {
7251 ERROR_DECL (security_error);
7252 if (!mono_security_core_clr_ensure_delegate_creation (method, security_error)) {
7253 if (throwOnBindFailure)
7254 mono_error_move (error, security_error);
7255 else
7256 mono_error_cleanup (security_error);
7257 return NULL_HANDLE;
7261 if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7262 if (!method->is_inflated) {
7263 mono_error_set_argument (error, "method", " Cannot bind to the target method because its signature differs from that of the delegate type");
7264 return NULL_HANDLE;
7268 MonoObjectHandle delegate = mono_object_new_handle (MONO_HANDLE_DOMAIN (ref_type), delegate_class, error);
7269 return_val_if_nok (error, NULL_HANDLE);
7271 if (!method_is_dynamic (method) && (!MONO_HANDLE_IS_NULL (target) && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass != mono_handle_class (target))) {
7272 method = mono_object_handle_get_virtual_method (target, method, error);
7273 return_val_if_nok (error, NULL_HANDLE);
7276 mono_delegate_ctor_with_method (delegate, target, NULL, method, error);
7277 return_val_if_nok (error, NULL_HANDLE);
7278 return delegate;
7281 MonoMulticastDelegateHandle
7282 ves_icall_System_Delegate_AllocDelegateLike_internal (MonoDelegateHandle delegate, MonoError *error)
7284 MonoClass *klass = mono_handle_class (delegate);
7285 g_assert (mono_class_has_parent (klass, mono_defaults.multicastdelegate_class));
7287 MonoMulticastDelegateHandle ret = MONO_HANDLE_CAST (MonoMulticastDelegate, mono_object_new_handle (MONO_HANDLE_DOMAIN (delegate), klass, error));
7288 return_val_if_nok (error, MONO_HANDLE_CAST (MonoMulticastDelegate, NULL_HANDLE));
7290 MONO_HANDLE_SETVAL (MONO_HANDLE_CAST (MonoDelegate, ret), invoke_impl, gpointer, mono_runtime_create_delegate_trampoline (klass));
7292 return ret;
7295 MonoReflectionMethodHandle
7296 ves_icall_System_Delegate_GetVirtualMethod_internal (MonoDelegateHandle delegate, MonoError *error)
7298 MonoObjectHandle delegate_target = MONO_HANDLE_NEW_GET (MonoObject, delegate, target);
7299 MonoMethod *m = mono_object_handle_get_virtual_method (delegate_target, MONO_HANDLE_GETVAL (delegate, method), error);
7300 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
7301 return mono_method_get_object_handle (mono_domain_get (), m, m->klass, error);
7304 /* System.Buffer */
7306 static gint32
7307 mono_array_get_byte_length (MonoArrayHandle array)
7309 int length;
7311 MonoClass * const klass = mono_handle_class (array);
7313 // This resembles mono_array_get_length, but adds the loop.
7315 if (mono_handle_array_has_bounds (array)) {
7316 length = 1;
7317 const int klass_rank = m_class_get_rank (klass);
7318 for (int i = 0; i < klass_rank; ++ i)
7319 length *= MONO_HANDLE_GETVAL (array, bounds [i].length);
7320 } else {
7321 length = mono_array_handle_length (array);
7324 switch (m_class_get_byval_arg (m_class_get_element_class (klass))->type) {
7325 case MONO_TYPE_I1:
7326 case MONO_TYPE_U1:
7327 case MONO_TYPE_BOOLEAN:
7328 return length;
7329 case MONO_TYPE_I2:
7330 case MONO_TYPE_U2:
7331 case MONO_TYPE_CHAR:
7332 return length << 1;
7333 case MONO_TYPE_I4:
7334 case MONO_TYPE_U4:
7335 case MONO_TYPE_R4:
7336 return length << 2;
7337 case MONO_TYPE_I:
7338 case MONO_TYPE_U:
7339 return length * sizeof (gpointer);
7340 case MONO_TYPE_I8:
7341 case MONO_TYPE_U8:
7342 case MONO_TYPE_R8:
7343 return length << 3;
7344 default:
7345 return -1;
7349 #ifndef ENABLE_NETCORE
7350 gint32
7351 ves_icall_System_Buffer_ByteLengthInternal (MonoArrayHandle array, MonoError* error)
7353 return mono_array_get_byte_length (array);
7356 void
7357 ves_icall_System_Buffer_MemcpyInternal (gpointer dest, gconstpointer src, gint32 count)
7359 memcpy (dest, src, count);
7362 MonoBoolean
7363 ves_icall_System_Buffer_BlockCopyInternal (MonoArrayHandle src, gint32 src_offset, MonoArrayHandle dest, gint32 dest_offset, gint32 count, MonoError* error)
7365 if (count < 0) {
7366 mono_error_set_argument (error, "count", "is negative");
7367 return FALSE;
7370 /* This is called directly from the class libraries without going through the managed wrapper */
7371 MONO_CHECK_ARG_NULL_HANDLE (src, FALSE);
7372 MONO_CHECK_ARG_NULL_HANDLE (dest, FALSE);
7374 /* watch out for integer overflow */
7375 if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
7376 return FALSE;
7378 MONO_ENTER_NO_SAFEPOINTS;
7380 guint8 const * const src_buf = (guint8*)MONO_HANDLE_RAW (src)->vector + src_offset;
7381 guint8* const dest_buf = (guint8*)MONO_HANDLE_RAW (dest)->vector + dest_offset;
7383 #if !HOST_WIN32
7385 // Windows memcpy is memmove and checks for overlap anyway, so skip
7386 // the check here that would not help.
7388 if (MONO_HANDLE_RAW (src) != MONO_HANDLE_RAW (dest))
7389 memcpy (dest_buf, src_buf, count);
7390 else
7391 #endif
7392 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
7394 MONO_EXIT_NO_SAFEPOINTS;
7396 return TRUE;
7398 #endif
7400 #ifndef DISABLE_REMOTING
7401 MonoObjectHandle
7402 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObjectHandle this_obj, MonoStringHandle class_name, MonoError *error)
7404 MonoDomain *domain = MONO_HANDLE_DOMAIN (this_obj);
7405 MonoRealProxyHandle rp = MONO_HANDLE_CAST (MonoRealProxy, this_obj);
7407 MonoObjectHandle res = mono_object_new_handle (domain, mono_defaults.transparent_proxy_class, error);
7408 return_val_if_nok (error, NULL_HANDLE);
7410 MonoTransparentProxyHandle tp = MONO_HANDLE_CAST (MonoTransparentProxy, res);
7412 MONO_HANDLE_SET (tp, rp, rp);
7414 MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
7415 MONO_HANDLE_GET (reftype, rp, class_to_proxy);
7416 MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
7417 MonoClass *klass = mono_class_from_mono_type_internal (type);
7419 // mono_remote_class_vtable cannot handle errors well, so force any loading error to occur early
7420 mono_class_setup_vtable (klass);
7421 if (mono_class_has_failure (klass)) {
7422 mono_error_set_for_class_failure (error, klass);
7423 return NULL_HANDLE;
7426 MonoObjectHandle remoting_obj = mono_object_handle_isinst (this_obj, mono_defaults.iremotingtypeinfo_class, error);
7427 return_val_if_nok (error, NULL_HANDLE);
7428 MONO_HANDLE_SETVAL (tp, custom_type_info, MonoBoolean, !MONO_HANDLE_IS_NULL (remoting_obj));
7430 MonoRemoteClass *remote_class = (MonoRemoteClass*)mono_remote_class (domain, class_name, klass, error);
7431 return_val_if_nok (error, NULL_HANDLE);
7432 MONO_HANDLE_SETVAL (tp, remote_class, MonoRemoteClass*, remote_class);
7434 MONO_HANDLE_SETVAL (res, vtable, MonoVTable*, (MonoVTable*)mono_remote_class_vtable (domain, remote_class, rp, error));
7435 return_val_if_nok (error, NULL_HANDLE);
7436 return res;
7439 MonoReflectionTypeHandle
7440 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxyHandle tp, MonoError *error)
7442 MonoRemoteClass *remote_class;
7444 g_assert (mono_handle_class (tp) == mono_defaults.transparent_proxy_class);
7445 remote_class = MONO_HANDLE_RAW (tp)->remote_class;
7446 g_assert (remote_class != NULL && remote_class->proxy_class != NULL);
7447 return mono_type_get_object_handle (mono_handle_domain (tp), m_class_get_byval_arg (remote_class->proxy_class), error);
7449 #endif
7451 /* System.Environment */
7453 MonoStringHandle
7454 ves_icall_System_Environment_get_UserName (MonoError *error)
7456 /* using glib is more portable */
7457 const gchar *user_name = g_get_user_name ();
7458 if (user_name != NULL)
7459 return mono_string_new_handle (mono_domain_get (), user_name, error);
7460 else
7461 return NULL_HANDLE_STRING;
7464 #ifndef HOST_WIN32
7465 static MonoStringHandle
7466 mono_icall_get_machine_name (MonoError *error)
7468 #if !defined(DISABLE_SOCKETS)
7469 MonoStringHandle result;
7470 char *buf;
7471 int n;
7472 #if defined _SC_HOST_NAME_MAX
7473 n = sysconf (_SC_HOST_NAME_MAX);
7474 if (n == -1)
7475 #endif
7476 n = 512;
7477 buf = (char*)g_malloc (n + 1);
7479 #if defined(HAVE_GETHOSTNAME)
7480 if (gethostname (buf, n) == 0){
7481 buf [n] = 0;
7482 int i;
7483 // try truncating the string at the first dot
7484 for (i = 0; i < n; i++) {
7485 if (buf [i] == '.') {
7486 buf [i] = 0;
7487 break;
7490 result = mono_string_new_handle (mono_domain_get (), buf, error);
7491 } else
7492 #endif
7493 result = MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
7495 g_free (buf);
7497 return result;
7498 #else
7499 return mono_string_new_handle (mono_domain_get (), "mono", error);
7500 #endif
7502 #endif /* !HOST_WIN32 */
7504 MonoStringHandle
7505 ves_icall_System_Environment_get_MachineName (MonoError *error)
7507 return mono_icall_get_machine_name (error);
7510 #ifndef HOST_WIN32
7511 static int
7512 mono_icall_get_platform (void)
7514 #if defined(__MACH__)
7515 /* OSX */
7517 // Notice that the value is hidden from user code, and only exposed
7518 // to mscorlib. This is due to Mono's Unix/MacOS code predating the
7519 // define and making assumptions based on Unix/128/4 values before there
7520 // was a MacOS define. Lots of code would assume that not-Unix meant
7521 // Windows, but in this case, it would be OSX.
7523 return 6;
7524 #else
7525 /* Unix */
7526 return 4;
7527 #endif
7529 #endif /* !HOST_WIN32 */
7532 ves_icall_System_Environment_get_Platform (void)
7534 return mono_icall_get_platform ();
7537 #ifndef HOST_WIN32
7538 static MonoStringHandle
7539 mono_icall_get_new_line (MonoError *error)
7541 return mono_string_new_handle (mono_domain_get (), "\n", error);
7543 #endif /* !HOST_WIN32 */
7545 #ifndef ENABLE_NETCORE
7546 MonoStringHandle
7547 ves_icall_System_Environment_get_NewLine (MonoError *error)
7549 return mono_icall_get_new_line (error);
7551 #endif
7553 #ifndef HOST_WIN32
7554 static inline MonoBoolean
7555 mono_icall_is_64bit_os (void)
7557 #if SIZEOF_VOID_P == 8
7558 return TRUE;
7559 #else
7560 #if defined(HAVE_SYS_UTSNAME_H)
7561 struct utsname name;
7563 if (uname (&name) >= 0) {
7564 return strcmp (name.machine, "x86_64") == 0 || strncmp (name.machine, "aarch64", 7) == 0 || strncmp (name.machine, "ppc64", 5) == 0 || strncmp (name.machine, "riscv64", 7) == 0;
7566 #endif
7567 return FALSE;
7568 #endif
7570 #endif /* !HOST_WIN32 */
7572 MonoBoolean
7573 ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
7575 return mono_icall_is_64bit_os ();
7578 MonoStringHandle
7579 ves_icall_System_Environment_GetEnvironmentVariable_native (const gchar *utf8_name, MonoError *error)
7581 gchar *value;
7583 if (utf8_name == NULL)
7584 return NULL_HANDLE_STRING;
7586 value = g_getenv (utf8_name);
7588 if (value == 0)
7589 return NULL_HANDLE_STRING;
7591 MonoStringHandle res = mono_string_new_handle (mono_domain_get (), value, error);
7592 g_free (value);
7593 return res;
7597 * There is no standard way to get at environ.
7599 #ifndef _MSC_VER
7600 #ifndef __MINGW32_VERSION
7601 #if defined(__APPLE__)
7602 #if defined (TARGET_OSX)
7603 /* Apple defines this in crt_externs.h but doesn't provide that header for
7604 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
7605 * in fact exist on all implementations (so far)
7607 G_BEGIN_DECLS
7608 gchar ***_NSGetEnviron(void);
7609 G_END_DECLS
7610 #define environ (*_NSGetEnviron())
7611 #else
7612 static char *mono_environ[1] = { NULL };
7613 #define environ mono_environ
7614 #endif /* defined (TARGET_OSX) */
7615 #else
7616 G_BEGIN_DECLS
7617 extern
7618 char **environ;
7619 G_END_DECLS
7620 #endif
7621 #endif
7622 #endif
7624 MonoArrayHandle
7625 ves_icall_System_Environment_GetCommandLineArgs (MonoError *error)
7627 MonoArrayHandle result = mono_runtime_get_main_args_handle (error);
7628 return result;
7631 #ifndef HOST_WIN32
7632 static MonoArrayHandle
7633 mono_icall_get_environment_variable_names (MonoError *error)
7635 MonoArrayHandle names;
7636 MonoDomain *domain;
7637 MonoStringHandle str;
7638 gchar **e, **parts;
7639 int n;
7641 n = 0;
7642 for (e = environ; *e != 0; ++ e)
7643 ++ n;
7645 domain = mono_domain_get ();
7646 names = mono_array_new_handle (domain, mono_defaults.string_class, n, error);
7647 return_val_if_nok (error, NULL_HANDLE_ARRAY);
7649 str = MONO_HANDLE_NEW (MonoString, NULL);
7650 n = 0;
7651 for (e = environ; *e != 0; ++ e) {
7652 parts = g_strsplit (*e, "=", 2);
7653 if (*parts != 0) {
7654 MonoString *s = mono_string_new_checked (domain, *parts, error);
7655 MONO_HANDLE_ASSIGN_RAW (str, s);
7656 if (!is_ok (error)) {
7657 g_strfreev (parts);
7658 return NULL_HANDLE_ARRAY;
7660 mono_array_handle_setref (names, n, str);
7663 g_strfreev (parts);
7665 ++ n;
7668 return names;
7670 #endif /* !HOST_WIN32 */
7672 MonoArrayHandle
7673 ves_icall_System_Environment_GetEnvironmentVariableNames (MonoError *error)
7675 return mono_icall_get_environment_variable_names (error);
7678 #ifndef ENABLE_NETCORE
7679 void
7680 ves_icall_System_Environment_InternalSetEnvironmentVariable (const gunichar2 *name, gint32 name_length,
7681 const gunichar2 *value, gint32 value_length, MonoError *error)
7683 #ifdef HOST_WIN32
7684 if (!value || !value_length || !value [0])
7685 value = NULL;
7687 SetEnvironmentVariableW (name, value);
7688 #else
7689 char *utf8_name = NULL;
7690 char *utf8_value = NULL;
7692 utf8_name = mono_utf16_to_utf8 (name, name_length, error); // FIXME: this should be ascii
7693 goto_if_nok (error, exit);
7695 if (!value || !value_length || !value [0]) {
7696 g_unsetenv (utf8_name);
7697 goto exit;
7700 utf8_value = mono_utf16_to_utf8 (value, value_length, error);
7701 goto_if_nok (error, exit);
7703 g_setenv (utf8_name, utf8_value, TRUE);
7704 exit:
7705 g_free (utf8_name);
7706 g_free (utf8_value);
7707 #endif
7709 #endif
7711 void
7712 ves_icall_System_Environment_Exit (int result)
7714 mono_environment_exitcode_set (result);
7716 if (!mono_runtime_try_shutdown ())
7717 mono_thread_exit ();
7719 #ifndef ENABLE_NETCORE
7720 /* Suspend all managed threads since the runtime is going away */
7721 mono_thread_suspend_all_other_threads ();
7722 #endif
7724 mono_runtime_quit_internal ();
7726 /* we may need to do some cleanup here... */
7727 exit (result);
7730 void
7731 ves_icall_System_Environment_FailFast (MonoStringHandle message, MonoExceptionHandle exception, MonoStringHandle errorSource, MonoError *error)
7733 if (MONO_HANDLE_IS_NULL (message)) {
7734 g_warning ("CLR: Managed code called FailFast without specifying a reason.");
7735 } else {
7736 char *msg = mono_string_handle_to_utf8 (message, error);
7737 g_warning ("CLR: Managed code called FailFast, saying \"%s\"", msg);
7738 #ifndef DISABLE_CRASH_REPORTING
7739 char *old_msg = mono_crash_save_failfast_msg (msg);
7740 g_free (old_msg);
7741 #else
7742 g_free (msg);
7743 #endif
7746 if (!MONO_HANDLE_IS_NULL (exception)) {
7747 mono_print_unhandled_exception_internal ((MonoObject *) MONO_HANDLE_RAW (exception));
7750 // NOTE: While this does trigger WER on Windows it doesn't quite provide all the
7751 // information in the error dump that CoreCLR would. On Windows 7+ we should call
7752 // RaiseFailFastException directly instead of relying on the C runtime doing it
7753 // for us and pass it as much information as possible. On Windows 8+ we can also
7754 // use the __fastfail intrinsic.
7755 abort ();
7758 #ifndef ENABLE_NETCORE
7759 MonoStringHandle
7760 ves_icall_System_Environment_GetGacPath (MonoError *error)
7762 return mono_string_new_handle (mono_domain_get (), mono_assembly_getrootdir (), error);
7764 #endif
7766 #ifndef HOST_WIN32
7767 static inline MonoStringHandle
7768 mono_icall_get_windows_folder_path (int folder, MonoError *error)
7770 error_init (error);
7771 g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
7772 return mono_string_new_handle (mono_domain_get (), "", error);
7774 #endif /* !HOST_WIN32 */
7776 #ifndef ENABLE_NETCORE
7777 MonoStringHandle
7778 ves_icall_System_Environment_GetWindowsFolderPath (int folder, MonoError *error)
7780 return mono_icall_get_windows_folder_path (folder, error);
7782 #endif
7784 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
7785 static MonoArrayHandle
7786 mono_icall_get_logical_drives (MonoError *error)
7788 gunichar2 buf [256], *ptr, *dname;
7789 gunichar2 *u16;
7790 guint initial_size = 127, size = 128;
7791 gint ndrives;
7792 MonoArrayHandle result;
7793 MonoStringHandle drivestr;
7794 MonoDomain *domain = mono_domain_get ();
7795 gint len;
7797 buf [0] = '\0';
7798 ptr = buf;
7800 while (size > initial_size) {
7801 size = (guint) mono_w32file_get_logical_drive (initial_size, ptr);
7802 if (size > initial_size) {
7803 if (ptr != buf)
7804 g_free (ptr);
7805 ptr = (gunichar2 *)g_malloc0 ((size + 1) * sizeof (gunichar2));
7806 initial_size = size;
7807 size++;
7811 /* Count strings */
7812 dname = ptr;
7813 ndrives = 0;
7814 do {
7815 while (*dname++);
7816 ndrives++;
7817 } while (*dname);
7819 dname = ptr;
7820 result = mono_array_new_handle (domain, mono_defaults.string_class, ndrives, error);
7821 goto_if_nok (error, leave);
7823 drivestr = MONO_HANDLE_NEW (MonoString, NULL);
7824 ndrives = 0;
7825 do {
7826 len = 0;
7827 u16 = dname;
7828 while (*u16) {
7829 u16++; len ++;
7831 MonoString *s = mono_string_new_utf16_checked (domain, dname, len, error);
7832 goto_if_nok (error, leave);
7833 MONO_HANDLE_ASSIGN_RAW (drivestr, s);
7835 mono_array_handle_setref (result, ndrives, drivestr);
7836 ndrives ++;
7837 while (*dname++);
7838 } while (*dname);
7840 leave:
7841 if (ptr != buf)
7842 g_free (ptr);
7844 return result;
7846 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
7848 #ifndef ENABLE_NETCORE
7849 MonoArrayHandle
7850 ves_icall_System_Environment_GetLogicalDrivesInternal (MonoError *error)
7852 return mono_icall_get_logical_drives (error);
7855 MonoStringHandle
7856 ves_icall_System_IO_DriveInfo_GetDriveFormat (const gunichar2 *path, gint32 path_length, MonoError *error)
7858 gunichar2 volume_name [MAX_PATH + 1];
7860 if (mono_w32file_get_file_system_type (path, volume_name, MAX_PATH + 1) == FALSE)
7861 return NULL_HANDLE_STRING;
7862 return mono_string_new_utf16_handle (mono_domain_get (), volume_name, g_utf16_len (volume_name), error);
7865 MonoStringHandle
7866 ves_icall_System_Environment_InternalGetHome (MonoError *error)
7868 const gchar *home_dir = g_get_home_dir ();
7869 if (home_dir != NULL)
7870 return mono_string_new_handle (mono_domain_get (), home_dir, error);
7871 else
7872 return NULL_HANDLE_STRING;
7875 static const char * const encodings [] = {
7876 (char *) 1,
7877 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
7878 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
7879 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
7880 (char *) 2,
7881 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
7882 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
7883 "x_unicode_2_0_utf_7",
7884 (char *) 3,
7885 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
7886 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
7887 (char *) 4,
7888 "utf_16", "UTF_16LE", "ucs_2", "unicode",
7889 "iso_10646_ucs2",
7890 (char *) 5,
7891 "unicodefffe", "utf_16be",
7892 (char *) 6,
7893 "iso_8859_1",
7894 (char *) 0
7898 * Returns the internal codepage, if the value of "int_code_page" is
7899 * 1 at entry, and we can not compute a suitable code page number,
7900 * returns the code page as a string
7902 MonoStringHandle
7903 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page, MonoError *error)
7905 error_init (error);
7906 const char *cset;
7907 const char *p;
7908 char *c;
7909 char *codepage = NULL;
7910 int code;
7911 int want_name = *int_code_page;
7912 int i;
7914 *int_code_page = -1;
7916 g_get_charset (&cset);
7917 c = codepage = g_strdup (cset);
7918 for (c = codepage; *c; c++){
7919 if (isascii (*c) && isalpha (*c))
7920 *c = tolower (*c);
7921 if (*c == '-')
7922 *c = '_';
7924 /* g_print ("charset: %s\n", cset); */
7926 /* handle some common aliases */
7927 p = encodings [0];
7928 code = 0;
7929 for (i = 0; p != 0; ){
7930 if ((gsize) p < 7){
7931 code = (gssize) p;
7932 p = encodings [++i];
7933 continue;
7935 if (strcmp (p, codepage) == 0){
7936 *int_code_page = code;
7937 break;
7939 p = encodings [++i];
7942 if (strstr (codepage, "utf_8") != NULL)
7943 *int_code_page |= 0x10000000;
7944 g_free (codepage);
7946 if (want_name && *int_code_page == -1)
7947 return mono_string_new_handle (mono_domain_get (), cset, error);
7948 return NULL_HANDLE_STRING;
7950 #endif
7952 MonoBoolean
7953 ves_icall_System_Environment_get_HasShutdownStarted (void)
7955 return mono_runtime_is_shutting_down () || mono_domain_is_unloading (mono_domain_get ());
7958 #ifndef HOST_WIN32
7960 #ifndef ENABLE_NETCORE
7961 void
7962 ves_icall_System_Environment_BroadcastSettingChange (MonoError *error)
7965 #endif
7967 #endif
7969 gint32
7970 ves_icall_System_Environment_get_TickCount (void)
7972 /* this will overflow after ~24 days */
7973 return (gint32) (mono_msec_boottime () & 0xffffffff);
7976 #if ENABLE_NETCORE
7977 gint64
7978 ves_icall_System_Environment_get_TickCount64 (void)
7980 return mono_msec_boottime ();
7982 #endif
7984 #ifndef ENABLE_NETCORE
7985 gint32
7986 ves_icall_System_Runtime_Versioning_VersioningHelper_GetRuntimeId (MonoError *error)
7988 return 9;
7990 #endif
7992 #ifndef DISABLE_REMOTING
7993 MonoBoolean
7994 ves_icall_IsTransparentProxy (MonoObjectHandle proxy, MonoError *error)
7996 if (MONO_HANDLE_IS_NULL (proxy))
7997 return 0;
7999 if (mono_class_is_transparent_proxy (mono_handle_class (proxy)))
8000 return 1;
8002 return 0;
8005 MonoReflectionMethodHandle
8006 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
8007 MonoReflectionTypeHandle rtype, MonoReflectionMethodHandle rmethod, MonoError *error)
8009 MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
8011 if (MONO_HANDLE_IS_NULL (rtype)) {
8012 mono_error_set_argument_null (error, "type", "");
8013 return ret;
8015 if (MONO_HANDLE_IS_NULL (rmethod)) {
8016 mono_error_set_argument_null (error, "method", "");
8017 return ret;
8020 MonoMethod *method = MONO_HANDLE_GETVAL (rmethod, method);
8021 MonoType *type = MONO_HANDLE_GETVAL (rtype, type);
8022 MonoClass *klass = mono_class_from_mono_type_internal (type);
8023 mono_class_init_checked (klass, error);
8024 return_val_if_nok (error, ret);
8026 if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass))
8027 return ret;
8029 if (method->flags & METHOD_ATTRIBUTE_STATIC)
8030 return ret;
8032 if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
8033 if (klass == method->klass || mono_class_is_subclass_of_internal (klass, method->klass, FALSE))
8034 ret = rmethod;
8035 return ret;
8038 mono_class_setup_vtable (klass);
8039 MonoMethod **vtable = m_class_get_vtable (klass);
8041 MonoMethod *res = NULL;
8042 if (mono_class_is_interface (method->klass)) {
8043 gboolean variance_used = FALSE;
8044 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
8045 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
8046 if (offs >= 0)
8047 res = vtable [offs + method->slot];
8048 } else {
8049 if (!(klass == method->klass || mono_class_is_subclass_of_internal (klass, method->klass, FALSE)))
8050 return ret;
8052 if (method->slot != -1)
8053 res = vtable [method->slot];
8056 if (!res)
8057 return ret;
8059 ret = mono_method_get_object_handle (mono_domain_get (), res, NULL, error);
8060 return ret;
8063 void
8064 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
8066 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
8067 MonoVTable *vtable = mono_class_vtable_checked (mono_domain_get (), klass, error);
8068 return_if_nok (error);
8070 mono_vtable_set_is_remote (vtable, enable);
8073 #else /* DISABLE_REMOTING */
8075 #ifndef ENABLE_NETCORE
8076 void
8077 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
8079 g_assert_not_reached ();
8081 #endif
8083 #endif
8085 #ifndef ENABLE_NETCORE
8086 MonoObjectHandle
8087 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionTypeHandle type, MonoError *error)
8089 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
8090 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
8091 mono_class_init_checked (klass, error);
8092 return_val_if_nok (error, NULL_HANDLE);
8094 if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || mono_class_is_abstract (klass)) {
8095 mono_error_set_argument (error, "type", "Type cannot be instantiated");
8096 return NULL_HANDLE;
8099 if (m_class_get_rank (klass) >= 1) {
8100 g_assert (m_class_get_rank (klass) == 1);
8101 return MONO_HANDLE_CAST (MonoObject, mono_array_new_handle (domain, m_class_get_element_class (klass), 0, error));
8102 } else {
8103 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8104 return_val_if_nok (error, NULL_HANDLE);
8106 /* Bypass remoting object creation check */
8107 return MONO_HANDLE_NEW (MonoObject, mono_object_new_alloc_specific_checked (vtable, error));
8111 MonoStringHandle
8112 ves_icall_System_IO_get_temp_path (MonoError *error)
8114 return mono_string_new_handle (mono_domain_get (), g_get_tmp_dir (), error);
8117 #if defined(ENABLE_MONODROID) || defined(ENABLE_MONOTOUCH) || defined(TARGET_WASM)
8119 // FIXME? Names should start "mono"?
8120 G_EXTERN_C gpointer CreateZStream (gint32 compress, MonoBoolean gzip, gpointer feeder, gpointer data);
8121 G_EXTERN_C gint32 CloseZStream (gpointer stream);
8122 G_EXTERN_C gint32 Flush (gpointer stream);
8123 G_EXTERN_C gint32 ReadZStream (gpointer stream, gpointer buffer, gint32 length);
8124 G_EXTERN_C gint32 WriteZStream (gpointer stream, gpointer buffer, gint32 length);
8126 gpointer
8127 ves_icall_System_IO_Compression_DeflateStreamNative_CreateZStream (gint32 compress, MonoBoolean gzip, gpointer feeder, gpointer data)
8129 #ifdef MONO_CROSS_COMPILE
8130 return NULL;
8131 #else
8132 return CreateZStream (compress, gzip, feeder, data);
8133 #endif
8136 gint32
8137 ves_icall_System_IO_Compression_DeflateStreamNative_CloseZStream (gpointer stream)
8139 #ifdef MONO_CROSS_COMPILE
8140 return 0;
8141 #else
8142 return CloseZStream (stream);
8143 #endif
8146 gint32
8147 ves_icall_System_IO_Compression_DeflateStreamNative_Flush (gpointer stream)
8149 #ifdef MONO_CROSS_COMPILE
8150 return 0;
8151 #else
8152 return Flush (stream);
8153 #endif
8156 gint32
8157 ves_icall_System_IO_Compression_DeflateStreamNative_ReadZStream (gpointer stream, gpointer buffer, gint32 length)
8159 #ifdef MONO_CROSS_COMPILE
8160 return 0;
8161 #else
8162 return ReadZStream (stream, buffer, length);
8163 #endif
8166 gint32
8167 ves_icall_System_IO_Compression_DeflateStreamNative_WriteZStream (gpointer stream, gpointer buffer, gint32 length)
8169 #ifdef MONO_CROSS_COMPILE
8170 return 0;
8171 #else
8172 return WriteZStream (stream, buffer, length);
8173 #endif
8176 #endif
8177 #endif /* ENABLE_NETCORE */
8179 #ifndef PLATFORM_NO_DRIVEINFO
8180 MonoBoolean
8181 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (const gunichar2 *path_name, gint32 path_name_length, guint64 *free_bytes_avail,
8182 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
8183 gint32 *error)
8185 g_assert (error);
8186 g_assert (free_bytes_avail);
8187 g_assert (total_number_of_bytes);
8188 g_assert (total_number_of_free_bytes);
8190 // FIXME check for embedded nuls here or managed
8192 *error = ERROR_SUCCESS;
8193 *free_bytes_avail = (guint64)-1;
8194 *total_number_of_bytes = (guint64)-1;
8195 *total_number_of_free_bytes = (guint64)-1;
8197 gboolean result = mono_w32file_get_disk_free_space (path_name, free_bytes_avail, total_number_of_bytes, total_number_of_free_bytes);
8198 if (!result)
8199 *error = mono_w32error_get_last ();
8201 return result;
8203 #endif /* PLATFORM_NO_DRIVEINFO */
8205 gpointer
8206 ves_icall_RuntimeMethodHandle_GetFunctionPointer (MonoMethod *method, MonoError *error)
8208 return mono_compile_method_checked (method, error);
8211 #ifndef ENABLE_NETCORE
8213 MonoStringHandle
8214 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (MonoError *error)
8216 gchar *path;
8218 const char *mono_cfg_dir = mono_get_config_dir ();
8219 if (!mono_cfg_dir)
8220 return mono_string_new_handle (mono_domain_get (), "", error);
8222 path = g_build_path (G_DIR_SEPARATOR_S, mono_cfg_dir, "mono", mono_get_runtime_info ()->framework_version, "machine.config", (const char*)NULL);
8224 mono_icall_make_platform_path (path);
8226 MonoStringHandle mcpath = mono_string_new_handle (mono_domain_get (), path, error);
8227 g_free (path);
8229 mono_error_assert_ok (error);
8231 return mcpath;
8234 MonoStringHandle
8235 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_app_config (MonoError *error)
8237 const gchar *app_config;
8238 MonoDomain *domain;
8239 gchar *config_file_name, *config_file_path;
8240 gsize len, config_file_path_length, config_ext_length;
8241 gchar *module;
8243 domain = mono_domain_get ();
8244 MonoStringHandle file = MONO_HANDLE_NEW (MonoString, domain->setup->configuration_file);
8245 if (MONO_HANDLE_IS_NULL (file) || MONO_HANDLE_GETVAL (file, length) == 0)
8246 return MONO_HANDLE_CAST (MonoString, mono_new_null ());
8248 // Retrieve config file and remove the extension
8249 config_file_name = mono_string_handle_to_utf8 (file, error);
8250 return_val_if_nok (error, MONO_HANDLE_CAST (MonoString, NULL_HANDLE));
8252 config_file_path = mono_portability_find_file (config_file_name, TRUE);
8253 if (!config_file_path)
8254 config_file_path = config_file_name;
8256 config_file_path_length = strlen (config_file_path);
8257 config_ext_length = strlen (".config");
8258 if (config_file_path_length <= config_ext_length) {
8259 if (config_file_name != config_file_path)
8260 g_free (config_file_name);
8261 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
8264 len = config_file_path_length - config_ext_length;
8265 module = (gchar *)g_malloc0 (len + 1);
8266 memcpy (module, config_file_path, len);
8267 // Get the config file from the module name
8268 app_config = mono_config_string_for_assembly_file (module);
8269 // Clean-up
8270 g_free (module);
8271 if (config_file_name != config_file_path)
8272 g_free (config_file_name);
8273 g_free (config_file_path);
8275 if (!app_config)
8276 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
8278 return mono_string_new_handle (mono_domain_get (), app_config, error);
8281 static MonoStringHandle
8282 get_bundled_machine_config (MonoError *error)
8284 const gchar *machine_config;
8286 machine_config = mono_get_machine_config ();
8288 if (!machine_config)
8289 return NULL_HANDLE_STRING;
8291 return mono_string_new_handle (mono_domain_get (), machine_config, error);
8294 MonoStringHandle
8295 ves_icall_System_Environment_get_bundled_machine_config (MonoError *error)
8297 return get_bundled_machine_config (error);
8300 MonoStringHandle
8301 ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
8303 return get_bundled_machine_config (error);
8306 MonoStringHandle
8307 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
8309 return get_bundled_machine_config (error);
8312 MonoStringHandle
8313 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (MonoError *error)
8315 const char *mono_cfg_dir = mono_get_config_dir ();
8316 if (!mono_cfg_dir)
8317 return mono_string_new_handle (mono_domain_get (), "", error);
8319 char *path = g_path_get_dirname (mono_cfg_dir);
8321 mono_icall_make_platform_path (path);
8323 MonoStringHandle ipath = mono_string_new_handle (mono_domain_get (), path, error);
8324 g_free (path);
8326 return ipath;
8329 MonoBoolean
8330 ves_icall_get_resources_ptr (MonoReflectionAssemblyHandle assembly, gpointer *result, gint32 *size, MonoError *error)
8332 MonoPEResourceDataEntry *entry;
8333 MonoImage *image;
8335 if (MONO_HANDLE_IS_NULL (assembly) || !result || !size)
8336 return FALSE;
8338 *result = NULL;
8339 *size = 0;
8340 MonoAssembly *assm = MONO_HANDLE_GETVAL (assembly, assembly);
8341 image = assm->image;
8342 entry = (MonoPEResourceDataEntry *)mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
8343 if (!entry)
8344 return FALSE;
8346 *result = mono_image_rva_map (image, entry->rde_data_offset);
8347 if (!(*result)) {
8348 g_free (entry);
8349 return FALSE;
8351 *size = entry->rde_size;
8352 g_free (entry);
8353 return TRUE;
8356 #endif /* ENABLE_NETCORE */
8358 MonoBoolean
8359 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (void)
8361 return mono_is_debugger_attached ();
8364 MonoBoolean
8365 ves_icall_System_Diagnostics_Debugger_IsLogging (void)
8367 return mono_get_runtime_callbacks ()->debug_log_is_enabled
8368 && mono_get_runtime_callbacks ()->debug_log_is_enabled ();
8371 void
8372 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoString *volatile* category, MonoString *volatile* message)
8374 if (mono_get_runtime_callbacks ()->debug_log)
8375 mono_get_runtime_callbacks ()->debug_log (level, *category, *message);
8378 #ifndef HOST_WIN32
8379 static inline void
8380 mono_icall_write_windows_debug_string (const gunichar2 *message)
8382 g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
8384 #endif /* !HOST_WIN32 */
8386 #ifndef ENABLE_NETCORE
8387 void
8388 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (const gunichar2 *message, MonoError *error)
8390 mono_icall_write_windows_debug_string (message);
8392 #endif
8394 /* Only used for value types */
8395 MonoObjectHandle
8396 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
8398 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
8399 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
8400 MonoClass *klass = mono_class_from_mono_type_internal (type);
8401 (void)klass;
8403 mono_class_init_checked (klass, error);
8404 return_val_if_nok (error, NULL_HANDLE);
8406 if (mono_class_is_nullable (klass))
8407 /* No arguments -> null */
8408 return NULL_HANDLE;
8410 return mono_object_new_handle (domain, klass, error);
8413 MonoReflectionMethodHandle
8414 ves_icall_RuntimeMethodInfo_get_base_method (MonoReflectionMethodHandle m, MonoBoolean definition, MonoError *error)
8416 MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
8418 MonoMethod *base = mono_method_get_base_method (method, definition, error);
8419 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
8420 if (base == method) {
8421 /* we want to short-circuit and return 'm' here. But we should
8422 return the same method object that
8423 mono_method_get_object_handle, below would return. Since
8424 that call takes NULL for the reftype argument, it will take
8425 base->klass as the reflected type for the MonoMethod. So we
8426 need to check that m also has base->klass as the reflected
8427 type. */
8428 MonoReflectionTypeHandle orig_reftype = MONO_HANDLE_NEW_GET (MonoReflectionType, m, reftype);
8429 MonoClass *orig_klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (orig_reftype, type));
8430 if (base->klass == orig_klass)
8431 return m;
8433 return mono_method_get_object_handle (mono_domain_get (), base, NULL, error);
8436 MonoStringHandle
8437 ves_icall_RuntimeMethodInfo_get_name (MonoReflectionMethodHandle m, MonoError *error)
8439 MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
8441 MonoStringHandle s = mono_string_new_handle (MONO_HANDLE_DOMAIN (m), method->name, error);
8442 return_val_if_nok (error, NULL_HANDLE_STRING);
8443 MONO_HANDLE_SET (m, name, s);
8444 return s;
8447 void
8448 ves_icall_System_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
8450 iter->sig = *(MonoMethodSignature**)argsp;
8452 g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
8453 g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
8455 iter->next_arg = 0;
8456 /* FIXME: it's not documented what start is exactly... */
8457 if (start) {
8458 iter->args = start;
8459 } else {
8460 iter->args = argsp + sizeof (gpointer);
8462 iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
8464 /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
8467 void
8468 ves_icall_System_ArgIterator_IntGetNextArg (MonoArgIterator *iter, MonoTypedRef *res)
8470 guint32 i, arg_size;
8471 gint32 align;
8473 i = iter->sig->sentinelpos + iter->next_arg;
8475 g_assert (i < iter->sig->param_count);
8477 res->type = iter->sig->params [i];
8478 res->klass = mono_class_from_mono_type_internal (res->type);
8479 arg_size = mono_type_stack_size (res->type, &align);
8480 #if defined(__arm__) || defined(__mips__)
8481 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
8482 #endif
8483 res->value = iter->args;
8484 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
8485 if (arg_size <= sizeof (gpointer)) {
8486 int dummy;
8487 int padding = arg_size - mono_type_size (res->type, &dummy);
8488 res->value = (guint8*)res->value + padding;
8490 #endif
8491 iter->args = (char*)iter->args + arg_size;
8492 iter->next_arg++;
8494 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res->type->type, arg_size, res->value); */
8497 void
8498 ves_icall_System_ArgIterator_IntGetNextArgWithType (MonoArgIterator *iter, MonoTypedRef *res, MonoType *type)
8500 guint32 i, arg_size;
8501 gint32 align;
8503 i = iter->sig->sentinelpos + iter->next_arg;
8505 g_assert (i < iter->sig->param_count);
8507 while (i < iter->sig->param_count) {
8508 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
8509 continue;
8510 res->type = iter->sig->params [i];
8511 res->klass = mono_class_from_mono_type_internal (res->type);
8512 /* FIXME: endianess issue... */
8513 arg_size = mono_type_stack_size (res->type, &align);
8514 #if defined(__arm__) || defined(__mips__)
8515 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
8516 #endif
8517 res->value = iter->args;
8518 iter->args = (char*)iter->args + arg_size;
8519 iter->next_arg++;
8520 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
8521 return;
8523 /* g_print ("arg type 0x%02x not found\n", res.type->type); */
8525 memset (res, 0, sizeof (MonoTypedRef));
8528 MonoType*
8529 ves_icall_System_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
8531 gint i;
8533 i = iter->sig->sentinelpos + iter->next_arg;
8535 g_assert (i < iter->sig->param_count);
8537 return iter->sig->params [i];
8540 MonoObjectHandle
8541 ves_icall_System_TypedReference_ToObject (MonoTypedRef* tref, MonoError *error)
8543 return typed_reference_to_object (tref, error);
8546 void
8547 ves_icall_System_TypedReference_InternalMakeTypedReference (MonoTypedRef *res, MonoObjectHandle target, MonoArrayHandle fields, MonoReflectionTypeHandle last_field, MonoError *error)
8549 MonoType *ftype = NULL;
8550 int i;
8552 memset (res, 0, sizeof (MonoTypedRef));
8554 g_assert (mono_array_handle_length (fields) > 0);
8556 (void)mono_handle_class (target);
8558 int offset = 0;
8559 for (i = 0; i < mono_array_handle_length (fields); ++i) {
8560 MonoClassField *f;
8561 MONO_HANDLE_ARRAY_GETVAL (f, fields, MonoClassField*, i);
8563 g_assert (f);
8565 if (i == 0)
8566 offset = f->offset;
8567 else
8568 offset += f->offset - sizeof (MonoObject);
8569 (void)mono_class_from_mono_type_internal (f->type);
8570 ftype = f->type;
8573 res->type = ftype;
8574 res->klass = mono_class_from_mono_type_internal (ftype);
8575 res->value = (guint8*)MONO_HANDLE_RAW (target) + offset;
8578 static void
8579 prelink_method (MonoMethod *method, MonoError *error)
8581 error_init (error);
8582 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8583 return;
8584 mono_lookup_pinvoke_call_internal (method, error);
8585 /* create the wrapper, too? */
8588 void
8589 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethodHandle method, MonoError *error)
8591 error_init (error);
8593 prelink_method (MONO_HANDLE_GETVAL (method, method), error);
8596 void
8597 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionTypeHandle type, MonoError *error)
8599 error_init (error);
8600 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
8601 MonoMethod* m;
8602 gpointer iter = NULL;
8604 mono_class_init_checked (klass, error);
8605 return_if_nok (error);
8607 while ((m = mono_class_get_methods (klass, &iter))) {
8608 prelink_method (m, error);
8609 return_if_nok (error);
8613 #ifndef ENABLE_NETCORE
8615 * used by System.Runtime.InteropServices.RuntimeInformation.(OS|Process)Architecture;
8616 * which use them in different ways for filling in an enum
8618 MonoStringHandle
8619 ves_icall_System_Runtime_InteropServices_RuntimeInformation_GetRuntimeArchitecture (MonoError *error)
8621 return mono_string_new_handle (mono_domain_get (), mono_config_get_cpu (), error);
8625 * used by System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform
8627 MonoStringHandle
8628 ves_icall_System_Runtime_InteropServices_RuntimeInformation_GetOSName (MonoError *error)
8630 return mono_string_new_handle (mono_domain_get (), mono_config_get_os (), error);
8632 #endif /* ENABLE_NETCORE */
8635 ves_icall_Interop_Sys_DoubleToString(double value, char *format, char *buffer, int bufferLength)
8637 #if defined(TARGET_ARM)
8638 /* workaround for faulty vcmp.f64 implementation on some 32bit ARM CPUs */
8639 guint64 bits = *(guint64 *) &value;
8640 if (bits == 0x1) { /* 4.9406564584124654E-324 */
8641 g_assert (!strcmp (format, "%.40e"));
8642 return snprintf (buffer, bufferLength, "%s", "4.9406564584124654417656879286822137236506e-324");
8643 } else if (bits == 0x4) { /* 2E-323 */
8644 g_assert (!strcmp (format, "%.40e"));
8645 return snprintf (buffer, bufferLength, "%s", "1.9762625833649861767062751714728854894602e-323");
8647 #endif
8649 return snprintf(buffer, bufferLength, format, value);
8652 void
8653 ves_icall_System_Runtime_RuntimeImports_ecvt_s(char *buffer, size_t sizeInBytes, double value, int count, int* dec, int* sign)
8655 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
8656 _ecvt_s(buffer, sizeInBytes, value, count, dec, sign);
8657 #endif
8661 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
8662 void
8663 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
8664 gint32 const **exponents,
8665 gunichar2 const **digitLowerTable,
8666 gunichar2 const **digitUpperTable,
8667 gint64 const **tenPowersList,
8668 gint32 const **decHexDigits)
8670 *mantissas = Formatter_MantissaBitsTable;
8671 *exponents = Formatter_TensExponentTable;
8672 *digitLowerTable = Formatter_DigitLowerTable;
8673 *digitUpperTable = Formatter_DigitUpperTable;
8674 *tenPowersList = Formatter_TenPowersList;
8675 *decHexDigits = Formatter_DecHexDigits;
8678 static gboolean
8679 add_modifier_to_array (MonoDomain *domain, MonoType *type, MonoArrayHandle dest, int dest_idx, MonoError *error)
8681 HANDLE_FUNCTION_ENTER ();
8682 error_init (error);
8683 MonoClass *klass = mono_class_from_mono_type_internal (type);
8685 MonoReflectionTypeHandle rt;
8686 rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
8687 goto_if_nok (error, leave);
8689 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rt);
8690 leave:
8691 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
8695 * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
8696 * and avoid useless allocations.
8698 static MonoArrayHandle
8699 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error)
8701 int i, count = 0;
8702 MonoDomain *domain = mono_domain_get ();
8704 int cmod_count = mono_type_custom_modifier_count (type);
8705 if (cmod_count == 0)
8706 goto fail;
8708 error_init (error);
8709 for (i = 0; i < cmod_count; ++i) {
8710 gboolean required;
8711 (void) mono_type_get_custom_modifier (type, i, &required, error);
8712 goto_if_nok (error, fail);
8713 if ((optional && !required) || (!optional && required))
8714 count++;
8716 if (!count)
8717 goto fail;
8719 MonoArrayHandle res;
8720 res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
8721 goto_if_nok (error, fail);
8722 count = 0;
8723 for (i = 0; i < cmod_count; ++i) {
8724 gboolean required;
8725 MonoType *cmod_type = mono_type_get_custom_modifier (type, i, &required, error);
8726 goto_if_nok (error, fail);
8727 if ((optional && !required) || (!optional && required)) {
8728 if (!add_modifier_to_array (domain, cmod_type, res, count, error))
8729 goto fail;
8730 count++;
8733 return res;
8734 fail:
8735 return MONO_HANDLE_NEW (MonoArray, NULL);
8738 MonoArrayHandle
8739 ves_icall_RuntimeParameterInfo_GetTypeModifiers (MonoReflectionTypeHandle rt, MonoObjectHandle member, int pos, MonoBoolean optional, MonoError *error)
8741 error_init (error);
8742 MonoType *type = MONO_HANDLE_GETVAL (rt, type);
8743 MonoClass *member_class = mono_handle_class (member);
8744 MonoMethod *method = NULL;
8745 MonoImage *image;
8746 MonoMethodSignature *sig;
8748 if (mono_class_is_reflection_method_or_constructor (member_class)) {
8749 method = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionMethod, member), method);
8750 } else if (m_class_get_image (member_class) == mono_defaults.corlib && !strcmp ("RuntimePropertyInfo", m_class_get_name (member_class))) {
8751 MonoProperty *prop = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionProperty, member), property);
8752 if (!(method = prop->get))
8753 method = prop->set;
8754 g_assert (method);
8755 } else {
8756 char *type_name = mono_type_get_full_name (member_class);
8757 mono_error_set_not_supported (error, "Custom modifiers on a ParamInfo with member %s are not supported", type_name);
8758 g_free (type_name);
8759 return NULL_HANDLE_ARRAY;
8762 image = m_class_get_image (method->klass);
8763 sig = mono_method_signature_internal (method);
8764 if (pos == -1)
8765 type = sig->ret;
8766 else
8767 type = sig->params [pos];
8769 return type_array_from_modifiers (image, type, optional, error);
8772 static MonoType*
8773 get_property_type (MonoProperty *prop)
8775 MonoMethodSignature *sig;
8776 if (prop->get) {
8777 sig = mono_method_signature_internal (prop->get);
8778 return sig->ret;
8779 } else if (prop->set) {
8780 sig = mono_method_signature_internal (prop->set);
8781 return sig->params [sig->param_count - 1];
8783 return NULL;
8786 MonoArrayHandle
8787 ves_icall_RuntimePropertyInfo_GetTypeModifiers (MonoReflectionPropertyHandle property, MonoBoolean optional, MonoError *error)
8789 error_init (error);
8790 MonoProperty *prop = MONO_HANDLE_GETVAL (property, property);
8791 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
8792 MonoType *type = get_property_type (prop);
8793 MonoImage *image = m_class_get_image (klass);
8795 if (!type)
8796 return NULL_HANDLE_ARRAY;
8797 return type_array_from_modifiers (image, type, optional, error);
8801 *Construct a MonoType suited to be used to decode a constant blob object.
8803 * @type is the target type which will be constructed
8804 * @blob_type is the blob type, for example, that comes from the constant table
8805 * @real_type is the expected constructed type.
8807 static void
8808 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
8810 type->type = blob_type;
8811 type->data.klass = NULL;
8812 if (blob_type == MONO_TYPE_CLASS)
8813 type->data.klass = mono_defaults.object_class;
8814 else if (real_type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (real_type->data.klass)) {
8815 /* For enums, we need to use the base type */
8816 type->type = MONO_TYPE_VALUETYPE;
8817 type->data.klass = mono_class_from_mono_type_internal (real_type);
8818 } else
8819 type->data.klass = mono_class_from_mono_type_internal (real_type);
8822 MonoObjectHandle
8823 ves_icall_property_info_get_default_value (MonoReflectionPropertyHandle property_handle, MonoError* error)
8825 MonoReflectionProperty* property = MONO_HANDLE_RAW (property_handle);
8827 MonoType blob_type;
8828 MonoProperty *prop = property->property;
8829 MonoType *type = get_property_type (prop);
8830 MonoDomain *domain = mono_object_domain (property);
8831 MonoTypeEnum def_type;
8832 const char *def_value;
8834 mono_class_init_internal (prop->parent);
8836 if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT)) {
8837 mono_error_set_invalid_operation (error, NULL);
8838 return NULL_HANDLE;
8841 def_value = mono_class_get_property_default_value (prop, &def_type);
8843 mono_type_from_blob_type (&blob_type, def_type, type);
8845 return mono_get_object_from_blob (domain, &blob_type, def_value, MONO_HANDLE_NEW (MonoString, NULL), error);
8848 MonoBoolean
8849 ves_icall_MonoCustomAttrs_IsDefinedInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, MonoError *error)
8851 MonoClass *attr_class = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (attr_type, type));
8853 mono_class_init_checked (attr_class, error);
8854 return_val_if_nok (error, FALSE);
8856 MonoCustomAttrInfo *cinfo = mono_reflection_get_custom_attrs_info_checked (obj, error);
8857 return_val_if_nok (error, FALSE);
8859 if (!cinfo)
8860 return FALSE;
8861 gboolean found = mono_custom_attrs_has_attr (cinfo, attr_class);
8862 if (!cinfo->cached)
8863 mono_custom_attrs_free (cinfo);
8864 return found;
8867 MonoArrayHandle
8868 ves_icall_MonoCustomAttrs_GetCustomAttributesInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, MonoBoolean pseudoattrs, MonoError *error)
8870 MonoClass *attr_class;
8871 if (MONO_HANDLE_IS_NULL (attr_type))
8872 attr_class = NULL;
8873 else
8874 attr_class = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (attr_type, type));
8876 if (attr_class) {
8877 mono_class_init_checked (attr_class, error);
8878 return_val_if_nok (error, NULL_HANDLE_ARRAY);
8881 return mono_reflection_get_custom_attrs_by_type_handle (obj, attr_class, error);
8884 MonoArrayHandle
8885 ves_icall_MonoCustomAttrs_GetCustomAttributesDataInternal (MonoObjectHandle obj, MonoError *error)
8887 return mono_reflection_get_custom_attrs_data_checked (obj, error);
8891 MonoStringHandle
8892 ves_icall_Mono_Runtime_GetDisplayName (MonoError *error)
8894 char *info;
8895 MonoStringHandle display_name;
8897 error_init (error);
8898 info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
8899 display_name = mono_string_new_handle (mono_domain_get (), info, error);
8900 g_free (info);
8901 return display_name;
8904 #ifndef HOST_WIN32
8905 static gint32
8906 mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
8908 return WAIT_TIMEOUT;
8910 #endif /* !HOST_WIN32 */
8912 #ifndef ENABLE_NETCORE
8913 gint32
8914 ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle (gpointer handle, gint32 milliseconds)
8916 return mono_icall_wait_for_input_idle (handle, milliseconds);
8919 gint32
8920 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcessId (void)
8922 return mono_process_current_pid ();
8925 MonoBoolean
8926 ves_icall_Mono_TlsProviderFactory_IsBtlsSupported (void)
8928 #if HAVE_BTLS
8929 return TRUE;
8930 #else
8931 return FALSE;
8932 #endif
8934 #endif /* ENABLE_NETCORE */
8936 #ifndef DISABLE_COM
8939 ves_icall_System_Runtime_InteropServices_Marshal_GetHRForException_WinRT(MonoExceptionHandle ex, MonoError *error)
8941 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetHRForException_WinRT internal call is not implemented.");
8942 return 0;
8945 MonoObjectHandle
8946 ves_icall_System_Runtime_InteropServices_Marshal_GetNativeActivationFactory(MonoObjectHandle type, MonoError *error)
8948 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetNativeActivationFactory internal call is not implemented.");
8949 return NULL_HANDLE;
8952 void*
8953 ves_icall_System_Runtime_InteropServices_Marshal_GetRawIUnknownForComObjectNoAddRef(MonoObjectHandle obj, MonoError *error)
8955 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetRawIUnknownForComObjectNoAddRef internal call is not implemented.");
8956 return NULL;
8959 MonoObjectHandle
8960 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_GetRestrictedErrorInfo(MonoError *error)
8962 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.GetRestrictedErrorInfo internal call is not implemented.");
8963 return NULL_HANDLE;
8966 MonoBoolean
8967 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoOriginateLanguageException (int ierr, MonoStringHandle message, void* languageException, MonoError *error)
8969 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoOriginateLanguageException internal call is not implemented.");
8970 return FALSE;
8973 void
8974 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoReportUnhandledError (MonoObjectHandle oerr, MonoError *error)
8976 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoReportUnhandledError internal call is not implemented.");
8980 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsCreateString(MonoStringHandle sourceString, int length, void** hstring, MonoError *error)
8982 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString internal call is not implemented.");
8983 return 0;
8987 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsDeleteString(void* hstring, MonoError *error)
8989 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString internal call is not implemented.");
8990 return 0;
8993 mono_unichar2*
8994 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsGetStringRawBuffer(void* hstring, unsigned* length, MonoError *error)
8996 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsGetStringRawBuffer internal call is not implemented.");
8997 return NULL;
9000 #endif
9002 #if !ENABLE_NETCORE
9004 void
9005 ves_icall_System_IO_LogcatTextWriter_Log (const char *appname, gint32 level, const char *message)
9007 g_log (appname, (GLogLevelFlags)level, "%s", message);
9010 #endif
9012 static const MonoIcallTableCallbacks *icall_table;
9013 static mono_mutex_t icall_mutex;
9014 static GHashTable *icall_hash = NULL;
9016 typedef struct _MonoIcallHashTableValue {
9017 gconstpointer method;
9018 guint32 flags;
9019 } MonoIcallHashTableValue;
9021 void
9022 mono_install_icall_table_callbacks (const MonoIcallTableCallbacks *cb)
9024 g_assert (cb->version == MONO_ICALL_TABLE_CALLBACKS_VERSION);
9025 icall_table = cb;
9028 void
9029 mono_icall_init (void)
9031 #ifndef DISABLE_ICALL_TABLES
9032 mono_icall_table_init ();
9033 #endif
9034 icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
9035 mono_os_mutex_init (&icall_mutex);
9038 static void
9039 mono_icall_lock (void)
9041 mono_locks_os_acquire (&icall_mutex, IcallLock);
9044 static void
9045 mono_icall_unlock (void)
9047 mono_locks_os_release (&icall_mutex, IcallLock);
9050 void
9051 mono_icall_cleanup (void)
9053 g_hash_table_destroy (icall_hash);
9054 mono_os_mutex_destroy (&icall_mutex);
9057 static void
9058 add_internal_call_with_flags (const char *name, gconstpointer method, guint32 flags)
9060 char *key = g_strdup (name);
9061 MonoIcallHashTableValue *value = g_new (MonoIcallHashTableValue, 1);
9062 if (key && value) {
9063 value->method = method;
9064 value->flags = flags;
9066 mono_icall_lock ();
9067 g_hash_table_insert (icall_hash, key, (gpointer)value);
9068 mono_icall_unlock ();
9073 * mono_add_internal_call:
9074 * \param name method specification to surface to the managed world
9075 * \param method pointer to a C method to invoke when the method is called
9077 * This method surfaces the C function pointed by \p method as a method
9078 * that has been surfaced in managed code with the method specified in
9079 * \p name as an internal call.
9081 * Internal calls are surfaced to all app domains loaded and they are
9082 * accessibly by a type with the specified name.
9084 * You must provide a fully qualified type name, that is namespaces
9085 * and type name, followed by a colon and the method name, with an
9086 * optional signature to bind.
9088 * For example, the following are all valid declarations:
9090 * \c MyApp.Services.ScriptService:Accelerate
9092 * \c MyApp.Services.ScriptService:Slowdown(int,bool)
9094 * You use method parameters in cases where there might be more than
9095 * one surface method to managed code. That way you can register different
9096 * internal calls for different method overloads.
9098 * The internal calls are invoked with no marshalling. This means that .NET
9099 * types like \c System.String are exposed as \c MonoString* parameters. This is
9100 * different than the way that strings are surfaced in P/Invoke.
9102 * For more information on how the parameters are marshalled, see the
9103 * <a href="http://www.mono-project.com/docs/advanced/embedding/">Mono Embedding</a>
9104 * page.
9106 * See the <a href="mono-api-methods.html#method-desc">Method Description</a>
9107 * reference for more information on the format of method descriptions.
9109 void
9110 mono_add_internal_call (const char *name, gconstpointer method)
9112 mono_add_internal_call_with_flags (name, method, FALSE);
9116 * mono_dangerous_add_raw_internal_call:
9117 * \param name method specification to surface to the managed world
9118 * \param method pointer to a C method to invoke when the method is called
9120 * Similar to \c mono_add_internal_call but with more requirements for correct
9121 * operation.
9123 * A thread running a dangerous raw internal call will avoid a thread state
9124 * transition on entry and exit, but it must take responsiblity for cooperating
9125 * with the Mono runtime.
9127 * The \p method must NOT:
9129 * Run for an unbounded amount of time without calling the mono runtime.
9130 * Additionally, the method must switch to GC Safe mode to perform all blocking
9131 * operations: performing blocking I/O, taking locks, etc.
9134 void
9135 mono_dangerous_add_raw_internal_call (const char *name, gconstpointer method)
9137 mono_add_internal_call_with_flags (name, method, TRUE);
9141 * mono_add_internal_call_with_flags:
9142 * \param name method specification to surface to the managed world
9143 * \param method pointer to a C method to invoke when the method is called
9144 * \param cooperative if \c TRUE, run icall in GC Unsafe (cooperatively suspended) mode,
9145 * otherwise GC Safe (blocking)
9147 * Like \c mono_add_internal_call, but if \p cooperative is \c TRUE the added
9148 * icall promises that it will use the coopertive API to inform the runtime
9149 * when it is running blocking operations, that it will not run for unbounded
9150 * amounts of time without safepointing, and that it will not hold managed
9151 * object references across suspend safepoints.
9153 * If \p cooperative is \c FALSE, run the icall in GC Safe mode - the icall may
9154 * block. The icall must obey the GC Safe rules, e.g. it must not touch
9155 * unpinned managed memory.
9158 void
9159 mono_add_internal_call_with_flags (const char *name, gconstpointer method, gboolean cooperative)
9161 add_internal_call_with_flags (name, method, cooperative ? MONO_ICALL_FLAGS_COOPERATIVE : MONO_ICALL_FLAGS_FOREIGN);
9164 void
9165 mono_add_internal_call_internal (const char *name, gconstpointer method)
9167 mono_add_internal_call_with_flags (name, method, TRUE);
9171 * we should probably export this as an helper (handle nested types).
9172 * Returns the number of chars written in buf.
9174 static int
9175 concat_class_name (char *buf, int bufsize, MonoClass *klass)
9177 int nspacelen, cnamelen;
9178 nspacelen = strlen (m_class_get_name_space (klass));
9179 cnamelen = strlen (m_class_get_name (klass));
9180 if (nspacelen + cnamelen + 2 > bufsize)
9181 return 0;
9182 if (nspacelen) {
9183 memcpy (buf, m_class_get_name_space (klass), nspacelen);
9184 buf [nspacelen ++] = '.';
9186 memcpy (buf + nspacelen, m_class_get_name (klass), cnamelen);
9187 buf [nspacelen + cnamelen] = 0;
9188 return nspacelen + cnamelen;
9191 static void
9192 no_icall_table (void)
9194 g_assert_not_reached ();
9197 gboolean
9198 mono_is_missing_icall_addr (gconstpointer addr)
9200 return addr == NULL || addr == no_icall_table;
9204 * Returns either NULL or no_icall_table for missing icalls.
9206 gconstpointer
9207 mono_lookup_internal_call_full_with_flags (MonoMethod *method, gboolean warn_on_missing, guint32 *flags)
9209 char *sigstart = NULL;
9210 char *tmpsig = NULL;
9211 char mname [2048];
9212 char *classname = NULL;
9213 int typelen = 0, mlen, siglen;
9214 gconstpointer res = NULL;
9215 gboolean locked = FALSE;
9217 g_assert (method != NULL);
9219 if (method->is_inflated)
9220 method = ((MonoMethodInflated *) method)->declaring;
9222 if (m_class_get_nested_in (method->klass)) {
9223 int pos = concat_class_name (mname, sizeof (mname)-2, m_class_get_nested_in (method->klass));
9224 if (!pos)
9225 goto exit;
9227 mname [pos++] = '/';
9228 mname [pos] = 0;
9230 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
9231 if (!typelen)
9232 goto exit;
9234 typelen += pos;
9235 } else {
9236 typelen = concat_class_name (mname, sizeof (mname), method->klass);
9237 if (!typelen)
9238 goto exit;
9241 classname = g_strdup (mname);
9243 mname [typelen] = ':';
9244 mname [typelen + 1] = ':';
9246 mlen = strlen (method->name);
9247 memcpy (mname + typelen + 2, method->name, mlen);
9248 sigstart = mname + typelen + 2 + mlen;
9249 *sigstart = 0;
9251 tmpsig = mono_signature_get_desc (mono_method_signature_internal (method), TRUE);
9252 siglen = strlen (tmpsig);
9253 if (typelen + mlen + siglen + 6 > sizeof (mname))
9254 goto exit;
9256 sigstart [0] = '(';
9257 memcpy (sigstart + 1, tmpsig, siglen);
9258 sigstart [siglen + 1] = ')';
9259 sigstart [siglen + 2] = 0;
9261 /* mono_marshal_get_native_wrapper () depends on this */
9262 if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor")) {
9263 res = (gconstpointer)ves_icall_System_String_ctor_RedirectToCreateString;
9264 goto exit;
9267 mono_icall_lock ();
9268 locked = TRUE;
9270 res = g_hash_table_lookup (icall_hash, mname);
9271 if (res) {
9272 MonoIcallHashTableValue *value = (MonoIcallHashTableValue *)res;
9273 if (flags)
9274 *flags = value->flags;
9275 res = value->method;
9276 goto exit;
9279 /* try without signature */
9280 *sigstart = 0;
9281 res = g_hash_table_lookup (icall_hash, mname);
9282 if (res) {
9283 MonoIcallHashTableValue *value = (MonoIcallHashTableValue *)res;
9284 if (flags)
9285 *flags = value->flags;
9286 res = value->method;
9287 goto exit;
9290 if (!icall_table) {
9291 /* Fail only when the result is actually used */
9292 res = (gconstpointer)no_icall_table;
9293 goto exit;
9294 } else {
9295 gboolean uses_handles = FALSE;
9296 g_assert (icall_table->lookup);
9297 res = icall_table->lookup (method, classname, sigstart - mlen, sigstart, &uses_handles);
9298 if (res && flags && uses_handles)
9299 *flags = *flags | MONO_ICALL_FLAGS_USES_HANDLES;
9300 mono_icall_unlock ();
9301 locked = FALSE;
9303 if (res)
9304 goto exit;
9306 if (warn_on_missing) {
9307 g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
9308 g_print ("\nYour mono runtime and class libraries are out of sync.\n");
9309 g_print ("The out of sync library is: %s\n", m_class_get_image (method->klass)->name);
9310 g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
9311 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");
9312 g_print ("If you see other errors or faults after this message they are probably related\n");
9313 g_print ("and you need to fix your mono install first.\n");
9316 res = NULL;
9319 exit:
9320 if (locked)
9321 mono_icall_unlock ();
9322 g_free (classname);
9323 g_free (tmpsig);
9324 return res;
9328 * mono_lookup_internal_call_full:
9329 * \param method the method to look up
9330 * \param uses_handles out argument if method needs handles around managed objects.
9331 * \returns a pointer to the icall code for the given method. If
9332 * \p uses_handles is not NULL, it will be set to TRUE if the method
9333 * needs managed objects wrapped using the infrastructure in handle.h
9335 * If the method is not found, warns and returns NULL.
9337 gconstpointer
9338 mono_lookup_internal_call_full (MonoMethod *method, gboolean warn_on_missing, mono_bool *uses_handles, mono_bool *foreign)
9340 if (uses_handles)
9341 *uses_handles = FALSE;
9342 if (foreign)
9343 *foreign = FALSE;
9345 guint32 flags = MONO_ICALL_FLAGS_NONE;
9346 gconstpointer addr = mono_lookup_internal_call_full_with_flags (method, warn_on_missing, &flags);
9348 if (uses_handles && (flags & MONO_ICALL_FLAGS_USES_HANDLES))
9349 *uses_handles = TRUE;
9350 if (foreign && (flags & MONO_ICALL_FLAGS_FOREIGN))
9351 *foreign = TRUE;
9352 return addr;
9356 * mono_lookup_internal_call:
9358 gpointer
9359 mono_lookup_internal_call (MonoMethod *method)
9361 return (gpointer)mono_lookup_internal_call_full (method, TRUE, NULL, NULL);
9365 * mono_lookup_icall_symbol:
9367 * Given the icall METHOD, returns its C symbol.
9369 const char*
9370 mono_lookup_icall_symbol (MonoMethod *m)
9372 if (!icall_table)
9373 return NULL;
9375 g_assert (icall_table->lookup_icall_symbol);
9376 gpointer func;
9377 func = (gpointer)mono_lookup_internal_call_full (m, FALSE, NULL, NULL);
9378 if (!func)
9379 return NULL;
9380 return icall_table->lookup_icall_symbol (func);
9383 #if defined(TARGET_WIN32) && defined(TARGET_X86)
9385 * Under windows, the default pinvoke calling convention is STDCALL but
9386 * we need CDECL.
9388 #define MONO_ICALL_SIGNATURE_CALL_CONVENTION MONO_CALL_C
9389 #else
9390 #define MONO_ICALL_SIGNATURE_CALL_CONVENTION 0
9391 #endif
9393 // Storage for these enums is pointer-sized as it gets replaced with MonoType*.
9395 // mono_create_icall_signatures depends on this order. Handle with care.
9396 // It is alphabetical.
9397 typedef enum ICallSigType {
9398 ICALL_SIG_TYPE_bool = 0x00,
9399 ICALL_SIG_TYPE_boolean = ICALL_SIG_TYPE_bool,
9400 ICALL_SIG_TYPE_double = 0x01,
9401 ICALL_SIG_TYPE_float = 0x02,
9402 ICALL_SIG_TYPE_int = 0x03,
9403 ICALL_SIG_TYPE_int16 = 0x04,
9404 ICALL_SIG_TYPE_int32 = 0x05,
9405 ICALL_SIG_TYPE_int8 = 0x06,
9406 ICALL_SIG_TYPE_long = 0x07,
9407 ICALL_SIG_TYPE_obj = 0x08,
9408 ICALL_SIG_TYPE_object = ICALL_SIG_TYPE_obj,
9409 ICALL_SIG_TYPE_ptr = ICALL_SIG_TYPE_int,
9410 ICALL_SIG_TYPE_ptrref = 0x09,
9411 ICALL_SIG_TYPE_string = 0x0A,
9412 ICALL_SIG_TYPE_uint16 = 0x0B,
9413 ICALL_SIG_TYPE_uint32 = 0x0C,
9414 ICALL_SIG_TYPE_uint8 = 0x0D,
9415 ICALL_SIG_TYPE_ulong = 0x0E,
9416 ICALL_SIG_TYPE_void = 0x0F,
9417 } ICallSigType;
9419 #define ICALL_SIG_TYPES_1(a) ICALL_SIG_TYPE_ ## a,
9420 #define ICALL_SIG_TYPES_2(a, b) ICALL_SIG_TYPES_1 (a ) ICALL_SIG_TYPES_1 (b)
9421 #define ICALL_SIG_TYPES_3(a, b, c) ICALL_SIG_TYPES_2 (a, b ) ICALL_SIG_TYPES_1 (c)
9422 #define ICALL_SIG_TYPES_4(a, b, c, d) ICALL_SIG_TYPES_3 (a, b, c ) ICALL_SIG_TYPES_1 (d)
9423 #define ICALL_SIG_TYPES_5(a, b, c, d, e) ICALL_SIG_TYPES_4 (a, b, c, d ) ICALL_SIG_TYPES_1 (e)
9424 #define ICALL_SIG_TYPES_6(a, b, c, d, e, f) ICALL_SIG_TYPES_5 (a, b, c, d, e) ICALL_SIG_TYPES_1 (f)
9425 #define ICALL_SIG_TYPES_7(a, b, c, d, e, f, g) ICALL_SIG_TYPES_6 (a, b, c, d, e, f) ICALL_SIG_TYPES_1 (g)
9426 #define ICALL_SIG_TYPES_8(a, b, c, d, e, f, g, h) ICALL_SIG_TYPES_7 (a, b, c, d, e, f, g) ICALL_SIG_TYPES_1 (h)
9428 #define ICALL_SIG_TYPES(n, types) ICALL_SIG_TYPES_ ## n types
9430 // A scheme to make these const would be nice.
9431 static struct {
9432 #define ICALL_SIG(n, xtypes) \
9433 struct { \
9434 MonoMethodSignature sig; \
9435 gsize types [n]; \
9436 } ICALL_SIG_NAME (n, xtypes);
9437 ICALL_SIGS
9438 MonoMethodSignature end; // terminal zeroed element
9439 } mono_icall_signatures = {
9440 #undef ICALL_SIG
9441 #define ICALL_SIG(n, types) { { \
9442 0, /* ret */ \
9443 n, /* param_count */ \
9444 -1, /* sentinelpos */ \
9445 0, /* generic_param_count */ \
9446 MONO_ICALL_SIGNATURE_CALL_CONVENTION, \
9447 0, /* hasthis */ \
9448 0, /* explicit_this */ \
9449 1, /* pinvoke */ \
9450 0, /* is_inflated */ \
9451 0, /* has_type_parameters */ \
9452 }, /* possible gap here, depending on MONO_ZERO_LEN_ARRAY */ \
9453 { ICALL_SIG_TYPES (n, types) } }, /* params and ret */
9454 ICALL_SIGS
9457 #undef ICALL_SIG
9458 #define ICALL_SIG(n, types) MonoMethodSignature * const ICALL_SIG_NAME (n, types) = &mono_icall_signatures.ICALL_SIG_NAME (n, types).sig;
9459 ICALL_SIGS
9460 #undef ICALL_SIG
9462 void
9463 mono_create_icall_signatures (void)
9465 // Fixup the mostly statically initialized icall signatures.
9466 // x = m_class_get_byval_arg (x)
9467 // Initialize ret with params [0] and params [i] with params [i + 1].
9468 // ptrref is special
9470 // FIXME This is a bit obscure.
9472 typedef MonoMethodSignature G_MAY_ALIAS MonoMethodSignature_a;
9473 typedef gsize G_MAY_ALIAS gsize_a;
9475 MonoType * const lookup [ ] = {
9476 m_class_get_byval_arg (mono_defaults.boolean_class), // ICALL_SIG_TYPE_bool
9477 m_class_get_byval_arg (mono_defaults.double_class), // ICALL_SIG_TYPE_double
9478 m_class_get_byval_arg (mono_defaults.single_class), // ICALL_SIG_TYPE_float
9479 m_class_get_byval_arg (mono_defaults.int_class), // ICALL_SIG_TYPE_int
9480 m_class_get_byval_arg (mono_defaults.int16_class), // ICALL_SIG_TYPE_int16
9481 m_class_get_byval_arg (mono_defaults.int32_class), // ICALL_SIG_TYPE_int32
9482 m_class_get_byval_arg (mono_defaults.sbyte_class), // ICALL_SIG_TYPE_int8
9483 m_class_get_byval_arg (mono_defaults.int64_class), // ICALL_SIG_TYPE_long
9484 m_class_get_byval_arg (mono_defaults.object_class), // ICALL_SIG_TYPE_obj
9485 mono_class_get_byref_type (mono_defaults.int_class), // ICALL_SIG_TYPE_ptrref
9486 m_class_get_byval_arg (mono_defaults.string_class), // ICALL_SIG_TYPE_string
9487 m_class_get_byval_arg (mono_defaults.uint16_class), // ICALL_SIG_TYPE_uint16
9488 m_class_get_byval_arg (mono_defaults.uint32_class), // ICALL_SIG_TYPE_uint32
9489 m_class_get_byval_arg (mono_defaults.byte_class), // ICALL_SIG_TYPE_uint8
9490 m_class_get_byval_arg (mono_defaults.uint64_class), // ICALL_SIG_TYPE_ulong
9491 m_class_get_byval_arg (mono_defaults.void_class), // ICALL_SIG_TYPE_void
9494 MonoMethodSignature_a *sig = (MonoMethodSignature*)&mono_icall_signatures;
9495 int n;
9496 while ((n = sig->param_count)) {
9497 --sig->param_count; // remove ret
9498 gsize_a *types = (gsize*)(sig + 1);
9499 for (int i = 0; i < n; ++i) {
9500 gsize index = *types++;
9501 g_assert (index < G_N_ELEMENTS (lookup));
9502 // Casts on next line are attempt to follow strict aliasing rules,
9503 // to ensure reading from *types precedes writing
9504 // to params [].
9505 *(gsize*)(i ? &sig->params [i - 1] : &sig->ret) = (gsize)lookup [index];
9507 sig = (MonoMethodSignature*)types;
9511 void
9512 mono_register_jit_icall_info (MonoJitICallInfo *info, gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean avoid_wrapper, const char *c_symbol)
9514 // Duplicate initialization is allowed and racy, assuming it is equivalent.
9516 info->name = name;
9517 info->func = func;
9518 info->sig = sig;
9519 info->c_symbol = c_symbol;
9521 // Fill in wrapper ahead of time, to just be func, to avoid
9522 // later initializing it to anything else. So therefore, no wrapper.
9523 if (avoid_wrapper) {
9524 info->wrapper = func;
9525 } else {
9526 // Leave it alone in case of a race.
9531 ves_icall_System_GC_GetCollectionCount (int generation)
9533 return mono_gc_collection_count (generation);
9537 ves_icall_System_GC_GetGeneration (MonoObjectHandle object, MonoError *error)
9539 return mono_gc_get_generation (MONO_HANDLE_RAW (object));
9543 ves_icall_System_GC_GetMaxGeneration (void)
9545 return mono_gc_max_generation ();
9548 gint64
9549 ves_icall_System_GC_GetAllocatedBytesForCurrentThread (void)
9551 return mono_gc_get_allocated_bytes_for_current_thread ();
9554 #ifdef ENABLE_NETCORE
9555 guint64
9556 ves_icall_System_GC_GetTotalAllocatedBytes (MonoBoolean precise, MonoError* error)
9558 return mono_gc_get_total_allocated_bytes (precise);
9560 #endif
9562 void
9563 ves_icall_System_GC_RecordPressure (gint64 value)
9565 mono_gc_add_memory_pressure (value);
9568 gint64
9569 ves_icall_System_Diagnostics_Stopwatch_GetTimestamp (void)
9571 return mono_100ns_ticks ();
9574 gint64
9575 ves_icall_System_Threading_Timer_GetTimeMonotonic (void)
9577 return mono_100ns_ticks ();
9580 gint64
9581 ves_icall_System_DateTime_GetSystemTimeAsFileTime (void)
9583 return mono_100ns_datetime ();
9587 ves_icall_System_Threading_Thread_SystemMaxStackSize (void)
9589 return mono_thread_info_get_system_max_stack_size ();
9592 MonoBoolean
9593 ves_icall_System_Threading_Thread_YieldInternal (void)
9595 mono_threads_platform_yield ();
9596 return TRUE;
9599 gint32
9600 ves_icall_System_Environment_get_ProcessorCount (void)
9602 return mono_cpu_count ();
9605 #if defined(ENABLE_MONODROID)
9607 G_EXTERN_C gpointer CreateNLSocket (void);
9608 G_EXTERN_C gint32 ReadEvents (gpointer sock, gpointer buffer, gint32 count, gint32 size);
9609 G_EXTERN_C gpointer CloseNLSocket (gpointer sock);
9611 gpointer
9612 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CreateNLSocket (void)
9614 return CreateNLSocket ();
9617 gint32
9618 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_ReadEvents (gpointer sock, gpointer buffer, gint32 count, gint32 size)
9620 return ReadEvents (sock, buffer, count, size);
9623 gpointer
9624 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CloseNLSocket (gpointer sock)
9626 return CloseNLSocket (sock);
9629 #endif
9631 // Generate wrappers.
9633 #define ICALL_TYPE(id,name,first) /* nothing */
9634 #define ICALL(id,name,func) /* nothing */
9635 #define NOHANDLES(inner) /* nothing */
9637 #define MONO_HANDLE_REGISTER_ICALL(func, ret, nargs, argtypes) MONO_HANDLE_REGISTER_ICALL_IMPLEMENT (func, ret, nargs, argtypes)
9639 // Some native functions are exposed via multiple managed names.
9640 // Producing a wrapper for these results in duplicate wrappers with the same names,
9641 // which fails to compile. Do not produce such duplicate wrappers. Alternatively,
9642 // a one line native function with a different name that calls the main one could be used.
9643 // i.e. the wrapper would also have a different name.
9644 #define HANDLES_REUSE_WRAPPER(...) /* nothing */
9646 #define HANDLES(id, name, func, ret, nargs, argtypes) \
9647 MONO_HANDLE_DECLARE (id, name, func, ret, nargs, argtypes); \
9648 MONO_HANDLE_IMPLEMENT (id, name, func, ret, nargs, argtypes)
9650 #include "metadata/icall-def.h"
9652 #undef HANDLES
9653 #undef HANDLES_REUSE_WRAPPER
9654 #undef ICALL_TYPE
9655 #undef ICALL
9656 #undef NOHANDLES
9657 #undef MONO_HANDLE_REGISTER_ICALL