[metadata] Fix leaks when handling a few attributes (#16675)
[mono-project.git] / mono / metadata / icall.c
blob4b536fa2fd57e805d65746882df71cbe0c174b7e
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/mono-route.h>
60 #include <mono/metadata/w32socket.h>
61 #include <mono/metadata/mono-endian.h>
62 #include <mono/metadata/tokentype.h>
63 #include <mono/metadata/metadata-internals.h>
64 #include <mono/metadata/class-internals.h>
65 #include <mono/metadata/class-init.h>
66 #include <mono/metadata/reflection-internals.h>
67 #include <mono/metadata/marshal.h>
68 #include <mono/metadata/gc-internals.h>
69 #include <mono/metadata/mono-gc.h>
70 #include <mono/metadata/rand.h>
71 #include <mono/metadata/appdomain-icalls.h>
72 #include <mono/metadata/string-icalls.h>
73 #include <mono/metadata/debug-helpers.h>
74 #include <mono/metadata/w32process.h>
75 #include <mono/metadata/environment.h>
76 #include <mono/metadata/profiler-private.h>
77 #include <mono/metadata/locales.h>
78 #include <mono/metadata/filewatcher.h>
79 #include <mono/metadata/security.h>
80 #include <mono/metadata/mono-config.h>
81 #include <mono/metadata/cil-coff.h>
82 #include <mono/metadata/number-formatter.h>
83 #include <mono/metadata/security-manager.h>
84 #include <mono/metadata/security-core-clr.h>
85 #include <mono/metadata/mono-perfcounters.h>
86 #include <mono/metadata/mono-debug.h>
87 #include <mono/metadata/mono-ptr-array.h>
88 #include <mono/metadata/verify-internals.h>
89 #include <mono/metadata/runtime.h>
90 #include <mono/metadata/file-mmap.h>
91 #include <mono/metadata/seq-points-data.h>
92 #include <mono/metadata/icall-table.h>
93 #include <mono/metadata/handle.h>
94 #include <mono/metadata/w32mutex.h>
95 #include <mono/metadata/w32semaphore.h>
96 #include <mono/metadata/w32event.h>
97 #include <mono/metadata/abi-details.h>
98 #include <mono/metadata/loader-internals.h>
99 #include <mono/utils/monobitset.h>
100 #include <mono/utils/mono-time.h>
101 #include <mono/utils/mono-proclib.h>
102 #include <mono/utils/mono-string.h>
103 #include <mono/utils/mono-error-internals.h>
104 #include <mono/utils/mono-mmap.h>
105 #include <mono/utils/mono-io-portability.h>
106 #include <mono/utils/mono-digest.h>
107 #include <mono/utils/bsearch.h>
108 #include <mono/utils/mono-os-mutex.h>
109 #include <mono/utils/mono-threads.h>
110 #include <mono/metadata/w32error.h>
111 #include <mono/utils/w32api.h>
112 #include <mono/utils/mono-merp.h>
113 #include <mono/utils/mono-state.h>
114 #include <mono/utils/mono-logger-internals.h>
115 #include <mono/utils/mono-math.h>
116 #if !defined(HOST_WIN32) && defined(HAVE_SYS_UTSNAME_H)
117 #include <sys/utsname.h>
118 #endif
119 #include "icall-decl.h"
120 #include "mono/utils/mono-threads-coop.h"
121 #include "mono/metadata/icall-signatures.h"
123 //#define MONO_DEBUG_ICALLARRAY
125 #ifdef MONO_DEBUG_ICALLARRAY
127 static char debug_icallarray; // 0:uninitialized 1:true 2:false
129 static gboolean
130 icallarray_print_enabled (void)
132 if (!debug_icallarray)
133 debug_icallarray = MONO_TRACE_IS_TRACED (G_LOG_LEVEL_DEBUG, MONO_TRACE_ICALLARRAY) ? 1 : 2;
134 return debug_icallarray == 1;
137 static void
138 icallarray_print (const char *format, ...)
140 if (!icallarray_print_enabled ())
141 return;
142 va_list args;
143 va_start (args, format);
144 g_printv (format, args);
145 va_end (args);
148 #else
149 #define icallarray_print_enabled() (FALSE)
150 #define icallarray_print(...) /* nothing */
151 #endif
153 /* Lazy class loading functions */
154 static GENERATE_GET_CLASS_WITH_CACHE (module, "System.Reflection", "Module")
156 static void
157 array_set_value_impl (MonoArrayHandle arr, MonoObjectHandle value, guint32 pos, gboolean strict_enums, gboolean strict_signs, MonoError *error);
159 static MonoArrayHandle
160 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error);
162 static inline MonoBoolean
163 is_generic_parameter (MonoType *type)
165 return !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR);
168 #ifndef HOST_WIN32
169 static inline void
170 mono_icall_make_platform_path (gchar *path)
172 return;
175 static inline const gchar *
176 mono_icall_get_file_path_prefix (const gchar *path)
178 return "file://";
180 #endif /* HOST_WIN32 */
182 #if MONO_LLVM_LOADED
184 static
185 MonoJitICallInfos mono_jit_icall_info;
187 MonoJitICallInfos*
188 mono_get_jit_icall_info (void)
190 return &mono_jit_icall_info;
193 #else
195 MonoJitICallInfos mono_jit_icall_info;
197 #endif
199 MonoObjectHandle
200 ves_icall_System_Array_GetValueImpl (MonoArrayHandle array, guint32 pos, MonoError *error)
202 MonoClass * const array_class = mono_handle_class (array);
203 MonoClass * const element_class = m_class_get_element_class (array_class);
205 #ifdef ENABLE_NETCORE
206 if (m_class_is_native_pointer (element_class)) {
207 mono_error_set_not_supported (error, NULL);
208 return NULL_HANDLE;
210 #endif
212 if (m_class_is_valuetype (element_class)) {
213 gsize element_size = mono_array_element_size (array_class);
214 gpointer element_address = mono_array_addr_with_size_fast (MONO_HANDLE_RAW (array), element_size, (gsize)pos);
215 return mono_value_box_handle (MONO_HANDLE_DOMAIN (array), element_class, element_address, error);
217 MonoObjectHandle result = mono_new_null ();
218 mono_handle_array_getref (result, array, pos);
219 return result;
222 MonoObjectHandle
223 ves_icall_System_Array_GetValue (MonoArrayHandle arr, MonoArrayHandle indices, MonoError *error)
225 MONO_CHECK_ARG_NULL_HANDLE (indices, NULL_HANDLE);
227 MonoClass * const indices_class = mono_handle_class (indices);
228 MonoClass * const array_class = mono_handle_class (arr);
230 g_assert (m_class_get_rank (indices_class) == 1);
232 if (MONO_HANDLE_GETVAL (indices, bounds) || MONO_HANDLE_GETVAL (indices, max_length) != m_class_get_rank (array_class)) {
233 mono_error_set_argument (error, NULL, NULL);
234 return NULL_HANDLE;
237 gint32 index = 0;
239 if (!MONO_HANDLE_GETVAL (arr, bounds)) {
240 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, 0);
241 if (index < 0 || index >= MONO_HANDLE_GETVAL (arr, max_length)) {
242 mono_error_set_index_out_of_range (error);
243 return NULL_HANDLE;
246 return ves_icall_System_Array_GetValueImpl (arr, index, error);
249 for (gint32 i = 0; i < m_class_get_rank (array_class); i++) {
250 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, i);
251 if ((index < MONO_HANDLE_GETVAL (arr, bounds [i].lower_bound)) ||
252 (index >= (mono_array_lower_bound_t)MONO_HANDLE_GETVAL (arr, bounds [i].length) + MONO_HANDLE_GETVAL (arr, bounds [i].lower_bound))) {
253 mono_error_set_index_out_of_range (error);
254 return NULL_HANDLE;
258 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, 0);
259 gint32 pos = index - MONO_HANDLE_GETVAL (arr, bounds [0].lower_bound);
260 for (gint32 i = 1; i < m_class_get_rank (array_class); i++) {
261 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, i);
262 pos = pos * MONO_HANDLE_GETVAL (arr, bounds [i].length) + index -
263 MONO_HANDLE_GETVAL (arr, bounds [i].lower_bound);
266 return ves_icall_System_Array_GetValueImpl (arr, pos, error);
269 void
270 ves_icall_System_Array_SetValueImpl (MonoArrayHandle arr, MonoObjectHandle value, guint32 pos, MonoError *error)
272 array_set_value_impl (arr, value, pos, FALSE, TRUE, error);
275 static inline void
276 set_invalid_cast (MonoError *error, MonoClass *src_class, MonoClass *dst_class)
278 mono_get_runtime_callbacks ()->set_cast_details (src_class, dst_class);
279 mono_error_set_invalid_cast (error);
282 #if ENABLE_NETCORE
283 void
284 ves_icall_System_Array_SetValueRelaxedImpl (MonoArrayHandle arr, MonoObjectHandle value, guint32 pos, MonoError *error)
286 array_set_value_impl (arr, value, pos, FALSE, FALSE, error);
289 // Copied from CoreCLR: https://github.com/dotnet/coreclr/blob/d3e39bc2f81e3dbf9e4b96347f62b49d8700336c/src/vm/invokeutil.cpp#L33
290 #define PT_Primitive 0x01000000
292 static const guint32 primitive_conversions [] = {
293 0x00, // MONO_TYPE_END
294 0x00, // MONO_TYPE_VOID
295 PT_Primitive | 0x0004, // MONO_TYPE_BOOLEAN
296 PT_Primitive | 0x3F88, // MONO_TYPE_CHAR (W = U2, CHAR, I4, U4, I8, U8, R4, R8)
297 PT_Primitive | 0x3550, // MONO_TYPE_I1 (W = I1, I2, I4, I8, R4, R8)
298 PT_Primitive | 0x3FE8, // MONO_TYPE_U1 (W = CHAR, U1, I2, U2, I4, U4, I8, U8, R4, R8)
299 PT_Primitive | 0x3540, // MONO_TYPE_I2 (W = I2, I4, I8, R4, R8)
300 PT_Primitive | 0x3F88, // MONO_TYPE_U2 (W = U2, CHAR, I4, U4, I8, U8, R4, R8)
301 PT_Primitive | 0x3500, // MONO_TYPE_I4 (W = I4, I8, R4, R8)
302 PT_Primitive | 0x3E00, // MONO_TYPE_U4 (W = U4, I8, R4, R8)
303 PT_Primitive | 0x3400, // MONO_TYPE_I8 (W = I8, R4, R8)
304 PT_Primitive | 0x3800, // MONO_TYPE_U8 (W = U8, R4, R8)
305 PT_Primitive | 0x3000, // MONO_TYPE_R4 (W = R4, R8)
306 PT_Primitive | 0x2000, // MONO_TYPE_R8 (W = R8)
309 // Copied from CoreCLR: https://github.com/dotnet/coreclr/blob/030a3ea9b8dbeae89c90d34441d4d9a1cf4a7de6/src/vm/invokeutil.h#L176
310 static
311 gboolean can_primitive_widen (MonoTypeEnum src_type, MonoTypeEnum dest_type)
313 if (dest_type > MONO_TYPE_R8 || src_type > MONO_TYPE_R8) {
314 return (MONO_TYPE_I == dest_type && MONO_TYPE_I == src_type) || (MONO_TYPE_U == dest_type && MONO_TYPE_U == src_type);
316 return ((1 << dest_type) & primitive_conversions [src_type]) != 0;
319 // Copied from CoreCLR: https://github.com/dotnet/coreclr/blob/eafa8648ebee92de1380278b15cd5c2b6ef11218/src/vm/array.cpp#L1406
320 static MonoTypeEnum
321 get_normalized_integral_array_element_type (MonoTypeEnum elementType)
323 // Array Primitive types such as E_T_I4 and E_T_U4 are interchangeable
324 // Enums with interchangeable underlying types are interchangable
325 // BOOL is NOT interchangeable with I1/U1, neither CHAR -- with I2/U2
327 switch (elementType) {
328 case MONO_TYPE_U1:
329 case MONO_TYPE_U2:
330 case MONO_TYPE_U4:
331 case MONO_TYPE_U8:
332 case MONO_TYPE_U:
333 return (MonoTypeEnum) (elementType - 1); // normalize to signed type
336 return elementType;
339 MonoBoolean
340 ves_icall_System_Array_CanChangePrimitive (MonoReflectionTypeHandle ref_src_type, MonoReflectionTypeHandle ref_dst_type, MonoBoolean reliable, MonoError *error)
342 MonoType *src_type = MONO_HANDLE_GETVAL (ref_src_type, type);
343 MonoType *dst_type = MONO_HANDLE_GETVAL (ref_dst_type, type);
345 g_assert (mono_type_is_primitive (src_type));
346 g_assert (mono_type_is_primitive (dst_type));
348 MonoTypeEnum normalized_src_type = get_normalized_integral_array_element_type (src_type->type);
349 MonoTypeEnum normalized_dst_type = get_normalized_integral_array_element_type (dst_type->type);
351 // Allow conversions like int <-> uint
352 if (normalized_src_type == normalized_dst_type) {
353 return TRUE;
356 // Widening is not allowed if reliable is true.
357 if (reliable) {
358 return FALSE;
361 // NOTE we don't use normalized types here so int -> ulong will be false
362 // see https://github.com/dotnet/coreclr/pull/25209#issuecomment-505952295
363 return can_primitive_widen (src_type->type, dst_type->type);
365 #endif
367 static void
368 array_set_value_impl (MonoArrayHandle arr_handle, MonoObjectHandle value_handle, guint32 pos, gboolean strict_enums, gboolean strict_signs, MonoError *error)
370 MonoClass *ac, *vc, *ec;
371 gint32 esize, vsize;
372 gpointer *ea = NULL, *va = NULL;
374 guint64 u64 = 0;
375 gint64 i64 = 0;
376 gdouble r64 = 0;
377 gboolean castOk = FALSE;
378 gboolean et_isenum = FALSE;
379 gboolean vt_isenum = FALSE;
381 error_init (error);
383 if (!MONO_HANDLE_IS_NULL (value_handle))
384 vc = mono_handle_class (value_handle);
385 else
386 vc = NULL;
388 ac = mono_handle_class (arr_handle);
389 ec = m_class_get_element_class (ac);
390 esize = mono_array_element_size (ac);
392 if (mono_class_is_nullable (ec)) {
393 #ifdef ENABLE_NETCORE
394 if (vc && m_class_is_primitive (vc) && vc != m_class_get_nullable_elem_class (ec)) {
395 // T -> Nullable<T> T must be exact
396 set_invalid_cast (error, vc, ec);
397 goto leave;
399 #endif
400 MONO_ENTER_NO_SAFEPOINTS;
401 ea = (gpointer*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (arr_handle), esize, pos);
402 if (!MONO_HANDLE_IS_NULL (value_handle))
403 va = (gpointer*) mono_object_unbox_internal (MONO_HANDLE_RAW (value_handle));
404 mono_nullable_init_unboxed ((guint8*)ea, va, ec);
405 MONO_EXIT_NO_SAFEPOINTS;
406 goto leave;
409 if (MONO_HANDLE_IS_NULL (value_handle)) {
410 MONO_ENTER_NO_SAFEPOINTS;
411 ea = (gpointer*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (arr_handle), esize, pos);
412 mono_gc_bzero_atomic (ea, esize);
413 MONO_EXIT_NO_SAFEPOINTS;
414 goto leave;
417 #ifdef ENABLE_NETCORE
418 #define WIDENING_MSG NULL
419 #define WIDENING_ARG NULL
420 #else
421 #define WIDENING_MSG "not a widening conversion"
422 #define WIDENING_ARG "value"
423 #endif
425 #define NO_WIDENING_CONVERSION G_STMT_START{ \
426 mono_error_set_argument (error, WIDENING_ARG, WIDENING_MSG); \
427 break; \
428 }G_STMT_END
430 #define CHECK_WIDENING_CONVERSION(extra) G_STMT_START{ \
431 if (esize < vsize + (extra)) { \
432 mono_error_set_argument (error, WIDENING_ARG, WIDENING_MSG); \
433 break; \
435 }G_STMT_END
437 #define INVALID_CAST G_STMT_START{ \
438 mono_get_runtime_callbacks ()->set_cast_details (vc, ec); \
439 mono_error_set_invalid_cast (error); \
440 break; \
441 }G_STMT_END
443 MonoTypeEnum et;
444 et = m_class_get_byval_arg (ec)->type;
445 MonoTypeEnum vt;
446 vt = m_class_get_byval_arg (vc)->type;
448 /* Check element (destination) type. */
449 switch (et) {
450 case MONO_TYPE_STRING:
451 switch (vt) {
452 case MONO_TYPE_STRING:
453 break;
454 default:
455 INVALID_CAST;
457 break;
458 case MONO_TYPE_BOOLEAN:
459 switch (vt) {
460 case MONO_TYPE_BOOLEAN:
461 break;
462 case MONO_TYPE_CHAR:
463 case MONO_TYPE_U1:
464 case MONO_TYPE_U2:
465 case MONO_TYPE_U4:
466 case MONO_TYPE_U8:
467 case MONO_TYPE_I1:
468 case MONO_TYPE_I2:
469 case MONO_TYPE_I4:
470 case MONO_TYPE_I8:
471 case MONO_TYPE_R4:
472 case MONO_TYPE_R8:
473 NO_WIDENING_CONVERSION;
474 break;
475 default:
476 INVALID_CAST;
478 break;
479 default:
480 break;
482 if (!is_ok (error))
483 goto leave;
485 castOk = mono_object_handle_isinst_mbyref_raw (value_handle, ec, error);
486 if (!is_ok (error))
487 goto leave;
489 if (!m_class_is_valuetype (ec)) {
490 if (!castOk)
491 INVALID_CAST;
492 if (is_ok (error))
493 MONO_HANDLE_ARRAY_SETREF (arr_handle, pos, value_handle);
494 goto leave;
497 if (castOk) {
498 MONO_ENTER_NO_SAFEPOINTS;
499 ea = (gpointer*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (arr_handle), esize, pos);
500 va = (gpointer*) mono_object_unbox_internal (MONO_HANDLE_RAW (value_handle));
501 if (m_class_has_references (ec))
502 mono_value_copy_internal (ea, va, ec);
503 else
504 mono_gc_memmove_atomic (ea, va, esize);
505 MONO_EXIT_NO_SAFEPOINTS;
507 goto leave;
510 if (!m_class_is_valuetype (vc))
511 INVALID_CAST;
513 if (!is_ok (error))
514 goto leave;
516 vsize = mono_class_value_size (vc, NULL);
518 et_isenum = et == MONO_TYPE_VALUETYPE && m_class_is_enumtype (m_class_get_byval_arg (ec)->data.klass);
519 vt_isenum = vt == MONO_TYPE_VALUETYPE && m_class_is_enumtype (m_class_get_byval_arg (vc)->data.klass);
521 #if ENABLE_NETCORE
522 if (strict_enums && et_isenum && !vt_isenum) {
523 INVALID_CAST;
524 goto leave;
526 #endif
528 if (et_isenum)
529 et = mono_class_enum_basetype_internal (m_class_get_byval_arg (ec)->data.klass)->type;
531 if (vt_isenum)
532 vt = mono_class_enum_basetype_internal (m_class_get_byval_arg (vc)->data.klass)->type;
534 #if ENABLE_NETCORE
535 // Treat MONO_TYPE_U/I as MONO_TYPE_U8/I8/U4/I4
536 #if SIZEOF_VOID_P == 8
537 vt = vt == MONO_TYPE_U ? MONO_TYPE_U8 : (vt == MONO_TYPE_I ? MONO_TYPE_I8 : vt);
538 et = et == MONO_TYPE_U ? MONO_TYPE_U8 : (et == MONO_TYPE_I ? MONO_TYPE_I8 : et);
539 #else
540 vt = vt == MONO_TYPE_U ? MONO_TYPE_U4 : (vt == MONO_TYPE_I ? MONO_TYPE_I4 : vt);
541 et = et == MONO_TYPE_U ? MONO_TYPE_U4 : (et == MONO_TYPE_I ? MONO_TYPE_I4 : et);
542 #endif
543 #endif
545 #define ASSIGN_UNSIGNED(etype) G_STMT_START{\
546 switch (vt) { \
547 case MONO_TYPE_U1: \
548 case MONO_TYPE_U2: \
549 case MONO_TYPE_U4: \
550 case MONO_TYPE_U8: \
551 case MONO_TYPE_CHAR: \
552 CHECK_WIDENING_CONVERSION(0); \
553 *(etype *) ea = (etype) u64; \
554 break; \
555 /* You can't assign a signed value to an unsigned array. */ \
556 case MONO_TYPE_I1: \
557 case MONO_TYPE_I2: \
558 case MONO_TYPE_I4: \
559 case MONO_TYPE_I8: \
560 if (!strict_signs) { \
561 CHECK_WIDENING_CONVERSION(0); \
562 *(etype *) ea = (etype) i64; \
563 break; \
565 /* You can't assign a floating point number to an integer array. */ \
566 case MONO_TYPE_R4: \
567 case MONO_TYPE_R8: \
568 NO_WIDENING_CONVERSION; \
569 break; \
570 default: \
571 INVALID_CAST; \
572 break; \
574 }G_STMT_END
576 #define ASSIGN_SIGNED(etype) G_STMT_START{\
577 switch (vt) { \
578 case MONO_TYPE_I1: \
579 case MONO_TYPE_I2: \
580 case MONO_TYPE_I4: \
581 case MONO_TYPE_I8: \
582 CHECK_WIDENING_CONVERSION(0); \
583 *(etype *) ea = (etype) i64; \
584 break; \
585 /* You can assign an unsigned value to a signed array if the array's */ \
586 /* element size is larger than the value size. */ \
587 case MONO_TYPE_U1: \
588 case MONO_TYPE_U2: \
589 case MONO_TYPE_U4: \
590 case MONO_TYPE_U8: \
591 case MONO_TYPE_CHAR: \
592 CHECK_WIDENING_CONVERSION(strict_signs ? 1 : 0); \
593 *(etype *) ea = (etype) u64; \
594 break; \
595 /* You can't assign a floating point number to an integer array. */ \
596 case MONO_TYPE_R4: \
597 case MONO_TYPE_R8: \
598 NO_WIDENING_CONVERSION; \
599 break; \
600 default: \
601 INVALID_CAST; \
602 break; \
604 }G_STMT_END
606 #define ASSIGN_REAL(etype) G_STMT_START{\
607 switch (vt) { \
608 case MONO_TYPE_R4: \
609 case MONO_TYPE_R8: \
610 CHECK_WIDENING_CONVERSION(0); \
611 *(etype *) ea = (etype) r64; \
612 break; \
613 /* All integer values fit into a floating point array, so we don't */ \
614 /* need to CHECK_WIDENING_CONVERSION here. */ \
615 case MONO_TYPE_I1: \
616 case MONO_TYPE_I2: \
617 case MONO_TYPE_I4: \
618 case MONO_TYPE_I8: \
619 *(etype *) ea = (etype) i64; \
620 break; \
621 case MONO_TYPE_U1: \
622 case MONO_TYPE_U2: \
623 case MONO_TYPE_U4: \
624 case MONO_TYPE_U8: \
625 case MONO_TYPE_CHAR: \
626 *(etype *) ea = (etype) u64; \
627 break; \
628 default: \
629 INVALID_CAST; \
630 break; \
632 }G_STMT_END
634 MONO_ENTER_NO_SAFEPOINTS;
635 g_assert (!MONO_HANDLE_IS_NULL (value_handle));
636 g_assert (m_class_is_valuetype (vc));
637 va = (gpointer*) mono_object_unbox_internal (MONO_HANDLE_RAW (value_handle));
638 ea = (gpointer*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (arr_handle), esize, pos);
640 switch (vt) {
641 case MONO_TYPE_U1:
642 u64 = *(guint8 *) va;
643 break;
644 case MONO_TYPE_U2:
645 u64 = *(guint16 *) va;
646 break;
647 case MONO_TYPE_U4:
648 u64 = *(guint32 *) va;
649 break;
650 case MONO_TYPE_U8:
651 u64 = *(guint64 *) va;
652 break;
653 case MONO_TYPE_I1:
654 i64 = *(gint8 *) va;
655 break;
656 case MONO_TYPE_I2:
657 i64 = *(gint16 *) va;
658 break;
659 case MONO_TYPE_I4:
660 i64 = *(gint32 *) va;
661 break;
662 case MONO_TYPE_I8:
663 i64 = *(gint64 *) va;
664 break;
665 case MONO_TYPE_R4:
666 r64 = *(gfloat *) va;
667 break;
668 case MONO_TYPE_R8:
669 r64 = *(gdouble *) va;
670 break;
671 case MONO_TYPE_CHAR:
672 u64 = *(guint16 *) va;
673 break;
674 case MONO_TYPE_BOOLEAN:
675 /* Boolean is only compatible with itself. */
676 switch (et) {
677 case MONO_TYPE_CHAR:
678 case MONO_TYPE_U1:
679 case MONO_TYPE_U2:
680 case MONO_TYPE_U4:
681 case MONO_TYPE_U8:
682 case MONO_TYPE_I1:
683 case MONO_TYPE_I2:
684 case MONO_TYPE_I4:
685 case MONO_TYPE_I8:
686 case MONO_TYPE_R4:
687 case MONO_TYPE_R8:
688 NO_WIDENING_CONVERSION;
689 break;
690 default:
691 INVALID_CAST;
693 break;
695 /* If we can't do a direct copy, let's try a widening conversion. */
697 if (is_ok (error)) {
698 switch (et) {
699 case MONO_TYPE_CHAR:
700 ASSIGN_UNSIGNED (guint16);
701 break;
702 case MONO_TYPE_U1:
703 ASSIGN_UNSIGNED (guint8);
704 break;
705 case MONO_TYPE_U2:
706 ASSIGN_UNSIGNED (guint16);
707 break;
708 case MONO_TYPE_U4:
709 ASSIGN_UNSIGNED (guint32);
710 break;
711 case MONO_TYPE_U8:
712 ASSIGN_UNSIGNED (guint64);
713 break;
714 case MONO_TYPE_I1:
715 ASSIGN_SIGNED (gint8);
716 break;
717 case MONO_TYPE_I2:
718 ASSIGN_SIGNED (gint16);
719 break;
720 case MONO_TYPE_I4:
721 ASSIGN_SIGNED (gint32);
722 break;
723 case MONO_TYPE_I8:
724 ASSIGN_SIGNED (gint64);
725 break;
726 case MONO_TYPE_R4:
727 ASSIGN_REAL (gfloat);
728 break;
729 case MONO_TYPE_R8:
730 ASSIGN_REAL (gdouble);
731 break;
732 default:
733 INVALID_CAST;
737 MONO_EXIT_NO_SAFEPOINTS;
739 #undef INVALID_CAST
740 #undef NO_WIDENING_CONVERSION
741 #undef CHECK_WIDENING_CONVERSION
742 #undef ASSIGN_UNSIGNED
743 #undef ASSIGN_SIGNED
744 #undef ASSIGN_REAL
746 leave:
747 return;
750 void
751 ves_icall_System_Array_SetValue (MonoArrayHandle arr, MonoObjectHandle value,
752 MonoArrayHandle idxs, MonoError *error)
754 icallarray_print ("%s\n", __func__);
756 MonoArrayBounds dim;
757 MonoClass *ac, *ic;
758 gint32 idx;
759 gint32 i, pos;
761 error_init (error);
763 if (MONO_HANDLE_IS_NULL (idxs)) {
764 #ifdef ENABLE_NETCORE
765 mono_error_set_argument_null (error, "indices", "");
766 #else
767 mono_error_set_argument_null (error, "idxs", "");
768 #endif
769 return;
772 ic = mono_handle_class (idxs);
773 ac = mono_handle_class (arr);
775 g_assert (m_class_get_rank (ic) == 1);
776 if (mono_handle_array_has_bounds (idxs) || MONO_HANDLE_GETVAL (idxs, max_length) != m_class_get_rank (ac)) {
777 #ifdef ENABLE_NETCORE
778 mono_error_set_argument (error, NULL, "");
779 #else
780 mono_error_set_argument (error, "idxs", "");
781 #endif
782 return;
785 if (!mono_handle_array_has_bounds (arr)) {
786 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, 0);
787 if (idx < 0 || idx >= MONO_HANDLE_GETVAL (arr, max_length)) {
788 mono_error_set_exception_instance (error, mono_get_exception_index_out_of_range ());
789 return;
792 array_set_value_impl (arr, value, idx, TRUE, TRUE, error);
793 return;
796 gint32 ac_rank = m_class_get_rank (ac);
797 for (i = 0; i < ac_rank; i++) {
798 mono_handle_array_get_bounds_dim (arr, i, &dim);
799 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, i);
800 if ((idx < dim.lower_bound) ||
801 (idx >= (mono_array_lower_bound_t)dim.length + dim.lower_bound)) {
802 mono_error_set_exception_instance (error, mono_get_exception_index_out_of_range ());
803 return;
807 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, 0);
808 mono_handle_array_get_bounds_dim (arr, 0, &dim);
809 pos = idx - dim.lower_bound;
810 for (i = 1; i < ac_rank; i++) {
811 mono_handle_array_get_bounds_dim (arr, i, &dim);
812 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, i);
813 pos = pos * dim.length + idx - dim.lower_bound;
816 array_set_value_impl (arr, value, pos, TRUE, TRUE, error);
819 MonoArrayHandle
820 ves_icall_System_Array_CreateInstanceImpl (MonoReflectionTypeHandle type, MonoArrayHandle lengths, MonoArrayHandle bounds, MonoError *error)
822 // FIXME? fixed could be used for lengths, bounds.
824 icallarray_print ("%s type:%p length:%p bounds:%p\n", __func__, type, lengths, bounds);
826 MONO_CHECK_ARG_NULL_HANDLE (type, NULL_HANDLE_ARRAY);
827 MONO_CHECK_ARG_NULL_HANDLE (lengths, NULL_HANDLE_ARRAY);
829 MONO_CHECK_ARG (lengths, mono_array_handle_length (lengths) > 0, NULL_HANDLE_ARRAY);
830 if (!MONO_HANDLE_IS_NULL (bounds))
831 MONO_CHECK_ARG (bounds, mono_array_handle_length (lengths) == mono_array_handle_length (bounds), NULL_HANDLE_ARRAY);
833 for (uintptr_t i = 0; i < mono_array_handle_length (lengths); ++i) {
834 gint32 length = 0;
835 MONO_HANDLE_ARRAY_GETVAL (length, lengths, gint32, i);
836 if (length < 0) {
837 mono_error_set_argument_out_of_range (error, NULL, "MonoArgumentException:NULL");
838 return NULL_HANDLE_ARRAY;
842 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
843 if (!mono_class_init_checked (klass, error))
844 return NULL_HANDLE_ARRAY;
846 if (m_class_get_byval_arg (m_class_get_element_class (klass))->type == MONO_TYPE_VOID) {
847 mono_error_set_not_supported (error, "Arrays of System.Void are not supported.");
848 return NULL_HANDLE_ARRAY;
851 /* vectors are not the same as one dimensional arrays with non-zero bounds */
852 gboolean bounded = FALSE;
853 if (!MONO_HANDLE_IS_NULL (bounds) && mono_array_handle_length (bounds) == 1) {
854 gint32 bound0 = 0;
855 MONO_HANDLE_ARRAY_GETVAL (bound0, bounds, gint32, 0);
856 bounded = bound0 != 0;
859 MonoClass * const aklass = mono_class_create_bounded_array (klass, mono_array_handle_length (lengths), bounded);
860 uintptr_t const aklass_rank = m_class_get_rank (aklass);
861 uintptr_t * const sizes = g_newa (uintptr_t, aklass_rank);
862 intptr_t * const lower_bounds = g_newa (intptr_t, aklass_rank);
864 // Copy lengths and lower_bounds from gint32 to [u]intptr_t.
866 for (uintptr_t i = 0; i < aklass_rank; ++i) {
867 MONO_HANDLE_ARRAY_GETVAL (sizes [i], lengths, gint32, i);
868 if (!MONO_HANDLE_IS_NULL (bounds))
869 MONO_HANDLE_ARRAY_GETVAL (lower_bounds [i], bounds, gint32, i);
870 else
871 lower_bounds [i] = 0;
874 return mono_array_new_full_handle (MONO_HANDLE_DOMAIN (type), aklass, sizes, lower_bounds, error);
877 gint32
878 ves_icall_System_Array_GetRank (MonoObjectHandle arr, MonoError *error)
880 gint32 const result = m_class_get_rank (mono_handle_class (arr));
882 icallarray_print ("%s arr:%p res:%d\n", __func__, MONO_HANDLE_RAW (arr), result);
884 return result;
887 static mono_array_size_t
888 mono_array_get_length (MonoArrayHandle arr, gint32 dimension, MonoError *error)
890 if (dimension < 0 || dimension >= m_class_get_rank (mono_handle_class (arr))) {
891 mono_error_set_index_out_of_range (error);
892 return 0;
895 return MONO_HANDLE_GETVAL (arr, bounds) ? MONO_HANDLE_GETVAL (arr, bounds [dimension].length)
896 : MONO_HANDLE_GETVAL (arr, max_length);
899 gint32
900 ves_icall_System_Array_GetLength (MonoArrayHandle arr, gint32 dimension, MonoError *error)
902 icallarray_print ("%s arr:%p dimension:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)dimension);
904 mono_array_size_t const length = mono_array_get_length (arr, dimension, error);
905 if (length > G_MAXINT32) {
906 mono_error_set_overflow (error);
907 return 0;
909 return (gint32)length;
912 gint64
913 ves_icall_System_Array_GetLongLength (MonoArrayHandle arr, gint32 dimension, MonoError *error)
915 icallarray_print ("%s arr:%p dimension:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)dimension);
917 return (gint64)mono_array_get_length (arr, dimension, error);
920 gint32
921 ves_icall_System_Array_GetLowerBound (MonoArrayHandle arr, gint32 dimension, MonoError *error)
923 icallarray_print ("%s arr:%p dimension:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)dimension);
925 if (dimension < 0 || dimension >= m_class_get_rank (mono_handle_class (arr))) {
926 mono_error_set_index_out_of_range (error);
927 return 0;
930 return MONO_HANDLE_GETVAL (arr, bounds) ? MONO_HANDLE_GETVAL (arr, bounds [dimension].lower_bound)
931 : 0;
934 void
935 ves_icall_System_Array_ClearInternal (MonoArrayHandle arr, int idx, int length, MonoError *error)
937 icallarray_print ("%s arr:%p idx:%d len:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)idx, (int)length);
939 int sz = mono_array_element_size (mono_handle_class (arr));
940 mono_gc_bzero_atomic (mono_array_addr_with_size_fast (MONO_HANDLE_RAW (arr), sz, idx), length * sz);
943 MonoBoolean
944 ves_icall_System_Array_FastCopy (MonoArrayHandle source, int source_idx, MonoArrayHandle dest, int dest_idx, int length, MonoError *error)
946 MonoVTable * const src_vtable = MONO_HANDLE_GETVAL (source, obj.vtable);
947 MonoVTable * const dest_vtable = MONO_HANDLE_GETVAL (dest, obj.vtable);
949 if (src_vtable->rank != dest_vtable->rank)
950 return FALSE;
952 MonoArrayBounds *source_bounds = MONO_HANDLE_GETVAL (source, bounds);
953 MonoArrayBounds *dest_bounds = MONO_HANDLE_GETVAL (dest, bounds);
955 for (int i = 0; i < src_vtable->rank; i++) {
956 if ((source_bounds && source_bounds [i].lower_bound > 0) ||
957 (dest_bounds && dest_bounds [i].lower_bound > 0))
958 return FALSE;
961 /* there's no integer overflow since mono_array_length_internal returns an unsigned integer */
962 if ((dest_idx + length > mono_array_handle_length (dest)) ||
963 (source_idx + length > mono_array_handle_length (source)))
964 return FALSE;
966 MonoClass * const src_class = m_class_get_element_class (src_vtable->klass);
967 MonoClass * const dest_class = m_class_get_element_class (dest_vtable->klass);
970 * Handle common cases.
973 /* Case1: object[] -> valuetype[] (ArrayList::ToArray)
974 We fallback to managed here since we need to typecheck each boxed valuetype before storing them in the dest array.
976 if (src_class == mono_defaults.object_class && m_class_is_valuetype (dest_class))
977 return FALSE;
979 /* Check if we're copying a char[] <==> (u)short[] */
980 if (src_class != dest_class) {
981 if (m_class_is_valuetype (dest_class) || m_class_is_enumtype (dest_class) ||
982 m_class_is_valuetype (src_class) || m_class_is_valuetype (src_class))
983 return FALSE;
985 /* 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. */
986 if (!mono_class_is_subclass_of_internal (src_class, dest_class, FALSE))
987 return FALSE;
989 if (m_class_is_native_pointer (src_class) || m_class_is_native_pointer (dest_class))
990 return FALSE;
993 if (m_class_is_valuetype (dest_class)) {
994 gsize const element_size = mono_array_element_size (MONO_HANDLE_GETVAL (source, obj.vtable->klass));
996 MONO_ENTER_NO_SAFEPOINTS; // gchandle would also work here, is slow, breaks profiler tests.
998 gconstpointer const source_addr =
999 mono_array_addr_with_size_fast (MONO_HANDLE_RAW (source), element_size, source_idx);
1000 if (m_class_has_references (dest_class)) {
1001 mono_value_copy_array_handle (dest, dest_idx, source_addr, length);
1002 } else {
1003 gpointer const dest_addr =
1004 mono_array_addr_with_size_fast (MONO_HANDLE_RAW (dest), element_size, dest_idx);
1005 mono_gc_memmove_atomic (dest_addr, source_addr, element_size * length);
1008 MONO_EXIT_NO_SAFEPOINTS;
1009 } else {
1010 mono_array_handle_memcpy_refs (dest, dest_idx, source, source_idx, length);
1013 return TRUE;
1016 void
1017 ves_icall_System_Array_GetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
1019 // FIXME?
1020 // Generic ref/out parameters are not supported by HANDLES(), so NOHANDLES().
1022 icallarray_print ("%s arr:%p pos:%u value:%p\n", __func__, arr, pos, value);
1024 MONO_REQ_GC_UNSAFE_MODE; // because of gpointer value
1026 MonoClass * const ac = mono_object_class (arr);
1027 gsize const esize = mono_array_element_size (ac);
1028 gconstpointer * const ea = (gconstpointer*)((char*)arr->vector + (pos * esize));
1030 mono_gc_memmove_atomic (value, ea, esize);
1033 void
1034 ves_icall_System_Array_SetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
1036 // FIXME?
1037 // Generic ref/out parameters are not supported by HANDLES(), so NOHANDLES().
1039 icallarray_print ("%s arr:%p pos:%u value:%p\n", __func__, arr, pos, value);
1041 MONO_REQ_GC_UNSAFE_MODE; // because of gpointer value
1044 MonoClass * const ac = mono_object_class (arr);
1045 MonoClass * const ec = m_class_get_element_class (ac);
1047 gsize const esize = mono_array_element_size (ac);
1048 gpointer * const ea = (gpointer*)((char*)arr->vector + (pos * esize));
1050 if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (ec))) {
1051 g_assert (esize == sizeof (gpointer));
1052 mono_gc_wbarrier_generic_store_internal (ea, *(MonoObject **)value);
1053 } else {
1054 g_assert (m_class_is_inited (ec));
1055 g_assert (esize == mono_class_value_size (ec, NULL));
1056 if (m_class_has_references (ec))
1057 mono_gc_wbarrier_value_copy_internal (ea, value, 1, ec);
1058 else
1059 mono_gc_memmove_atomic (ea, value, esize);
1063 void
1064 #if ENABLE_NETCORE
1065 ves_icall_System_Runtime_RuntimeImports_Memmove (guint8 *destination, guint8 *source, size_t byte_count)
1066 #else
1067 ves_icall_System_Runtime_RuntimeImports_Memmove (guint8 *destination, guint8 *source, guint byte_count)
1068 #endif
1070 mono_gc_memmove_atomic (destination, source, byte_count);
1073 #if ENABLE_NETCORE
1074 void
1075 ves_icall_System_Runtime_RuntimeImports_RhBulkMoveWithWriteBarrier (guint8 *destination, guint8 *source, size_t byte_count)
1077 mono_gc_wbarrier_range_copy (destination, source, byte_count);
1079 #else
1080 void
1081 ves_icall_System_Runtime_RuntimeImports_Memmove_wbarrier (guint8 *destination, guint8 *source, guint len, MonoType *type)
1083 if (MONO_TYPE_IS_REFERENCE (type))
1084 mono_gc_wbarrier_arrayref_copy_internal (destination, source, len);
1085 else
1086 mono_gc_wbarrier_value_copy_internal (destination, source, len, mono_class_from_mono_type_internal (type));
1088 #endif
1090 void
1091 #if ENABLE_NETCORE
1092 ves_icall_System_Runtime_RuntimeImports_ZeroMemory (guint8 *p, size_t byte_length)
1093 #else
1094 ves_icall_System_Runtime_RuntimeImports_ZeroMemory (guint8 *p, guint byte_length)
1095 #endif
1097 memset (p, 0, byte_length);
1100 void
1101 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArrayHandle array, MonoClassField *field_handle, MonoError *error)
1103 MonoClass *klass = mono_handle_class (array);
1104 guint32 size = mono_array_element_size (klass);
1105 MonoType *type = mono_type_get_underlying_type (m_class_get_byval_arg (m_class_get_element_class (klass)));
1106 int align;
1107 const char *field_data;
1109 if (MONO_TYPE_IS_REFERENCE (type) || type->type == MONO_TYPE_VALUETYPE) {
1110 mono_error_set_argument (error, "array", "Cannot initialize array of non-primitive type");
1111 return;
1114 MonoType *field_type = mono_field_get_type_checked (field_handle, error);
1115 if (!field_type)
1116 return;
1118 if (!(field_type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
1119 mono_error_set_argument_format (error, "field_handle", "Field '%s' doesn't have an RVA", mono_field_get_name (field_handle));
1120 return;
1123 size *= MONO_HANDLE_GETVAL(array, max_length);
1124 field_data = mono_field_get_data (field_handle);
1126 if (size > mono_type_size (field_handle->type, &align)) {
1127 mono_error_set_argument (error, "field_handle", "Field not large enough to fill array");
1128 return;
1131 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1132 #define SWAP(n) { \
1133 guint ## n *data = (guint ## n *) mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0); \
1134 guint ## n *src = (guint ## n *) field_data; \
1135 int i, \
1136 nEnt = (size / sizeof(guint ## n)); \
1138 for (i = 0; i < nEnt; i++) { \
1139 data[i] = read ## n (&src[i]); \
1143 /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
1145 switch (type->type) {
1146 case MONO_TYPE_CHAR:
1147 case MONO_TYPE_I2:
1148 case MONO_TYPE_U2:
1149 SWAP (16);
1150 break;
1151 case MONO_TYPE_I4:
1152 case MONO_TYPE_U4:
1153 case MONO_TYPE_R4:
1154 SWAP (32);
1155 break;
1156 case MONO_TYPE_I8:
1157 case MONO_TYPE_U8:
1158 case MONO_TYPE_R8:
1159 SWAP (64);
1160 break;
1161 default:
1162 memcpy (mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0), field_data, size);
1163 break;
1165 #else
1166 memcpy (mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0), field_data, size);
1167 #endif
1170 gint
1171 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
1173 return offsetof (MonoString, chars);
1176 MonoObjectHandle
1177 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObjectHandle obj, MonoError *error)
1179 if (MONO_HANDLE_IS_NULL (obj) || !m_class_is_valuetype (mono_handle_class (obj)))
1180 return obj;
1182 return mono_object_clone_handle (obj, error);
1185 void
1186 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle, MonoError *error)
1188 MonoClass *klass;
1189 MonoVTable *vtable;
1191 MONO_CHECK_ARG_NULL (handle,);
1193 klass = mono_class_from_mono_type_internal (handle);
1194 MONO_CHECK_ARG (handle, klass,);
1196 if (mono_class_is_gtd (klass))
1197 return;
1199 vtable = mono_class_vtable_checked (mono_domain_get (), klass, error);
1200 return_if_nok (error);
1202 /* This will call the type constructor */
1203 mono_runtime_class_init_full (vtable, error);
1206 void
1207 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (MonoImage *image, MonoError *error)
1209 mono_image_check_for_module_cctor (image);
1210 if (!image->has_module_cctor)
1211 return;
1213 MonoClass *module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, error);
1214 return_if_nok (error);
1216 MonoVTable * vtable = mono_class_vtable_checked (mono_domain_get (), module_klass, error);
1217 return_if_nok (error);
1219 mono_runtime_class_init_full (vtable, error);
1222 MonoBoolean
1223 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
1225 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
1226 // It does not work on win32
1227 #elif defined(TARGET_ANDROID) || defined(__linux__)
1228 // No need for now
1229 #else
1230 guint8 *stack_addr;
1231 guint8 *current;
1232 size_t stack_size;
1233 int min_size;
1234 MonoInternalThread *thread;
1236 mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
1237 /* if we have no info we are optimistic and assume there is enough room */
1238 if (!stack_addr)
1239 return TRUE;
1241 thread = mono_thread_internal_current ();
1242 // .net seems to check that at least 50% of stack is available
1243 min_size = thread->stack_size / 2;
1245 // TODO: It's not always set
1246 if (!min_size)
1247 return TRUE;
1249 current = (guint8 *)&stack_addr;
1250 if (current > stack_addr) {
1251 if ((current - stack_addr) < min_size)
1252 return FALSE;
1253 } else {
1254 if (current - (stack_addr - stack_size) < min_size)
1255 return FALSE;
1257 #endif
1258 return TRUE;
1261 #ifdef ENABLE_NETCORE
1262 MonoObjectHandle
1263 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetUninitializedObjectInternal (MonoType *handle, MonoError *error)
1265 MonoClass *klass;
1267 g_assert (handle);
1269 klass = mono_class_from_mono_type_internal (handle);
1270 if (m_class_is_string (klass)) {
1271 mono_error_set_argument (error, NULL, NULL);
1272 return NULL_HANDLE;
1275 if (m_class_is_abstract (klass) || m_class_is_interface (klass) || m_class_is_gtd (klass)) {
1276 mono_error_set_member_access (error, NULL, NULL);
1277 return NULL_HANDLE;
1280 if (m_class_is_byreflike (klass)) {
1281 mono_error_set_not_supported (error, NULL, NULL);
1282 return NULL_HANDLE;
1285 if (m_class_is_nullable (klass))
1286 return mono_object_new_handle (mono_domain_get (), m_class_get_nullable_elem_class (klass), error);
1287 else
1288 return mono_object_new_handle (mono_domain_get (), klass, error);
1291 void
1292 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_PrepareMethod (MonoMethod *method, gpointer inst_types, int n_inst_types, MonoError *error)
1294 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT) {
1295 mono_error_set_argument (error, NULL, NULL);
1296 return;
1299 MonoGenericContainer *container = NULL;
1300 if (method->is_generic)
1301 container = mono_method_get_generic_container (method);
1302 else if (m_class_is_gtd (method->klass))
1303 container = mono_class_get_generic_container (method->klass);
1304 if (container) {
1305 int nparams = container->type_argc + (container->parent ? container->parent->type_argc : 0);
1306 if (nparams != n_inst_types) {
1307 mono_error_set_argument (error, NULL, NULL);
1308 return;
1312 // FIXME: Implement
1314 #endif
1316 MonoObjectHandle
1317 ves_icall_System_Object_MemberwiseClone (MonoObjectHandle this_obj, MonoError *error)
1319 return mono_object_clone_handle (this_obj, error);
1322 gint32
1323 ves_icall_System_ValueType_InternalGetHashCode (MonoObjectHandle this_obj, MonoArrayHandleOut fields, MonoError *error)
1325 MonoClass *klass;
1326 MonoClassField **unhandled = NULL;
1327 int count = 0;
1328 gint32 result = (int)(gsize)mono_defaults.int32_class;
1329 MonoClassField* field;
1330 gpointer iter;
1332 klass = mono_handle_class (this_obj);
1334 if (mono_class_num_fields (klass) == 0)
1335 return result;
1338 * Compute the starting value of the hashcode for fields of primitive
1339 * types, and return the remaining fields in an array to the managed side.
1340 * This way, we can avoid costly reflection operations in managed code.
1342 iter = NULL;
1343 while ((field = mono_class_get_fields_internal (klass, &iter))) {
1344 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1345 continue;
1346 if (mono_field_is_deleted (field))
1347 continue;
1348 gpointer addr = (guint8*)MONO_HANDLE_RAW (this_obj) + field->offset;
1349 /* FIXME: Add more types */
1350 switch (field->type->type) {
1351 case MONO_TYPE_I4:
1352 result ^= *(gint32*)addr;
1353 break;
1354 case MONO_TYPE_PTR:
1355 result ^= mono_aligned_addr_hash (*(gpointer*)addr);
1356 break;
1357 case MONO_TYPE_STRING: {
1358 MonoString *s;
1359 s = *(MonoString**)addr;
1360 if (s != NULL)
1361 result ^= mono_string_hash_internal (s);
1362 break;
1364 default:
1365 if (!unhandled)
1366 unhandled = g_newa (MonoClassField*, mono_class_num_fields (klass));
1367 unhandled [count ++] = field;
1371 if (unhandled) {
1372 MonoArrayHandle fields_arr = mono_array_new_handle (mono_domain_get (), mono_defaults.object_class, count, error);
1373 return_val_if_nok (error, 0);
1374 MONO_HANDLE_ASSIGN (fields, fields_arr);
1375 MonoObjectHandle h = MONO_HANDLE_NEW (MonoObject, NULL);
1376 for (int i = 0; i < count; ++i) {
1377 MonoObject *o = mono_field_get_value_object_checked (mono_handle_domain (this_obj), unhandled [i], MONO_HANDLE_RAW (this_obj), error);
1378 return_val_if_nok (error, 0);
1379 MONO_HANDLE_ASSIGN_RAW (h, o);
1380 mono_array_handle_setref (fields_arr, i, h);
1382 } else {
1383 MONO_HANDLE_ASSIGN (fields, NULL_HANDLE);
1385 return result;
1388 MonoBoolean
1389 ves_icall_System_ValueType_Equals (MonoObjectHandle this_obj, MonoObjectHandle that, MonoArrayHandleOut fields, MonoError *error)
1391 MonoClass *klass;
1392 MonoClassField **unhandled = NULL;
1393 MonoClassField* field;
1394 gpointer iter;
1395 int count = 0;
1397 MONO_CHECK_ARG_NULL_HANDLE (that, FALSE);
1399 MONO_HANDLE_ASSIGN (fields, NULL_HANDLE);
1401 if (mono_handle_vtable (this_obj) != mono_handle_vtable (that))
1402 return FALSE;
1404 klass = mono_handle_class (this_obj);
1406 if (m_class_is_enumtype (klass) && mono_class_enum_basetype_internal (klass) && mono_class_enum_basetype_internal (klass)->type == MONO_TYPE_I4)
1407 return *(gint32*)mono_handle_get_data_unsafe (this_obj) == *(gint32*)mono_handle_get_data_unsafe (that);
1410 * Do the comparison for fields of primitive type and return a result if
1411 * possible. Otherwise, return the remaining fields in an array to the
1412 * managed side. This way, we can avoid costly reflection operations in
1413 * managed code.
1415 iter = NULL;
1416 while ((field = mono_class_get_fields_internal (klass, &iter))) {
1417 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1418 continue;
1419 if (mono_field_is_deleted (field))
1420 continue;
1421 guint8 *this_field = (guint8 *)MONO_HANDLE_RAW (this_obj) + field->offset;
1422 guint8 *that_field = (guint8 *)MONO_HANDLE_RAW (that) + field->offset;
1424 #define UNALIGNED_COMPARE(type) \
1425 do { \
1426 type left, right; \
1427 memcpy (&left, this_field, sizeof (type)); \
1428 memcpy (&right, that_field, sizeof (type)); \
1429 if (left != right) \
1430 return FALSE; \
1431 } while (0)
1433 /* FIXME: Add more types */
1434 switch (field->type->type) {
1435 case MONO_TYPE_U1:
1436 case MONO_TYPE_I1:
1437 case MONO_TYPE_BOOLEAN:
1438 if (*this_field != *that_field)
1439 return FALSE;
1440 break;
1441 case MONO_TYPE_U2:
1442 case MONO_TYPE_I2:
1443 case MONO_TYPE_CHAR:
1444 #ifdef NO_UNALIGNED_ACCESS
1445 if (G_UNLIKELY ((intptr_t) this_field & 1 || (intptr_t) that_field & 1))
1446 UNALIGNED_COMPARE (gint16);
1447 else
1448 #endif
1449 if (*(gint16 *) this_field != *(gint16 *) that_field)
1450 return FALSE;
1451 break;
1452 case MONO_TYPE_U4:
1453 case MONO_TYPE_I4:
1454 #ifdef NO_UNALIGNED_ACCESS
1455 if (G_UNLIKELY ((intptr_t) this_field & 3 || (intptr_t) that_field & 3))
1456 UNALIGNED_COMPARE (gint32);
1457 else
1458 #endif
1459 if (*(gint32 *) this_field != *(gint32 *) that_field)
1460 return FALSE;
1461 break;
1462 case MONO_TYPE_U8:
1463 case MONO_TYPE_I8:
1464 #ifdef NO_UNALIGNED_ACCESS
1465 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1466 UNALIGNED_COMPARE (gint64);
1467 else
1468 #endif
1469 if (*(gint64 *) this_field != *(gint64 *) that_field)
1470 return FALSE;
1471 break;
1473 case MONO_TYPE_R4: {
1474 float d1, d2;
1475 #ifdef NO_UNALIGNED_ACCESS
1476 memcpy (&d1, this_field, sizeof (float));
1477 memcpy (&d2, that_field, sizeof (float));
1478 #else
1479 d1 = *(float *) this_field;
1480 d2 = *(float *) that_field;
1481 #endif
1482 if (d1 != d2 && !(mono_isnan (d1) && mono_isnan (d2)))
1483 return FALSE;
1484 break;
1486 case MONO_TYPE_R8: {
1487 double d1, d2;
1488 #ifdef NO_UNALIGNED_ACCESS
1489 memcpy (&d1, this_field, sizeof (double));
1490 memcpy (&d2, that_field, sizeof (double));
1491 #else
1492 d1 = *(double *) this_field;
1493 d2 = *(double *) that_field;
1494 #endif
1495 if (d1 != d2 && !(mono_isnan (d1) && mono_isnan (d2)))
1496 return FALSE;
1497 break;
1499 case MONO_TYPE_PTR:
1500 #ifdef NO_UNALIGNED_ACCESS
1501 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1502 UNALIGNED_COMPARE (gpointer);
1503 else
1504 #endif
1505 if (*(gpointer *) this_field != *(gpointer *) that_field)
1506 return FALSE;
1507 break;
1508 case MONO_TYPE_STRING: {
1509 MonoString *s1, *s2;
1510 guint32 s1len, s2len;
1511 s1 = *(MonoString**)this_field;
1512 s2 = *(MonoString**)that_field;
1513 if (s1 == s2)
1514 break;
1515 if ((s1 == NULL) || (s2 == NULL))
1516 return FALSE;
1517 s1len = mono_string_length_internal (s1);
1518 s2len = mono_string_length_internal (s2);
1519 if (s1len != s2len)
1520 return FALSE;
1522 if (memcmp (mono_string_chars_internal (s1), mono_string_chars_internal (s2), s1len * sizeof (gunichar2)) != 0)
1523 return FALSE;
1524 break;
1526 default:
1527 if (!unhandled)
1528 unhandled = g_newa (MonoClassField*, mono_class_num_fields (klass));
1529 unhandled [count ++] = field;
1532 #undef UNALIGNED_COMPARE
1534 if (m_class_is_enumtype (klass))
1535 /* enums only have one non-static field */
1536 break;
1539 if (unhandled) {
1540 MonoArrayHandle fields_arr = mono_array_new_handle (mono_domain_get (), mono_defaults.object_class, count * 2, error);
1541 return_val_if_nok (error, 0);
1542 MONO_HANDLE_ASSIGN (fields, fields_arr);
1543 MonoObjectHandle h = MONO_HANDLE_NEW (MonoObject, NULL);
1544 for (int i = 0; i < count; ++i) {
1545 MonoObject *o = mono_field_get_value_object_checked (mono_handle_domain (this_obj), unhandled [i], MONO_HANDLE_RAW (this_obj), error);
1546 return_val_if_nok (error, FALSE);
1547 MONO_HANDLE_ASSIGN_RAW (h, o);
1548 mono_array_handle_setref (fields_arr, i * 2, h);
1550 o = mono_field_get_value_object_checked (mono_handle_domain (this_obj), unhandled [i], MONO_HANDLE_RAW (that), error);
1551 return_val_if_nok (error, FALSE);
1552 MONO_HANDLE_ASSIGN_RAW (h, o);
1553 mono_array_handle_setref (fields_arr, (i * 2) + 1, h);
1555 return FALSE;
1556 } else {
1557 return TRUE;
1561 MonoReflectionTypeHandle
1562 ves_icall_System_Object_GetType (MonoObjectHandle obj, MonoError *error)
1564 MonoDomain *domain = MONO_HANDLE_DOMAIN (obj);
1565 MonoClass *klass = mono_handle_class (obj);
1566 #ifndef DISABLE_REMOTING
1567 if (mono_class_is_transparent_proxy (klass)) {
1568 MonoTransparentProxyHandle proxy_obj = MONO_HANDLE_CAST (MonoTransparentProxy, obj);
1569 MonoRemoteClass *remote_class = MONO_HANDLE_GETVAL (proxy_obj, remote_class);
1570 /* If it's a transparent proxy for an interface, return the
1571 * interface type, not the unhelpful proxy_class class (which
1572 * is just MarshalByRefObject). */
1573 MonoType *proxy_type =
1574 mono_remote_class_is_interface_proxy (remote_class) ?
1575 m_class_get_byval_arg (remote_class->interfaces[0]) :
1576 m_class_get_byval_arg (remote_class->proxy_class);
1577 return mono_type_get_object_handle (domain, proxy_type, error);
1578 } else
1579 #endif
1580 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
1583 static gboolean
1584 get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1586 MonoMethod **dest = (MonoMethod **)data;
1588 /* skip unmanaged frames */
1589 if (!managed)
1590 return FALSE;
1592 if (!(*dest)) {
1593 if (!strcmp (m_class_get_name_space (m->klass), "System.Reflection"))
1594 return FALSE;
1595 *dest = m;
1596 return TRUE;
1598 return FALSE;
1601 static gboolean
1602 in_corlib_name_space (MonoClass *klass, const char *name_space)
1604 return m_class_get_image (klass) == mono_defaults.corlib &&
1605 !strcmp (m_class_get_name_space (klass), name_space);
1608 static gboolean
1609 get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1611 MonoMethod **dest = (MonoMethod **)data;
1613 /* skip unmanaged frames */
1614 if (!managed)
1615 return FALSE;
1617 if (m->wrapper_type != MONO_WRAPPER_NONE)
1618 return FALSE;
1620 if (m == *dest) {
1621 *dest = NULL;
1622 return FALSE;
1625 if (in_corlib_name_space (m->klass, "System.Reflection"))
1626 return FALSE;
1628 if (!(*dest)) {
1629 *dest = m;
1630 return TRUE;
1632 return FALSE;
1635 static gboolean
1636 get_caller_no_system_or_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1638 MonoMethod **dest = (MonoMethod **)data;
1640 /* skip unmanaged frames */
1641 if (!managed)
1642 return FALSE;
1644 if (m->wrapper_type != MONO_WRAPPER_NONE)
1645 return FALSE;
1647 if (m == *dest) {
1648 *dest = NULL;
1649 return FALSE;
1652 if (in_corlib_name_space (m->klass, "System.Reflection") || in_corlib_name_space (m->klass, "System"))
1653 return FALSE;
1655 if (!(*dest)) {
1656 *dest = m;
1657 return TRUE;
1659 return FALSE;
1663 * mono_runtime_get_caller_no_system_or_reflection:
1665 * Walk the stack of the current thread and find the first managed method that
1666 * is not in the mscorlib System or System.Reflection namespace. This skips
1667 * unmanaged callers and wrapper methods.
1669 * \returns a pointer to the \c MonoMethod or NULL if we walked past all the
1670 * callers.
1672 MonoMethod*
1673 mono_runtime_get_caller_no_system_or_reflection (void)
1675 MonoMethod *dest = NULL;
1676 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1677 return dest;
1681 * mono_runtime_get_caller_from_stack_mark:
1683 * Walk the stack and return the assembly of the method referenced
1684 * by the stack mark STACK_MARK.
1686 MonoAssembly*
1687 mono_runtime_get_caller_from_stack_mark (MonoStackCrawlMark *stack_mark)
1689 // FIXME: Use the stack mark
1690 MonoMethod *dest = NULL;
1691 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1692 if (dest)
1693 return m_class_get_image (dest->klass)->assembly;
1694 else
1695 return NULL;
1698 static MonoReflectionTypeHandle
1699 type_from_parsed_name (MonoTypeNameParse *info, MonoStackCrawlMark *stack_mark, MonoBoolean ignoreCase, MonoAssembly **caller_assembly, MonoError *error)
1701 MonoMethod *m;
1702 MonoType *type = NULL;
1703 MonoAssembly *assembly = NULL;
1704 gboolean type_resolve = FALSE;
1705 MonoImage *rootimage = NULL;
1707 error_init (error);
1710 * We must compute the calling assembly as type loading must happen under a metadata context.
1711 * For example. The main assembly is a.exe and Type.GetType is called from dir/b.dll. Without
1712 * the metadata context (basedir currently) set to dir/b.dll we won't be able to load a dir/c.dll.
1714 m = mono_method_get_last_managed ();
1715 if (m && m_class_get_image (m->klass) != mono_defaults.corlib) {
1716 /* Happens with inlining */
1717 assembly = m_class_get_image (m->klass)->assembly;
1718 } else {
1719 assembly = mono_runtime_get_caller_from_stack_mark (stack_mark);
1721 if (assembly) {
1722 type_resolve = TRUE;
1723 rootimage = assembly->image;
1724 } else {
1725 g_warning (G_STRLOC);
1727 *caller_assembly = assembly;
1729 if (info->assembly.name)
1730 assembly = mono_assembly_load (&info->assembly, assembly ? assembly->basedir : NULL, NULL);
1732 if (assembly) {
1733 /* When loading from the current assembly, AppDomain.TypeResolve will not be called yet */
1734 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, TRUE, &type_resolve, error);
1735 goto_if_nok (error, fail);
1738 // XXXX - aleksey -
1739 // Say we're looking for System.Generic.Dict<int, Local>
1740 // we FAIL the get type above, because S.G.Dict isn't in assembly->image. So we drop down here.
1741 // but then we FAIL AGAIN because now we pass null as the image and the rootimage and everything
1742 // is messed up when we go to construct the Local as the type arg...
1744 // By contrast, if we started with Mine<System.Generic.Dict<int, Local>> we'd go in with assembly->image
1745 // as the root and then even the detour into generics would still not screw us when we went to load Local.
1746 if (!info->assembly.name && !type) {
1747 /* try mscorlib */
1748 type = mono_reflection_get_type_checked (rootimage, NULL, info, ignoreCase, TRUE, &type_resolve, error);
1749 goto_if_nok (error, fail);
1751 if (assembly && !type && type_resolve) {
1752 type_resolve = FALSE; /* This will invoke TypeResolve if not done in the first 'if' */
1753 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, TRUE, &type_resolve, error);
1754 goto_if_nok (error, fail);
1757 if (!type)
1758 goto fail;
1760 return mono_type_get_object_handle (mono_domain_get (), type, error);
1761 fail:
1762 return MONO_HANDLE_NEW (MonoReflectionType, NULL);
1765 MonoReflectionTypeHandle
1766 ves_icall_System_RuntimeTypeHandle_internal_from_name (MonoStringHandle name,
1767 MonoStackCrawlMark *stack_mark,
1768 MonoReflectionAssemblyHandle callerAssembly,
1769 MonoBoolean throwOnError,
1770 MonoBoolean ignoreCase,
1771 MonoBoolean reflectionOnly,
1772 MonoError *error)
1774 MonoTypeNameParse info;
1775 gboolean free_info = FALSE;
1776 MonoAssembly *caller_assembly;
1777 MonoReflectionTypeHandle type = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1779 /* The callerAssembly argument is unused for now */
1781 char *str = mono_string_handle_to_utf8 (name, error);
1782 goto_if_nok (error, leave);
1784 free_info = TRUE;
1785 if (!mono_reflection_parse_type_checked (str, &info, error))
1786 goto leave;
1788 /* mono_reflection_parse_type() mangles the string */
1790 MONO_HANDLE_ASSIGN (type, type_from_parsed_name (&info, (MonoStackCrawlMark*)stack_mark, ignoreCase, &caller_assembly, error));
1792 goto_if_nok (error, leave);
1794 if (MONO_HANDLE_IS_NULL (type)) {
1795 if (throwOnError) {
1796 char *tname = info.name_space ? g_strdup_printf ("%s.%s", info.name_space, info.name) : g_strdup (info.name);
1797 char *aname;
1798 if (info.assembly.name)
1799 aname = mono_stringify_assembly_name (&info.assembly);
1800 else if (caller_assembly)
1801 aname = mono_stringify_assembly_name (mono_assembly_get_name_internal (caller_assembly));
1802 else
1803 aname = g_strdup ("");
1804 mono_error_set_type_load_name (error, tname, aname, "");
1806 goto leave;
1809 leave:
1810 if (free_info)
1811 mono_reflection_free_type_info (&info);
1812 g_free (str);
1813 if (!is_ok (error)) {
1814 if (!throwOnError) {
1815 mono_error_cleanup (error);
1816 error_init (error);
1818 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
1819 } else
1820 return type;
1824 MonoReflectionTypeHandle
1825 ves_icall_System_Type_internal_from_handle (MonoType *handle, MonoError *error)
1827 MonoDomain *domain = mono_domain_get ();
1829 return mono_type_get_object_handle (domain, handle, error);
1832 MonoType*
1833 ves_icall_Mono_RuntimeClassHandle_GetTypeFromClass (MonoClass *klass, MonoError *error)
1835 return m_class_get_byval_arg (klass);
1838 void
1839 ves_icall_Mono_RuntimeGPtrArrayHandle_GPtrArrayFree (GPtrArray *ptr_array, MonoError *error)
1841 g_ptr_array_free (ptr_array, TRUE);
1844 void
1845 ves_icall_Mono_SafeStringMarshal_GFree (void *c_str, MonoError *error)
1847 g_free (c_str);
1850 char*
1851 ves_icall_Mono_SafeStringMarshal_StringToUtf8 (MonoStringHandle s, MonoError *error)
1853 return mono_string_handle_to_utf8 (s, error);
1856 /* System.TypeCode */
1857 typedef enum {
1858 TYPECODE_EMPTY,
1859 TYPECODE_OBJECT,
1860 TYPECODE_DBNULL,
1861 TYPECODE_BOOLEAN,
1862 TYPECODE_CHAR,
1863 TYPECODE_SBYTE,
1864 TYPECODE_BYTE,
1865 TYPECODE_INT16,
1866 TYPECODE_UINT16,
1867 TYPECODE_INT32,
1868 TYPECODE_UINT32,
1869 TYPECODE_INT64,
1870 TYPECODE_UINT64,
1871 TYPECODE_SINGLE,
1872 TYPECODE_DOUBLE,
1873 TYPECODE_DECIMAL,
1874 TYPECODE_DATETIME,
1875 TYPECODE_STRING = 18
1876 } TypeCode;
1878 guint32
1879 ves_icall_type_GetTypeCodeInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
1881 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1882 int t = type->type;
1884 if (type->byref)
1885 return TYPECODE_OBJECT;
1887 handle_enum:
1888 switch (t) {
1889 case MONO_TYPE_VOID:
1890 return TYPECODE_OBJECT;
1891 case MONO_TYPE_BOOLEAN:
1892 return TYPECODE_BOOLEAN;
1893 case MONO_TYPE_U1:
1894 return TYPECODE_BYTE;
1895 case MONO_TYPE_I1:
1896 return TYPECODE_SBYTE;
1897 case MONO_TYPE_U2:
1898 return TYPECODE_UINT16;
1899 case MONO_TYPE_I2:
1900 return TYPECODE_INT16;
1901 case MONO_TYPE_CHAR:
1902 return TYPECODE_CHAR;
1903 case MONO_TYPE_PTR:
1904 case MONO_TYPE_U:
1905 case MONO_TYPE_I:
1906 return TYPECODE_OBJECT;
1907 case MONO_TYPE_U4:
1908 return TYPECODE_UINT32;
1909 case MONO_TYPE_I4:
1910 return TYPECODE_INT32;
1911 case MONO_TYPE_U8:
1912 return TYPECODE_UINT64;
1913 case MONO_TYPE_I8:
1914 return TYPECODE_INT64;
1915 case MONO_TYPE_R4:
1916 return TYPECODE_SINGLE;
1917 case MONO_TYPE_R8:
1918 return TYPECODE_DOUBLE;
1919 case MONO_TYPE_VALUETYPE: {
1920 MonoClass *klass = type->data.klass;
1922 if (m_class_is_enumtype (klass)) {
1923 t = mono_class_enum_basetype_internal (klass)->type;
1924 goto handle_enum;
1925 } else if (mono_is_corlib_image (m_class_get_image (klass))) {
1926 if (strcmp (m_class_get_name_space (klass), "System") == 0) {
1927 if (strcmp (m_class_get_name (klass), "Decimal") == 0)
1928 return TYPECODE_DECIMAL;
1929 else if (strcmp (m_class_get_name (klass), "DateTime") == 0)
1930 return TYPECODE_DATETIME;
1933 return TYPECODE_OBJECT;
1935 case MONO_TYPE_STRING:
1936 return TYPECODE_STRING;
1937 case MONO_TYPE_SZARRAY:
1938 case MONO_TYPE_ARRAY:
1939 case MONO_TYPE_OBJECT:
1940 case MONO_TYPE_VAR:
1941 case MONO_TYPE_MVAR:
1942 case MONO_TYPE_TYPEDBYREF:
1943 return TYPECODE_OBJECT;
1944 case MONO_TYPE_CLASS:
1946 MonoClass *klass = type->data.klass;
1947 if (m_class_get_image (klass) == mono_defaults.corlib && strcmp (m_class_get_name_space (klass), "System") == 0) {
1948 if (strcmp (m_class_get_name (klass), "DBNull") == 0)
1949 return TYPECODE_DBNULL;
1952 return TYPECODE_OBJECT;
1953 case MONO_TYPE_GENERICINST:
1954 return TYPECODE_OBJECT;
1955 default:
1956 g_error ("type 0x%02x not handled in GetTypeCode()", t);
1958 return 0;
1961 static MonoType*
1962 mono_type_get_underlying_type_ignore_byref (MonoType *type)
1964 if (type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (type->data.klass))
1965 return mono_class_enum_basetype_internal (type->data.klass);
1966 if (type->type == MONO_TYPE_GENERICINST && m_class_is_enumtype (type->data.generic_class->container_class))
1967 return mono_class_enum_basetype_internal (type->data.generic_class->container_class);
1968 return type;
1971 guint32
1972 ves_icall_RuntimeTypeHandle_type_is_assignable_from (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_c, MonoError *error)
1974 g_assert (!MONO_HANDLE_IS_NULL (ref_type));
1976 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1977 MonoClass *klass = mono_class_from_mono_type_internal (type);
1978 MonoType *ctype = MONO_HANDLE_GETVAL (ref_c, type);
1979 MonoClass *klassc = mono_class_from_mono_type_internal (ctype);
1981 if (type->byref ^ ctype->byref)
1982 return FALSE;
1984 if (type->byref) {
1985 MonoType *t = mono_type_get_underlying_type_ignore_byref (type);
1986 MonoType *ot = mono_type_get_underlying_type_ignore_byref (ctype);
1988 klass = mono_class_from_mono_type_internal (t);
1989 klassc = mono_class_from_mono_type_internal (ot);
1991 if (mono_type_is_primitive (t)) {
1992 return mono_type_is_primitive (ot) && m_class_get_instance_size (klass) == m_class_get_instance_size (klassc);
1993 } else if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) {
1994 return t->type == ot->type && t->data.generic_param->num == ot->data.generic_param->num;
1995 } else if (t->type == MONO_TYPE_PTR || t->type == MONO_TYPE_FNPTR) {
1996 return t->type == ot->type;
1997 } else {
1998 if (ot->type == MONO_TYPE_VAR || ot->type == MONO_TYPE_MVAR)
1999 return FALSE;
2001 if (m_class_is_valuetype (klass))
2002 return klass == klassc;
2003 return m_class_is_valuetype (klass) == m_class_is_valuetype (klassc);
2007 gboolean result;
2008 mono_class_is_assignable_from_checked (klass, klassc, &result, error);
2009 return (guint32)result;
2012 MonoBoolean
2013 ves_icall_RuntimeTypeHandle_is_subclass_of (MonoType *childType, MonoType *baseType)
2015 ERROR_DECL (error);
2016 mono_bool result = FALSE;
2017 MonoClass *childClass;
2018 MonoClass *baseClass;
2020 childClass = mono_class_from_mono_type_internal (childType);
2021 baseClass = mono_class_from_mono_type_internal (baseType);
2023 if (G_UNLIKELY (childType->byref)) {
2024 result = !baseType->byref && baseClass == mono_defaults.object_class;
2025 goto done;
2028 if (G_UNLIKELY (baseType->byref)) {
2029 result = FALSE;
2030 goto done;
2033 if (childType == baseType) {
2034 /* .NET IsSubclassOf is not reflexive */
2035 result = FALSE;
2036 goto done;
2039 if (G_UNLIKELY (is_generic_parameter (childType))) {
2040 /* slow path: walk the type hierarchy looking at base types
2041 * until we see baseType. If the current type is not a gparam,
2042 * break out of the loop and use is_subclass_of.
2044 MonoClass *c = mono_generic_param_get_base_type (childClass);
2046 result = FALSE;
2047 while (c != NULL) {
2048 if (c == baseClass) {
2049 result = TRUE;
2050 break;
2052 if (!is_generic_parameter (m_class_get_byval_arg (c))) {
2053 result = mono_class_is_subclass_of_internal (c, baseClass, FALSE);
2054 break;
2055 } else
2056 c = mono_generic_param_get_base_type (c);
2058 } else {
2059 result = mono_class_is_subclass_of_internal (childClass, baseClass, FALSE);
2061 done:
2062 mono_error_set_pending_exception (error);
2063 return result;
2066 guint32
2067 ves_icall_RuntimeTypeHandle_IsInstanceOfType (MonoReflectionTypeHandle ref_type, MonoObjectHandle obj, MonoError *error)
2069 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2070 MonoClass *klass = mono_class_from_mono_type_internal (type);
2071 mono_class_init_checked (klass, error);
2072 return_val_if_nok (error, FALSE);
2073 MonoObjectHandle inst = mono_object_handle_isinst (obj, klass, error);
2074 return_val_if_nok (error, FALSE);
2075 return !MONO_HANDLE_IS_NULL (inst);
2078 guint32
2079 ves_icall_RuntimeTypeHandle_GetAttributes (MonoReflectionTypeHandle ref_type, MonoError *error)
2081 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2083 #ifdef ENABLE_NETCORE
2084 if (type->byref || type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR)
2085 return TYPE_ATTRIBUTE_NOT_PUBLIC;
2086 #endif
2088 MonoClass *klass = mono_class_from_mono_type_internal (type);
2089 return mono_class_get_flags (klass);
2092 MonoReflectionMarshalAsAttributeHandle
2093 ves_icall_System_Reflection_FieldInfo_get_marshal_info (MonoReflectionFieldHandle field_h, MonoError *error)
2095 MonoDomain *domain = MONO_HANDLE_DOMAIN (field_h);
2096 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
2097 MonoClass *klass = field->parent;
2099 MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
2100 if (mono_class_is_gtd (klass) ||
2101 (gklass && gklass->context.class_inst->is_open))
2102 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
2104 MonoType *ftype = mono_field_get_type_internal (field);
2105 if (ftype && !(ftype->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL))
2106 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
2108 MonoMarshalType *info = mono_marshal_load_type_info (klass);
2110 for (int i = 0; i < info->num_fields; ++i) {
2111 if (info->fields [i].field == field) {
2112 if (!info->fields [i].mspec)
2113 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
2114 else {
2115 return mono_reflection_marshal_as_attribute_from_marshal_spec (domain, klass, info->fields [i].mspec, error);
2120 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
2123 MonoReflectionFieldHandle
2124 ves_icall_System_Reflection_FieldInfo_internal_from_handle_type (MonoClassField *handle, MonoType *type, MonoError *error)
2126 MonoClass *klass;
2128 g_assert (handle);
2130 if (!type) {
2131 klass = handle->parent;
2132 } else {
2133 klass = mono_class_from_mono_type_internal (type);
2135 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
2137 if (!found)
2138 /* The managed code will throw the exception */
2139 return MONO_HANDLE_CAST (MonoReflectionField, NULL_HANDLE);
2142 return mono_field_get_object_handle (mono_domain_get (), klass, handle, error);
2145 MonoReflectionEventHandle
2146 ves_icall_System_Reflection_EventInfo_internal_from_handle_type (MonoEvent *handle, MonoType *type, MonoError *error)
2148 MonoClass *klass;
2150 g_assert (handle);
2152 if (!type) {
2153 klass = handle->parent;
2154 } else {
2155 klass = mono_class_from_mono_type_internal (type);
2157 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
2158 if (!found)
2159 /* Managed code will throw an exception */
2160 return MONO_HANDLE_CAST (MonoReflectionEvent, NULL_HANDLE);
2163 return mono_event_get_object_handle (mono_domain_get (), klass, handle, error);
2166 MonoReflectionPropertyHandle
2167 ves_icall_System_Reflection_RuntimePropertyInfo_internal_from_handle_type (MonoProperty *handle, MonoType *type, MonoError *error)
2169 MonoClass *klass;
2171 g_assert (handle);
2173 if (!type) {
2174 klass = handle->parent;
2175 } else {
2176 klass = mono_class_from_mono_type_internal (type);
2178 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
2179 if (!found)
2180 /* Managed code will throw an exception */
2181 return MONO_HANDLE_CAST (MonoReflectionProperty, NULL_HANDLE);
2184 return mono_property_get_object_handle (mono_domain_get (), klass, handle, error);
2187 MonoArrayHandle
2188 ves_icall_System_Reflection_FieldInfo_GetTypeModifiers (MonoReflectionFieldHandle field_h, MonoBoolean optional, MonoError *error)
2190 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
2192 MonoType *type = mono_field_get_type_checked (field, error);
2193 return_val_if_nok (error, NULL_HANDLE_ARRAY);
2195 return type_array_from_modifiers (m_class_get_image (field->parent), type, optional, error);
2199 ves_icall_get_method_attributes (MonoMethod *method)
2201 return method->flags;
2204 void
2205 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info, MonoError *error)
2207 MonoDomain *domain = mono_domain_get ();
2209 MonoMethodSignature* sig = mono_method_signature_checked (method, error);
2210 return_if_nok (error);
2212 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (method->klass), error);
2213 return_if_nok (error);
2215 MONO_STRUCT_SETREF_INTERNAL (info, parent, MONO_HANDLE_RAW (rt));
2217 MONO_HANDLE_ASSIGN (rt, mono_type_get_object_handle (domain, sig->ret, error));
2218 return_if_nok (error);
2220 MONO_STRUCT_SETREF_INTERNAL (info, ret, MONO_HANDLE_RAW (rt));
2222 info->attrs = method->flags;
2223 info->implattrs = method->iflags;
2224 guint32 callconv;
2225 if (sig->call_convention == MONO_CALL_DEFAULT)
2226 callconv = sig->sentinelpos >= 0 ? 2 : 1;
2227 else {
2228 if (sig->call_convention == MONO_CALL_VARARG || sig->sentinelpos >= 0)
2229 callconv = 2;
2230 else
2231 callconv = 1;
2233 callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6);
2234 info->callconv = callconv;
2237 MonoArrayHandle
2238 ves_icall_System_Reflection_MonoMethodInfo_get_parameter_info (MonoMethod *method, MonoReflectionMethodHandle member, MonoError *error)
2240 MonoDomain *domain = mono_domain_get ();
2242 MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
2243 MONO_HANDLE_GET (reftype, member, reftype);
2244 MonoClass *klass = NULL;
2245 if (!MONO_HANDLE_IS_NULL (reftype))
2246 klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (reftype, type));
2247 return mono_param_get_objects_internal (domain, method, klass, error);
2250 MonoReflectionMarshalAsAttributeHandle
2251 ves_icall_System_MonoMethodInfo_get_retval_marshal (MonoMethod *method, MonoError *error)
2253 MonoDomain *domain = mono_domain_get ();
2254 MonoReflectionMarshalAsAttributeHandle res = MONO_HANDLE_NEW (MonoReflectionMarshalAsAttribute, NULL);
2256 MonoMarshalSpec **mspecs = g_new (MonoMarshalSpec*, mono_method_signature_internal (method)->param_count + 1);
2257 mono_method_get_marshal_info (method, mspecs);
2259 if (mspecs [0]) {
2260 MONO_HANDLE_ASSIGN (res, mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [0], error));
2261 goto_if_nok (error, leave);
2264 leave:
2265 for (int i = mono_method_signature_internal (method)->param_count; i >= 0; i--)
2266 if (mspecs [i])
2267 mono_metadata_free_marshal_spec (mspecs [i]);
2268 g_free (mspecs);
2270 return res;
2273 gint32
2274 ves_icall_RuntimeFieldInfo_GetFieldOffset (MonoReflectionFieldHandle field, MonoError *error)
2276 MonoClassField *class_field = MONO_HANDLE_GETVAL (field, field);
2277 mono_class_setup_fields (class_field->parent);
2279 return class_field->offset - MONO_ABI_SIZEOF (MonoObject);
2282 MonoReflectionTypeHandle
2283 ves_icall_RuntimeFieldInfo_GetParentType (MonoReflectionFieldHandle field, MonoBoolean declaring, MonoError *error)
2285 MonoDomain *domain = MONO_HANDLE_DOMAIN (field);
2286 MonoClass *parent;
2288 if (declaring) {
2289 MonoClassField *f = MONO_HANDLE_GETVAL (field, field);
2290 parent = f->parent;
2291 } else {
2292 parent = MONO_HANDLE_GETVAL (field, klass);
2295 return mono_type_get_object_handle (domain, m_class_get_byval_arg (parent), error);
2298 MonoObject *
2299 ves_icall_RuntimeFieldInfo_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
2301 ERROR_DECL (error);
2302 MonoClass *fklass = field->klass;
2303 MonoClassField *cf = field->field;
2304 MonoDomain *domain = mono_object_domain (field);
2306 if (mono_asmctx_get_kind (&m_class_get_image (fklass)->assembly->context) == MONO_ASMCTX_REFONLY) {
2307 mono_error_set_invalid_operation (error,
2308 "It is illegal to get the value on a field on a type loaded using the ReflectionOnly methods.");
2309 mono_error_set_pending_exception (error);
2310 return NULL;
2313 if (mono_security_core_clr_enabled () &&
2314 !mono_security_core_clr_ensure_reflection_access_field (cf, error)) {
2315 mono_error_set_pending_exception (error);
2316 return NULL;
2319 #ifndef DISABLE_REMOTING
2320 if (G_UNLIKELY (obj != NULL && mono_class_is_transparent_proxy (mono_object_class (obj)))) {
2321 /* We get here if someone used a
2322 * System.Reflection.FieldInfo:GetValue on a
2323 * ContextBoundObject's or cross-domain MarshalByRefObject's
2324 * transparent proxy. */
2325 MonoObject *result = mono_load_remote_field_new_checked (obj, fklass, cf, error);
2326 mono_error_set_pending_exception (error);
2327 return result;
2329 #endif
2331 MonoObject * result = mono_field_get_value_object_checked (domain, cf, obj, error);
2332 mono_error_set_pending_exception (error);
2333 return result;
2336 void
2337 ves_icall_RuntimeFieldInfo_SetValueInternal (MonoReflectionFieldHandle field, MonoObjectHandle obj, MonoObjectHandle value, MonoError *error)
2339 MonoClassField *cf = MONO_HANDLE_GETVAL (field, field);
2341 MonoClass *field_klass = MONO_HANDLE_GETVAL (field, klass);
2342 if (mono_asmctx_get_kind (&m_class_get_image (field_klass)->assembly->context) == MONO_ASMCTX_REFONLY) {
2343 mono_error_set_invalid_operation (error, "It is illegal to set the value on a field on a type loaded using the ReflectionOnly methods.");
2344 return;
2347 if (mono_security_core_clr_enabled () &&
2348 !mono_security_core_clr_ensure_reflection_access_field (cf, error)) {
2349 return;
2352 #ifndef DISABLE_REMOTING
2353 if (G_UNLIKELY (!MONO_HANDLE_IS_NULL (obj) && mono_class_is_transparent_proxy (mono_handle_class (obj)))) {
2354 /* We get here if someone used a
2355 * System.Reflection.FieldInfo:SetValue on a
2356 * ContextBoundObject's or cross-domain MarshalByRefObject's
2357 * transparent proxy. */
2358 /* FIXME: use handles for mono_store_remote_field_new_checked */
2359 MonoObject *v = MONO_HANDLE_RAW (value);
2360 MonoObject *o = MONO_HANDLE_RAW (obj);
2361 mono_store_remote_field_new_checked (o, field_klass, cf, v, error);
2362 return;
2364 #endif
2366 MonoType *type = mono_field_get_type_checked (cf, error);
2367 return_if_nok (error);
2369 gboolean isref = FALSE;
2370 uint32_t value_gchandle = 0;
2371 gchar *v = NULL;
2372 if (!type->byref) {
2373 switch (type->type) {
2374 case MONO_TYPE_U1:
2375 case MONO_TYPE_I1:
2376 case MONO_TYPE_BOOLEAN:
2377 case MONO_TYPE_U2:
2378 case MONO_TYPE_I2:
2379 case MONO_TYPE_CHAR:
2380 case MONO_TYPE_U:
2381 case MONO_TYPE_I:
2382 case MONO_TYPE_U4:
2383 case MONO_TYPE_I4:
2384 case MONO_TYPE_R4:
2385 case MONO_TYPE_U8:
2386 case MONO_TYPE_I8:
2387 case MONO_TYPE_R8:
2388 case MONO_TYPE_VALUETYPE:
2389 case MONO_TYPE_PTR:
2390 isref = FALSE;
2391 if (!MONO_HANDLE_IS_NULL (value))
2392 v = (char*)mono_object_handle_pin_unbox (value, &value_gchandle);
2393 break;
2394 case MONO_TYPE_STRING:
2395 case MONO_TYPE_OBJECT:
2396 case MONO_TYPE_CLASS:
2397 case MONO_TYPE_ARRAY:
2398 case MONO_TYPE_SZARRAY:
2399 /* Do nothing */
2400 isref = TRUE;
2401 break;
2402 case MONO_TYPE_GENERICINST: {
2403 MonoGenericClass *gclass = type->data.generic_class;
2404 g_assert (!gclass->context.class_inst->is_open);
2406 if (mono_class_is_nullable (mono_class_from_mono_type_internal (type))) {
2407 MonoClass *nklass = mono_class_from_mono_type_internal (type);
2410 * Convert the boxed vtype into a Nullable structure.
2411 * This is complicated by the fact that Nullables have
2412 * a variable structure.
2414 MonoObjectHandle nullable = mono_object_new_handle (mono_domain_get (), nklass, error);
2415 return_if_nok (error);
2417 uint32_t nullable_gchandle = 0;
2418 guint8 *nval = (guint8*)mono_object_handle_pin_unbox (nullable, &nullable_gchandle);
2419 mono_nullable_init_from_handle (nval, value, nklass);
2421 isref = FALSE;
2422 value_gchandle = nullable_gchandle;
2423 v = (gchar*)nval;
2425 else {
2426 isref = !m_class_is_valuetype (gclass->container_class);
2427 if (!isref && !MONO_HANDLE_IS_NULL (value)) {
2428 v = (char*)mono_object_handle_pin_unbox (value, &value_gchandle);
2431 break;
2433 default:
2434 g_error ("type 0x%x not handled in "
2435 "ves_icall_FieldInfo_SetValueInternal", type->type);
2436 return;
2440 /* either value is a reference type, or it's a value type and we pinned
2441 * it and v points to the payload. */
2442 g_assert ((isref && v == NULL && value_gchandle == 0) ||
2443 (!isref && v != NULL && value_gchandle != 0) ||
2444 (!isref && v == NULL && value_gchandle == 0));
2446 if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
2447 MonoVTable *vtable = mono_class_vtable_checked (MONO_HANDLE_DOMAIN (field), cf->parent, error);
2448 goto_if_nok (error, leave);
2450 if (!vtable->initialized) {
2451 if (!mono_runtime_class_init_full (vtable, error))
2452 goto leave;
2454 if (isref)
2455 mono_field_static_set_value_internal (vtable, cf, MONO_HANDLE_RAW (value)); /* FIXME make mono_field_static_set_value work with handles for value */
2456 else
2457 mono_field_static_set_value_internal (vtable, cf, v);
2458 } else {
2460 if (isref)
2461 MONO_HANDLE_SET_FIELD_REF (obj, cf, value);
2462 else
2463 mono_field_set_value_internal (MONO_HANDLE_RAW (obj), cf, v); /* FIXME: make mono_field_set_value take a handle for obj */
2465 leave:
2466 if (value_gchandle)
2467 mono_gchandle_free_internal (value_gchandle);
2470 static MonoObjectHandle
2471 typed_reference_to_object (MonoTypedRef *tref, MonoError *error)
2473 HANDLE_FUNCTION_ENTER ();
2474 MonoObjectHandle result;
2475 if (MONO_TYPE_IS_REFERENCE (tref->type)) {
2476 MonoObject** objp = (MonoObject **)tref->value;
2477 result = MONO_HANDLE_NEW (MonoObject, *objp);
2478 } else if (mono_type_is_pointer (tref->type)) {
2479 /* Boxed as UIntPtr */
2480 result = mono_value_box_handle (mono_domain_get (), mono_get_uintptr_class (), tref->value, error);
2481 } else {
2482 result = mono_value_box_handle (mono_domain_get (), tref->klass, tref->value, error);
2484 HANDLE_FUNCTION_RETURN_REF (MonoObject, result);
2487 MonoObjectHandle
2488 ves_icall_System_RuntimeFieldHandle_GetValueDirect (MonoReflectionFieldHandle field_h, MonoReflectionTypeHandle field_type_h, MonoTypedRef *obj, MonoReflectionTypeHandle context_type_h, MonoError *error)
2490 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
2491 MonoClass *klass = mono_class_from_mono_type_internal (field->type);
2493 if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (field->parent))) {
2494 mono_error_set_not_implemented (error, "");
2495 return MONO_HANDLE_NEW (MonoObject, NULL);
2496 } else if (MONO_TYPE_IS_REFERENCE (field->type)) {
2497 return MONO_HANDLE_NEW (MonoObject, *(MonoObject**)((guint8*)obj->value + field->offset - sizeof (MonoObject)));
2498 } else {
2499 return mono_value_box_handle (mono_domain_get (), klass, (guint8*)obj->value + field->offset - sizeof (MonoObject), error);
2503 void
2504 ves_icall_System_RuntimeFieldHandle_SetValueDirect (MonoReflectionFieldHandle field_h, MonoReflectionTypeHandle field_type_h, MonoTypedRef *obj, MonoObjectHandle value_h, MonoReflectionTypeHandle context_type_h, MonoError *error)
2506 MonoClassField *f = MONO_HANDLE_GETVAL (field_h, field);
2508 g_assert (obj);
2510 if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (f->parent))) {
2511 MonoObjectHandle objHandle = typed_reference_to_object (obj, error);
2512 return_if_nok (error);
2513 ves_icall_RuntimeFieldInfo_SetValueInternal (field_h, objHandle, value_h, error);
2514 } else if (MONO_TYPE_IS_REFERENCE (f->type)) {
2515 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), MONO_HANDLE_RAW (value_h), FALSE);
2516 } else {
2517 guint gchandle = 0;
2518 g_assert (MONO_HANDLE_RAW (value_h));
2519 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), mono_object_handle_pin_unbox (value_h, &gchandle), FALSE);
2520 mono_gchandle_free_internal (gchandle);
2524 MonoObjectHandle
2525 ves_icall_RuntimeFieldInfo_GetRawConstantValue (MonoReflectionFieldHandle rfield, MonoError* error)
2527 MonoObjectHandle o_handle = NULL_HANDLE_INIT;
2529 MonoObject *o = NULL;
2530 MonoClassField *field = MONO_HANDLE_GETVAL (rfield, field);
2531 MonoClass *klass;
2532 MonoDomain *domain = MONO_HANDLE_DOMAIN (rfield);
2533 gchar *v;
2534 MonoTypeEnum def_type;
2535 const char *def_value;
2536 MonoType *t;
2538 mono_class_init_internal (field->parent);
2540 t = mono_field_get_type_checked (field, error);
2541 goto_if_nok (error, return_null);
2543 if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT))
2544 goto invalid_operation;
2546 if (image_is_dynamic (m_class_get_image (field->parent))) {
2547 MonoClass *klass = field->parent;
2548 int fidx = field - m_class_get_fields (klass);
2549 MonoFieldDefaultValue *def_values = mono_class_get_field_def_values (klass);
2551 g_assert (def_values);
2552 def_type = def_values [fidx].def_type;
2553 def_value = def_values [fidx].data;
2555 if (def_type == MONO_TYPE_END)
2556 goto invalid_operation;
2557 } else {
2558 def_value = mono_class_get_field_default_value (field, &def_type);
2559 /* FIXME, maybe we should try to raise TLE if field->parent is broken */
2560 if (!def_value)
2561 goto invalid_operation;
2564 /*FIXME unify this with reflection.c:mono_get_object_from_blob*/
2565 switch (def_type) {
2566 case MONO_TYPE_U1:
2567 case MONO_TYPE_I1:
2568 case MONO_TYPE_BOOLEAN:
2569 case MONO_TYPE_U2:
2570 case MONO_TYPE_I2:
2571 case MONO_TYPE_CHAR:
2572 case MONO_TYPE_U:
2573 case MONO_TYPE_I:
2574 case MONO_TYPE_U4:
2575 case MONO_TYPE_I4:
2576 case MONO_TYPE_R4:
2577 case MONO_TYPE_U8:
2578 case MONO_TYPE_I8:
2579 case MONO_TYPE_R8: {
2580 MonoType *t;
2582 /* boxed value type */
2583 t = g_new0 (MonoType, 1);
2584 t->type = def_type;
2585 klass = mono_class_from_mono_type_internal (t);
2586 g_free (t);
2587 o = mono_object_new_checked (domain, klass, error);
2588 goto_if_nok (error, return_null);
2589 o_handle = MONO_HANDLE_NEW (MonoObject, o);
2590 v = ((gchar *) o) + sizeof (MonoObject);
2591 mono_get_constant_value_from_blob (domain, def_type, def_value, v, error);
2592 goto_if_nok (error, return_null);
2593 break;
2595 case MONO_TYPE_STRING:
2596 case MONO_TYPE_CLASS:
2597 mono_get_constant_value_from_blob (domain, def_type, def_value, &o, error);
2598 goto_if_nok (error, return_null);
2599 o_handle = MONO_HANDLE_NEW (MonoObject, o);
2600 break;
2601 default:
2602 g_assert_not_reached ();
2605 goto exit;
2606 invalid_operation:
2607 mono_error_set_invalid_operation (error, NULL);
2608 // fall through
2609 return_null:
2610 o_handle = NULL_HANDLE;
2611 // fall through
2612 exit:
2613 return o_handle;
2616 MonoReflectionTypeHandle
2617 ves_icall_RuntimeFieldInfo_ResolveType (MonoReflectionFieldHandle ref_field, MonoError *error)
2619 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_field);
2620 MonoClassField *field = MONO_HANDLE_GETVAL (ref_field, field);
2621 MonoType *type = mono_field_get_type_checked (field, error);
2622 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
2623 return mono_type_get_object_handle (domain, type, error);
2626 void
2627 ves_icall_RuntimePropertyInfo_get_property_info (MonoReflectionPropertyHandle property, MonoPropertyInfo *info, PInfo req_info, MonoError *error)
2629 MonoDomain *domain = MONO_HANDLE_DOMAIN (property);
2630 const MonoProperty *pproperty = MONO_HANDLE_GETVAL (property, property);
2632 if ((req_info & PInfo_ReflectedType) != 0) {
2633 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
2634 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2635 return_if_nok (error);
2637 MONO_STRUCT_SETREF_INTERNAL (info, parent, MONO_HANDLE_RAW (rt));
2639 if ((req_info & PInfo_DeclaringType) != 0) {
2640 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (pproperty->parent), error);
2641 return_if_nok (error);
2643 MONO_STRUCT_SETREF_INTERNAL (info, declaring_type, MONO_HANDLE_RAW (rt));
2646 if ((req_info & PInfo_Name) != 0) {
2647 MonoStringHandle name = mono_string_new_handle (domain, pproperty->name, error);
2648 return_if_nok (error);
2650 MONO_STRUCT_SETREF_INTERNAL (info, name, MONO_HANDLE_RAW (name));
2653 if ((req_info & PInfo_Attributes) != 0)
2654 info->attrs = pproperty->attrs;
2656 if ((req_info & PInfo_GetMethod) != 0) {
2657 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2658 MonoReflectionMethodHandle rm;
2659 if (pproperty->get &&
2660 (((pproperty->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2661 pproperty->get->klass == property_klass)) {
2662 rm = mono_method_get_object_handle (domain, pproperty->get, property_klass, error);
2663 return_if_nok (error);
2664 } else {
2665 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2668 MONO_STRUCT_SETREF_INTERNAL (info, get, MONO_HANDLE_RAW (rm));
2670 if ((req_info & PInfo_SetMethod) != 0) {
2671 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2672 MonoReflectionMethodHandle rm;
2673 if (pproperty->set &&
2674 (((pproperty->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2675 pproperty->set->klass == property_klass)) {
2676 rm = mono_method_get_object_handle (domain, pproperty->set, property_klass, error);
2677 return_if_nok (error);
2678 } else {
2679 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2682 MONO_STRUCT_SETREF_INTERNAL (info, set, MONO_HANDLE_RAW (rm));
2685 * There may be other methods defined for properties, though, it seems they are not exposed
2686 * in the reflection API
2690 static gboolean
2691 add_event_other_methods_to_array (MonoDomain *domain, MonoMethod *m, MonoArrayHandle dest, int i, MonoError *error)
2693 HANDLE_FUNCTION_ENTER ();
2694 error_init (error);
2695 MonoReflectionMethodHandle rm = mono_method_get_object_handle (domain, m, NULL, error);
2696 goto_if_nok (error, leave);
2697 MONO_HANDLE_ARRAY_SETREF (dest, i, rm);
2698 leave:
2699 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2702 void
2703 ves_icall_RuntimeEventInfo_get_event_info (MonoReflectionMonoEventHandle ref_event, MonoEventInfo *info, MonoError *error)
2705 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_event);
2707 MonoClass *klass = MONO_HANDLE_GETVAL (ref_event, klass);
2708 MonoEvent *event = MONO_HANDLE_GETVAL (ref_event, event);
2710 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2711 return_if_nok (error);
2712 MONO_STRUCT_SETREF_INTERNAL (info, reflected_type, MONO_HANDLE_RAW (rt));
2714 rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (event->parent), error);
2715 return_if_nok (error);
2716 MONO_STRUCT_SETREF_INTERNAL (info, declaring_type, MONO_HANDLE_RAW (rt));
2718 MonoStringHandle ev_name = mono_string_new_handle (domain, event->name, error);
2719 return_if_nok (error);
2720 MONO_STRUCT_SETREF_INTERNAL (info, name, MONO_HANDLE_RAW (ev_name));
2722 info->attrs = event->attrs;
2724 MonoReflectionMethodHandle rm;
2725 if (event->add) {
2726 rm = mono_method_get_object_handle (domain, event->add, klass, error);
2727 return_if_nok (error);
2728 } else {
2729 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2732 MONO_STRUCT_SETREF_INTERNAL (info, add_method, MONO_HANDLE_RAW (rm));
2734 if (event->remove) {
2735 rm = mono_method_get_object_handle (domain, event->remove, klass, error);
2736 return_if_nok (error);
2737 } else {
2738 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2741 MONO_STRUCT_SETREF_INTERNAL (info, remove_method, MONO_HANDLE_RAW (rm));
2743 if (event->raise) {
2744 rm = mono_method_get_object_handle (domain, event->raise, klass, error);
2745 return_if_nok (error);
2746 } else {
2747 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2750 MONO_STRUCT_SETREF_INTERNAL (info, raise_method, MONO_HANDLE_RAW (rm));
2752 #ifndef MONO_SMALL_CONFIG
2753 if (event->other) {
2754 int i, n = 0;
2755 while (event->other [n])
2756 n++;
2757 MonoArrayHandle info_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, n, error);
2758 return_if_nok (error);
2760 MONO_STRUCT_SETREF_INTERNAL (info, other_methods, MONO_HANDLE_RAW (info_arr));
2762 for (i = 0; i < n; i++)
2763 if (!add_event_other_methods_to_array (domain, event->other [i], info_arr, i, error))
2764 return;
2766 #endif
2769 static void
2770 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
2772 int i;
2773 MonoClass *ic;
2775 mono_class_setup_interfaces (klass, error);
2776 return_if_nok (error);
2778 int klass_interface_count = m_class_get_interface_count (klass);
2779 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
2780 for (i = 0; i < klass_interface_count; i++) {
2781 ic = klass_interfaces [i];
2782 g_hash_table_insert (ifaces, ic, ic);
2784 collect_interfaces (ic, ifaces, error);
2785 return_if_nok (error);
2789 typedef struct {
2790 MonoArrayHandle iface_array;
2791 MonoGenericContext *context;
2792 MonoError *error;
2793 MonoDomain *domain;
2794 int next_idx;
2795 } FillIfaceArrayData;
2797 static void
2798 fill_iface_array (gpointer key, gpointer value, gpointer user_data)
2800 HANDLE_FUNCTION_ENTER ();
2801 FillIfaceArrayData *data = (FillIfaceArrayData *)user_data;
2802 MonoClass *ic = (MonoClass *)key;
2803 MonoType *ret = m_class_get_byval_arg (ic), *inflated = NULL;
2804 MonoError *error = data->error;
2806 goto_if_nok (error, leave);
2808 if (data->context && mono_class_is_ginst (ic) && mono_class_get_generic_class (ic)->context.class_inst->is_open) {
2809 inflated = ret = mono_class_inflate_generic_type_checked (ret, data->context, error);
2810 goto_if_nok (error, leave);
2813 MonoReflectionTypeHandle rt;
2814 rt = mono_type_get_object_handle (data->domain, ret, error);
2815 goto_if_nok (error, leave);
2817 MONO_HANDLE_ARRAY_SETREF (data->iface_array, data->next_idx, rt);
2818 data->next_idx++;
2820 if (inflated)
2821 mono_metadata_free_type (inflated);
2822 leave:
2823 HANDLE_FUNCTION_RETURN ();
2826 static guint
2827 get_interfaces_hash (gconstpointer v1)
2829 MonoClass *k = (MonoClass*)v1;
2831 return m_class_get_type_token (k);
2834 MonoArrayHandle
2835 ves_icall_RuntimeType_GetInterfaces (MonoReflectionTypeHandle ref_type, MonoError *error)
2837 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2838 MonoClass *klass = mono_class_from_mono_type_internal (type);
2840 GHashTable *iface_hash = g_hash_table_new (get_interfaces_hash, NULL);
2842 MonoGenericContext *context = NULL;
2843 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open) {
2844 context = mono_class_get_context (klass);
2845 klass = mono_class_get_generic_class (klass)->container_class;
2848 for (MonoClass *parent = klass; parent; parent = m_class_get_parent (parent)) {
2849 mono_class_setup_interfaces (parent, error);
2850 goto_if_nok (error, fail);
2851 collect_interfaces (parent, iface_hash, error);
2852 goto_if_nok (error, fail);
2855 MonoDomain *domain;
2856 domain = MONO_HANDLE_DOMAIN (ref_type);
2858 int len;
2859 len = g_hash_table_size (iface_hash);
2860 if (len == 0) {
2861 g_hash_table_destroy (iface_hash);
2862 if (!domain->empty_types) {
2863 domain->empty_types = mono_array_new_cached (domain, mono_defaults.runtimetype_class, 0, error);
2864 goto_if_nok (error, fail);
2866 return MONO_HANDLE_NEW (MonoArray, domain->empty_types);
2869 FillIfaceArrayData data;
2870 data.iface_array = MONO_HANDLE_NEW (MonoArray, mono_array_new_cached (domain, mono_defaults.runtimetype_class, len, error));
2871 goto_if_nok (error, fail);
2872 data.context = context;
2873 data.error = error;
2874 data.domain = domain;
2875 data.next_idx = 0;
2877 g_hash_table_foreach (iface_hash, fill_iface_array, &data);
2879 goto_if_nok (error, fail);
2881 g_hash_table_destroy (iface_hash);
2882 return data.iface_array;
2884 fail:
2885 g_hash_table_destroy (iface_hash);
2886 return NULL_HANDLE_ARRAY;
2889 static gboolean
2890 set_interface_map_data_method_object (MonoDomain *domain, MonoMethod *method, MonoClass *iclass, int ioffset, MonoClass *klass, MonoArrayHandle targets, MonoArrayHandle methods, int i, MonoError *error)
2892 HANDLE_FUNCTION_ENTER ();
2893 error_init (error);
2894 MonoReflectionMethodHandle member = mono_method_get_object_handle (domain, method, iclass, error);
2895 goto_if_nok (error, leave);
2897 MONO_HANDLE_ARRAY_SETREF (methods, i, member);
2899 MONO_HANDLE_ASSIGN (member, mono_method_get_object_handle (domain, m_class_get_vtable (klass) [i + ioffset], klass, error));
2900 goto_if_nok (error, leave);
2902 MONO_HANDLE_ARRAY_SETREF (targets, i, member);
2904 leave:
2905 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2908 void
2909 ves_icall_RuntimeType_GetInterfaceMapData (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_iface, MonoArrayHandleOut targets, MonoArrayHandleOut methods, MonoError *error)
2911 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2912 MonoClass *klass = mono_class_from_mono_type_internal (type);
2913 MonoType *iface = MONO_HANDLE_GETVAL (ref_iface, type);
2914 MonoClass *iclass = mono_class_from_mono_type_internal (iface);
2916 mono_class_init_checked (klass, error);
2917 return_if_nok (error);
2918 mono_class_init_checked (iclass, error);
2919 return_if_nok (error);
2921 mono_class_setup_vtable (klass);
2923 gboolean variance_used;
2924 int ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
2925 if (ioffset == -1)
2926 return;
2928 int len = mono_class_num_methods (iclass);
2929 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2930 MonoArrayHandle targets_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
2931 return_if_nok (error);
2932 MONO_HANDLE_ASSIGN (targets, targets_arr);
2934 MonoArrayHandle methods_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
2935 return_if_nok (error);
2936 MONO_HANDLE_ASSIGN (methods, methods_arr);
2938 MonoMethod* method;
2939 int i = 0;
2940 gpointer iter = NULL;
2941 while ((method = mono_class_get_methods (iclass, &iter))) {
2942 if (!set_interface_map_data_method_object (domain, method, iclass, ioffset, klass, targets, methods, i, error))
2943 return;
2944 i ++;
2948 void
2949 ves_icall_RuntimeType_GetPacking (MonoReflectionTypeHandle ref_type, guint32 *packing, guint32 *size, MonoError *error)
2951 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2952 MonoClass *klass = mono_class_from_mono_type_internal (type);
2954 mono_class_init_checked (klass, error);
2955 return_if_nok (error);
2957 if (image_is_dynamic (m_class_get_image (klass))) {
2958 MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, ref_type);
2959 *packing = MONO_HANDLE_GETVAL (tb, packing_size);
2960 *size = MONO_HANDLE_GETVAL (tb, class_size);
2961 } else {
2962 mono_metadata_packing_from_typedef (m_class_get_image (klass), m_class_get_type_token (klass), packing, size);
2966 MonoReflectionTypeHandle
2967 ves_icall_RuntimeTypeHandle_GetElementType (MonoReflectionTypeHandle ref_type, MonoError *error)
2969 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2970 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2972 if (!type->byref && type->type == MONO_TYPE_SZARRAY) {
2973 return mono_type_get_object_handle (domain, m_class_get_byval_arg (type->data.klass), error);
2976 MonoClass *klass = mono_class_from_mono_type_internal (type);
2977 mono_class_init_checked (klass, error);
2978 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
2980 // GetElementType should only return a type for:
2981 // Array Pointer PassedByRef
2982 if (type->byref)
2983 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2984 else if (m_class_get_element_class (klass) && MONO_CLASS_IS_ARRAY (klass))
2985 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_element_class (klass)), error);
2986 else if (m_class_get_element_class (klass) && type->type == MONO_TYPE_PTR)
2987 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_element_class (klass)), error);
2988 else
2989 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2992 MonoReflectionTypeHandle
2993 ves_icall_RuntimeTypeHandle_GetBaseType (MonoReflectionTypeHandle ref_type, MonoError *error)
2995 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2996 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2998 if (type->byref)
2999 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3001 MonoClass *klass = mono_class_from_mono_type_internal (type);
3002 if (!m_class_get_parent (klass))
3003 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3005 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_parent (klass)), error);
3008 guint32
3009 ves_icall_RuntimeTypeHandle_GetCorElementType (MonoReflectionTypeHandle ref_type, MonoError *error)
3011 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3013 if (type->byref)
3014 return MONO_TYPE_BYREF;
3015 else
3016 return (guint32)type->type;
3019 MonoBoolean
3020 ves_icall_RuntimeTypeHandle_HasReferences (MonoReflectionTypeHandle ref_type, MonoError *error)
3022 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3023 MonoClass *klass;
3025 klass = mono_class_from_mono_type_internal (type);
3026 mono_class_init_internal (klass);
3027 return m_class_has_references (klass);
3030 MonoBoolean
3031 ves_icall_RuntimeTypeHandle_IsByRefLike (MonoReflectionTypeHandle ref_type, MonoError *error)
3033 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3034 /* .NET Core says byref types are not IsByRefLike */
3035 if (type->byref)
3036 return FALSE;
3037 MonoClass *klass = mono_class_from_mono_type_internal (type);
3038 return m_class_is_byreflike (klass);
3041 MonoBoolean
3042 ves_icall_RuntimeTypeHandle_IsComObject (MonoReflectionTypeHandle ref_type, MonoError *error)
3044 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3045 MonoClass *klass = mono_class_from_mono_type_internal (type);
3046 mono_class_init_checked (klass, error);
3047 return_val_if_nok (error, FALSE);
3049 return mono_class_is_com_object (klass);
3052 guint32
3053 ves_icall_reflection_get_token (MonoObjectHandle obj, MonoError *error)
3055 error_init (error);
3056 return mono_reflection_get_token_checked (obj, error);
3059 MonoReflectionModuleHandle
3060 ves_icall_RuntimeTypeHandle_GetModule (MonoReflectionTypeHandle type, MonoError *error)
3062 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
3063 MonoType *t = MONO_HANDLE_GETVAL (type, type);
3064 MonoClass *klass = mono_class_from_mono_type_internal (t);
3065 return mono_module_get_object_handle (domain, m_class_get_image (klass), error);
3068 MonoReflectionAssemblyHandle
3069 ves_icall_RuntimeTypeHandle_GetAssembly (MonoReflectionTypeHandle type, MonoError *error)
3071 MonoDomain *domain = mono_domain_get ();
3072 MonoType *t = MONO_HANDLE_GETVAL (type, type);
3073 MonoClass *klass = mono_class_from_mono_type_internal (t);
3074 return mono_assembly_get_object_handle (domain, m_class_get_image (klass)->assembly, error);
3077 MonoReflectionTypeHandle
3078 ves_icall_RuntimeType_get_DeclaringType (MonoReflectionTypeHandle ref_type, MonoError *error)
3080 MonoDomain *domain = mono_domain_get ();
3081 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3082 MonoClass *klass;
3084 if (type->byref)
3085 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3086 if (type->type == MONO_TYPE_VAR) {
3087 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
3088 klass = param ? param->owner.klass : NULL;
3089 } else if (type->type == MONO_TYPE_MVAR) {
3090 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
3091 klass = param ? param->owner.method->klass : NULL;
3092 } else {
3093 klass = m_class_get_nested_in (mono_class_from_mono_type_internal (type));
3096 if (!klass)
3097 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3099 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
3102 MonoStringHandle
3103 ves_icall_RuntimeType_get_Name (MonoReflectionTypeHandle reftype, MonoError *error)
3105 MonoDomain *domain = mono_domain_get ();
3106 MonoType *type = MONO_HANDLE_RAW(reftype)->type;
3107 MonoClass *klass = mono_class_from_mono_type_internal (type);
3109 if (type->byref) {
3110 char *n = g_strdup_printf ("%s&", m_class_get_name (klass));
3111 MonoStringHandle res = mono_string_new_handle (domain, n, error);
3113 g_free (n);
3115 return res;
3116 } else {
3117 return mono_string_new_handle (domain, m_class_get_name (klass), error);
3121 MonoStringHandle
3122 ves_icall_RuntimeType_get_Namespace (MonoReflectionTypeHandle type, MonoError *error)
3124 MonoDomain *domain = mono_domain_get ();
3125 MonoClass *klass = mono_class_from_mono_type_handle (type);
3127 MonoClass *klass_nested_in;
3128 while ((klass_nested_in = m_class_get_nested_in (klass)))
3129 klass = klass_nested_in;
3131 if (m_class_get_name_space (klass) [0] == '\0')
3132 return NULL_HANDLE_STRING;
3133 else
3134 return mono_string_new_handle (domain, m_class_get_name_space (klass), error);
3137 gint32
3138 ves_icall_RuntimeTypeHandle_GetArrayRank (MonoReflectionTypeHandle ref_type, MonoError *error)
3140 error_init (error);
3141 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3143 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
3144 mono_error_set_argument (error, "type", "Type must be an array type");
3145 return 0;
3148 MonoClass *klass = mono_class_from_mono_type_internal (type);
3150 return m_class_get_rank (klass);
3153 static MonoArrayHandle
3154 create_type_array (MonoDomain *domain, MonoBoolean runtimeTypeArray, int count, MonoError *error)
3156 return mono_array_new_handle (domain, runtimeTypeArray ? mono_defaults.runtimetype_class : mono_defaults.systemtype_class, count, error);
3159 static gboolean
3160 set_type_object_in_array (MonoDomain *domain, MonoType *type, MonoArrayHandle dest, int i, MonoError *error)
3162 HANDLE_FUNCTION_ENTER();
3163 error_init (error);
3164 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, type, error);
3165 goto_if_nok (error, leave);
3167 MONO_HANDLE_ARRAY_SETREF (dest, i, rt);
3169 leave:
3170 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3173 MonoArrayHandle
3174 ves_icall_RuntimeType_GetGenericArguments (MonoReflectionTypeHandle ref_type, MonoBoolean runtimeTypeArray, MonoError *error)
3176 error_init (error);
3177 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3179 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3180 MonoClass *klass = mono_class_from_mono_type_internal (type);
3182 MonoArrayHandle res = MONO_HANDLE_NEW (MonoArray, NULL);
3183 if (mono_class_is_gtd (klass)) {
3184 MonoGenericContainer *container = mono_class_get_generic_container (klass);
3185 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, container->type_argc, error));
3186 goto_if_nok (error, leave);
3187 for (int i = 0; i < container->type_argc; ++i) {
3188 MonoClass *pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
3190 if (!set_type_object_in_array (domain, m_class_get_byval_arg (pklass), res, i, error))
3191 goto leave;
3194 } else if (mono_class_is_ginst (klass)) {
3195 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
3196 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, inst->type_argc, error));
3197 goto_if_nok (error, leave);
3198 for (int i = 0; i < inst->type_argc; ++i) {
3199 if (!set_type_object_in_array (domain, inst->type_argv [i], res, i, error))
3200 goto leave;
3204 leave:
3205 return res;
3208 MonoBoolean
3209 ves_icall_RuntimeTypeHandle_IsGenericTypeDefinition (MonoReflectionTypeHandle ref_type, MonoError *error)
3211 error_init (error);
3213 if (!IS_MONOTYPE (MONO_HANDLE_RAW(ref_type)))
3214 return FALSE;
3216 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3217 if (type->byref)
3218 return FALSE;
3220 MonoClass *klass = mono_class_from_mono_type_internal (type);
3221 return mono_class_is_gtd (klass);
3224 MonoReflectionTypeHandle
3225 ves_icall_RuntimeTypeHandle_GetGenericTypeDefinition_impl (MonoReflectionTypeHandle ref_type, MonoError *error)
3227 error_init (error);
3228 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3230 MonoReflectionTypeHandle ret = MONO_HANDLE_NEW (MonoReflectionType, NULL);
3232 if (type->byref)
3233 goto leave;
3235 MonoClass *klass;
3236 klass = mono_class_from_mono_type_internal (type);
3238 if (mono_class_is_gtd (klass)) {
3239 /* check this one */
3240 MONO_HANDLE_ASSIGN (ret, ref_type);
3241 goto leave;
3243 if (mono_class_is_ginst (klass)) {
3244 MonoClass *generic_class = mono_class_get_generic_class (klass)->container_class;
3246 guint32 ref_info_handle = mono_class_get_ref_info_handle (generic_class);
3248 if (m_class_was_typebuilder (generic_class) && ref_info_handle) {
3249 MonoObjectHandle tb = mono_gchandle_get_target_handle (ref_info_handle);
3250 g_assert (!MONO_HANDLE_IS_NULL (tb));
3251 MONO_HANDLE_ASSIGN (ret, tb);
3252 } else {
3253 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3254 MONO_HANDLE_ASSIGN (ret, mono_type_get_object_handle (domain, m_class_get_byval_arg (generic_class), error));
3257 leave:
3258 return ret;
3261 MonoReflectionTypeHandle
3262 ves_icall_RuntimeType_MakeGenericType (MonoReflectionTypeHandle reftype, MonoArrayHandle type_array, MonoError *error)
3264 error_init (error);
3265 MonoDomain *domain = MONO_HANDLE_DOMAIN (reftype);
3267 g_assert (IS_MONOTYPE_HANDLE (reftype));
3268 MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
3269 mono_class_init_checked (mono_class_from_mono_type_internal (type), error);
3270 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
3272 int count = mono_array_handle_length (type_array);
3273 MonoType **types = g_new0 (MonoType *, count);
3275 MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
3276 for (int i = 0; i < count; i++) {
3277 MONO_HANDLE_ARRAY_GETREF (t, type_array, i);
3278 types [i] = MONO_HANDLE_GETVAL (t, type);
3281 MonoType *geninst = mono_reflection_bind_generic_parameters (reftype, count, types, error);
3282 g_free (types);
3283 if (!geninst) {
3284 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3287 MonoClass *klass = mono_class_from_mono_type_internal (geninst);
3289 /*we might inflate to the GTD*/
3290 if (mono_class_is_ginst (klass) && !mono_verifier_class_is_valid_generic_instantiation (klass)) {
3291 mono_error_set_argument (error, "typeArguments", "Invalid generic arguments");
3292 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
3295 return mono_type_get_object_handle (domain, geninst, error);
3298 MonoBoolean
3299 ves_icall_RuntimeTypeHandle_HasInstantiation (MonoReflectionTypeHandle ref_type, MonoError *error)
3301 error_init (error);
3302 MonoClass *klass;
3304 if (!IS_MONOTYPE (MONO_HANDLE_RAW (ref_type)))
3305 return FALSE;
3307 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3308 if (type->byref)
3309 return FALSE;
3311 klass = mono_class_from_mono_type_internal (type);
3312 return mono_class_is_ginst (klass) || mono_class_is_gtd (klass);
3315 gint32
3316 ves_icall_RuntimeType_GetGenericParameterPosition (MonoReflectionTypeHandle ref_type, MonoError *error)
3318 error_init (error);
3319 if (!IS_MONOTYPE_HANDLE (ref_type))
3320 return -1;
3321 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3323 if (is_generic_parameter (type))
3324 return mono_type_get_generic_param_num (type);
3325 return -1;
3328 MonoGenericParamInfo *
3329 ves_icall_RuntimeTypeHandle_GetGenericParameterInfo (MonoReflectionTypeHandle ref_type, MonoError *error)
3331 error_init (error);
3332 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3333 return mono_generic_param_info (type->data.generic_param);
3336 MonoBoolean
3337 ves_icall_RuntimeTypeHandle_IsGenericVariable (MonoReflectionTypeHandle ref_type, MonoError *error)
3339 MonoType *type = MONO_HANDLE_GETVAL(ref_type, type);
3340 return is_generic_parameter (type);
3343 MonoReflectionMethodHandle
3344 ves_icall_RuntimeType_GetCorrespondingInflatedMethod (MonoReflectionTypeHandle ref_type,
3345 MonoReflectionMethodHandle generic,
3346 MonoError *error)
3348 error_init (error);
3349 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3350 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3351 MonoClass *klass = mono_class_from_mono_type_internal (type);
3353 mono_class_init_checked (klass, error);
3354 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3356 MonoMethod *generic_method = MONO_HANDLE_GETVAL (generic, method);
3358 MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3359 MonoMethod *method;
3360 gpointer iter = NULL;
3361 while ((method = mono_class_get_methods (klass, &iter))) {
3362 if (method->token == generic_method->token) {
3363 ret = mono_method_get_object_handle (domain, method, klass, error);
3364 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3368 return ret;
3371 MonoReflectionMethodHandle
3372 ves_icall_RuntimeType_get_DeclaringMethod (MonoReflectionTypeHandle ref_type, MonoError *error)
3374 error_init (error);
3375 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3376 MonoReflectionMethodHandle ret = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
3378 if (type->byref || (type->type != MONO_TYPE_MVAR && type->type != MONO_TYPE_VAR)) {
3379 mono_error_set_invalid_operation (error, "DeclaringMethod can only be used on generic arguments");
3380 goto leave;
3382 if (type->type == MONO_TYPE_VAR)
3383 goto leave;
3385 MonoMethod *method;
3386 method = mono_type_get_generic_param_owner (type)->owner.method;
3387 g_assert (method);
3389 MonoDomain *domain;
3390 domain = MONO_HANDLE_DOMAIN (ref_type);
3392 MONO_HANDLE_ASSIGN (ret, mono_method_get_object_handle (domain, method, method->klass, error));
3393 leave:
3394 return ret;
3397 #ifndef ENABLE_NETCORE
3398 MonoBoolean
3399 ves_icall_System_RuntimeType_IsTypeExportedToWindowsRuntime (MonoError *error)
3401 error_init (error);
3402 mono_error_set_not_implemented (error, "%s", "System.RuntimeType.IsTypeExportedToWindowsRuntime");
3403 return FALSE;
3406 MonoBoolean
3407 ves_icall_System_RuntimeType_IsWindowsRuntimeObjectType (MonoError *error)
3409 error_init (error);
3410 mono_error_set_not_implemented (error, "%s", "System.RuntimeType.IsWindowsRuntimeObjectType");
3411 return FALSE;
3413 #endif /* ENABLE_NETCORE */
3415 void
3416 ves_icall_RuntimeMethodInfo_GetPInvoke (MonoReflectionMethodHandle ref_method, int* flags, MonoStringHandleOut entry_point, MonoStringHandleOut dll_name, MonoError *error)
3418 MonoDomain *domain = mono_domain_get ();
3419 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3420 MonoImage *image = m_class_get_image (method->klass);
3421 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
3422 MonoTableInfo *tables = image->tables;
3423 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3424 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3425 guint32 im_cols [MONO_IMPLMAP_SIZE];
3426 guint32 scope_token;
3427 const char *import = NULL;
3428 const char *scope = NULL;
3430 error_init (error);
3432 if (image_is_dynamic (image)) {
3433 MonoReflectionMethodAux *method_aux =
3434 (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)image)->method_aux_hash, method);
3435 if (method_aux) {
3436 import = method_aux->dllentry;
3437 scope = method_aux->dll;
3440 if (!import || !scope) {
3441 mono_error_set_argument (error, "method", "System.Refleciton.Emit method with invalid pinvoke information");
3442 return;
3445 else {
3446 if (piinfo->implmap_idx) {
3447 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3449 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
3450 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
3451 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
3452 scope = mono_metadata_string_heap (image, scope_token);
3456 *flags = piinfo->piflags;
3457 MONO_HANDLE_ASSIGN (entry_point, mono_string_new_handle (domain, import, error));
3458 return_if_nok (error);
3459 MONO_HANDLE_ASSIGN (dll_name, mono_string_new_handle (domain, scope, error));
3462 MonoReflectionMethodHandle
3463 ves_icall_RuntimeMethodInfo_GetGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *error)
3465 error_init (error);
3466 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3468 if (method->is_generic)
3469 return ref_method;
3471 if (!method->is_inflated)
3472 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3474 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
3476 MonoMethod *result = imethod->declaring;
3477 /* Not a generic method. */
3478 if (!result->is_generic)
3479 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3481 if (image_is_dynamic (m_class_get_image (method->klass))) {
3482 MonoDynamicImage *image = (MonoDynamicImage*)m_class_get_image (method->klass);
3485 * FIXME: Why is this stuff needed at all ? Why can't the code below work for
3486 * the dynamic case as well ?
3488 mono_image_lock ((MonoImage*)image);
3489 MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, (MonoReflectionMethod*)mono_g_hash_table_lookup (image->generic_def_objects, imethod));
3490 mono_image_unlock ((MonoImage*)image);
3492 if (!MONO_HANDLE_IS_NULL (res))
3493 return res;
3496 if (imethod->context.class_inst) {
3497 MonoClass *klass = ((MonoMethod *) imethod)->klass;
3498 /*Generic methods gets the context of the GTD.*/
3499 if (mono_class_get_context (klass)) {
3500 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
3501 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3505 return mono_method_get_object_handle (MONO_HANDLE_DOMAIN (ref_method), result, NULL, error);
3508 MonoBoolean
3509 ves_icall_RuntimeMethodInfo_get_IsGenericMethod (MonoReflectionMethodHandle ref_method, MonoError *erro)
3511 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3512 return mono_method_signature_internal (method)->generic_param_count != 0;
3515 MonoBoolean
3516 ves_icall_RuntimeMethodInfo_get_IsGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *Error)
3518 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3519 return method->is_generic;
3522 static gboolean
3523 set_array_generic_argument_handle_inflated (MonoDomain *domain, MonoGenericInst *inst, int i, MonoArrayHandle arr, MonoError *error)
3525 HANDLE_FUNCTION_ENTER ();
3526 error_init (error);
3527 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, inst->type_argv [i], error);
3528 goto_if_nok (error, leave);
3529 MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3530 leave:
3531 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3534 static gboolean
3535 set_array_generic_argument_handle_gparam (MonoDomain *domain, MonoGenericContainer *container, int i, MonoArrayHandle arr, MonoError *error)
3537 HANDLE_FUNCTION_ENTER ();
3538 error_init (error);
3539 MonoGenericParam *param = mono_generic_container_get_param (container, i);
3540 MonoClass *pklass = mono_class_create_generic_parameter (param);
3541 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (pklass), error);
3542 goto_if_nok (error, leave);
3543 MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3544 leave:
3545 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3548 MonoArrayHandle
3549 ves_icall_RuntimeMethodInfo_GetGenericArguments (MonoReflectionMethodHandle ref_method, MonoError *error)
3551 error_init (error);
3552 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_method);
3553 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3555 if (method->is_inflated) {
3556 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
3558 if (inst) {
3559 int count = inst->type_argc;
3560 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3561 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3563 for (int i = 0; i < count; i++) {
3564 if (!set_array_generic_argument_handle_inflated (domain, inst, i, res, error))
3565 break;
3567 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3568 return res;
3572 int count = mono_method_signature_internal (method)->generic_param_count;
3573 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3574 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3576 MonoGenericContainer *container = mono_method_get_generic_container (method);
3577 for (int i = 0; i < count; i++) {
3578 if (!set_array_generic_argument_handle_gparam (domain, container, i, res, error))
3579 break;
3581 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3582 return res;
3585 MonoObjectHandle
3586 ves_icall_InternalInvoke (MonoReflectionMethodHandle method_handle, MonoObjectHandle this_arg_handle,
3587 MonoArrayHandle params_handle, MonoExceptionHandleOut exception_out, MonoError *error)
3589 MonoReflectionMethod* const method = MONO_HANDLE_RAW (method_handle);
3590 MonoObject* const this_arg = MONO_HANDLE_RAW (this_arg_handle);
3591 MonoArray* const params = MONO_HANDLE_RAW (params_handle);
3594 * Invoke from reflection is supposed to always be a virtual call (the API
3595 * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
3596 * greater flexibility.
3598 MonoMethod *m = method->method;
3599 MonoMethodSignature* const sig = mono_method_signature_internal (m);
3600 MonoImage *image = NULL;
3601 int pcount = 0;
3602 void *obj = this_arg;
3603 char *this_name = NULL;
3604 char *target_name = NULL;
3605 char *msg = NULL;
3606 MonoObject *result = NULL;
3607 MonoArray *arr = NULL;
3608 MonoException *exception = NULL;
3610 *MONO_HANDLE_REF (exception_out) = NULL;
3612 if (mono_security_core_clr_enabled () &&
3613 !mono_security_core_clr_ensure_reflection_access_method (m, error)) {
3614 goto return_null;
3617 if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
3618 if (!mono_class_vtable_checked (mono_object_domain (method), m->klass, error)) {
3619 mono_error_cleanup (error); /* FIXME does this make sense? */
3620 error_init_reuse (error);
3621 exception = mono_class_get_exception_for_failure (m->klass);
3622 goto return_null;
3625 if (this_arg) {
3626 if (!mono_object_isinst_checked (this_arg, m->klass, error)) {
3627 if (!is_ok (error)) {
3628 exception = mono_error_convert_to_exception (error);
3629 goto return_null;
3631 this_name = mono_type_get_full_name (mono_object_class (this_arg));
3632 target_name = mono_type_get_full_name (m->klass);
3633 msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
3634 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", msg);
3635 goto return_null;
3637 m = mono_object_get_virtual_method_internal (this_arg, m);
3638 /* must pass the pointer to the value for valuetype methods */
3639 if (m_class_is_valuetype (m->klass)) {
3640 obj = mono_object_unbox_internal (this_arg);
3641 // FIXMEcoop? Does obj need to be put into a handle?
3643 } else if (strcmp (m->name, ".ctor") && !m->wrapper_type) {
3644 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Non-static method requires a target.");
3645 goto return_null;
3649 if ((m->klass != NULL && m_class_is_byreflike (m->klass)) || m_class_is_byreflike (mono_class_from_mono_type_internal (sig->ret))) {
3650 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method with stack pointers via reflection");
3651 goto return_null;
3653 #if ENABLE_NETCORE
3654 if (sig->ret->byref) {
3655 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
3656 if (ret_byval->type == MONO_TYPE_VOID) {
3657 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "ByRef to void return values are not supported in reflection invocation");
3658 goto return_null;
3660 if (m_class_is_byreflike (mono_class_from_mono_type_internal (ret_byval))) {
3661 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method returning ByRef to ByRefLike type via reflection");
3662 goto return_null;
3665 #else
3666 if (sig->ret->byref) {
3667 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method returning ByRef type via reflection");
3668 goto return_null;
3670 #endif
3672 pcount = params? mono_array_length_internal (params): 0;
3673 if (pcount != sig->param_count) {
3674 exception = mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetParameterCountException");
3675 goto return_null;
3678 if (mono_class_is_abstract (m->klass) && !strcmp (m->name, ".ctor") && !this_arg) {
3679 exception = mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Cannot invoke constructor of an abstract class.");
3680 goto return_null;
3683 image = m_class_get_image (m->klass);
3684 if (mono_asmctx_get_kind (&image->assembly->context) == MONO_ASMCTX_REFONLY) {
3685 exception = mono_get_exception_invalid_operation ("It is illegal to invoke a method on a type loaded using the ReflectionOnly api.");
3686 goto return_null;
3689 if (image_is_dynamic (image) && !((MonoDynamicImage*)image)->run) {
3690 exception = mono_get_exception_not_supported ("Cannot invoke a method in a dynamic assembly without run access.");
3691 goto return_null;
3694 if (m_class_get_rank (m->klass) && !strcmp (m->name, ".ctor")) {
3695 int i;
3696 pcount = mono_array_length_internal (params);
3697 uintptr_t * const lengths = g_newa (uintptr_t, pcount);
3698 /* Note: the synthetized array .ctors have int32 as argument type */
3699 for (i = 0; i < pcount; ++i)
3700 lengths [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, i) + sizeof (MonoObject));
3702 if (m_class_get_rank (m->klass) == 1 && sig->param_count == 2 && m_class_get_rank (m_class_get_element_class (m->klass))) {
3703 /* This is a ctor for jagged arrays. MS creates an array of arrays. */
3704 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, error);
3705 goto_if_nok (error, return_null);
3707 MonoArrayHandle subarray_handle = MONO_HANDLE_NEW (MonoArray, NULL);
3709 for (i = 0; i < mono_array_length_internal (arr); ++i) {
3710 MonoArray *subarray = mono_array_new_full_checked (mono_object_domain (params), m_class_get_element_class (m->klass), &lengths [1], NULL, error);
3711 goto_if_nok (error, return_null);
3712 MONO_HANDLE_ASSIGN_RAW (subarray_handle, subarray); // FIXME? Overkill?
3713 mono_array_setref_fast (arr, i, subarray);
3715 goto exit;
3718 if (m_class_get_rank (m->klass) == pcount) {
3719 /* Only lengths provided. */
3720 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, error);
3721 goto_if_nok (error, return_null);
3722 goto exit;
3723 } else {
3724 g_assert (pcount == (m_class_get_rank (m->klass) * 2));
3725 /* The arguments are lower-bound-length pairs */
3726 intptr_t * const lower_bounds = (intptr_t *)g_alloca (sizeof (intptr_t) * pcount);
3728 for (i = 0; i < pcount / 2; ++i) {
3729 lower_bounds [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, (i * 2)) + sizeof (MonoObject));
3730 lengths [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, (i * 2) + 1) + sizeof (MonoObject));
3733 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, lower_bounds, error);
3734 goto_if_nok (error, return_null);
3735 goto exit;
3738 result = mono_runtime_invoke_array_checked (m, obj, params, error);
3739 goto exit;
3740 return_null:
3741 result = NULL;
3742 arr = NULL;
3743 exit:
3744 if (exception) {
3745 MONO_HANDLE_NEW (MonoException, exception); // FIXME? overkill?
3746 mono_gc_wbarrier_generic_store_internal (MONO_HANDLE_REF (exception_out), (MonoObject*)exception);
3748 g_free (target_name);
3749 g_free (this_name);
3750 g_free (msg);
3751 g_assert (!result || !arr); // only one, or neither, should be set
3752 return result ? MONO_HANDLE_NEW (MonoObject, result) : arr ? MONO_HANDLE_NEW (MonoObject, (MonoObject*)arr) : NULL_HANDLE;
3755 #ifndef DISABLE_REMOTING
3756 static void
3757 internal_execute_field_getter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs, MonoError *error)
3759 error_init (error);
3760 MonoArray *out_args;
3761 MonoClass *k = mono_object_class (this_arg);
3762 MonoString *name;
3763 char *str;
3765 /* If this is a proxy, then it must be a CBO */
3766 if (mono_class_is_transparent_proxy (k)) {
3767 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
3768 this_arg = tp->rp->unwrapped_server;
3769 g_assert (this_arg);
3770 k = mono_object_class (this_arg);
3773 name = mono_array_get_internal (params, MonoString *, 1);
3774 str = mono_string_to_utf8_checked_internal (name, error);
3775 return_if_nok (error);
3777 do {
3778 MonoClassField* field = mono_class_get_field_from_name_full (k, str, NULL);
3779 if (field) {
3780 g_free (str);
3781 MonoClass *field_klass = mono_class_from_mono_type_internal (field->type);
3782 MonoObject *result;
3783 if (m_class_is_valuetype (field_klass)) {
3784 result = mono_value_box_checked (domain, field_klass, (char *)this_arg + field->offset, error);
3785 return_if_nok (error);
3786 } else
3787 result = (MonoObject *)*((gpointer *)((char *)this_arg + field->offset));
3789 out_args = mono_array_new_checked (domain, mono_defaults.object_class, 1, error);
3790 return_if_nok (error);
3791 mono_gc_wbarrier_generic_store_internal (outArgs, (MonoObject*) out_args);
3792 mono_array_setref_internal (out_args, 0, result);
3793 return;
3795 k = m_class_get_parent (k);
3796 } while (k);
3798 g_free (str);
3799 g_assert_not_reached ();
3802 static void
3803 internal_execute_field_setter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs, MonoError *error)
3805 error_init (error);
3806 MonoArray *out_args;
3807 MonoClass *k = mono_object_class (this_arg);
3808 MonoString *name;
3809 guint32 size;
3810 gint32 align;
3811 char *str;
3813 /* If this is a proxy, then it must be a CBO */
3814 if (mono_class_is_transparent_proxy (k)) {
3815 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
3816 this_arg = tp->rp->unwrapped_server;
3817 g_assert (this_arg);
3818 k = mono_object_class (this_arg);
3821 name = mono_array_get_internal (params, MonoString *, 1);
3822 str = mono_string_to_utf8_checked_internal (name, error);
3823 return_if_nok (error);
3825 do {
3826 MonoClassField* field = mono_class_get_field_from_name_full (k, str, NULL);
3827 if (field) {
3828 g_free (str);
3829 MonoClass *field_klass = mono_class_from_mono_type_internal (field->type);
3830 MonoObject *val = (MonoObject *)mono_array_get_internal (params, gpointer, 2);
3832 if (m_class_is_valuetype (field_klass)) {
3833 size = mono_type_size (field->type, &align);
3834 g_assert (size == mono_class_value_size (field_klass, NULL));
3835 mono_gc_wbarrier_value_copy_internal ((char *)this_arg + field->offset, (char*)val + sizeof (MonoObject), 1, field_klass);
3836 } else {
3837 mono_gc_wbarrier_set_field_internal (this_arg, (char*)this_arg + field->offset, val);
3840 out_args = mono_array_new_checked (domain, mono_defaults.object_class, 0, error);
3841 return_if_nok (error);
3842 mono_gc_wbarrier_generic_store_internal (outArgs, (MonoObject*) out_args);
3843 return;
3846 k = m_class_get_parent (k);
3847 } while (k);
3849 g_free (str);
3850 g_assert_not_reached ();
3853 MonoObject *
3854 ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs)
3856 ERROR_DECL (error);
3857 MonoDomain *domain = mono_object_domain (method);
3858 MonoMethod *m = method->method;
3859 MonoMethodSignature *sig = mono_method_signature_internal (m);
3860 MonoArray *out_args;
3861 MonoObject *result;
3862 int i, j, outarg_count = 0;
3864 if (m->klass == mono_defaults.object_class) {
3865 if (!strcmp (m->name, "FieldGetter")) {
3866 internal_execute_field_getter (domain, this_arg, params, outArgs, error);
3867 mono_error_set_pending_exception (error);
3868 return NULL;
3869 } else if (!strcmp (m->name, "FieldSetter")) {
3870 internal_execute_field_setter (domain, this_arg, params, outArgs, error);
3871 mono_error_set_pending_exception (error);
3872 return NULL;
3876 for (i = 0; i < mono_array_length_internal (params); i++) {
3877 if (sig->params [i]->byref)
3878 outarg_count++;
3881 out_args = mono_array_new_checked (domain, mono_defaults.object_class, outarg_count, error);
3882 if (mono_error_set_pending_exception (error))
3883 return NULL;
3885 /* handle constructors only for objects already allocated */
3886 if (!strcmp (method->method->name, ".ctor"))
3887 g_assert (this_arg);
3889 /* This can be called only on MBR objects, so no need to unbox for valuetypes. */
3890 g_assert (!m_class_is_valuetype (method->method->klass));
3891 result = mono_runtime_invoke_array_checked (method->method, this_arg, params, error);
3892 if (mono_error_set_pending_exception (error))
3893 return NULL;
3895 for (i = 0, j = 0; i < mono_array_length_internal (params); i++) {
3896 if (sig->params [i]->byref) {
3897 gpointer arg;
3898 arg = mono_array_get_internal (params, gpointer, i);
3899 mono_array_setref_internal (out_args, j, arg);
3900 j++;
3904 mono_gc_wbarrier_generic_store_internal (outArgs, (MonoObject*) out_args);
3906 return result;
3908 #endif
3910 static guint64
3911 read_enum_value (const char *mem, int type)
3913 switch (type) {
3914 case MONO_TYPE_BOOLEAN:
3915 case MONO_TYPE_U1:
3916 return *(guint8*)mem;
3917 case MONO_TYPE_I1:
3918 return *(gint8*)mem;
3919 case MONO_TYPE_CHAR:
3920 case MONO_TYPE_U2:
3921 return read16 (mem);
3922 case MONO_TYPE_I2:
3923 return (gint16) read16 (mem);
3924 case MONO_TYPE_U4:
3925 case MONO_TYPE_R4:
3926 return read32 (mem);
3927 case MONO_TYPE_I4:
3928 return (gint32) read32 (mem);
3929 case MONO_TYPE_U8:
3930 case MONO_TYPE_I8:
3931 case MONO_TYPE_R8:
3932 return read64 (mem);
3933 case MONO_TYPE_U:
3934 case MONO_TYPE_I:
3935 #if SIZEOF_REGISTER == 8
3936 return read64 (mem);
3937 #else
3938 return read32 (mem);
3939 #endif
3940 default:
3941 g_assert_not_reached ();
3943 return 0;
3946 static void
3947 write_enum_value (void *mem, int type, guint64 value)
3949 switch (type) {
3950 case MONO_TYPE_U1:
3951 case MONO_TYPE_I1:
3952 case MONO_TYPE_BOOLEAN: {
3953 guint8 *p = (guint8*)mem;
3954 *p = value;
3955 break;
3957 case MONO_TYPE_U2:
3958 case MONO_TYPE_I2:
3959 case MONO_TYPE_CHAR: {
3960 guint16 *p = (guint16 *)mem;
3961 *p = value;
3962 break;
3964 case MONO_TYPE_U4:
3965 case MONO_TYPE_I4:
3966 case MONO_TYPE_R4: {
3967 guint32 *p = (guint32 *)mem;
3968 *p = value;
3969 break;
3971 case MONO_TYPE_U8:
3972 case MONO_TYPE_I8:
3973 case MONO_TYPE_R8: {
3974 guint64 *p = (guint64 *)mem;
3975 *p = value;
3976 break;
3978 case MONO_TYPE_U:
3979 case MONO_TYPE_I: {
3980 #if SIZEOF_REGISTER == 8
3981 guint64 *p = (guint64 *)mem;
3982 *p = value;
3983 #else
3984 guint32 *p = (guint32 *)mem;
3985 *p = value;
3986 break;
3987 #endif
3988 break;
3990 default:
3991 g_assert_not_reached ();
3993 return;
3996 MonoObjectHandle
3997 ves_icall_System_Enum_ToObject (MonoReflectionTypeHandle enumType, guint64 value, MonoError *error)
3999 MonoDomain *domain;
4000 MonoClass *enumc;
4001 MonoObjectHandle resultHandle;
4002 MonoType *etype;
4004 domain = MONO_HANDLE_DOMAIN (enumType);
4005 enumc = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (enumType, type));
4007 mono_class_init_checked (enumc, error);
4008 goto_if_nok (error, return_null);
4010 etype = mono_class_enum_basetype_internal (enumc);
4012 resultHandle = mono_object_new_handle (domain, enumc, error);
4013 goto_if_nok (error, return_null);
4015 write_enum_value (mono_handle_unbox_unsafe (resultHandle), etype->type, value);
4017 return resultHandle;
4019 return_null:
4020 return MONO_HANDLE_NEW (MonoObject, NULL);
4023 MonoBoolean
4024 ves_icall_System_Enum_InternalHasFlag (MonoObjectHandle a, MonoObjectHandle b, MonoError *error)
4026 int size = mono_class_value_size (mono_handle_class (a), NULL);
4027 guint64 a_val = 0, b_val = 0;
4029 memcpy (&a_val, mono_handle_unbox_unsafe (a), size);
4030 memcpy (&b_val, mono_handle_unbox_unsafe (b), size);
4032 return (a_val & b_val) == b_val;
4035 MonoObjectHandle
4036 ves_icall_System_Enum_get_value (MonoObjectHandle ehandle, MonoError *error)
4038 MonoObjectHandle resultHandle;
4039 MonoClass *enumc;
4040 int size;
4042 goto_if (MONO_HANDLE_IS_NULL (ehandle), return_null);
4044 g_assert (m_class_is_enumtype (mono_handle_class (ehandle)));
4046 enumc = mono_class_from_mono_type_internal (mono_class_enum_basetype_internal (mono_handle_class (ehandle)));
4048 resultHandle = mono_object_new_handle (MONO_HANDLE_DOMAIN (ehandle), enumc, error);
4049 goto_if_nok (error, return_null);
4050 size = mono_class_value_size (enumc, NULL);
4052 memcpy (mono_handle_unbox_unsafe (resultHandle), mono_handle_unbox_unsafe (ehandle), size);
4054 return resultHandle;
4055 return_null:
4056 return MONO_HANDLE_NEW (MonoObject, NULL);
4059 MonoReflectionTypeHandle
4060 ves_icall_System_Enum_get_underlying_type (MonoReflectionTypeHandle type, MonoError *error)
4062 MonoType *etype;
4063 MonoClass *klass;
4065 klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
4066 mono_class_init_checked (klass, error);
4067 goto_if_nok (error, return_null);
4069 etype = mono_class_enum_basetype_internal (klass);
4070 if (!etype) {
4071 mono_error_set_argument (error, "enumType", "Type provided must be an Enum.");
4072 goto return_null;
4075 return mono_type_get_object_handle (MONO_HANDLE_DOMAIN (type), etype, error);
4077 return_null:
4078 return MONO_HANDLE_NEW (MonoReflectionType, NULL);
4082 ves_icall_System_Enum_InternalGetCorElementType (MonoObjectHandle this_handle, MonoError *error)
4084 MonoClass *klass = MONO_HANDLE_GETVAL (this_handle, vtable)->klass;
4086 return (int)m_class_get_byval_arg (m_class_get_element_class (klass))->type;
4090 ves_icall_System_Enum_compare_value_to (MonoObjectHandle enumHandle, MonoObjectHandle otherHandle, MonoError *error)
4092 if (MONO_HANDLE_IS_NULL (otherHandle))
4093 return 1;
4095 if (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass != MONO_HANDLE_GETVAL (otherHandle, vtable)->klass)
4096 return 2;
4098 gpointer tdata = mono_handle_unbox_unsafe (enumHandle);
4099 gpointer odata = mono_handle_unbox_unsafe (otherHandle);
4100 MonoType *basetype = mono_class_enum_basetype_internal (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass);
4101 g_assert (basetype);
4103 #define COMPARE_ENUM_VALUES(ENUM_TYPE) do { \
4104 ENUM_TYPE me = *((ENUM_TYPE*)tdata); \
4105 ENUM_TYPE other = *((ENUM_TYPE*)odata); \
4106 if (me == other) \
4107 return 0; \
4108 return me > other ? 1 : -1; \
4109 } while (0)
4111 switch (basetype->type) {
4112 case MONO_TYPE_BOOLEAN:
4113 case MONO_TYPE_U1:
4114 COMPARE_ENUM_VALUES (guint8);
4115 case MONO_TYPE_I1:
4116 COMPARE_ENUM_VALUES (gint8);
4117 case MONO_TYPE_CHAR:
4118 case MONO_TYPE_U2:
4119 COMPARE_ENUM_VALUES (guint16);
4120 case MONO_TYPE_I2:
4121 COMPARE_ENUM_VALUES (gint16);
4122 case MONO_TYPE_U4:
4123 COMPARE_ENUM_VALUES (guint32);
4124 case MONO_TYPE_I4:
4125 COMPARE_ENUM_VALUES (gint32);
4126 case MONO_TYPE_R4:
4127 COMPARE_ENUM_VALUES (gfloat);
4128 case MONO_TYPE_U8:
4129 COMPARE_ENUM_VALUES (guint64);
4130 case MONO_TYPE_I8:
4131 COMPARE_ENUM_VALUES (gint64);
4132 case MONO_TYPE_R8:
4133 COMPARE_ENUM_VALUES (gdouble);
4134 case MONO_TYPE_U:
4135 #if SIZEOF_REGISTER == 8
4136 COMPARE_ENUM_VALUES (guint64);
4137 #else
4138 COMPARE_ENUM_VALUES (guint32);
4139 #endif
4140 case MONO_TYPE_I:
4141 #if SIZEOF_REGISTER == 8
4142 COMPARE_ENUM_VALUES (gint64);
4143 #else
4144 COMPARE_ENUM_VALUES (gint32);
4145 #endif
4147 #undef COMPARE_ENUM_VALUES
4148 /* indicates that the enum was of an unsupported underlying type */
4149 return 3;
4153 ves_icall_System_Enum_get_hashcode (MonoObjectHandle enumHandle, MonoError *error)
4155 gpointer data = mono_handle_unbox_unsafe (enumHandle);
4156 MonoType *basetype = mono_class_enum_basetype_internal (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass);
4157 g_assert (basetype);
4159 switch (basetype->type) {
4160 case MONO_TYPE_I1: {
4161 gint8 value = *((gint8*)data);
4162 return ((int)value ^ (int)value << 8);
4164 case MONO_TYPE_U1:
4165 return *((guint8*)data);
4166 case MONO_TYPE_CHAR:
4167 case MONO_TYPE_U2:
4168 return *((guint16*)data);
4170 case MONO_TYPE_I2: {
4171 gint16 value = *((gint16*)data);
4172 return ((int)(guint16)value | (((int)value) << 16));
4174 case MONO_TYPE_U4:
4175 case MONO_TYPE_R4:
4176 return *((guint32*)data);
4177 case MONO_TYPE_I4:
4178 return *((gint32*)data);
4179 case MONO_TYPE_U8:
4180 case MONO_TYPE_I8:
4181 case MONO_TYPE_R8: {
4182 gint64 value = *((gint64*)data);
4183 return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
4185 case MONO_TYPE_I:
4186 case MONO_TYPE_U: {
4187 #if SIZEOF_REGISTER == 8
4188 gint64 value = *((gint64*)data);
4189 return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
4190 #else
4191 return *((guint32*)data);
4192 #endif
4194 default:
4195 g_error ("Implement type 0x%02x in get_hashcode", basetype->type);
4197 return 0;
4200 static void
4201 get_enum_field (MonoDomain *domain, MonoArrayHandle names, MonoArrayHandle values, int base_type, MonoClassField *field, guint* j, guint64 *previous_value, gboolean *sorted, MonoError *error)
4203 error_init (error);
4204 HANDLE_FUNCTION_ENTER();
4205 guint64 field_value;
4206 const char *p;
4207 MonoTypeEnum def_type;
4209 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
4210 goto leave;
4211 if (strcmp ("value__", mono_field_get_name (field)) == 0)
4212 goto leave;
4213 if (mono_field_is_deleted (field))
4214 goto leave;
4215 MonoStringHandle name;
4216 name = mono_string_new_handle (domain, mono_field_get_name (field), error);
4217 goto_if_nok (error, leave);
4218 MONO_HANDLE_ARRAY_SETREF (names, *j, name);
4220 p = mono_class_get_field_default_value (field, &def_type);
4221 /* len = */ mono_metadata_decode_blob_size (p, &p);
4223 field_value = read_enum_value (p, base_type);
4224 MONO_HANDLE_ARRAY_SETVAL (values, guint64, *j, field_value);
4226 if (*previous_value > field_value)
4227 *sorted = FALSE;
4229 *previous_value = field_value;
4230 (*j)++;
4231 leave:
4232 HANDLE_FUNCTION_RETURN();
4235 MonoBoolean
4236 ves_icall_System_Enum_GetEnumValuesAndNames (MonoReflectionTypeHandle type, MonoArrayHandleOut values, MonoArrayHandleOut names, MonoError *error)
4238 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
4239 MonoClass *enumc = mono_class_from_mono_type_internal (MONO_HANDLE_RAW(type)->type);
4240 guint j = 0, nvalues;
4241 gpointer iter;
4242 MonoClassField *field;
4243 int base_type;
4244 guint64 previous_value = 0;
4245 gboolean sorted = TRUE;
4247 error_init (error);
4248 mono_class_init_checked (enumc, error);
4249 return_val_if_nok (error, FALSE);
4251 if (!m_class_is_enumtype (enumc)) {
4252 #if ENABLE_NETCORE
4253 mono_error_set_argument (error, NULL, "Type provided must be an Enum.");
4254 #else
4255 mono_error_set_argument (error, "enumType", "Type provided must be an Enum.");
4256 #endif
4257 return TRUE;
4260 base_type = mono_class_enum_basetype_internal (enumc)->type;
4262 nvalues = mono_class_num_fields (enumc) > 0 ? mono_class_num_fields (enumc) - 1 : 0;
4263 MONO_HANDLE_ASSIGN(names, mono_array_new_handle (domain, mono_defaults.string_class, nvalues, error));
4264 return_val_if_nok (error, FALSE);
4265 MONO_HANDLE_ASSIGN(values, mono_array_new_handle (domain, mono_defaults.uint64_class, nvalues, error));
4266 return_val_if_nok (error, FALSE);
4268 iter = NULL;
4269 while ((field = mono_class_get_fields_internal (enumc, &iter))) {
4270 get_enum_field(domain, names, values, base_type, field, &j, &previous_value, &sorted, error);
4271 if (!is_ok (error))
4272 break;
4274 return_val_if_nok (error, FALSE);
4276 return sorted || base_type == MONO_TYPE_R4 || base_type == MONO_TYPE_R8;
4279 enum {
4280 BFLAGS_IgnoreCase = 1,
4281 BFLAGS_DeclaredOnly = 2,
4282 BFLAGS_Instance = 4,
4283 BFLAGS_Static = 8,
4284 BFLAGS_Public = 0x10,
4285 BFLAGS_NonPublic = 0x20,
4286 BFLAGS_FlattenHierarchy = 0x40,
4287 BFLAGS_InvokeMethod = 0x100,
4288 BFLAGS_CreateInstance = 0x200,
4289 BFLAGS_GetField = 0x400,
4290 BFLAGS_SetField = 0x800,
4291 BFLAGS_GetProperty = 0x1000,
4292 BFLAGS_SetProperty = 0x2000,
4293 BFLAGS_ExactBinding = 0x10000,
4294 BFLAGS_SuppressChangeType = 0x20000,
4295 BFLAGS_OptionalParamBinding = 0x40000
4298 enum {
4299 MLISTTYPE_All = 0,
4300 MLISTTYPE_CaseSensitive = 1,
4301 MLISTTYPE_CaseInsensitive = 2,
4302 MLISTTYPE_HandleToInfo = 3
4305 GPtrArray*
4306 ves_icall_RuntimeType_GetFields_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 bflags, guint32 mlisttype, MonoError *error)
4308 error_init (error);
4309 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4311 if (type->byref) {
4312 return g_ptr_array_new ();
4315 int (*compare_func) (const char *s1, const char *s2) = NULL;
4316 compare_func = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
4318 MonoClass *startklass, *klass;
4319 klass = startklass = mono_class_from_mono_type_internal (type);
4321 GPtrArray *ptr_array = g_ptr_array_sized_new (16);
4323 handle_parent:
4324 if (mono_class_has_failure (klass)) {
4325 mono_error_set_for_class_failure (error, klass);
4326 goto fail;
4329 MonoClassField *field;
4330 gpointer iter;
4331 iter = NULL;
4332 while ((field = mono_class_get_fields_lazy (klass, &iter))) {
4333 guint32 flags = mono_field_get_flags (field);
4334 int match = 0;
4335 if (mono_field_is_deleted_with_flags (field, flags))
4336 continue;
4337 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
4338 if (bflags & BFLAGS_Public)
4339 match++;
4340 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
4341 if (bflags & BFLAGS_NonPublic) {
4342 match++;
4345 if (!match)
4346 continue;
4347 match = 0;
4348 if (flags & FIELD_ATTRIBUTE_STATIC) {
4349 if (bflags & BFLAGS_Static)
4350 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4351 match++;
4352 } else {
4353 if (bflags & BFLAGS_Instance)
4354 match++;
4357 if (!match)
4358 continue;
4360 if (((mlisttype != MLISTTYPE_All) && (utf8_name != NULL)) && compare_func (mono_field_get_name (field), utf8_name))
4361 continue;
4363 g_ptr_array_add (ptr_array, field);
4365 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
4366 goto handle_parent;
4368 return ptr_array;
4370 fail:
4371 g_ptr_array_free (ptr_array, TRUE);
4372 return NULL;
4375 static gboolean
4376 method_nonpublic (MonoMethod* method, gboolean start_klass)
4378 switch (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) {
4379 case METHOD_ATTRIBUTE_ASSEM:
4380 return (start_klass || mono_defaults.generic_ilist_class);
4381 case METHOD_ATTRIBUTE_PRIVATE:
4382 return start_klass;
4383 case METHOD_ATTRIBUTE_PUBLIC:
4384 return FALSE;
4385 default:
4386 return TRUE;
4390 GPtrArray*
4391 mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, guint32 mlisttype, gboolean allow_ctors, MonoError *error)
4393 GPtrArray *array;
4394 MonoClass *startklass;
4395 MonoMethod *method;
4396 gpointer iter;
4397 int match, nslots;
4398 /*FIXME, use MonoBitSet*/
4399 guint32 method_slots_default [8];
4400 guint32 *method_slots = NULL;
4401 int (*compare_func) (const char *s1, const char *s2) = NULL;
4403 array = g_ptr_array_new ();
4404 startklass = klass;
4405 error_init (error);
4407 compare_func = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
4409 /* An optimization for calls made from Delegate:CreateDelegate () */
4410 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))) {
4411 method = mono_get_delegate_invoke_internal (klass);
4412 g_assert (method);
4414 g_ptr_array_add (array, method);
4415 return array;
4418 mono_class_setup_methods (klass);
4419 mono_class_setup_vtable (klass);
4420 if (mono_class_has_failure (klass))
4421 goto loader_error;
4423 if (is_generic_parameter (m_class_get_byval_arg (klass)))
4424 nslots = mono_class_get_vtable_size (m_class_get_parent (klass));
4425 else
4426 nslots = MONO_CLASS_IS_INTERFACE_INTERNAL (klass) ? mono_class_num_methods (klass) : mono_class_get_vtable_size (klass);
4427 if (nslots >= sizeof (method_slots_default) * 8) {
4428 method_slots = g_new0 (guint32, nslots / 32 + 1);
4429 } else {
4430 method_slots = method_slots_default;
4431 memset (method_slots, 0, sizeof (method_slots_default));
4433 handle_parent:
4434 mono_class_setup_methods (klass);
4435 mono_class_setup_vtable (klass);
4436 if (mono_class_has_failure (klass))
4437 goto loader_error;
4439 iter = NULL;
4440 while ((method = mono_class_get_methods (klass, &iter))) {
4441 match = 0;
4442 if (method->slot != -1) {
4443 g_assert (method->slot < nslots);
4444 if (method_slots [method->slot >> 5] & (1 << (method->slot & 0x1f)))
4445 continue;
4446 if (!(method->flags & METHOD_ATTRIBUTE_NEW_SLOT))
4447 method_slots [method->slot >> 5] |= 1 << (method->slot & 0x1f);
4450 if (!allow_ctors && method->name [0] == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0))
4451 continue;
4452 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4453 if (bflags & BFLAGS_Public)
4454 match++;
4455 } else if ((bflags & BFLAGS_NonPublic) && method_nonpublic (method, (klass == startklass))) {
4456 match++;
4458 if (!match)
4459 continue;
4460 match = 0;
4461 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4462 if (bflags & BFLAGS_Static)
4463 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4464 match++;
4465 } else {
4466 if (bflags & BFLAGS_Instance)
4467 match++;
4470 if (!match)
4471 continue;
4473 if ((mlisttype != MLISTTYPE_All) && (name != NULL)) {
4474 if (compare_func (name, method->name))
4475 continue;
4478 match = 0;
4479 g_ptr_array_add (array, method);
4481 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
4482 goto handle_parent;
4483 if (method_slots != method_slots_default)
4484 g_free (method_slots);
4486 return array;
4488 loader_error:
4489 if (method_slots != method_slots_default)
4490 g_free (method_slots);
4491 g_ptr_array_free (array, TRUE);
4493 g_assert (mono_class_has_failure (klass));
4494 mono_error_set_for_class_failure (error, klass);
4495 return NULL;
4498 GPtrArray*
4499 ves_icall_RuntimeType_GetMethodsByName_native (MonoReflectionTypeHandle ref_type, const char *mname, guint32 bflags, guint32 mlisttype, MonoError *error)
4501 error_init (error);
4502 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4504 MonoClass *klass = mono_class_from_mono_type_internal (type);
4505 if (type->byref) {
4506 return g_ptr_array_new ();
4509 return mono_class_get_methods_by_name (klass, mname, bflags, mlisttype, FALSE, error);
4512 GPtrArray*
4513 ves_icall_RuntimeType_GetConstructors_native (MonoReflectionTypeHandle ref_type, guint32 bflags, MonoError *error)
4515 error_init (error);
4516 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4517 if (type->byref) {
4518 return g_ptr_array_new ();
4521 MonoClass *startklass, *klass;
4522 klass = startklass = mono_class_from_mono_type_internal (type);
4524 mono_class_setup_methods (klass);
4525 if (mono_class_has_failure (klass)) {
4526 mono_error_set_for_class_failure (error, klass);
4527 return NULL;
4531 GPtrArray *res_array = g_ptr_array_sized_new (4); /* FIXME, guestimating */
4533 MonoMethod *method;
4534 gpointer iter = NULL;
4535 while ((method = mono_class_get_methods (klass, &iter))) {
4536 int match = 0;
4537 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
4538 continue;
4539 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4540 if (bflags & BFLAGS_Public)
4541 match++;
4542 } else {
4543 if (bflags & BFLAGS_NonPublic)
4544 match++;
4546 if (!match)
4547 continue;
4548 match = 0;
4549 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4550 if (bflags & BFLAGS_Static)
4551 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4552 match++;
4553 } else {
4554 if (bflags & BFLAGS_Instance)
4555 match++;
4558 if (!match)
4559 continue;
4560 g_ptr_array_add (res_array, method);
4563 return res_array;
4566 static guint
4567 property_hash (gconstpointer data)
4569 MonoProperty *prop = (MonoProperty*)data;
4571 return g_str_hash (prop->name);
4574 static gboolean
4575 property_accessor_override (MonoMethod *method1, MonoMethod *method2)
4577 if (method1->slot != -1 && method1->slot == method2->slot)
4578 return TRUE;
4580 if (mono_class_get_generic_type_definition (method1->klass) == mono_class_get_generic_type_definition (method2->klass)) {
4581 if (method1->is_inflated)
4582 method1 = ((MonoMethodInflated*) method1)->declaring;
4583 if (method2->is_inflated)
4584 method2 = ((MonoMethodInflated*) method2)->declaring;
4587 return mono_metadata_signature_equal (mono_method_signature_internal (method1), mono_method_signature_internal (method2));
4590 static gboolean
4591 property_equal (MonoProperty *prop1, MonoProperty *prop2)
4593 // Properties are hide-by-name-and-signature
4594 if (!g_str_equal (prop1->name, prop2->name))
4595 return FALSE;
4597 /* If we see a property in a generic method, we want to
4598 compare the generic signatures, not the inflated signatures
4599 because we might conflate two properties that were
4600 distinct:
4602 class Foo<T,U> {
4603 public T this[T t] { getter { return t; } } // method 1
4604 public U this[U u] { getter { return u; } } // method 2
4607 If we see int Foo<int,int>::Item[int] we need to know if
4608 the indexer came from method 1 or from method 2, and we
4609 shouldn't conflate them. (Bugzilla 36283)
4611 if (prop1->get && prop2->get && !property_accessor_override (prop1->get, prop2->get))
4612 return FALSE;
4614 if (prop1->set && prop2->set && !property_accessor_override (prop1->set, prop2->set))
4615 return FALSE;
4617 return TRUE;
4620 static gboolean
4621 property_accessor_nonpublic (MonoMethod* accessor, gboolean start_klass)
4623 if (!accessor)
4624 return FALSE;
4626 return method_nonpublic (accessor, start_klass);
4629 GPtrArray*
4630 ves_icall_RuntimeType_GetPropertiesByName_native (MonoReflectionTypeHandle ref_type, gchar *propname, guint32 bflags, guint32 mlisttype, MonoError *error)
4632 #if ENABLE_NETCORE
4633 // Fetch non-public properties as well because they can hide public properties with the same name in base classes
4634 bflags |= BFLAGS_NonPublic;
4635 #endif
4636 error_init (error);
4637 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4640 if (type->byref) {
4641 return g_ptr_array_new ();
4645 MonoClass *startklass, *klass;
4646 klass = startklass = mono_class_from_mono_type_internal (type);
4648 int (*compare_func) (const char *s1, const char *s2) = (mlisttype == MLISTTYPE_CaseInsensitive) ? mono_utf8_strcasecmp : strcmp;
4650 GPtrArray *res_array = g_ptr_array_sized_new (8); /*This the average for ASP.NET types*/
4652 GHashTable *properties = g_hash_table_new (property_hash, (GEqualFunc)property_equal);
4654 handle_parent:
4655 mono_class_setup_methods (klass);
4656 mono_class_setup_vtable (klass);
4657 if (mono_class_has_failure (klass)) {
4658 mono_error_set_for_class_failure (error, klass);
4659 goto loader_error;
4662 MonoProperty *prop;
4663 gpointer iter;
4664 iter = NULL;
4665 while ((prop = mono_class_get_properties (klass, &iter))) {
4666 int match = 0;
4667 MonoMethod *method = prop->get;
4668 if (!method)
4669 method = prop->set;
4670 guint32 flags = 0;
4671 if (method)
4672 flags = method->flags;
4674 if ((prop->get && ((prop->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)) ||
4675 (prop->set && ((prop->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC))) {
4676 if (bflags & BFLAGS_Public)
4677 match++;
4678 } else if (bflags & BFLAGS_NonPublic) {
4679 if (property_accessor_nonpublic(prop->get, startklass == klass) ||
4680 property_accessor_nonpublic(prop->set, startklass == klass)) {
4681 match++;
4684 if (!match)
4685 continue;
4687 match = 0;
4688 if (flags & METHOD_ATTRIBUTE_STATIC) {
4689 if (bflags & BFLAGS_Static)
4690 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4691 match++;
4692 } else {
4693 if (bflags & BFLAGS_Instance)
4694 match++;
4697 if (!match)
4698 continue;
4699 match = 0;
4701 if ((mlisttype != MLISTTYPE_All) && (propname != NULL) && compare_func (propname, prop->name))
4702 continue;
4704 if (g_hash_table_lookup (properties, prop))
4705 continue;
4707 g_ptr_array_add (res_array, prop);
4709 g_hash_table_insert (properties, prop, prop);
4711 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass))) {
4712 #if ENABLE_NETCORE
4713 // BFLAGS_NonPublic should be excluded for base classes
4714 bflags &= ~BFLAGS_NonPublic;
4715 #endif
4716 goto handle_parent;
4719 g_hash_table_destroy (properties);
4721 return res_array;
4724 loader_error:
4725 if (properties)
4726 g_hash_table_destroy (properties);
4727 g_ptr_array_free (res_array, TRUE);
4729 return NULL;
4732 static guint
4733 event_hash (gconstpointer data)
4735 MonoEvent *event = (MonoEvent*)data;
4737 return g_str_hash (event->name);
4740 static gboolean
4741 event_equal (MonoEvent *event1, MonoEvent *event2)
4743 // Events are hide-by-name
4744 return g_str_equal (event1->name, event2->name);
4747 GPtrArray*
4748 ves_icall_RuntimeType_GetEvents_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 mlisttype, MonoError *error)
4750 error_init (error);
4751 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4753 if (type->byref) {
4754 return g_ptr_array_new ();
4757 int (*compare_func) (const char *s1, const char *s2) = (mlisttype == MLISTTYPE_CaseInsensitive) ? mono_utf8_strcasecmp : strcmp;
4759 GPtrArray *res_array = g_ptr_array_sized_new (4);
4761 MonoClass *startklass, *klass;
4762 klass = startklass = mono_class_from_mono_type_internal (type);
4764 GHashTable *events = g_hash_table_new (event_hash, (GEqualFunc)event_equal);
4765 handle_parent:
4766 mono_class_setup_methods (klass);
4767 mono_class_setup_vtable (klass);
4768 if (mono_class_has_failure (klass)) {
4769 mono_error_set_for_class_failure (error, klass);
4770 goto failure;
4773 MonoEvent *event;
4774 gpointer iter;
4775 iter = NULL;
4776 while ((event = mono_class_get_events (klass, &iter))) {
4778 // Remove inherited privates and inherited
4779 // without add/remove/raise methods
4780 if (klass != startklass)
4782 MonoMethod *method = event->add;
4783 if (!method)
4784 method = event->remove;
4785 if (!method)
4786 method = event->raise;
4787 if (!method)
4788 continue;
4789 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PRIVATE)
4790 continue;
4793 if ((mlisttype != MLISTTYPE_All) && (utf8_name != NULL) && compare_func (event->name, utf8_name))
4794 continue;
4796 if (g_hash_table_lookup (events, event))
4797 continue;
4799 g_ptr_array_add (res_array, event);
4801 g_hash_table_insert (events, event, event);
4803 if ((klass = m_class_get_parent (klass)))
4804 goto handle_parent;
4806 g_hash_table_destroy (events);
4808 return res_array;
4810 failure:
4811 if (events != NULL)
4812 g_hash_table_destroy (events);
4814 g_ptr_array_free (res_array, TRUE);
4816 return NULL;
4819 GPtrArray *
4820 ves_icall_RuntimeType_GetNestedTypes_native (MonoReflectionTypeHandle ref_type, char *str, guint32 bflags, guint32 mlisttype, MonoError *error)
4822 error_init (error);
4823 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4825 if (type->byref) {
4826 return g_ptr_array_new ();
4829 int (*compare_func) (const char *s1, const char *s2) = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
4831 MonoClass *klass = mono_class_from_mono_type_internal (type);
4834 * If a nested type is generic, return its generic type definition.
4835 * Note that this means that the return value is essentially the set
4836 * of nested types of the generic type definition of @klass.
4838 * A note in MSDN claims that a generic type definition can have
4839 * nested types that aren't generic. In any case, the container of that
4840 * nested type would be the generic type definition.
4842 if (mono_class_is_ginst (klass))
4843 klass = mono_class_get_generic_class (klass)->container_class;
4845 GPtrArray *res_array = g_ptr_array_new ();
4847 MonoClass *nested;
4848 gpointer iter = NULL;
4849 while ((nested = mono_class_get_nested_types (klass, &iter))) {
4850 int match = 0;
4851 if ((mono_class_get_flags (nested) & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
4852 if (bflags & BFLAGS_Public)
4853 match++;
4854 } else {
4855 if (bflags & BFLAGS_NonPublic)
4856 match++;
4858 if (!match)
4859 continue;
4861 if ((mlisttype != MLISTTYPE_All) && (str != NULL) && compare_func (m_class_get_name (nested), str))
4862 continue;
4864 g_ptr_array_add (res_array, m_class_get_byval_arg (nested));
4867 return res_array;
4870 static MonoType*
4871 get_type_from_module_builder_module (MonoArrayHandle modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
4873 HANDLE_FUNCTION_ENTER ();
4874 error_init (error);
4875 MonoType *type = NULL;
4876 MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW (MonoReflectionModuleBuilder, NULL);
4877 MONO_HANDLE_ARRAY_GETREF (mb, modules, i);
4878 MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
4879 type = mono_reflection_get_type_checked (&dynamic_image->image, &dynamic_image->image, info, ignoreCase, FALSE, type_resolve, error);
4880 HANDLE_FUNCTION_RETURN_VAL (type);
4883 static MonoType*
4884 get_type_from_module_builder_loaded_modules (MonoArrayHandle loaded_modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
4886 HANDLE_FUNCTION_ENTER ();
4887 error_init (error);
4888 MonoType *type = NULL;
4889 MonoReflectionModuleHandle mod = MONO_HANDLE_NEW (MonoReflectionModule, NULL);
4890 MONO_HANDLE_ARRAY_GETREF (mod, loaded_modules, i);
4891 MonoImage *image = MONO_HANDLE_GETVAL (mod, image);
4892 type = mono_reflection_get_type_checked (image, image, info, ignoreCase, FALSE, type_resolve, error);
4893 HANDLE_FUNCTION_RETURN_VAL (type);
4896 MonoReflectionTypeHandle
4897 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssemblyHandle assembly_h, MonoReflectionModuleHandle module, MonoStringHandle name, MonoBoolean throwOnError, MonoBoolean ignoreCase, MonoError *error)
4899 error_init (error);
4900 ERROR_DECL (parse_error);
4902 MonoTypeNameParse info;
4903 gboolean type_resolve;
4905 /* On MS.NET, this does not fire a TypeResolve event */
4906 type_resolve = TRUE;
4907 char *str = mono_string_handle_to_utf8 (name, error);
4908 goto_if_nok (error, fail);
4910 /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
4911 if (!mono_reflection_parse_type_checked (str, &info, parse_error)) {
4912 g_free (str);
4913 mono_reflection_free_type_info (&info);
4914 mono_error_cleanup (parse_error);
4915 if (throwOnError) {
4916 #if ENABLE_NETCORE
4917 mono_error_set_argument (error, "typeName@0", "failed to parse the type");
4918 #else
4919 mono_error_set_argument (error, "typeName", "failed to parse the type");
4920 #endif
4921 goto fail;
4923 /*g_print ("failed parse\n");*/
4924 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4927 if (info.assembly.name) {
4928 g_free (str);
4929 mono_reflection_free_type_info (&info);
4930 if (throwOnError) {
4931 /* 1.0 and 2.0 throw different exceptions */
4932 if (mono_defaults.generic_ilist_class)
4933 mono_error_set_argument (error, NULL, "Type names passed to Assembly.GetType() must not specify an assembly.");
4934 else
4935 mono_error_set_type_load_name (error, g_strdup (""), g_strdup (""), "Type names passed to Assembly.GetType() must not specify an assembly.");
4936 goto fail;
4938 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4941 MonoType *type;
4942 type = NULL;
4943 if (!MONO_HANDLE_IS_NULL (module)) {
4944 MonoImage *image = MONO_HANDLE_GETVAL (module, image);
4945 if (image) {
4946 type = mono_reflection_get_type_checked (image, image, &info, ignoreCase, FALSE, &type_resolve, error);
4947 if (!is_ok (error)) {
4948 g_free (str);
4949 mono_reflection_free_type_info (&info);
4950 goto fail;
4954 else {
4955 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4956 if (assembly_is_dynamic (assembly)) {
4957 /* Enumerate all modules */
4958 MonoReflectionAssemblyBuilderHandle abuilder = MONO_HANDLE_NEW (MonoReflectionAssemblyBuilder, NULL);
4959 MONO_HANDLE_ASSIGN (abuilder, assembly_h);
4960 int i;
4962 MonoArrayHandle modules = MONO_HANDLE_NEW (MonoArray, NULL);
4963 MONO_HANDLE_GET (modules, abuilder, modules);
4964 if (!MONO_HANDLE_IS_NULL (modules)) {
4965 int n = mono_array_handle_length (modules);
4966 for (i = 0; i < n; ++i) {
4967 type = get_type_from_module_builder_module (modules, i, &info, ignoreCase, &type_resolve, error);
4968 if (!is_ok (error)) {
4969 g_free (str);
4970 mono_reflection_free_type_info (&info);
4971 goto fail;
4973 if (type)
4974 break;
4978 MonoArrayHandle loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL);
4979 MONO_HANDLE_GET (loaded_modules, abuilder, loaded_modules);
4980 if (!type && !MONO_HANDLE_IS_NULL (loaded_modules)) {
4981 int n = mono_array_handle_length (loaded_modules);
4982 for (i = 0; i < n; ++i) {
4983 type = get_type_from_module_builder_loaded_modules (loaded_modules, i, &info, ignoreCase, &type_resolve, error);
4985 if (!is_ok (error)) {
4986 g_free (str);
4987 mono_reflection_free_type_info (&info);
4988 goto fail;
4990 if (type)
4991 break;
4995 else {
4996 type = mono_reflection_get_type_checked (assembly->image, assembly->image, &info, ignoreCase, FALSE, &type_resolve, error);
4997 if (!is_ok (error)) {
4998 g_free (str);
4999 mono_reflection_free_type_info (&info);
5000 goto fail;
5004 g_free (str);
5005 mono_reflection_free_type_info (&info);
5007 if (!type) {
5008 if (throwOnError) {
5009 ERROR_DECL (inner_error);
5010 char *type_name = mono_string_handle_to_utf8 (name, inner_error);
5011 mono_error_assert_ok (inner_error);
5012 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5013 char *assmname = mono_stringify_assembly_name (&assembly->aname);
5014 mono_error_set_type_load_name (error, type_name, assmname, "%s", "");
5015 goto fail;
5018 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
5021 if (type->type == MONO_TYPE_CLASS) {
5022 MonoClass *klass = mono_type_get_class (type);
5024 /* need to report exceptions ? */
5025 if (throwOnError && mono_class_has_failure (klass)) {
5026 /* report SecurityException (or others) that occured when loading the assembly */
5027 mono_error_set_for_class_failure (error, klass);
5028 goto fail;
5032 /* g_print ("got it\n"); */
5033 return mono_type_get_object_handle (MONO_HANDLE_DOMAIN (assembly_h), type, error);
5034 fail:
5035 g_assert (!is_ok (error));
5036 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
5039 static gboolean
5040 replace_shadow_path (MonoDomain *domain, gchar *dirname, gchar **filename)
5042 gchar *content;
5043 gchar *shadow_ini_file;
5044 gsize len;
5046 /* Check for shadow-copied assembly */
5047 if (mono_is_shadow_copy_enabled (domain, dirname)) {
5048 shadow_ini_file = g_build_filename (dirname, "__AssemblyInfo__.ini", (const char*)NULL);
5049 content = NULL;
5050 if (!g_file_get_contents (shadow_ini_file, &content, &len, NULL) ||
5051 !g_file_test (content, G_FILE_TEST_IS_REGULAR)) {
5052 g_free (content);
5053 content = NULL;
5055 g_free (shadow_ini_file);
5056 if (content != NULL) {
5057 g_free (*filename);
5058 *filename = content;
5059 return TRUE;
5062 return FALSE;
5065 MonoStringHandle
5066 ves_icall_System_Reflection_RuntimeAssembly_get_code_base (MonoReflectionAssemblyHandle assembly, MonoBoolean escaped, MonoError *error)
5068 error_init (error);
5069 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5070 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
5071 gchar *absolute;
5072 gchar *dirname;
5074 if (g_path_is_absolute (mass->image->name)) {
5075 absolute = g_strdup (mass->image->name);
5076 dirname = g_path_get_dirname (absolute);
5077 } else {
5078 absolute = g_build_filename (mass->basedir, mass->image->name, (const char*)NULL);
5079 dirname = g_strdup (mass->basedir);
5082 replace_shadow_path (domain, dirname, &absolute);
5083 g_free (dirname);
5085 mono_icall_make_platform_path (absolute);
5087 gchar *uri;
5088 if (escaped) {
5089 uri = g_filename_to_uri (absolute, NULL, NULL);
5090 } else {
5091 const gchar *prepend = mono_icall_get_file_path_prefix (absolute);
5092 uri = g_strconcat (prepend, absolute, (const char*)NULL);
5095 g_free (absolute);
5097 MonoStringHandle res;
5098 if (uri) {
5099 res = mono_string_new_handle (domain, uri, error);
5100 g_free (uri);
5101 } else {
5102 res = MONO_HANDLE_NEW (MonoString, NULL);
5104 return res;
5107 MonoBoolean
5108 ves_icall_System_Reflection_RuntimeAssembly_get_global_assembly_cache (MonoReflectionAssemblyHandle assembly, MonoError *error)
5110 error_init (error);
5111 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly,assembly);
5113 return mass->in_gac;
5116 MonoReflectionAssemblyHandle
5117 ves_icall_System_Reflection_Assembly_load_with_partial_name (MonoStringHandle mname, MonoObjectHandle evidence, MonoError *error)
5119 gchar *name;
5120 MonoImageOpenStatus status;
5121 MonoReflectionAssemblyHandle result = MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5123 name = mono_string_handle_to_utf8 (mname, error);
5124 goto_if_nok (error, leave);
5125 MonoAssembly *res;
5126 res = mono_assembly_load_with_partial_name_internal (name, mono_domain_default_alc (mono_domain_get ()), &status);
5128 g_free (name);
5130 if (res == NULL)
5131 goto leave;
5132 result = mono_assembly_get_object_handle (mono_domain_get (), res, error);
5133 leave:
5134 return result;
5137 MonoStringHandle
5138 ves_icall_System_Reflection_RuntimeAssembly_get_location (MonoReflectionAssemblyHandle refassembly, MonoError *error)
5140 MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
5141 MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
5142 const char *image_name = m_image_get_filename (assembly->image);
5143 return mono_string_new_handle (domain, image_name != NULL ? image_name : "", error);
5146 MonoBoolean
5147 ves_icall_System_Reflection_RuntimeAssembly_get_ReflectionOnly (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5149 error_init (error);
5150 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5151 return mono_asmctx_get_kind (&assembly->context) == MONO_ASMCTX_REFONLY;
5154 MonoStringHandle
5155 ves_icall_System_Reflection_RuntimeAssembly_InternalImageRuntimeVersion (MonoReflectionAssemblyHandle refassembly, MonoError *error)
5157 MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
5158 MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
5160 return mono_string_new_handle (domain, assembly->image->version, error);
5163 MonoReflectionMethodHandle
5164 ves_icall_System_Reflection_RuntimeAssembly_get_EntryPoint (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5166 error_init (error);
5167 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5168 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5169 MonoMethod *method;
5171 MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
5172 guint32 token = mono_image_get_entry_point (assembly->image);
5174 if (!token)
5175 goto leave;
5176 method = mono_get_method_checked (assembly->image, token, NULL, NULL, error);
5177 goto_if_nok (error, leave);
5179 MONO_HANDLE_ASSIGN (res, mono_method_get_object_handle (domain, method, NULL, error));
5180 leave:
5181 return res;
5184 MonoReflectionModuleHandle
5185 ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAssemblyHandle assembly, MonoError *error)
5187 error_init (error);
5188 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5189 MonoAssembly *a = MONO_HANDLE_GETVAL (assembly, assembly);
5190 return mono_module_get_object_handle (domain, a->image, error);
5193 static gboolean
5194 add_manifest_resource_name_to_array (MonoDomain *domain, MonoImage *image, MonoTableInfo *table, int i, MonoArrayHandle dest, MonoError *error)
5196 HANDLE_FUNCTION_ENTER ();
5197 error_init (error);
5198 const char *val = mono_metadata_string_heap (image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
5199 MonoStringHandle str = mono_string_new_handle (domain, val, error);
5200 goto_if_nok (error, leave);
5201 MONO_HANDLE_ARRAY_SETREF (dest, i, str);
5202 leave:
5203 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5206 MonoArrayHandle
5207 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceNames (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5209 error_init (error);
5210 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5211 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5212 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
5213 MonoArrayHandle result = mono_array_new_handle (domain, mono_defaults.string_class, table->rows, error);
5214 goto_if_nok (error, fail);
5215 int i;
5217 for (i = 0; i < table->rows; ++i) {
5218 if (!add_manifest_resource_name_to_array (domain, assembly->image, table, i, result, error))
5219 goto fail;
5221 return result;
5222 fail:
5223 return NULL_HANDLE_ARRAY;
5226 MonoBoolean
5227 ves_icall_System_Reflection_RuntimeAssembly_GetAotIdInternal (MonoArrayHandle guid_h, MonoError *error)
5229 g_assert (mono_array_handle_length (guid_h) == 16);
5231 guint8 *aotid = mono_runtime_get_aotid_arr ();
5232 if (!aotid) {
5233 return FALSE;
5234 } else {
5235 MONO_ENTER_NO_SAFEPOINTS;
5236 guint8 *data = (guint8*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (guid_h), 1, 0);
5237 memcpy (data, aotid, 16);
5238 MONO_EXIT_NO_SAFEPOINTS;
5239 return TRUE;
5243 static MonoAssemblyName*
5244 create_referenced_assembly_name (MonoDomain *domain, MonoImage *image, MonoTableInfo *t, int i, MonoError *error)
5246 error_init (error);
5247 MonoAssemblyName *aname = g_new0 (MonoAssemblyName, 1);
5249 mono_assembly_get_assemblyref_checked (image, i, aname, error);
5250 return_val_if_nok (error, NULL);
5251 aname->hash_alg = ASSEMBLY_HASH_SHA1 /* SHA1 (default) */;
5252 /* name and culture are pointers into the image tables, but we need
5253 * real malloc'd strings (so that we can g_free() them later from
5254 * Mono.RuntimeMarshal.FreeAssemblyName) */
5255 aname->name = g_strdup (aname->name);
5256 aname->culture = g_strdup (aname->culture);
5257 /* Don't need the hash value in managed */
5258 aname->hash_value = NULL;
5259 aname->hash_len = 0;
5260 g_assert (aname->public_key == NULL);
5262 /* note: this function doesn't return the codebase on purpose (i.e. it can
5263 be used under partial trust as path information isn't present). */
5264 return aname;
5267 GPtrArray*
5268 ves_icall_System_Reflection_Assembly_InternalGetReferencedAssemblies (MonoReflectionAssemblyHandle assembly, MonoError *error)
5270 error_init (error);
5271 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5272 MonoAssembly *ass = MONO_HANDLE_GETVAL(assembly, assembly);
5273 MonoImage *image = ass->image;
5275 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
5276 int count = t->rows;
5278 GPtrArray *result = g_ptr_array_sized_new (count);
5280 for (int i = 0; i < count; i++) {
5281 MonoAssemblyName *aname = create_referenced_assembly_name (domain, image, t, i, error);
5282 if (!is_ok (error))
5283 break;
5284 g_ptr_array_add (result, aname);
5286 return result;
5289 /* move this in some file in mono/util/ */
5290 static char *
5291 g_concat_dir_and_file (const char *dir, const char *file)
5293 g_return_val_if_fail (dir != NULL, NULL);
5294 g_return_val_if_fail (file != NULL, NULL);
5297 * If the directory name doesn't have a / on the end, we need
5298 * to add one so we get a proper path to the file
5300 if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
5301 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, (const char*)NULL);
5302 else
5303 return g_strconcat (dir, file, (const char*)NULL);
5306 void *
5307 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, gint32 *size, MonoReflectionModuleHandleOut ref_module, MonoError *error)
5309 error_init (error);
5310 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5311 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5312 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
5313 guint32 i;
5314 guint32 cols [MONO_MANIFEST_SIZE];
5315 guint32 impl, file_idx;
5316 const char *val;
5317 MonoImage *module;
5319 char *n = mono_string_handle_to_utf8 (name, error);
5320 return_val_if_nok (error, NULL);
5322 for (i = 0; i < table->rows; ++i) {
5323 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
5324 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
5325 if (strcmp (val, n) == 0)
5326 break;
5328 g_free (n);
5329 if (i == table->rows)
5330 return NULL;
5331 /* FIXME */
5332 impl = cols [MONO_MANIFEST_IMPLEMENTATION];
5333 if (impl) {
5335 * this code should only be called after obtaining the
5336 * ResourceInfo and handling the other cases.
5338 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
5339 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
5341 module = mono_image_load_file_for_image_checked (assembly->image, file_idx, error);
5342 if (!is_ok (error) || !module)
5343 return NULL;
5345 else
5346 module = assembly->image;
5349 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
5350 return_val_if_nok (error, NULL);
5351 MONO_HANDLE_ASSIGN (ref_module, rm);
5353 return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
5356 static gboolean
5357 get_manifest_resource_info_internal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info, MonoError *error)
5359 HANDLE_FUNCTION_ENTER ();
5360 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5361 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5362 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
5363 int i;
5364 guint32 cols [MONO_MANIFEST_SIZE];
5365 guint32 file_cols [MONO_FILE_SIZE];
5366 const char *val;
5367 char *n;
5369 gboolean result = FALSE;
5371 n = mono_string_handle_to_utf8 (name, error);
5372 goto_if_nok (error, leave);
5374 for (i = 0; i < table->rows; ++i) {
5375 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
5376 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
5377 if (strcmp (val, n) == 0)
5378 break;
5380 g_free (n);
5381 if (i == table->rows)
5382 goto leave;
5384 if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
5385 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST);
5387 else {
5388 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
5389 case MONO_IMPLEMENTATION_FILE:
5390 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
5391 table = &assembly->image->tables [MONO_TABLE_FILE];
5392 mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
5393 val = mono_metadata_string_heap (assembly->image, file_cols [MONO_FILE_NAME]);
5394 MONO_HANDLE_SET (info, filename, mono_string_new_handle (domain, val, error));
5395 if (file_cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA)
5396 MONO_HANDLE_SETVAL (info, location, guint32, 0);
5397 else
5398 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED);
5399 break;
5401 case MONO_IMPLEMENTATION_ASSEMBLYREF:
5402 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
5403 mono_assembly_load_reference (assembly->image, i - 1);
5404 if (assembly->image->references [i - 1] == REFERENCE_MISSING) {
5405 mono_error_set_file_not_found (error, NULL, "Assembly %d referenced from assembly %s not found ", i - 1, assembly->image->name);
5406 goto leave;
5408 MonoReflectionAssemblyHandle assm_obj;
5409 assm_obj = mono_assembly_get_object_handle (mono_domain_get (), assembly->image->references [i - 1], error);
5410 goto_if_nok (error, leave);
5411 MONO_HANDLE_SET (info, assembly, assm_obj);
5413 /* Obtain info recursively */
5414 get_manifest_resource_info_internal (assm_obj, name, info, error);
5415 goto_if_nok (error, leave);
5416 guint32 location;
5417 location = MONO_HANDLE_GETVAL (info, location);
5418 location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
5419 MONO_HANDLE_SETVAL (info, location, guint32, location);
5420 break;
5422 case MONO_IMPLEMENTATION_EXP_TYPE:
5423 g_assert_not_reached ();
5424 break;
5428 result = TRUE;
5429 leave:
5430 HANDLE_FUNCTION_RETURN_VAL (result);
5433 MonoBoolean
5434 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInfoInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info_h, MonoError *error)
5436 error_init (error);
5437 return get_manifest_resource_info_internal (assembly_h, name, info_h, error);
5440 static gboolean
5441 add_filename_to_files_array (MonoDomain *domain, MonoAssembly * assembly, MonoTableInfo *table, int i, MonoArrayHandle dest, int dest_idx, MonoError *error)
5443 HANDLE_FUNCTION_ENTER();
5444 error_init (error);
5445 const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
5446 char *n = g_concat_dir_and_file (assembly->basedir, val);
5447 MonoStringHandle str = mono_string_new_handle (domain, n, error);
5448 g_free (n);
5449 goto_if_nok (error, leave);
5450 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, str);
5451 leave:
5452 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5455 MonoObjectHandle
5456 ves_icall_System_Reflection_RuntimeAssembly_GetFilesInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoBoolean resource_modules, MonoError *error)
5458 error_init (error);
5459 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5460 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5461 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_FILE];
5462 int i, count;
5464 /* check hash if needed */
5465 if (!MONO_HANDLE_IS_NULL(name)) {
5466 char *n = mono_string_handle_to_utf8 (name, error);
5467 goto_if_nok (error, fail);
5469 for (i = 0; i < table->rows; ++i) {
5470 const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
5471 if (strcmp (val, n) == 0) {
5472 g_free (n);
5473 n = g_concat_dir_and_file (assembly->basedir, val);
5474 MonoStringHandle fn = mono_string_new_handle (domain, n, error);
5475 g_free (n);
5476 goto_if_nok (error, fail);
5477 return MONO_HANDLE_CAST (MonoObject, fn);
5480 g_free (n);
5481 return NULL_HANDLE;
5484 count = 0;
5485 for (i = 0; i < table->rows; ++i) {
5486 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA))
5487 count ++;
5490 MonoArrayHandle result;
5491 result = mono_array_new_handle (domain, mono_defaults.string_class, count, error);
5492 goto_if_nok (error, fail);
5494 count = 0;
5495 for (i = 0; i < table->rows; ++i) {
5496 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
5497 if (!add_filename_to_files_array (domain, assembly, table, i, result, count, error))
5498 goto fail;
5499 count++;
5502 return MONO_HANDLE_CAST (MonoObject, result);
5503 fail:
5504 return NULL_HANDLE;
5507 static gboolean
5508 add_module_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int *dest_idx, MonoImage* module, MonoError *error)
5510 HANDLE_FUNCTION_ENTER ();
5511 error_init (error);
5512 if (module) {
5513 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
5514 goto_if_nok (error, leave);
5516 MONO_HANDLE_ARRAY_SETREF (dest, *dest_idx, rm);
5517 ++(*dest_idx);
5520 leave:
5521 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5524 static gboolean
5525 add_file_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int dest_idx, MonoImage *image, MonoTableInfo *table, int table_idx, MonoError *error)
5527 HANDLE_FUNCTION_ENTER ();
5528 error_init (error);
5530 guint32 cols [MONO_FILE_SIZE];
5531 mono_metadata_decode_row (table, table_idx, cols, MONO_FILE_SIZE);
5532 if (cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA) {
5533 MonoReflectionModuleHandle rm = mono_module_file_get_object_handle (domain, image, table_idx, error);
5534 goto_if_nok (error, leave);
5535 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5536 } else {
5537 MonoImage *m = mono_image_load_file_for_image_checked (image, table_idx + 1, error);
5538 goto_if_nok (error, leave);
5539 if (!m) {
5540 const char *filename = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
5541 mono_error_set_file_not_found (error, filename, "%s", "");
5542 goto leave;
5544 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, m, error);
5545 goto_if_nok (error, leave);
5546 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5549 leave:
5550 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5553 MonoArrayHandle
5554 ves_icall_System_Reflection_RuntimeAssembly_GetModulesInternal (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5556 error_init (error);
5557 MonoDomain *domain = mono_domain_get();
5558 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5559 MonoClass *klass;
5560 int i, j, file_count = 0;
5561 MonoImage **modules;
5562 guint32 module_count, real_module_count;
5563 MonoTableInfo *table;
5564 MonoImage *image = assembly->image;
5566 g_assert (image != NULL);
5567 g_assert (!assembly_is_dynamic (assembly));
5569 table = &image->tables [MONO_TABLE_FILE];
5570 file_count = table->rows;
5572 modules = image->modules;
5573 module_count = image->module_count;
5575 real_module_count = 0;
5576 for (i = 0; i < module_count; ++i)
5577 if (modules [i])
5578 real_module_count ++;
5580 klass = mono_class_get_module_class ();
5581 MonoArrayHandle res = mono_array_new_handle (domain, klass, 1 + real_module_count + file_count, error);
5582 goto_if_nok (error, fail);
5584 MonoReflectionModuleHandle image_obj;
5585 image_obj = mono_module_get_object_handle (domain, image, error);
5586 goto_if_nok (error, fail);
5588 MONO_HANDLE_ARRAY_SETREF (res, 0, image_obj);
5590 j = 1;
5591 for (i = 0; i < module_count; ++i)
5592 if (!add_module_to_modules_array (domain, res, &j, modules[i], error))
5593 goto fail;
5595 for (i = 0; i < file_count; ++i, ++j) {
5596 if (!add_file_to_modules_array (domain, res, j, image, table, i, error))
5597 goto fail;
5600 return res;
5601 fail:
5602 return NULL_HANDLE_ARRAY;
5605 MonoReflectionMethodHandle
5606 ves_icall_GetCurrentMethod (MonoError *error)
5608 error_init (error);
5610 MonoMethod *m = mono_method_get_last_managed ();
5612 if (!m) {
5613 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5614 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5617 while (m->is_inflated)
5618 m = ((MonoMethodInflated*)m)->declaring;
5620 return mono_method_get_object_handle (mono_domain_get (), m, NULL, error);
5623 static MonoMethod*
5624 mono_method_get_equivalent_method (MonoMethod *method, MonoClass *klass)
5626 int offset = -1, i;
5627 if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) {
5628 ERROR_DECL (error);
5629 MonoMethod *result;
5630 MonoMethodInflated *inflated = (MonoMethodInflated*)method;
5631 //method is inflated, we should inflate it on the other class
5632 MonoGenericContext ctx;
5633 ctx.method_inst = inflated->context.method_inst;
5634 ctx.class_inst = inflated->context.class_inst;
5635 if (mono_class_is_ginst (klass))
5636 ctx.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
5637 else if (mono_class_is_gtd (klass))
5638 ctx.class_inst = mono_class_get_generic_container (klass)->context.class_inst;
5639 result = mono_class_inflate_generic_method_full_checked (inflated->declaring, klass, &ctx, error);
5640 g_assert (is_ok (error)); /* FIXME don't swallow the error */
5641 return result;
5644 mono_class_setup_methods (method->klass);
5645 if (mono_class_has_failure (method->klass))
5646 return NULL;
5647 int mcount = mono_class_get_method_count (method->klass);
5648 MonoMethod **method_klass_methods = m_class_get_methods (method->klass);
5649 for (i = 0; i < mcount; ++i) {
5650 if (method_klass_methods [i] == method) {
5651 offset = i;
5652 break;
5655 mono_class_setup_methods (klass);
5656 if (mono_class_has_failure (klass))
5657 return NULL;
5658 g_assert (offset >= 0 && offset < mono_class_get_method_count (klass));
5659 return m_class_get_methods (klass) [offset];
5662 MonoReflectionMethodHandle
5663 ves_icall_System_Reflection_RuntimeMethodInfo_GetMethodFromHandleInternalType_native (MonoMethod *method, MonoType *type, MonoBoolean generic_check, MonoError *error)
5665 error_init (error);
5666 MonoClass *klass;
5667 if (type && generic_check) {
5668 klass = mono_class_from_mono_type_internal (type);
5669 if (mono_class_get_generic_type_definition (method->klass) != mono_class_get_generic_type_definition (klass))
5670 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5672 if (method->klass != klass) {
5673 method = mono_method_get_equivalent_method (method, klass);
5674 if (!method)
5675 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5677 } else if (type)
5678 klass = mono_class_from_mono_type_internal (type);
5679 else
5680 klass = method->klass;
5681 return mono_method_get_object_handle (mono_domain_get (), method, klass, error);
5684 MonoReflectionMethodBodyHandle
5685 ves_icall_System_Reflection_RuntimeMethodInfo_GetMethodBodyInternal (MonoMethod *method, MonoError *error)
5687 error_init (error);
5688 return mono_method_body_get_object_handle (mono_domain_get (), method, error);
5691 #if ENABLE_NETCORE
5692 MonoReflectionAssemblyHandle
5693 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (MonoStackCrawlMark *stack_mark, MonoError *error)
5695 MonoAssembly *assembly;
5696 assembly = mono_runtime_get_caller_from_stack_mark (stack_mark);
5697 g_assert (assembly);
5698 return mono_assembly_get_object_handle (mono_domain_get (), assembly, error);
5700 #else
5701 MonoReflectionAssemblyHandle
5702 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (MonoError *error)
5704 error_init (error);
5706 MonoMethod *dest = NULL;
5707 mono_stack_walk_no_il (get_executing, &dest);
5708 g_assert (dest);
5709 return mono_assembly_get_object_handle (mono_domain_get (), m_class_get_image (dest->klass)->assembly, error);
5711 #endif
5713 MonoReflectionAssemblyHandle
5714 ves_icall_System_Reflection_Assembly_GetEntryAssembly (MonoError *error)
5716 error_init (error);
5718 MonoDomain* domain = mono_domain_get ();
5720 if (!domain->entry_assembly)
5721 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5723 return mono_assembly_get_object_handle (domain, domain->entry_assembly, error);
5726 MonoReflectionAssemblyHandle
5727 ves_icall_System_Reflection_Assembly_GetCallingAssembly (MonoError *error)
5729 error_init (error);
5730 MonoMethod *m;
5731 MonoMethod *dest;
5733 dest = NULL;
5734 mono_stack_walk_no_il (get_executing, &dest);
5735 m = dest;
5736 mono_stack_walk_no_il (get_caller_no_reflection, &dest);
5737 if (!dest)
5738 dest = m;
5739 if (!m) {
5740 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5741 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5743 return mono_assembly_get_object_handle (mono_domain_get (), m_class_get_image (dest->klass)->assembly, error);
5746 MonoStringHandle
5747 ves_icall_System_RuntimeType_getFullName (MonoReflectionTypeHandle object, MonoBoolean full_name,
5748 MonoBoolean assembly_qualified, MonoError *error)
5750 MonoDomain *domain = mono_object_domain (MONO_HANDLE_RAW (object));
5751 MonoType *type = MONO_HANDLE_RAW (object)->type;
5752 MonoTypeNameFormat format;
5753 MonoStringHandle res;
5754 gchar *name;
5756 if (full_name)
5757 format = assembly_qualified ?
5758 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED :
5759 MONO_TYPE_NAME_FORMAT_FULL_NAME;
5760 else
5761 format = MONO_TYPE_NAME_FORMAT_REFLECTION;
5763 name = mono_type_get_name_full (type, format);
5764 if (!name)
5765 return NULL_HANDLE_STRING;
5767 if (full_name && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
5768 g_free (name);
5769 return NULL_HANDLE_STRING;
5772 res = mono_string_new_handle (domain, name, error);
5773 g_free (name);
5775 return res;
5779 ves_icall_RuntimeType_get_core_clr_security_level (MonoReflectionTypeHandle rfield, MonoError *error)
5781 error_init (error);
5782 MonoType *type = MONO_HANDLE_GETVAL (rfield, type);
5783 MonoClass *klass = mono_class_from_mono_type_internal (type);
5785 mono_class_init_checked (klass, error);
5786 return_val_if_nok (error, -1);
5787 return mono_security_core_clr_class_level (klass);
5791 ves_icall_RuntimeFieldInfo_get_core_clr_security_level (MonoReflectionFieldHandle rfield, MonoError *error)
5793 MonoClassField *field = MONO_HANDLE_GETVAL (rfield, field);
5794 return mono_security_core_clr_field_level (field, TRUE);
5798 ves_icall_RuntimeMethodInfo_get_core_clr_security_level (MonoReflectionMethodHandle rfield, MonoError *error)
5800 MonoMethod *method = MONO_HANDLE_GETVAL (rfield, method);
5801 return mono_security_core_clr_method_level (method, TRUE);
5804 MonoStringHandle
5805 ves_icall_System_Reflection_RuntimeAssembly_get_fullname (MonoReflectionAssemblyHandle assembly, MonoError *error)
5807 error_init (error);
5808 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5809 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
5810 gchar *name;
5812 name = mono_stringify_assembly_name (&mass->aname);
5813 MonoStringHandle res = mono_string_new_handle (domain, name, error);
5814 g_free (name);
5815 return res;
5818 MonoAssemblyName *
5819 ves_icall_System_Reflection_AssemblyName_GetNativeName (MonoAssembly *mass)
5821 return &mass->aname;
5824 void
5825 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoStringHandle fname, MonoAssemblyName *name, MonoStringHandleOut normalized_codebase, MonoError *error)
5827 char *filename;
5828 MonoImageOpenStatus status = MONO_IMAGE_OK;
5829 char *codebase = NULL;
5830 gboolean res;
5831 MonoImage *image;
5832 char *dirname;
5834 error_init (error);
5836 MonoDomain *domain = MONO_HANDLE_DOMAIN (fname);
5837 filename = mono_string_handle_to_utf8 (fname, error);
5838 return_if_nok (error);
5840 dirname = g_path_get_dirname (filename);
5841 replace_shadow_path (mono_domain_get (), dirname, &filename);
5842 g_free (dirname);
5844 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "InternalGetAssemblyName (\"%s\")", filename);
5846 MonoAssemblyLoadContext *alc = mono_domain_default_alc (domain);
5847 image = mono_image_open_a_lot (alc, filename, &status, TRUE, FALSE);
5849 if (!image){
5850 if (status == MONO_IMAGE_IMAGE_INVALID)
5851 mono_error_set_bad_image_by_name (error, filename, "Invalid Image");
5852 else
5853 mono_error_set_file_not_found (error, filename, "%s", "");
5854 g_free (filename);
5855 return;
5858 res = mono_assembly_fill_assembly_name_full (image, name, TRUE);
5859 if (!res) {
5860 mono_image_close (image);
5861 g_free (filename);
5862 mono_error_set_argument (error, "assemblyFile", "The file does not contain a manifest");
5863 return;
5866 if (filename != NULL && *filename != '\0') {
5867 gchar *result;
5869 codebase = g_strdup (filename);
5871 mono_icall_make_platform_path (codebase);
5873 const gchar *prepend = mono_icall_get_file_path_prefix (codebase);
5875 result = g_strconcat (prepend, codebase, (const char*)NULL);
5876 g_free (codebase);
5877 codebase = result;
5879 MONO_HANDLE_ASSIGN (normalized_codebase, mono_string_new_handle (mono_domain_get (), codebase, error));
5880 g_free (codebase);
5882 mono_image_close (image);
5883 g_free (filename);
5886 MonoBoolean
5887 ves_icall_System_Reflection_RuntimeAssembly_LoadPermissions (MonoReflectionAssemblyHandle assembly_h,
5888 char **minimum, guint32 *minLength, char **optional, guint32 *optLength, char **refused, guint32 *refLength, MonoError *error)
5890 error_init (error);
5891 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5892 MonoBoolean result = FALSE;
5893 MonoDeclSecurityEntry entry;
5895 /* SecurityAction.RequestMinimum */
5896 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQMIN, &entry)) {
5897 *minimum = entry.blob;
5898 *minLength = entry.size;
5899 result = TRUE;
5901 /* SecurityAction.RequestOptional */
5902 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQOPT, &entry)) {
5903 *optional = entry.blob;
5904 *optLength = entry.size;
5905 result = TRUE;
5907 /* SecurityAction.RequestRefuse */
5908 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQREFUSE, &entry)) {
5909 *refused = entry.blob;
5910 *refLength = entry.size;
5911 result = TRUE;
5914 return result;
5917 static gboolean
5918 mono_module_type_is_visible (MonoTableInfo *tdef, MonoImage *image, int type)
5920 guint32 attrs, visibility;
5921 do {
5922 attrs = mono_metadata_decode_row_col (tdef, type - 1, MONO_TYPEDEF_FLAGS);
5923 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5924 if (visibility != TYPE_ATTRIBUTE_PUBLIC && visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC)
5925 return FALSE;
5927 } while ((type = mono_metadata_token_index (mono_metadata_nested_in_typedef (image, type))));
5929 return TRUE;
5932 static void
5933 image_get_type (MonoDomain *domain, MonoImage *image, MonoTableInfo *tdef, int table_idx, int count, MonoArrayHandle res, MonoArrayHandle exceptions, MonoBoolean exportedOnly, MonoError *error)
5935 error_init (error);
5936 HANDLE_FUNCTION_ENTER ();
5937 ERROR_DECL (klass_error);
5938 MonoClass *klass = mono_class_get_checked (image, table_idx | MONO_TOKEN_TYPE_DEF, klass_error);
5940 if (klass) {
5941 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
5942 return_if_nok (error);
5944 MONO_HANDLE_ARRAY_SETREF (res, count, rt);
5945 } else {
5946 MonoExceptionHandle ex = mono_error_convert_to_exception_handle (klass_error);
5947 MONO_HANDLE_ARRAY_SETREF (exceptions, count, ex);
5949 HANDLE_FUNCTION_RETURN ();
5952 static MonoArrayHandle
5953 mono_module_get_types (MonoDomain *domain, MonoImage *image, MonoArrayHandleOut exceptions, MonoBoolean exportedOnly, MonoError *error)
5955 MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
5956 int i, count;
5958 error_init (error);
5960 /* we start the count from 1 because we skip the special type <Module> */
5961 if (exportedOnly) {
5962 count = 0;
5963 for (i = 1; i < tdef->rows; ++i) {
5964 if (mono_module_type_is_visible (tdef, image, i + 1))
5965 count++;
5967 } else {
5968 count = tdef->rows - 1;
5970 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.runtimetype_class, count, error);
5971 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5972 MONO_HANDLE_ASSIGN (exceptions, mono_array_new_handle (domain, mono_defaults.exception_class, count, error));
5973 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5974 count = 0;
5975 for (i = 1; i < tdef->rows; ++i) {
5976 if (!exportedOnly || mono_module_type_is_visible (tdef, image, i+1)) {
5977 image_get_type (domain, image, tdef, i + 1, count, res, exceptions, exportedOnly, error);
5978 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5979 count++;
5983 return res;
5986 static void
5987 append_module_types (MonoDomain *domain, MonoArrayHandleOut res, MonoArrayHandleOut exceptions, MonoImage *image, MonoBoolean exportedOnly, MonoError *error)
5989 HANDLE_FUNCTION_ENTER ();
5990 error_init (error);
5991 MonoArrayHandle ex2 = MONO_HANDLE_NEW (MonoArray, NULL);
5992 MonoArrayHandle res2 = mono_module_get_types (domain, image, ex2, exportedOnly, error);
5993 goto_if_nok (error, leave);
5995 /* Append the new types to the end of the array */
5996 if (mono_array_handle_length (res2) > 0) {
5997 guint32 len1, len2;
5999 len1 = mono_array_handle_length (res);
6000 len2 = mono_array_handle_length (res2);
6002 MonoArrayHandle res3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
6003 goto_if_nok (error, leave);
6005 mono_array_handle_memcpy_refs (res3, 0, res, 0, len1);
6006 mono_array_handle_memcpy_refs (res3, len1, res2, 0, len2);
6007 MONO_HANDLE_ASSIGN (res, res3);
6009 MonoArrayHandle ex3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
6010 goto_if_nok (error, leave);
6012 mono_array_handle_memcpy_refs (ex3, 0, exceptions, 0, len1);
6013 mono_array_handle_memcpy_refs (ex3, len1, ex2, 0, len2);
6014 MONO_HANDLE_ASSIGN (exceptions, ex3);
6016 leave:
6017 HANDLE_FUNCTION_RETURN ();
6020 static void
6021 set_class_failure_in_array (MonoArrayHandle exl, int i, MonoClass *klass)
6023 HANDLE_FUNCTION_ENTER ();
6024 ERROR_DECL (unboxed_error);
6025 mono_error_set_for_class_failure (unboxed_error, klass);
6027 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, mono_error_convert_to_exception (unboxed_error));
6028 MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
6029 HANDLE_FUNCTION_RETURN ();
6032 MonoArrayHandle
6033 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssemblyHandle assembly_handle, MonoBoolean exportedOnly, MonoError *error)
6035 MonoArrayHandle exceptions = MONO_HANDLE_NEW(MonoArray, NULL);
6036 int i;
6038 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_handle);
6039 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_handle, assembly);
6041 g_assert (!assembly_is_dynamic (assembly));
6042 MonoImage *image = assembly->image;
6043 MonoTableInfo *table = &image->tables [MONO_TABLE_FILE];
6044 MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, exportedOnly, error);
6045 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6047 /* Append data from all modules in the assembly */
6048 for (i = 0; i < table->rows; ++i) {
6049 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
6050 MonoImage *loaded_image = mono_assembly_load_module_checked (image->assembly, i + 1, error);
6051 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6053 if (loaded_image) {
6054 append_module_types (domain, res, exceptions, loaded_image, exportedOnly, error);
6055 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6060 /* the ReflectionTypeLoadException must have all the types (Types property),
6061 * NULL replacing types which throws an exception. The LoaderException must
6062 * contain all exceptions for NULL items.
6065 int len = mono_array_handle_length (res);
6067 int ex_count = 0;
6068 GList *list = NULL;
6069 MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
6070 for (i = 0; i < len; i++) {
6071 MONO_HANDLE_ARRAY_GETREF (t, res, i);
6073 if (!MONO_HANDLE_IS_NULL (t)) {
6074 MonoClass *klass = mono_type_get_class (MONO_HANDLE_GETVAL (t, type));
6075 if ((klass != NULL) && mono_class_has_failure (klass)) {
6076 /* keep the class in the list */
6077 list = g_list_append (list, klass);
6078 /* and replace Type with NULL */
6079 MONO_HANDLE_ARRAY_SETREF (res, i, NULL_HANDLE);
6081 } else {
6082 ex_count ++;
6086 if (list || ex_count) {
6087 GList *tmp = NULL;
6088 int j, length = g_list_length (list) + ex_count;
6090 MonoArrayHandle exl = mono_array_new_handle (domain, mono_defaults.exception_class, length, error);
6091 if (!is_ok (error)) {
6092 g_list_free (list);
6093 return NULL_HANDLE_ARRAY;
6095 /* Types for which mono_class_get_checked () succeeded */
6096 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
6097 for (i = 0, tmp = list; tmp; i++, tmp = tmp->next) {
6098 set_class_failure_in_array (exl, i, (MonoClass*)tmp->data);
6100 /* Types for which it don't */
6101 for (j = 0; j < mono_array_handle_length (exceptions); ++j) {
6102 MONO_HANDLE_ARRAY_GETREF (exc, exceptions, j);
6103 if (!MONO_HANDLE_IS_NULL (exc)) {
6104 g_assert (i < length);
6105 MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
6106 i ++;
6109 g_list_free (list);
6110 list = NULL;
6112 MONO_HANDLE_ASSIGN (exc, mono_get_exception_reflection_type_load_checked (res, exl, error));
6113 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6114 mono_error_set_exception_handle (error, exc);
6115 return NULL_HANDLE_ARRAY;
6118 return res;
6121 #if ENABLE_NETCORE
6122 MonoArrayHandle
6123 ves_icall_System_Reflection_RuntimeAssembly_GetExportedTypes (MonoReflectionAssemblyHandle assembly_handle, MonoError *error)
6125 return ves_icall_System_Reflection_Assembly_GetTypes (assembly_handle, TRUE, error);
6128 static void
6129 get_top_level_forwarded_type (MonoImage *image, MonoTableInfo *table, int i, MonoArrayHandle types, MonoArrayHandle exceptions, int *aindex, int *exception_count)
6131 ERROR_DECL (local_error);
6132 guint32 cols [MONO_EXP_TYPE_SIZE];
6133 MonoClass *klass;
6134 MonoReflectionTypeHandle rt;
6136 mono_metadata_decode_row (table, i, cols, MONO_EXP_TYPE_SIZE);
6137 if (!(cols [MONO_EXP_TYPE_FLAGS] & TYPE_ATTRIBUTE_FORWARDER))
6138 return;
6139 guint32 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
6140 const char *name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
6141 const char *nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
6143 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF);
6144 guint32 assembly_idx = impl >> MONO_IMPLEMENTATION_BITS;
6146 mono_assembly_load_reference (image, assembly_idx - 1);
6147 g_assert (image->references [assembly_idx - 1]);
6149 HANDLE_FUNCTION_ENTER ();
6151 if (image->references [assembly_idx - 1] == REFERENCE_MISSING) {
6152 MonoExceptionHandle ex = MONO_HANDLE_NEW (MonoException, mono_get_exception_bad_image_format ("Invalid image"));
6153 MONO_HANDLE_ARRAY_SETREF (types, *aindex, NULL_HANDLE);
6154 MONO_HANDLE_ARRAY_SETREF (exceptions, *aindex, ex);
6155 (*exception_count)++; (*aindex)++;
6156 goto exit;
6158 klass = mono_class_from_name_checked (image->references [assembly_idx - 1]->image, nspace, name, local_error);
6159 if (!is_ok (local_error)) {
6160 MonoExceptionHandle ex = mono_error_convert_to_exception_handle (local_error);
6161 MONO_HANDLE_ARRAY_SETREF (types, *aindex, NULL_HANDLE);
6162 MONO_HANDLE_ARRAY_SETREF (exceptions, *aindex, ex);
6163 mono_error_cleanup (local_error);
6164 (*exception_count)++; (*aindex)++;
6165 goto exit;
6167 rt = mono_type_get_object_handle (mono_domain_get (), m_class_get_byval_arg (klass), local_error);
6168 if (!is_ok (local_error)) {
6169 MonoExceptionHandle ex = mono_error_convert_to_exception_handle (local_error);
6170 MONO_HANDLE_ARRAY_SETREF (types, *aindex, NULL_HANDLE);
6171 MONO_HANDLE_ARRAY_SETREF (exceptions, *aindex, ex);
6172 mono_error_cleanup (local_error);
6173 (*exception_count)++; (*aindex)++;
6174 goto exit;
6176 MONO_HANDLE_ARRAY_SETREF (types, *aindex, rt);
6177 MONO_HANDLE_ARRAY_SETREF (exceptions, *aindex, NULL_HANDLE);
6178 (*aindex)++;
6180 exit:
6181 HANDLE_FUNCTION_RETURN ();
6184 MonoArrayHandle
6185 ves_icall_System_Reflection_RuntimeAssembly_GetTopLevelForwardedTypes (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
6187 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
6188 MonoImage *image = assembly->image;
6189 int count = 0;
6191 g_assert (!assembly_is_dynamic (assembly));
6192 MonoTableInfo *table = &image->tables [MONO_TABLE_EXPORTEDTYPE];
6193 for (int i = 0; i < table->rows; ++i) {
6194 if (mono_metadata_decode_row_col (table, i, MONO_EXP_TYPE_FLAGS) & TYPE_ATTRIBUTE_FORWARDER)
6195 count ++;
6198 MonoArrayHandle types = mono_array_new_handle (mono_domain_get (), mono_defaults.runtimetype_class, count, error);
6199 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6200 MonoArrayHandle exceptions = mono_array_new_handle (mono_domain_get (), mono_defaults.exception_class, count, error);
6201 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6203 int aindex = 0;
6204 int exception_count = 0;
6205 for (int i = 0; i < table->rows; ++i) {
6206 get_top_level_forwarded_type (image, table, i, types, exceptions, &aindex, &exception_count);
6209 if (exception_count > 0) {
6210 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
6211 MONO_HANDLE_ASSIGN (exc, mono_get_exception_reflection_type_load_checked (types, exceptions, error));
6212 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6213 mono_error_set_exception_handle (error, exc);
6214 return NULL_HANDLE_ARRAY;
6217 return types;
6219 #endif
6221 void
6222 ves_icall_Mono_RuntimeMarshal_FreeAssemblyName (MonoAssemblyName *aname, MonoBoolean free_struct, MonoError *error)
6224 mono_assembly_name_free (aname);
6225 if (free_struct)
6226 g_free (aname);
6229 void
6230 ves_icall_Mono_Runtime_DisableMicrosoftTelemetry (MonoError *error)
6232 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
6233 mono_merp_disable ();
6234 #else
6235 // Icall has platform check in managed too.
6236 g_assert_not_reached ();
6237 #endif
6240 void
6241 ves_icall_Mono_Runtime_AnnotateMicrosoftTelemetry (const char *key, const char *value, MonoError *error)
6243 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
6244 if (!mono_merp_enabled ())
6245 g_error ("Cannot add attributes to telemetry without enabling subsystem");
6246 mono_merp_add_annotation (key, value);
6247 #else
6248 // Icall has platform check in managed too.
6249 g_assert_not_reached ();
6250 #endif
6253 void
6254 ves_icall_Mono_Runtime_EnableMicrosoftTelemetry (const char *appBundleID, const char *appSignature, const char *appVersion, const char *merpGUIPath, const char *eventType, const char *appPath, const char *configDir, MonoError *error)
6256 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
6257 mono_merp_enable (appBundleID, appSignature, appVersion, merpGUIPath, eventType, appPath, configDir);
6259 mono_get_runtime_callbacks ()->install_state_summarizer ();
6260 #else
6261 // Icall has platform check in managed too.
6262 g_assert_not_reached ();
6263 #endif
6266 // Number derived from trials on relevant hardware.
6267 // If it seems large, please confirm it's safe to shrink
6268 // before doing so.
6269 #define MONO_MAX_SUMMARY_LEN_ICALL 500000
6271 MonoStringHandle
6272 ves_icall_Mono_Runtime_ExceptionToState (MonoExceptionHandle exc_handle, guint64 *portable_hash_out, guint64 *unportable_hash_out, MonoError *error)
6274 MonoStringHandle result;
6276 #ifndef DISABLE_CRASH_REPORTING
6277 if (mono_get_eh_callbacks ()->mono_summarize_exception) {
6278 // FIXME: Push handles down into mini/mini-exceptions.c
6279 MonoException *exc = MONO_HANDLE_RAW (exc_handle);
6280 MonoThreadSummary out;
6281 mono_get_eh_callbacks ()->mono_summarize_exception (exc, &out);
6283 *portable_hash_out = (guint64) out.hashes.offset_free_hash;
6284 *unportable_hash_out = (guint64) out.hashes.offset_rich_hash;
6286 MonoStateWriter writer;
6287 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
6288 mono_state_writer_init (&writer, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
6289 mono_native_state_init (&writer);
6290 gboolean first_thread_added = TRUE;
6291 mono_native_state_add_thread (&writer, &out, NULL, first_thread_added, TRUE);
6292 char *output = mono_native_state_free (&writer, FALSE);
6293 result = mono_string_new_handle (mono_domain_get (), output, error);
6294 g_free (output);
6295 g_free (scratch);
6296 return result;
6298 #endif
6300 *portable_hash_out = 0;
6301 *unportable_hash_out = 0;
6302 result = mono_string_new_handle (mono_domain_get (), "", error);
6303 return result;
6306 void
6307 ves_icall_Mono_Runtime_SendMicrosoftTelemetry (const char *payload, guint64 portable_hash, guint64 unportable_hash, MonoError *error)
6309 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
6310 if (!mono_merp_enabled ())
6311 g_error ("Cannot send telemetry without registering parameters first");
6313 pid_t crashed_pid = getpid ();
6315 MonoStackHash hashes;
6316 memset (&hashes, 0, sizeof (MonoStackHash));
6317 hashes.offset_free_hash = portable_hash;
6318 hashes.offset_rich_hash = unportable_hash;
6320 // Tells mono that we want to send the HANG EXC_TYPE.
6321 const char *signal = "SIGTERM";
6323 gboolean success = mono_merp_invoke (crashed_pid, signal, payload, &hashes);
6324 if (!success) {
6325 //g_assert_not_reached ();
6326 mono_error_set_generic_error (error, "System", "Exception", "We were unable to start the Microsoft Error Reporting client.");
6328 #else
6329 // Icall has platform check in managed too.
6330 g_assert_not_reached ();
6331 #endif
6334 void
6335 ves_icall_Mono_Runtime_DumpTelemetry (const char *payload, guint64 portable_hash, guint64 unportable_hash, MonoError *error)
6337 #ifndef DISABLE_CRASH_REPORTING
6338 MonoStackHash hashes;
6339 memset (&hashes, 0, sizeof (MonoStackHash));
6340 hashes.offset_free_hash = portable_hash;
6341 hashes.offset_rich_hash = unportable_hash;
6342 mono_crash_dump (payload, &hashes);
6343 #else
6344 return;
6345 #endif
6348 MonoStringHandle
6349 ves_icall_Mono_Runtime_DumpStateSingle (guint64 *portable_hash, guint64 *unportable_hash, MonoError *error)
6351 MonoStringHandle result;
6353 #ifndef DISABLE_CRASH_REPORTING
6354 MonoStackHash hashes;
6355 memset (&hashes, 0, sizeof (MonoStackHash));
6356 MonoContext *ctx = NULL;
6358 MonoThreadSummary this_thread;
6359 if (!mono_threads_summarize_one (&this_thread, ctx))
6360 return mono_string_new_handle (mono_domain_get (), "", error);
6362 *portable_hash = (guint64) this_thread.hashes.offset_free_hash;
6363 *unportable_hash = (guint64) this_thread.hashes.offset_rich_hash;
6365 MonoStateWriter writer;
6366 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
6367 mono_state_writer_init (&writer, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
6368 mono_native_state_init (&writer);
6369 gboolean first_thread_added = TRUE;
6370 mono_native_state_add_thread (&writer, &this_thread, NULL, first_thread_added, TRUE);
6371 char *output = mono_native_state_free (&writer, FALSE);
6372 result = mono_string_new_handle (mono_domain_get (), output, error);
6373 g_free (output);
6374 g_free (scratch);
6375 #else
6376 *portable_hash = 0;
6377 *unportable_hash = 0;
6378 result = mono_string_new_handle (mono_domain_get (), "", error);
6379 #endif
6381 return result;
6385 void
6386 ves_icall_Mono_Runtime_RegisterReportingForNativeLib (const char *path_suffix, const char *module_name)
6388 #ifndef DISABLE_CRASH_REPORTING
6389 if (mono_get_eh_callbacks ()->mono_register_native_library)
6390 mono_get_eh_callbacks ()->mono_register_native_library (path_suffix, module_name);
6391 #endif
6394 void
6395 ves_icall_Mono_Runtime_RegisterReportingForAllNativeLibs ()
6397 #ifndef DISABLE_CRASH_REPORTING
6398 if (mono_get_eh_callbacks ()->mono_allow_all_native_libraries)
6399 mono_get_eh_callbacks ()->mono_allow_all_native_libraries ();
6400 #endif
6403 void
6404 ves_icall_Mono_Runtime_EnableCrashReportingLog (const char *directory, MonoError *error)
6406 #ifndef DISABLE_CRASH_REPORTING
6407 mono_summarize_set_timeline_dir (directory);
6408 #endif
6412 ves_icall_Mono_Runtime_CheckCrashReportingLog (const char *directory, MonoBoolean clear, MonoError *error)
6414 int ret;
6415 #ifndef DISABLE_CRASH_REPORTING
6416 ret = (int) mono_summarize_timeline_read_level (directory, clear != 0);
6417 #else
6418 ret = 0;
6419 #endif
6420 return ret;
6423 MonoStringHandle
6424 ves_icall_Mono_Runtime_DumpStateTotal (guint64 *portable_hash, guint64 *unportable_hash, MonoError *error)
6426 MonoStringHandle result;
6428 #ifndef DISABLE_CRASH_REPORTING
6429 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
6431 char *out;
6432 MonoStackHash hashes;
6433 memset (&hashes, 0, sizeof (MonoStackHash));
6434 MonoContext *ctx = NULL;
6436 mono_get_runtime_callbacks ()->install_state_summarizer ();
6438 mono_summarize_timeline_start ();
6440 gboolean success = mono_threads_summarize (ctx, &out, &hashes, TRUE, FALSE, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
6441 mono_summarize_timeline_phase_log (MonoSummaryCleanup);
6443 if (!success)
6444 return mono_string_new_handle (mono_domain_get (), "", error);
6446 *portable_hash = (guint64) hashes.offset_free_hash;
6447 *unportable_hash = (guint64) hashes.offset_rich_hash;
6448 result = mono_string_new_handle (mono_domain_get (), out, error);
6450 // out is now a pointer into garbage memory
6451 g_free (scratch);
6453 mono_summarize_timeline_phase_log (MonoSummaryDone);
6454 #else
6455 *portable_hash = 0;
6456 *unportable_hash = 0;
6457 result = mono_string_new_handle (mono_domain_get (), "", error);
6458 #endif
6460 return result;
6463 MonoBoolean
6464 ves_icall_System_Reflection_AssemblyName_ParseAssemblyName (const char *name, MonoAssemblyName *aname, MonoBoolean *is_version_defined_arg, MonoBoolean *is_token_defined_arg)
6466 gboolean is_version_defined = FALSE;
6467 gboolean is_token_defined = FALSE;
6468 gboolean result = FALSE;
6470 result = mono_assembly_name_parse_full (name, aname, TRUE, &is_version_defined, &is_token_defined);
6472 *is_version_defined_arg = (MonoBoolean)is_version_defined;
6473 *is_token_defined_arg = (MonoBoolean)is_token_defined;
6475 return result;
6478 MonoReflectionTypeHandle
6479 ves_icall_System_Reflection_RuntimeModule_GetGlobalType (MonoImage *image, MonoError *error)
6481 MonoDomain *domain = mono_domain_get ();
6482 MonoClass *klass;
6484 g_assert (image);
6486 MonoReflectionTypeHandle ret = MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6488 if (image_is_dynamic (image) && ((MonoDynamicImage*)image)->initial_image)
6489 /* These images do not have a global type */
6490 goto leave;
6492 klass = mono_class_get_checked (image, 1 | MONO_TOKEN_TYPE_DEF, error);
6493 goto_if_nok (error, leave);
6495 ret = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
6496 leave:
6497 return ret;
6500 void
6501 ves_icall_System_Reflection_RuntimeModule_GetGuidInternal (MonoImage *image, MonoArrayHandle guid_h, MonoError *error)
6503 g_assert (mono_array_handle_length (guid_h) == 16);
6505 if (!image->metadata_only) {
6506 g_assert (image->heap_guid.data);
6507 g_assert (image->heap_guid.size >= 16);
6509 MONO_ENTER_NO_SAFEPOINTS;
6510 guint8 *data = (guint8*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (guid_h), 1, 0);
6511 memcpy (data, (guint8*)image->heap_guid.data, 16);
6512 MONO_EXIT_NO_SAFEPOINTS;
6513 } else {
6514 MONO_ENTER_NO_SAFEPOINTS;
6515 guint8 *data = (guint8*) mono_array_addr_with_size_internal (MONO_HANDLE_RAW (guid_h), 1, 0);
6516 memset (data, 0, 16);
6517 MONO_EXIT_NO_SAFEPOINTS;
6521 #ifndef HOST_WIN32
6522 static inline gpointer
6523 mono_icall_module_get_hinstance (MonoImage *image)
6525 return (gpointer) (-1);
6527 #endif /* HOST_WIN32 */
6529 gpointer
6530 ves_icall_System_Reflection_RuntimeModule_GetHINSTANCE (MonoImage *image, MonoError *error)
6532 return mono_icall_module_get_hinstance (image);
6535 void
6536 ves_icall_System_Reflection_RuntimeModule_GetPEKind (MonoImage *image, gint32 *pe_kind, gint32 *machine, MonoError *error)
6538 if (image_is_dynamic (image)) {
6539 MonoDynamicImage *dyn = (MonoDynamicImage*)image;
6540 *pe_kind = dyn->pe_kind;
6541 *machine = dyn->machine;
6543 else {
6544 *pe_kind = (image->image_info->cli_cli_header.ch_flags & 0x3);
6545 *machine = image->image_info->cli_header.coff.coff_machine;
6549 gint32
6550 ves_icall_System_Reflection_RuntimeModule_GetMDStreamVersion (MonoImage *image, MonoError *error)
6552 return (image->md_version_major << 16) | (image->md_version_minor);
6555 MonoArrayHandle
6556 ves_icall_System_Reflection_RuntimeModule_InternalGetTypes (MonoImage *image, MonoError *error)
6558 error_init (error);
6560 MonoDomain *domain = mono_domain_get ();
6562 if (!image) {
6563 MonoArrayHandle arr = mono_array_new_handle (domain, mono_defaults.runtimetype_class, 0, error);
6564 return arr;
6565 } else {
6566 MonoArrayHandle exceptions = MONO_HANDLE_NEW (MonoArray, NULL);
6567 MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, FALSE, error);
6568 return_val_if_nok (error, MONO_HANDLE_CAST(MonoArray, NULL_HANDLE));
6570 int n = mono_array_handle_length (exceptions);
6571 MonoExceptionHandle ex = MONO_HANDLE_NEW (MonoException, NULL);
6572 for (int i = 0; i < n; ++i) {
6573 MONO_HANDLE_ARRAY_GETREF(ex, exceptions, i);
6574 if (!MONO_HANDLE_IS_NULL (ex)) {
6575 mono_error_set_exception_handle (error, ex);
6576 return MONO_HANDLE_CAST(MonoArray, NULL_HANDLE);
6579 return res;
6583 static gboolean
6584 mono_memberref_is_method (MonoImage *image, guint32 token)
6586 if (!image_is_dynamic (image)) {
6587 guint32 cols [MONO_MEMBERREF_SIZE];
6588 const char *sig;
6589 const MonoTableInfo *table = &image->tables [MONO_TABLE_MEMBERREF];
6590 int idx = mono_metadata_token_index (token) - 1;
6591 if (idx < 0 || table->rows <= idx) {
6592 return FALSE;
6594 mono_metadata_decode_row (table, idx, cols, MONO_MEMBERREF_SIZE);
6595 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6596 mono_metadata_decode_blob_size (sig, &sig);
6597 return (*sig != 0x6);
6598 } else {
6599 ERROR_DECL (error);
6600 MonoClass *handle_class;
6602 if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL, error)) {
6603 mono_error_cleanup (error); /* just probing, ignore error */
6604 return FALSE;
6607 return mono_defaults.methodhandle_class == handle_class;
6611 static MonoGenericInst *
6612 get_generic_inst_from_array_handle (MonoArrayHandle type_args)
6614 int type_argc = mono_array_handle_length (type_args);
6615 int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *);
6617 MonoGenericInst *ginst = (MonoGenericInst *)g_alloca (size);
6618 memset (ginst, 0, sizeof (MonoGenericInst));
6619 ginst->type_argc = type_argc;
6620 for (int i = 0; i < type_argc; i++) {
6621 MONO_HANDLE_ARRAY_GETVAL (ginst->type_argv[i], type_args, MonoType*, i);
6623 ginst->is_open = FALSE;
6624 for (int i = 0; i < type_argc; i++) {
6625 if (mono_class_is_open_constructed_type (ginst->type_argv[i])) {
6626 ginst->is_open = TRUE;
6627 break;
6631 return mono_metadata_get_canonical_generic_inst (ginst);
6634 static void
6635 init_generic_context_from_args_handles (MonoGenericContext *context, MonoArrayHandle type_args, MonoArrayHandle method_args)
6637 if (!MONO_HANDLE_IS_NULL (type_args)) {
6638 context->class_inst = get_generic_inst_from_array_handle (type_args);
6639 } else {
6640 context->class_inst = NULL;
6642 if (!MONO_HANDLE_IS_NULL (method_args)) {
6643 context->method_inst = get_generic_inst_from_array_handle (method_args);
6644 } else {
6645 context->method_inst = NULL;
6650 static MonoType*
6651 module_resolve_type_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6653 HANDLE_FUNCTION_ENTER ();
6654 error_init (error);
6655 MonoType *result = NULL;
6656 MonoClass *klass;
6657 int table = mono_metadata_token_table (token);
6658 int index = mono_metadata_token_index (token);
6659 MonoGenericContext context;
6661 *resolve_error = ResolveTokenError_Other;
6663 /* Validate token */
6664 if ((table != MONO_TABLE_TYPEDEF) && (table != MONO_TABLE_TYPEREF) &&
6665 (table != MONO_TABLE_TYPESPEC)) {
6666 *resolve_error = ResolveTokenError_BadTable;
6667 goto leave;
6670 if (image_is_dynamic (image)) {
6671 if ((table == MONO_TABLE_TYPEDEF) || (table == MONO_TABLE_TYPEREF)) {
6672 ERROR_DECL (inner_error);
6673 klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6674 mono_error_cleanup (inner_error);
6675 result = klass ? m_class_get_byval_arg (klass) : NULL;
6676 goto leave;
6679 init_generic_context_from_args_handles (&context, type_args, method_args);
6680 ERROR_DECL (inner_error);
6681 klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6682 mono_error_cleanup (inner_error);
6683 result = klass ? m_class_get_byval_arg (klass) : NULL;
6684 goto leave;
6687 if ((index <= 0) || (index > image->tables [table].rows)) {
6688 *resolve_error = ResolveTokenError_OutOfRange;
6689 goto leave;
6692 init_generic_context_from_args_handles (&context, type_args, method_args);
6693 klass = mono_class_get_checked (image, token, error);
6694 if (klass)
6695 klass = mono_class_inflate_generic_class_checked (klass, &context, error);
6696 goto_if_nok (error, leave);
6698 if (klass)
6699 result = m_class_get_byval_arg (klass);
6700 leave:
6701 HANDLE_FUNCTION_RETURN_VAL (result);
6704 MonoType*
6705 ves_icall_System_Reflection_RuntimeModule_ResolveTypeToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6707 return module_resolve_type_token (image, token, type_args, method_args, resolve_error, error);
6710 static MonoMethod*
6711 module_resolve_method_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6713 HANDLE_FUNCTION_ENTER ();
6714 error_init (error);
6715 MonoMethod *method = NULL;
6716 int table = mono_metadata_token_table (token);
6717 int index = mono_metadata_token_index (token);
6718 MonoGenericContext context;
6720 *resolve_error = ResolveTokenError_Other;
6722 /* Validate token */
6723 if ((table != MONO_TABLE_METHOD) && (table != MONO_TABLE_METHODSPEC) &&
6724 (table != MONO_TABLE_MEMBERREF)) {
6725 *resolve_error = ResolveTokenError_BadTable;
6726 goto leave;
6729 if (image_is_dynamic (image)) {
6730 if (table == MONO_TABLE_METHOD) {
6731 ERROR_DECL (inner_error);
6732 method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6733 mono_error_cleanup (inner_error);
6734 goto leave;
6737 if ((table == MONO_TABLE_MEMBERREF) && !(mono_memberref_is_method (image, token))) {
6738 *resolve_error = ResolveTokenError_BadTable;
6739 goto leave;
6742 init_generic_context_from_args_handles (&context, type_args, method_args);
6743 ERROR_DECL (inner_error);
6744 method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6745 mono_error_cleanup (inner_error);
6746 goto leave;
6749 if ((index <= 0) || (index > image->tables [table].rows)) {
6750 *resolve_error = ResolveTokenError_OutOfRange;
6751 goto leave;
6753 if ((table == MONO_TABLE_MEMBERREF) && (!mono_memberref_is_method (image, token))) {
6754 *resolve_error = ResolveTokenError_BadTable;
6755 goto leave;
6758 init_generic_context_from_args_handles (&context, type_args, method_args);
6759 method = mono_get_method_checked (image, token, NULL, &context, error);
6761 leave:
6762 HANDLE_FUNCTION_RETURN_VAL (method);
6765 MonoMethod*
6766 ves_icall_System_Reflection_RuntimeModule_ResolveMethodToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6768 return module_resolve_method_token (image, token, type_args, method_args, resolve_error, error);
6771 MonoStringHandle
6772 ves_icall_System_Reflection_RuntimeModule_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error, MonoError *error)
6774 int index = mono_metadata_token_index (token);
6776 *resolve_error = ResolveTokenError_Other;
6778 /* Validate token */
6779 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
6780 *resolve_error = ResolveTokenError_BadTable;
6781 return NULL_HANDLE_STRING;
6784 if (image_is_dynamic (image)) {
6785 ERROR_DECL (ignore_inner_error);
6786 // FIXME ignoring error
6787 // FIXME Push MONO_HANDLE_NEW to lower layers.
6788 MonoStringHandle result = MONO_HANDLE_NEW (MonoString, (MonoString*)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, ignore_inner_error));
6789 mono_error_cleanup (ignore_inner_error);
6790 return result;
6793 if ((index <= 0) || (index >= image->heap_us.size)) {
6794 *resolve_error = ResolveTokenError_OutOfRange;
6795 return NULL_HANDLE_STRING;
6798 /* FIXME: What to do if the index points into the middle of a string ? */
6799 return mono_ldstr_handle (mono_domain_get (), image, index, error);
6802 static MonoClassField*
6803 module_resolve_field_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6805 HANDLE_FUNCTION_ENTER ();
6806 MonoClass *klass;
6807 int table = mono_metadata_token_table (token);
6808 int index = mono_metadata_token_index (token);
6809 MonoGenericContext context;
6810 MonoClassField *field = NULL;
6812 error_init (error);
6813 *resolve_error = ResolveTokenError_Other;
6815 /* Validate token */
6816 if ((table != MONO_TABLE_FIELD) && (table != MONO_TABLE_MEMBERREF)) {
6817 *resolve_error = ResolveTokenError_BadTable;
6818 goto leave;
6821 if (image_is_dynamic (image)) {
6822 if (table == MONO_TABLE_FIELD) {
6823 ERROR_DECL (inner_error);
6824 field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6825 mono_error_cleanup (inner_error);
6826 goto leave;
6829 if (mono_memberref_is_method (image, token)) {
6830 *resolve_error = ResolveTokenError_BadTable;
6831 goto leave;
6834 init_generic_context_from_args_handles (&context, type_args, method_args);
6835 ERROR_DECL (inner_error);
6836 field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6837 mono_error_cleanup (inner_error);
6838 goto leave;
6841 if ((index <= 0) || (index > image->tables [table].rows)) {
6842 *resolve_error = ResolveTokenError_OutOfRange;
6843 goto leave;
6845 if ((table == MONO_TABLE_MEMBERREF) && (mono_memberref_is_method (image, token))) {
6846 *resolve_error = ResolveTokenError_BadTable;
6847 goto leave;
6850 init_generic_context_from_args_handles (&context, type_args, method_args);
6851 field = mono_field_from_token_checked (image, token, &klass, &context, error);
6853 leave:
6854 HANDLE_FUNCTION_RETURN_VAL (field);
6857 MonoClassField*
6858 ves_icall_System_Reflection_RuntimeModule_ResolveFieldToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6860 return module_resolve_field_token (image, token, type_args, method_args, resolve_error, error);
6863 MonoObjectHandle
6864 ves_icall_System_Reflection_RuntimeModule_ResolveMemberToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *error, MonoError *merror)
6866 int table = mono_metadata_token_table (token);
6868 error_init (merror);
6869 *error = ResolveTokenError_Other;
6871 switch (table) {
6872 case MONO_TABLE_TYPEDEF:
6873 case MONO_TABLE_TYPEREF:
6874 case MONO_TABLE_TYPESPEC: {
6875 MonoType *t = module_resolve_type_token (image, token, type_args, method_args, error, merror);
6876 if (t) {
6877 return MONO_HANDLE_CAST (MonoObject, mono_type_get_object_handle (mono_domain_get (), t, merror));
6879 else
6880 return NULL_HANDLE;
6882 case MONO_TABLE_METHOD:
6883 case MONO_TABLE_METHODSPEC: {
6884 MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
6885 if (m) {
6886 return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
6887 } else
6888 return NULL_HANDLE;
6890 case MONO_TABLE_FIELD: {
6891 MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
6892 if (f) {
6893 return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
6895 else
6896 return NULL_HANDLE;
6898 case MONO_TABLE_MEMBERREF:
6899 if (mono_memberref_is_method (image, token)) {
6900 MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
6901 if (m) {
6902 return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
6903 } else
6904 return NULL_HANDLE;
6906 else {
6907 MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
6908 if (f) {
6909 return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
6911 else
6912 return NULL_HANDLE;
6914 break;
6916 default:
6917 *error = ResolveTokenError_BadTable;
6920 return NULL_HANDLE;
6923 MonoArrayHandle
6924 ves_icall_System_Reflection_RuntimeModule_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error, MonoError *error)
6926 error_init (error);
6927 int table = mono_metadata_token_table (token);
6928 int idx = mono_metadata_token_index (token);
6929 MonoTableInfo *tables = image->tables;
6930 guint32 sig, len;
6931 const char *ptr;
6933 *resolve_error = ResolveTokenError_OutOfRange;
6935 /* FIXME: Support other tables ? */
6936 if (table != MONO_TABLE_STANDALONESIG)
6937 return NULL_HANDLE_ARRAY;
6939 if (image_is_dynamic (image))
6940 return NULL_HANDLE_ARRAY;
6942 if ((idx == 0) || (idx > tables [MONO_TABLE_STANDALONESIG].rows))
6943 return NULL_HANDLE_ARRAY;
6945 sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
6947 ptr = mono_metadata_blob_heap (image, sig);
6948 len = mono_metadata_decode_blob_size (ptr, &ptr);
6950 MonoArrayHandle res = mono_array_new_handle (mono_domain_get (), mono_defaults.byte_class, len, error);
6951 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6953 // FIXME MONO_ENTER_NO_SAFEPOINTS instead of pin/gchandle.
6955 uint32_t h;
6956 gpointer array_base = MONO_ARRAY_HANDLE_PIN (res, guint8, 0, &h);
6957 memcpy (array_base, ptr, len);
6958 mono_gchandle_free_internal (h);
6960 return res;
6963 static void
6964 check_for_invalid_type (MonoClass *klass, MonoError *error)
6966 char *name;
6968 error_init (error);
6970 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_TYPEDBYREF)
6971 return;
6973 name = mono_type_get_full_name (klass);
6974 mono_error_set_type_load_name (error, name, g_strdup (""), "");
6977 MonoReflectionTypeHandle
6978 ves_icall_RuntimeType_make_array_type (MonoReflectionTypeHandle ref_type, int rank, MonoError *error)
6980 error_init (error);
6981 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6983 MonoClass *klass = mono_class_from_mono_type_internal (type);
6984 check_for_invalid_type (klass, error);
6985 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6987 MonoClass *aklass;
6988 if (rank == 0) //single dimension array
6989 aklass = mono_class_create_array (klass, 1);
6990 else
6991 aklass = mono_class_create_bounded_array (klass, rank, TRUE);
6993 if (mono_class_has_failure (aklass)) {
6994 mono_error_set_for_class_failure (error, aklass);
6995 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6998 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6999 return mono_type_get_object_handle (domain, m_class_get_byval_arg (aklass), error);
7002 MonoReflectionTypeHandle
7003 ves_icall_RuntimeType_make_byref_type (MonoReflectionTypeHandle ref_type, MonoError *error)
7005 error_init (error);
7006 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7008 MonoClass *klass = mono_class_from_mono_type_internal (type);
7009 mono_class_init_checked (klass, error);
7010 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
7012 check_for_invalid_type (klass, error);
7013 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
7015 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
7016 return mono_type_get_object_handle (domain, m_class_get_this_arg (klass), error);
7019 MonoReflectionTypeHandle
7020 ves_icall_RuntimeType_MakePointerType (MonoReflectionTypeHandle ref_type, MonoError *error)
7022 error_init (error);
7023 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
7024 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7025 MonoClass *klass = mono_class_from_mono_type_internal (type);
7026 mono_class_init_checked (klass, error);
7027 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
7029 check_for_invalid_type (klass, error);
7030 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
7032 MonoClass *pklass = mono_class_create_ptr (type);
7034 return mono_type_get_object_handle (domain, m_class_get_byval_arg (pklass), error);
7037 MonoObjectHandle
7038 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionTypeHandle ref_type, MonoObjectHandle target,
7039 MonoReflectionMethodHandle info, MonoBoolean throwOnBindFailure, MonoError *error)
7041 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7042 MonoClass *delegate_class = mono_class_from_mono_type_internal (type);
7043 MonoMethod *method = MONO_HANDLE_GETVAL (info, method);
7044 MonoMethodSignature *sig = mono_method_signature_internal (method);
7046 mono_class_init_checked (delegate_class, error);
7047 return_val_if_nok (error, NULL_HANDLE);
7049 if (!(m_class_get_parent (delegate_class) == mono_defaults.multicastdelegate_class)) {
7050 /* FIXME improve this exception message */
7051 mono_error_set_execution_engine (error, "file %s: line %d (%s): assertion failed: (%s)", __FILE__, __LINE__,
7052 __func__,
7053 "delegate_class->parent == mono_defaults.multicastdelegate_class");
7054 return NULL_HANDLE;
7057 if (mono_security_core_clr_enabled ()) {
7058 ERROR_DECL (security_error);
7059 if (!mono_security_core_clr_ensure_delegate_creation (method, security_error)) {
7060 if (throwOnBindFailure)
7061 mono_error_move (error, security_error);
7062 else
7063 mono_error_cleanup (security_error);
7064 return NULL_HANDLE;
7068 if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7069 if (!method->is_inflated) {
7070 mono_error_set_argument (error, "method", " Cannot bind to the target method because its signature differs from that of the delegate type");
7071 return NULL_HANDLE;
7075 MonoObjectHandle delegate = mono_object_new_handle (MONO_HANDLE_DOMAIN (ref_type), delegate_class, error);
7076 return_val_if_nok (error, NULL_HANDLE);
7078 if (!method_is_dynamic (method) && (!MONO_HANDLE_IS_NULL (target) && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass != mono_handle_class (target))) {
7079 method = mono_object_handle_get_virtual_method (target, method, error);
7080 return_val_if_nok (error, NULL_HANDLE);
7083 mono_delegate_ctor_with_method (delegate, target, NULL, method, error);
7084 return_val_if_nok (error, NULL_HANDLE);
7085 return delegate;
7088 MonoMulticastDelegateHandle
7089 ves_icall_System_Delegate_AllocDelegateLike_internal (MonoDelegateHandle delegate, MonoError *error)
7091 error_init (error);
7093 MonoClass *klass = mono_handle_class (delegate);
7094 g_assert (mono_class_has_parent (klass, mono_defaults.multicastdelegate_class));
7096 MonoMulticastDelegateHandle ret = MONO_HANDLE_CAST (MonoMulticastDelegate, mono_object_new_handle (MONO_HANDLE_DOMAIN (delegate), klass, error));
7097 return_val_if_nok (error, MONO_HANDLE_CAST (MonoMulticastDelegate, NULL_HANDLE));
7099 MONO_HANDLE_SETVAL (MONO_HANDLE_CAST (MonoDelegate, ret), invoke_impl, gpointer, mono_runtime_create_delegate_trampoline (klass));
7101 return ret;
7104 MonoReflectionMethodHandle
7105 ves_icall_System_Delegate_GetVirtualMethod_internal (MonoDelegateHandle delegate, MonoError *error)
7107 error_init (error);
7109 MonoObjectHandle delegate_target = MONO_HANDLE_NEW_GET (MonoObject, delegate, target);
7110 MonoMethod *m = mono_object_handle_get_virtual_method (delegate_target, MONO_HANDLE_GETVAL (delegate, method), error);
7111 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
7112 return mono_method_get_object_handle (mono_domain_get (), m, m->klass, error);
7115 /* System.Buffer */
7117 static gint32
7118 mono_array_get_byte_length (MonoArrayHandle array)
7120 int length;
7122 MonoClass * const klass = mono_handle_class (array);
7124 // This resembles mono_array_get_length, but adds the loop.
7126 if (mono_handle_array_has_bounds (array)) {
7127 length = 1;
7128 const int klass_rank = m_class_get_rank (klass);
7129 for (int i = 0; i < klass_rank; ++ i)
7130 length *= MONO_HANDLE_GETVAL (array, bounds [i].length);
7131 } else {
7132 length = mono_array_handle_length (array);
7135 switch (m_class_get_byval_arg (m_class_get_element_class (klass))->type) {
7136 case MONO_TYPE_I1:
7137 case MONO_TYPE_U1:
7138 case MONO_TYPE_BOOLEAN:
7139 return length;
7140 case MONO_TYPE_I2:
7141 case MONO_TYPE_U2:
7142 case MONO_TYPE_CHAR:
7143 return length << 1;
7144 case MONO_TYPE_I4:
7145 case MONO_TYPE_U4:
7146 case MONO_TYPE_R4:
7147 return length << 2;
7148 case MONO_TYPE_I:
7149 case MONO_TYPE_U:
7150 return length * sizeof (gpointer);
7151 case MONO_TYPE_I8:
7152 case MONO_TYPE_U8:
7153 case MONO_TYPE_R8:
7154 return length << 3;
7155 default:
7156 return -1;
7160 gint32
7161 ves_icall_System_Buffer_ByteLengthInternal (MonoArrayHandle array, MonoError* error)
7163 return mono_array_get_byte_length (array);
7166 void
7167 ves_icall_System_Buffer_MemcpyInternal (gpointer dest, gconstpointer src, gint32 count)
7169 memcpy (dest, src, count);
7172 MonoBoolean
7173 ves_icall_System_Buffer_BlockCopyInternal (MonoArrayHandle src, gint32 src_offset, MonoArrayHandle dest, gint32 dest_offset, gint32 count, MonoError* error)
7175 if (count < 0) {
7176 mono_error_set_argument (error, "count", "is negative");
7177 return FALSE;
7180 /* This is called directly from the class libraries without going through the managed wrapper */
7181 MONO_CHECK_ARG_NULL_HANDLE (src, FALSE);
7182 MONO_CHECK_ARG_NULL_HANDLE (dest, FALSE);
7184 /* watch out for integer overflow */
7185 if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
7186 return FALSE;
7188 MONO_ENTER_NO_SAFEPOINTS;
7190 guint8 const * const src_buf = (guint8*)MONO_HANDLE_RAW (src)->vector + src_offset;
7191 guint8* const dest_buf = (guint8*)MONO_HANDLE_RAW (dest)->vector + dest_offset;
7193 #if !HOST_WIN32
7195 // Windows memcpy is memmove and checks for overlap anyway, so skip
7196 // the check here that would not help.
7198 if (MONO_HANDLE_RAW (src) != MONO_HANDLE_RAW (dest))
7199 memcpy (dest_buf, src_buf, count);
7200 else
7201 #endif
7202 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
7204 MONO_EXIT_NO_SAFEPOINTS;
7206 return TRUE;
7209 #ifndef DISABLE_REMOTING
7210 MonoObjectHandle
7211 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObjectHandle this_obj, MonoStringHandle class_name, MonoError *error)
7213 error_init (error);
7214 MonoDomain *domain = MONO_HANDLE_DOMAIN (this_obj);
7215 MonoRealProxyHandle rp = MONO_HANDLE_CAST (MonoRealProxy, this_obj);
7217 MonoObjectHandle res = mono_object_new_handle (domain, mono_defaults.transparent_proxy_class, error);
7218 return_val_if_nok (error, NULL_HANDLE);
7220 MonoTransparentProxyHandle tp = MONO_HANDLE_CAST (MonoTransparentProxy, res);
7222 MONO_HANDLE_SET (tp, rp, rp);
7224 MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
7225 MONO_HANDLE_GET (reftype, rp, class_to_proxy);
7226 MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
7227 MonoClass *klass = mono_class_from_mono_type_internal (type);
7229 // mono_remote_class_vtable cannot handle errors well, so force any loading error to occur early
7230 mono_class_setup_vtable (klass);
7231 if (mono_class_has_failure (klass)) {
7232 mono_error_set_for_class_failure (error, klass);
7233 return NULL_HANDLE;
7236 MonoObjectHandle remoting_obj = mono_object_handle_isinst (this_obj, mono_defaults.iremotingtypeinfo_class, error);
7237 return_val_if_nok (error, NULL_HANDLE);
7238 MONO_HANDLE_SETVAL (tp, custom_type_info, MonoBoolean, !MONO_HANDLE_IS_NULL (remoting_obj));
7240 MonoRemoteClass *remote_class = (MonoRemoteClass*)mono_remote_class (domain, class_name, klass, error);
7241 return_val_if_nok (error, NULL_HANDLE);
7242 MONO_HANDLE_SETVAL (tp, remote_class, MonoRemoteClass*, remote_class);
7244 MONO_HANDLE_SETVAL (res, vtable, MonoVTable*, (MonoVTable*)mono_remote_class_vtable (domain, remote_class, rp, error));
7245 return_val_if_nok (error, NULL_HANDLE);
7246 return res;
7249 MonoReflectionTypeHandle
7250 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxyHandle tp, MonoError *error)
7252 MonoRemoteClass *remote_class;
7254 g_assert (mono_handle_class (tp) == mono_defaults.transparent_proxy_class);
7255 remote_class = MONO_HANDLE_RAW (tp)->remote_class;
7256 g_assert (remote_class != NULL && remote_class->proxy_class != NULL);
7257 return mono_type_get_object_handle (mono_handle_domain (tp), m_class_get_byval_arg (remote_class->proxy_class), error);
7259 #endif
7261 /* System.Environment */
7263 MonoStringHandle
7264 ves_icall_System_Environment_get_UserName (MonoError *error)
7266 error_init (error);
7267 /* using glib is more portable */
7268 const gchar *user_name = g_get_user_name ();
7269 if (user_name != NULL)
7270 return mono_string_new_handle (mono_domain_get (), user_name, error);
7271 else
7272 return NULL_HANDLE_STRING;
7275 #ifndef HOST_WIN32
7276 static MonoStringHandle
7277 mono_icall_get_machine_name (MonoError *error)
7279 error_init (error);
7280 #if !defined(DISABLE_SOCKETS)
7281 MonoStringHandle result;
7282 char *buf;
7283 int n, i;
7284 #if defined _SC_HOST_NAME_MAX
7285 n = sysconf (_SC_HOST_NAME_MAX);
7286 if (n == -1)
7287 #endif
7288 n = 512;
7289 buf = (char*)g_malloc (n + 1);
7291 #if defined(HAVE_GETHOSTNAME)
7292 if (gethostname (buf, n) == 0){
7293 buf [n] = 0;
7294 // try truncating the string at the first dot
7295 for (i = 0; i < n; i++) {
7296 if (buf [i] == '.') {
7297 buf [i] = 0;
7298 break;
7301 result = mono_string_new_handle (mono_domain_get (), buf, error);
7302 } else
7303 #endif
7304 result = MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
7306 g_free (buf);
7308 return result;
7309 #else
7310 return mono_string_new_handle (mono_domain_get (), "mono", error);
7311 #endif
7313 #endif /* !HOST_WIN32 */
7315 MonoStringHandle
7316 ves_icall_System_Environment_get_MachineName (MonoError *error)
7318 error_init (error);
7319 return mono_icall_get_machine_name (error);
7322 #ifndef HOST_WIN32
7323 static int
7324 mono_icall_get_platform (void)
7326 #if defined(__MACH__)
7327 /* OSX */
7329 // Notice that the value is hidden from user code, and only exposed
7330 // to mscorlib. This is due to Mono's Unix/MacOS code predating the
7331 // define and making assumptions based on Unix/128/4 values before there
7332 // was a MacOS define. Lots of code would assume that not-Unix meant
7333 // Windows, but in this case, it would be OSX.
7335 return 6;
7336 #else
7337 /* Unix */
7338 return 4;
7339 #endif
7341 #endif /* !HOST_WIN32 */
7344 ves_icall_System_Environment_get_Platform (void)
7346 return mono_icall_get_platform ();
7349 #ifndef HOST_WIN32
7350 static MonoStringHandle
7351 mono_icall_get_new_line (MonoError *error)
7353 error_init (error);
7354 return mono_string_new_handle (mono_domain_get (), "\n", error);
7356 #endif /* !HOST_WIN32 */
7358 MonoStringHandle
7359 ves_icall_System_Environment_get_NewLine (MonoError *error)
7361 return mono_icall_get_new_line (error);
7364 #ifndef HOST_WIN32
7365 static inline MonoBoolean
7366 mono_icall_is_64bit_os (void)
7368 #if SIZEOF_VOID_P == 8
7369 return TRUE;
7370 #else
7371 #if defined(HAVE_SYS_UTSNAME_H)
7372 struct utsname name;
7374 if (uname (&name) >= 0) {
7375 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;
7377 #endif
7378 return FALSE;
7379 #endif
7381 #endif /* !HOST_WIN32 */
7383 MonoBoolean
7384 ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
7386 return mono_icall_is_64bit_os ();
7389 MonoStringHandle
7390 ves_icall_System_Environment_GetEnvironmentVariable_native (const gchar *utf8_name, MonoError *error)
7392 gchar *value;
7394 if (utf8_name == NULL)
7395 return NULL_HANDLE_STRING;
7397 value = g_getenv (utf8_name);
7399 if (value == 0)
7400 return NULL_HANDLE_STRING;
7402 MonoStringHandle res = mono_string_new_handle (mono_domain_get (), value, error);
7403 g_free (value);
7404 return res;
7408 * There is no standard way to get at environ.
7410 #ifndef _MSC_VER
7411 #ifndef __MINGW32_VERSION
7412 #if defined(__APPLE__)
7413 #if defined (TARGET_OSX)
7414 /* Apple defines this in crt_externs.h but doesn't provide that header for
7415 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
7416 * in fact exist on all implementations (so far)
7418 G_BEGIN_DECLS
7419 gchar ***_NSGetEnviron(void);
7420 G_END_DECLS
7421 #define environ (*_NSGetEnviron())
7422 #else
7423 static char *mono_environ[1] = { NULL };
7424 #define environ mono_environ
7425 #endif /* defined (TARGET_OSX) */
7426 #else
7427 G_BEGIN_DECLS
7428 extern
7429 char **environ;
7430 G_END_DECLS
7431 #endif
7432 #endif
7433 #endif
7435 MonoArrayHandle
7436 ves_icall_System_Environment_GetCommandLineArgs (MonoError *error)
7438 error_init (error);
7439 MonoArrayHandle result = mono_runtime_get_main_args_handle (error);
7440 return result;
7443 #ifndef HOST_WIN32
7444 static MonoArrayHandle
7445 mono_icall_get_environment_variable_names (MonoError *error)
7447 MonoArrayHandle names;
7448 MonoDomain *domain;
7449 MonoStringHandle str;
7450 gchar **e, **parts;
7451 int n;
7453 n = 0;
7454 for (e = environ; *e != 0; ++ e)
7455 ++ n;
7457 domain = mono_domain_get ();
7458 names = mono_array_new_handle (domain, mono_defaults.string_class, n, error);
7459 return_val_if_nok (error, NULL_HANDLE_ARRAY);
7461 str = MONO_HANDLE_NEW (MonoString, NULL);
7462 n = 0;
7463 for (e = environ; *e != 0; ++ e) {
7464 parts = g_strsplit (*e, "=", 2);
7465 if (*parts != 0) {
7466 MonoString *s = mono_string_new_checked (domain, *parts, error);
7467 MONO_HANDLE_ASSIGN_RAW (str, s);
7468 if (!is_ok (error)) {
7469 g_strfreev (parts);
7470 return NULL_HANDLE_ARRAY;
7472 mono_array_handle_setref (names, n, str);
7475 g_strfreev (parts);
7477 ++ n;
7480 return names;
7482 #endif /* !HOST_WIN32 */
7484 MonoArrayHandle
7485 ves_icall_System_Environment_GetEnvironmentVariableNames (MonoError *error)
7487 return mono_icall_get_environment_variable_names (error);
7490 void
7491 ves_icall_System_Environment_InternalSetEnvironmentVariable (const gunichar2 *name, gint32 name_length,
7492 const gunichar2 *value, gint32 value_length, MonoError *error)
7494 #ifdef HOST_WIN32
7495 if (!value || !value_length || !value [0])
7496 value = NULL;
7498 SetEnvironmentVariableW (name, value);
7499 #else
7500 char *utf8_name = NULL;
7501 char *utf8_value = NULL;
7503 utf8_name = mono_utf16_to_utf8 (name, name_length, error); // FIXME: this should be ascii
7504 goto_if_nok (error, exit);
7506 if (!value || !value_length || !value [0]) {
7507 g_unsetenv (utf8_name);
7508 goto exit;
7511 utf8_value = mono_utf16_to_utf8 (value, value_length, error);
7512 goto_if_nok (error, exit);
7514 g_setenv (utf8_name, utf8_value, TRUE);
7515 exit:
7516 g_free (utf8_name);
7517 g_free (utf8_value);
7518 #endif
7521 void
7522 ves_icall_System_Environment_Exit (int result)
7524 mono_environment_exitcode_set (result);
7526 if (!mono_runtime_try_shutdown ())
7527 mono_thread_exit ();
7529 /* Suspend all managed threads since the runtime is going away */
7530 mono_thread_suspend_all_other_threads ();
7532 mono_runtime_quit ();
7534 /* we may need to do some cleanup here... */
7535 exit (result);
7538 void
7539 ves_icall_System_Environment_FailFast (MonoStringHandle message, MonoExceptionHandle exception, MonoStringHandle errorSource, MonoError *error)
7541 if (MONO_HANDLE_IS_NULL (message)) {
7542 g_warning ("CLR: Managed code called FailFast without specifying a reason.");
7543 } else {
7544 char *msg = mono_string_handle_to_utf8 (message, error);
7545 g_warning ("CLR: Managed code called FailFast, saying \"%s\"", msg);
7546 g_free (msg);
7549 if (!MONO_HANDLE_IS_NULL (exception)) {
7550 mono_print_unhandled_exception_internal ((MonoObject *) MONO_HANDLE_RAW (exception));
7553 // NOTE: While this does trigger WER on Windows it doesn't quite provide all the
7554 // information in the error dump that CoreCLR would. On Windows 7+ we should call
7555 // RaiseFailFastException directly instead of relying on the C runtime doing it
7556 // for us and pass it as much information as possible. On Windows 8+ we can also
7557 // use the __fastfail intrinsic.
7558 abort ();
7561 MonoStringHandle
7562 ves_icall_System_Environment_GetGacPath (MonoError *error)
7564 return mono_string_new_handle (mono_domain_get (), mono_assembly_getrootdir (), error);
7567 #ifndef HOST_WIN32
7568 static inline MonoStringHandle
7569 mono_icall_get_windows_folder_path (int folder, MonoError *error)
7571 error_init (error);
7572 g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
7573 return mono_string_new_handle (mono_domain_get (), "", error);
7575 #endif /* !HOST_WIN32 */
7577 MonoStringHandle
7578 ves_icall_System_Environment_GetWindowsFolderPath (int folder, MonoError *error)
7580 return mono_icall_get_windows_folder_path (folder, error);
7583 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
7584 static MonoArrayHandle
7585 mono_icall_get_logical_drives (MonoError *error)
7587 gunichar2 buf [256], *ptr, *dname;
7588 gunichar2 *u16;
7589 guint initial_size = 127, size = 128;
7590 gint ndrives;
7591 MonoArrayHandle result;
7592 MonoStringHandle drivestr;
7593 MonoDomain *domain = mono_domain_get ();
7594 gint len;
7596 buf [0] = '\0';
7597 ptr = buf;
7599 while (size > initial_size) {
7600 size = (guint) mono_w32file_get_logical_drive (initial_size, ptr);
7601 if (size > initial_size) {
7602 if (ptr != buf)
7603 g_free (ptr);
7604 ptr = (gunichar2 *)g_malloc0 ((size + 1) * sizeof (gunichar2));
7605 initial_size = size;
7606 size++;
7610 /* Count strings */
7611 dname = ptr;
7612 ndrives = 0;
7613 do {
7614 while (*dname++);
7615 ndrives++;
7616 } while (*dname);
7618 dname = ptr;
7619 result = mono_array_new_handle (domain, mono_defaults.string_class, ndrives, error);
7620 goto_if_nok (error, leave);
7622 drivestr = MONO_HANDLE_NEW (MonoString, NULL);
7623 ndrives = 0;
7624 do {
7625 len = 0;
7626 u16 = dname;
7627 while (*u16) {
7628 u16++; len ++;
7630 MonoString *s = mono_string_new_utf16_checked (domain, dname, len, error);
7631 goto_if_nok (error, leave);
7632 MONO_HANDLE_ASSIGN_RAW (drivestr, s);
7634 mono_array_handle_setref (result, ndrives, drivestr);
7635 ndrives ++;
7636 while (*dname++);
7637 } while (*dname);
7639 leave:
7640 if (ptr != buf)
7641 g_free (ptr);
7643 return result;
7645 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
7647 MonoArrayHandle
7648 ves_icall_System_Environment_GetLogicalDrivesInternal (MonoError *error)
7650 return mono_icall_get_logical_drives (error);
7653 MonoStringHandle
7654 ves_icall_System_IO_DriveInfo_GetDriveFormat (const gunichar2 *path, gint32 path_length, MonoError *error)
7656 gunichar2 volume_name [MAX_PATH + 1];
7658 if (mono_w32file_get_file_system_type (path, volume_name, MAX_PATH + 1) == FALSE)
7659 return NULL_HANDLE_STRING;
7660 return mono_string_new_utf16_handle (mono_domain_get (), volume_name, g_utf16_len (volume_name), error);
7663 MonoStringHandle
7664 ves_icall_System_Environment_InternalGetHome (MonoError *error)
7666 const gchar *home_dir = g_get_home_dir ();
7667 if (home_dir != NULL)
7668 return mono_string_new_handle (mono_domain_get (), home_dir, error);
7669 else
7670 return NULL_HANDLE_STRING;
7673 static const char * const encodings [] = {
7674 (char *) 1,
7675 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
7676 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
7677 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
7678 (char *) 2,
7679 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
7680 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
7681 "x_unicode_2_0_utf_7",
7682 (char *) 3,
7683 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
7684 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
7685 (char *) 4,
7686 "utf_16", "UTF_16LE", "ucs_2", "unicode",
7687 "iso_10646_ucs2",
7688 (char *) 5,
7689 "unicodefffe", "utf_16be",
7690 (char *) 6,
7691 "iso_8859_1",
7692 (char *) 0
7696 * Returns the internal codepage, if the value of "int_code_page" is
7697 * 1 at entry, and we can not compute a suitable code page number,
7698 * returns the code page as a string
7700 MonoStringHandle
7701 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page, MonoError *error)
7703 error_init (error);
7704 const char *cset;
7705 const char *p;
7706 char *c;
7707 char *codepage = NULL;
7708 int code;
7709 int want_name = *int_code_page;
7710 int i;
7712 *int_code_page = -1;
7714 g_get_charset (&cset);
7715 c = codepage = g_strdup (cset);
7716 for (c = codepage; *c; c++){
7717 if (isascii (*c) && isalpha (*c))
7718 *c = tolower (*c);
7719 if (*c == '-')
7720 *c = '_';
7722 /* g_print ("charset: %s\n", cset); */
7724 /* handle some common aliases */
7725 p = encodings [0];
7726 code = 0;
7727 for (i = 0; p != 0; ){
7728 if ((gsize) p < 7){
7729 code = (gssize) p;
7730 p = encodings [++i];
7731 continue;
7733 if (strcmp (p, codepage) == 0){
7734 *int_code_page = code;
7735 break;
7737 p = encodings [++i];
7740 if (strstr (codepage, "utf_8") != NULL)
7741 *int_code_page |= 0x10000000;
7742 g_free (codepage);
7744 if (want_name && *int_code_page == -1)
7745 return mono_string_new_handle (mono_domain_get (), cset, error);
7746 return NULL_HANDLE_STRING;
7749 MonoBoolean
7750 ves_icall_System_Environment_get_HasShutdownStarted (void)
7752 return mono_runtime_is_shutting_down () || mono_domain_is_unloading (mono_domain_get ());
7755 #ifndef HOST_WIN32
7757 #ifndef ENABLE_NETCORE
7758 void
7759 ves_icall_System_Environment_BroadcastSettingChange (MonoError *error)
7762 #endif
7764 #endif
7766 gint32
7767 ves_icall_System_Environment_get_TickCount (void)
7769 /* this will overflow after ~24 days */
7770 return (gint32) (mono_msec_boottime () & 0xffffffff);
7773 #if ENABLE_NETCORE
7774 gint64
7775 ves_icall_System_Environment_get_TickCount64 (void)
7777 return mono_msec_boottime ();
7779 #endif
7781 #ifndef ENABLE_NETCORE
7782 gint32
7783 ves_icall_System_Runtime_Versioning_VersioningHelper_GetRuntimeId (MonoError *error)
7785 return 9;
7787 #endif
7789 #ifndef DISABLE_REMOTING
7790 MonoBoolean
7791 ves_icall_IsTransparentProxy (MonoObjectHandle proxy, MonoError *error)
7793 if (MONO_HANDLE_IS_NULL (proxy))
7794 return 0;
7796 if (mono_class_is_transparent_proxy (mono_handle_class (proxy)))
7797 return 1;
7799 return 0;
7802 MonoReflectionMethodHandle
7803 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
7804 MonoReflectionTypeHandle rtype, MonoReflectionMethodHandle rmethod, MonoError *error)
7806 MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
7808 if (MONO_HANDLE_IS_NULL (rtype)) {
7809 mono_error_set_argument_null (error, "type", "");
7810 return ret;
7812 if (MONO_HANDLE_IS_NULL (rmethod)) {
7813 mono_error_set_argument_null (error, "method", "");
7814 return ret;
7817 MonoMethod *method = MONO_HANDLE_GETVAL (rmethod, method);
7818 MonoType *type = MONO_HANDLE_GETVAL (rtype, type);
7819 MonoClass *klass = mono_class_from_mono_type_internal (type);
7820 mono_class_init_checked (klass, error);
7821 return_val_if_nok (error, ret);
7823 if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass))
7824 return ret;
7826 if (method->flags & METHOD_ATTRIBUTE_STATIC)
7827 return ret;
7829 if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
7830 if (klass == method->klass || mono_class_is_subclass_of_internal (klass, method->klass, FALSE))
7831 ret = rmethod;
7832 return ret;
7835 mono_class_setup_vtable (klass);
7836 MonoMethod **vtable = m_class_get_vtable (klass);
7838 MonoMethod *res = NULL;
7839 if (mono_class_is_interface (method->klass)) {
7840 gboolean variance_used = FALSE;
7841 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
7842 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
7843 if (offs >= 0)
7844 res = vtable [offs + method->slot];
7845 } else {
7846 if (!(klass == method->klass || mono_class_is_subclass_of_internal (klass, method->klass, FALSE)))
7847 return ret;
7849 if (method->slot != -1)
7850 res = vtable [method->slot];
7853 if (!res)
7854 return ret;
7856 ret = mono_method_get_object_handle (mono_domain_get (), res, NULL, error);
7857 return ret;
7860 void
7861 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
7863 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
7864 MonoVTable *vtable = mono_class_vtable_checked (mono_domain_get (), klass, error);
7865 return_if_nok (error);
7867 mono_vtable_set_is_remote (vtable, enable);
7870 #else /* DISABLE_REMOTING */
7872 #ifndef ENABLE_NETCORE
7873 void
7874 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
7876 g_assert_not_reached ();
7878 #endif
7880 #endif
7882 #ifndef ENABLE_NETCORE
7883 MonoObjectHandle
7884 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionTypeHandle type, MonoError *error)
7886 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
7887 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
7888 mono_class_init_checked (klass, error);
7889 return_val_if_nok (error, NULL_HANDLE);
7891 if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || mono_class_is_abstract (klass)) {
7892 mono_error_set_argument (error, "type", "Type cannot be instantiated");
7893 return NULL_HANDLE;
7896 if (m_class_get_rank (klass) >= 1) {
7897 g_assert (m_class_get_rank (klass) == 1);
7898 return MONO_HANDLE_CAST (MonoObject, mono_array_new_handle (domain, m_class_get_element_class (klass), 0, error));
7899 } else {
7900 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
7901 return_val_if_nok (error, NULL_HANDLE);
7903 /* Bypass remoting object creation check */
7904 return MONO_HANDLE_NEW (MonoObject, mono_object_new_alloc_specific_checked (vtable, error));
7908 MonoStringHandle
7909 ves_icall_System_IO_get_temp_path (MonoError *error)
7911 return mono_string_new_handle (mono_domain_get (), g_get_tmp_dir (), error);
7914 #endif /* ENABLE_NETCORE */
7916 #if defined(ENABLE_MONODROID) || defined(ENABLE_MONOTOUCH) || defined(TARGET_WASM)
7918 // FIXME? Names should start "mono"?
7919 G_EXTERN_C gpointer CreateZStream (gint32 compress, MonoBoolean gzip, gpointer feeder, gpointer data);
7920 G_EXTERN_C gint32 CloseZStream (gpointer stream);
7921 G_EXTERN_C gint32 Flush (gpointer stream);
7922 G_EXTERN_C gint32 ReadZStream (gpointer stream, gpointer buffer, gint32 length);
7923 G_EXTERN_C gint32 WriteZStream (gpointer stream, gpointer buffer, gint32 length);
7925 gpointer
7926 ves_icall_System_IO_Compression_DeflateStreamNative_CreateZStream (gint32 compress, MonoBoolean gzip, gpointer feeder, gpointer data)
7928 #ifdef MONO_CROSS_COMPILE
7929 return NULL;
7930 #else
7931 return CreateZStream (compress, gzip, feeder, data);
7932 #endif
7935 gint32
7936 ves_icall_System_IO_Compression_DeflateStreamNative_CloseZStream (gpointer stream)
7938 #ifdef MONO_CROSS_COMPILE
7939 return 0;
7940 #else
7941 return CloseZStream (stream);
7942 #endif
7945 gint32
7946 ves_icall_System_IO_Compression_DeflateStreamNative_Flush (gpointer stream)
7948 #ifdef MONO_CROSS_COMPILE
7949 return 0;
7950 #else
7951 return Flush (stream);
7952 #endif
7955 gint32
7956 ves_icall_System_IO_Compression_DeflateStreamNative_ReadZStream (gpointer stream, gpointer buffer, gint32 length)
7958 #ifdef MONO_CROSS_COMPILE
7959 return 0;
7960 #else
7961 return ReadZStream (stream, buffer, length);
7962 #endif
7965 gint32
7966 ves_icall_System_IO_Compression_DeflateStreamNative_WriteZStream (gpointer stream, gpointer buffer, gint32 length)
7968 #ifdef MONO_CROSS_COMPILE
7969 return 0;
7970 #else
7971 return WriteZStream (stream, buffer, length);
7972 #endif
7975 #endif
7977 #ifndef PLATFORM_NO_DRIVEINFO
7978 MonoBoolean
7979 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (const gunichar2 *path_name, gint32 path_name_length, guint64 *free_bytes_avail,
7980 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
7981 gint32 *error)
7983 g_assert (error);
7984 g_assert (free_bytes_avail);
7985 g_assert (total_number_of_bytes);
7986 g_assert (total_number_of_free_bytes);
7988 // FIXME check for embedded nuls here or managed
7990 *error = ERROR_SUCCESS;
7991 *free_bytes_avail = (guint64)-1;
7992 *total_number_of_bytes = (guint64)-1;
7993 *total_number_of_free_bytes = (guint64)-1;
7995 gboolean result = mono_w32file_get_disk_free_space (path_name, free_bytes_avail, total_number_of_bytes, total_number_of_free_bytes);
7996 if (!result)
7997 *error = mono_w32error_get_last ();
7999 return result;
8001 #endif /* PLATFORM_NO_DRIVEINFO */
8003 gpointer
8004 ves_icall_RuntimeMethodHandle_GetFunctionPointer (MonoMethod *method, MonoError *error)
8006 return mono_compile_method_checked (method, error);
8009 #ifndef ENABLE_NETCORE
8011 MonoStringHandle
8012 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (MonoError *error)
8014 gchar *path;
8016 const char *mono_cfg_dir = mono_get_config_dir ();
8017 if (!mono_cfg_dir)
8018 return mono_string_new_handle (mono_domain_get (), "", error);
8020 path = g_build_path (G_DIR_SEPARATOR_S, mono_cfg_dir, "mono", mono_get_runtime_info ()->framework_version, "machine.config", (const char*)NULL);
8022 mono_icall_make_platform_path (path);
8024 MonoStringHandle mcpath = mono_string_new_handle (mono_domain_get (), path, error);
8025 g_free (path);
8027 mono_error_assert_ok (error);
8029 return mcpath;
8032 MonoStringHandle
8033 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_app_config (MonoError *error)
8035 const gchar *app_config;
8036 MonoDomain *domain;
8037 gchar *config_file_name, *config_file_path;
8038 gsize len, config_file_path_length, config_ext_length;
8039 gchar *module;
8041 domain = mono_domain_get ();
8042 MonoStringHandle file = MONO_HANDLE_NEW (MonoString, domain->setup->configuration_file);
8043 if (MONO_HANDLE_IS_NULL (file) || MONO_HANDLE_GETVAL (file, length) == 0)
8044 return MONO_HANDLE_CAST (MonoString, mono_new_null ());
8046 // Retrieve config file and remove the extension
8047 config_file_name = mono_string_handle_to_utf8 (file, error);
8048 return_val_if_nok (error, MONO_HANDLE_CAST (MonoString, NULL_HANDLE));
8050 config_file_path = mono_portability_find_file (config_file_name, TRUE);
8051 if (!config_file_path)
8052 config_file_path = config_file_name;
8054 config_file_path_length = strlen (config_file_path);
8055 config_ext_length = strlen (".config");
8056 if (config_file_path_length <= config_ext_length) {
8057 if (config_file_name != config_file_path)
8058 g_free (config_file_name);
8059 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
8062 len = config_file_path_length - config_ext_length;
8063 module = (gchar *)g_malloc0 (len + 1);
8064 memcpy (module, config_file_path, len);
8065 // Get the config file from the module name
8066 app_config = mono_config_string_for_assembly_file (module);
8067 // Clean-up
8068 g_free (module);
8069 if (config_file_name != config_file_path)
8070 g_free (config_file_name);
8071 g_free (config_file_path);
8073 if (!app_config)
8074 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
8076 return mono_string_new_handle (mono_domain_get (), app_config, error);
8079 static MonoStringHandle
8080 get_bundled_machine_config (MonoError *error)
8082 const gchar *machine_config;
8084 machine_config = mono_get_machine_config ();
8086 if (!machine_config)
8087 return NULL_HANDLE_STRING;
8089 return mono_string_new_handle (mono_domain_get (), machine_config, error);
8092 MonoStringHandle
8093 ves_icall_System_Environment_get_bundled_machine_config (MonoError *error)
8095 return get_bundled_machine_config (error);
8098 MonoStringHandle
8099 ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
8101 return get_bundled_machine_config (error);
8104 MonoStringHandle
8105 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
8107 return get_bundled_machine_config (error);
8110 MonoStringHandle
8111 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (MonoError *error)
8113 const char *mono_cfg_dir = mono_get_config_dir ();
8114 if (!mono_cfg_dir)
8115 return mono_string_new_handle (mono_domain_get (), "", error);
8117 char *path = g_path_get_dirname (mono_cfg_dir);
8119 mono_icall_make_platform_path (path);
8121 MonoStringHandle ipath = mono_string_new_handle (mono_domain_get (), path, error);
8122 g_free (path);
8124 return ipath;
8127 MonoBoolean
8128 ves_icall_get_resources_ptr (MonoReflectionAssemblyHandle assembly, gpointer *result, gint32 *size, MonoError *error)
8130 MonoPEResourceDataEntry *entry;
8131 MonoImage *image;
8133 if (MONO_HANDLE_IS_NULL (assembly) || !result || !size)
8134 return FALSE;
8136 *result = NULL;
8137 *size = 0;
8138 MonoAssembly *assm = MONO_HANDLE_GETVAL (assembly, assembly);
8139 image = assm->image;
8140 entry = (MonoPEResourceDataEntry *)mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
8141 if (!entry)
8142 return FALSE;
8144 *result = mono_image_rva_map (image, entry->rde_data_offset);
8145 if (!(*result)) {
8146 g_free (entry);
8147 return FALSE;
8149 *size = entry->rde_size;
8150 g_free (entry);
8151 return TRUE;
8154 #endif /* ENABLE_NETCORE */
8156 MonoBoolean
8157 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (MonoError *error)
8159 return mono_is_debugger_attached ();
8162 MonoBoolean
8163 ves_icall_System_Diagnostics_Debugger_IsLogging (MonoError *error)
8165 return mono_get_runtime_callbacks ()->debug_log_is_enabled
8166 && mono_get_runtime_callbacks ()->debug_log_is_enabled ();
8169 void
8170 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoStringHandle category, MonoStringHandle message, MonoError *error)
8172 if (mono_get_runtime_callbacks ()->debug_log)
8173 mono_get_runtime_callbacks ()->debug_log (level, category, message);
8176 #ifndef HOST_WIN32
8177 static inline void
8178 mono_icall_write_windows_debug_string (const gunichar2 *message)
8180 g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
8182 #endif /* !HOST_WIN32 */
8184 #ifndef ENABLE_NETCORE
8185 void
8186 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (const gunichar2 *message, MonoError *error)
8188 mono_icall_write_windows_debug_string (message);
8190 #endif
8192 /* Only used for value types */
8193 MonoObjectHandle
8194 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
8196 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
8197 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
8198 MonoClass *klass = mono_class_from_mono_type_internal (type);
8199 (void)klass;
8201 mono_class_init_checked (klass, error);
8202 return_val_if_nok (error, NULL_HANDLE);
8204 if (mono_class_is_nullable (klass))
8205 /* No arguments -> null */
8206 return NULL_HANDLE;
8208 return mono_object_new_handle (domain, klass, error);
8211 MonoReflectionMethodHandle
8212 ves_icall_RuntimeMethodInfo_get_base_method (MonoReflectionMethodHandle m, MonoBoolean definition, MonoError *error)
8214 MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
8216 MonoMethod *base = mono_method_get_base_method (method, definition, error);
8217 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
8218 if (base == method) {
8219 /* we want to short-circuit and return 'm' here. But we should
8220 return the same method object that
8221 mono_method_get_object_handle, below would return. Since
8222 that call takes NULL for the reftype argument, it will take
8223 base->klass as the reflected type for the MonoMethod. So we
8224 need to check that m also has base->klass as the reflected
8225 type. */
8226 MonoReflectionTypeHandle orig_reftype = MONO_HANDLE_NEW_GET (MonoReflectionType, m, reftype);
8227 MonoClass *orig_klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (orig_reftype, type));
8228 if (base->klass == orig_klass)
8229 return m;
8231 return mono_method_get_object_handle (mono_domain_get (), base, NULL, error);
8234 MonoStringHandle
8235 ves_icall_RuntimeMethodInfo_get_name (MonoReflectionMethodHandle m, MonoError *error)
8237 MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
8239 MonoStringHandle s = mono_string_new_handle (MONO_HANDLE_DOMAIN (m), method->name, error);
8240 return_val_if_nok (error, NULL_HANDLE_STRING);
8241 MONO_HANDLE_SET (m, name, s);
8242 return s;
8245 void
8246 ves_icall_System_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
8248 iter->sig = *(MonoMethodSignature**)argsp;
8250 g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
8251 g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
8253 iter->next_arg = 0;
8254 /* FIXME: it's not documented what start is exactly... */
8255 if (start) {
8256 iter->args = start;
8257 } else {
8258 iter->args = argsp + sizeof (gpointer);
8260 iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
8262 /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
8265 void
8266 ves_icall_System_ArgIterator_IntGetNextArg (MonoArgIterator *iter, MonoTypedRef *res)
8268 guint32 i, arg_size;
8269 gint32 align;
8271 i = iter->sig->sentinelpos + iter->next_arg;
8273 g_assert (i < iter->sig->param_count);
8275 res->type = iter->sig->params [i];
8276 res->klass = mono_class_from_mono_type_internal (res->type);
8277 arg_size = mono_type_stack_size (res->type, &align);
8278 #if defined(__arm__) || defined(__mips__)
8279 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
8280 #endif
8281 res->value = iter->args;
8282 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
8283 if (arg_size <= sizeof (gpointer)) {
8284 int dummy;
8285 int padding = arg_size - mono_type_size (res->type, &dummy);
8286 res->value = (guint8*)res->value + padding;
8288 #endif
8289 iter->args = (char*)iter->args + arg_size;
8290 iter->next_arg++;
8292 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res->type->type, arg_size, res->value); */
8295 void
8296 ves_icall_System_ArgIterator_IntGetNextArgWithType (MonoArgIterator *iter, MonoTypedRef *res, MonoType *type)
8298 guint32 i, arg_size;
8299 gint32 align;
8301 i = iter->sig->sentinelpos + iter->next_arg;
8303 g_assert (i < iter->sig->param_count);
8305 while (i < iter->sig->param_count) {
8306 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
8307 continue;
8308 res->type = iter->sig->params [i];
8309 res->klass = mono_class_from_mono_type_internal (res->type);
8310 /* FIXME: endianess issue... */
8311 arg_size = mono_type_stack_size (res->type, &align);
8312 #if defined(__arm__) || defined(__mips__)
8313 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
8314 #endif
8315 res->value = iter->args;
8316 iter->args = (char*)iter->args + arg_size;
8317 iter->next_arg++;
8318 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
8319 return;
8321 /* g_print ("arg type 0x%02x not found\n", res.type->type); */
8323 memset (res, 0, sizeof (MonoTypedRef));
8326 MonoType*
8327 ves_icall_System_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
8329 gint i;
8331 i = iter->sig->sentinelpos + iter->next_arg;
8333 g_assert (i < iter->sig->param_count);
8335 return iter->sig->params [i];
8338 MonoObjectHandle
8339 ves_icall_System_TypedReference_ToObject (MonoTypedRef* tref, MonoError *error)
8341 return typed_reference_to_object (tref, error);
8344 void
8345 ves_icall_System_TypedReference_InternalMakeTypedReference (MonoTypedRef *res, MonoObjectHandle target, MonoArrayHandle fields, MonoReflectionTypeHandle last_field, MonoError *error)
8347 MonoType *ftype = NULL;
8348 int i;
8350 memset (res, 0, sizeof (MonoTypedRef));
8352 g_assert (mono_array_handle_length (fields) > 0);
8354 (void)mono_handle_class (target);
8356 int offset = 0;
8357 for (i = 0; i < mono_array_handle_length (fields); ++i) {
8358 MonoClassField *f;
8359 MONO_HANDLE_ARRAY_GETVAL (f, fields, MonoClassField*, i);
8361 g_assert (f);
8363 if (i == 0)
8364 offset = f->offset;
8365 else
8366 offset += f->offset - sizeof (MonoObject);
8367 (void)mono_class_from_mono_type_internal (f->type);
8368 ftype = f->type;
8371 res->type = ftype;
8372 res->klass = mono_class_from_mono_type_internal (ftype);
8373 res->value = (guint8*)MONO_HANDLE_RAW (target) + offset;
8376 static void
8377 prelink_method (MonoMethod *method, MonoError *error)
8379 error_init (error);
8380 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8381 return;
8382 mono_lookup_pinvoke_call_internal (method, error);
8383 /* create the wrapper, too? */
8386 void
8387 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethodHandle method, MonoError *error)
8389 error_init (error);
8391 prelink_method (MONO_HANDLE_GETVAL (method, method), error);
8394 void
8395 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionTypeHandle type, MonoError *error)
8397 error_init (error);
8398 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
8399 MonoMethod* m;
8400 gpointer iter = NULL;
8402 mono_class_init_checked (klass, error);
8403 return_if_nok (error);
8405 while ((m = mono_class_get_methods (klass, &iter))) {
8406 prelink_method (m, error);
8407 return_if_nok (error);
8411 #ifndef ENABLE_NETCORE
8413 * used by System.Runtime.InteropServices.RuntimeInformation.(OS|Process)Architecture;
8414 * which use them in different ways for filling in an enum
8416 MonoStringHandle
8417 ves_icall_System_Runtime_InteropServices_RuntimeInformation_GetRuntimeArchitecture (MonoError *error)
8419 error_init (error);
8420 return mono_string_new_handle (mono_domain_get (), mono_config_get_cpu (), error);
8424 * used by System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform
8426 MonoStringHandle
8427 ves_icall_System_Runtime_InteropServices_RuntimeInformation_GetOSName (MonoError *error)
8429 error_init (error);
8430 return mono_string_new_handle (mono_domain_get (), mono_config_get_os (), error);
8432 #endif /* ENABLE_NETCORE */
8435 ves_icall_Interop_Sys_DoubleToString(double value, char *format, char *buffer, int bufferLength)
8437 #if defined(TARGET_ARM)
8438 /* workaround for faulty vcmp.f64 implementation on some 32bit ARM CPUs */
8439 guint64 bits = *(guint64 *) &value;
8440 if (bits == 0x1) { /* 4.9406564584124654E-324 */
8441 g_assert (!strcmp (format, "%.40e"));
8442 return snprintf (buffer, bufferLength, "%s", "4.9406564584124654417656879286822137236506e-324");
8443 } else if (bits == 0x4) { /* 2E-323 */
8444 g_assert (!strcmp (format, "%.40e"));
8445 return snprintf (buffer, bufferLength, "%s", "1.9762625833649861767062751714728854894602e-323");
8447 #endif
8449 return snprintf(buffer, bufferLength, format, value);
8452 void
8453 ves_icall_System_Runtime_RuntimeImports_ecvt_s(char *buffer, size_t sizeInBytes, double value, int count, int* dec, int* sign)
8455 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
8456 _ecvt_s(buffer, sizeInBytes, value, count, dec, sign);
8457 #endif
8461 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
8462 void
8463 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
8464 gint32 const **exponents,
8465 gunichar2 const **digitLowerTable,
8466 gunichar2 const **digitUpperTable,
8467 gint64 const **tenPowersList,
8468 gint32 const **decHexDigits)
8470 *mantissas = Formatter_MantissaBitsTable;
8471 *exponents = Formatter_TensExponentTable;
8472 *digitLowerTable = Formatter_DigitLowerTable;
8473 *digitUpperTable = Formatter_DigitUpperTable;
8474 *tenPowersList = Formatter_TenPowersList;
8475 *decHexDigits = Formatter_DecHexDigits;
8478 static gboolean
8479 add_modifier_to_array (MonoDomain *domain, MonoType *type, MonoArrayHandle dest, int dest_idx, MonoError *error)
8481 HANDLE_FUNCTION_ENTER ();
8482 error_init (error);
8483 MonoClass *klass = mono_class_from_mono_type_internal (type);
8485 MonoReflectionTypeHandle rt;
8486 rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
8487 goto_if_nok (error, leave);
8489 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rt);
8490 leave:
8491 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
8495 * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
8496 * and avoid useless allocations.
8498 static MonoArrayHandle
8499 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error)
8501 int i, count = 0;
8502 MonoDomain *domain = mono_domain_get ();
8504 int cmod_count = mono_type_custom_modifier_count (type);
8505 if (cmod_count == 0)
8506 goto fail;
8508 error_init (error);
8509 for (i = 0; i < cmod_count; ++i) {
8510 gboolean required;
8511 (void) mono_type_get_custom_modifier (type, i, &required, error);
8512 goto_if_nok (error, fail);
8513 if ((optional && !required) || (!optional && required))
8514 count++;
8516 if (!count)
8517 goto fail;
8519 MonoArrayHandle res;
8520 res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
8521 goto_if_nok (error, fail);
8522 count = 0;
8523 for (i = 0; i < cmod_count; ++i) {
8524 gboolean required;
8525 MonoType *cmod_type = mono_type_get_custom_modifier (type, i, &required, error);
8526 goto_if_nok (error, fail);
8527 if ((optional && !required) || (!optional && required)) {
8528 if (!add_modifier_to_array (domain, cmod_type, res, count, error))
8529 goto fail;
8530 count++;
8533 return res;
8534 fail:
8535 return MONO_HANDLE_NEW (MonoArray, NULL);
8538 MonoArrayHandle
8539 ves_icall_RuntimeParameterInfo_GetTypeModifiers (MonoReflectionTypeHandle rt, MonoObjectHandle member, int pos, MonoBoolean optional, MonoError *error)
8541 error_init (error);
8542 MonoType *type = MONO_HANDLE_GETVAL (rt, type);
8543 MonoClass *member_class = mono_handle_class (member);
8544 MonoMethod *method = NULL;
8545 MonoImage *image;
8546 MonoMethodSignature *sig;
8548 if (mono_class_is_reflection_method_or_constructor (member_class)) {
8549 method = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionMethod, member), method);
8550 } else if (m_class_get_image (member_class) == mono_defaults.corlib && !strcmp ("RuntimePropertyInfo", m_class_get_name (member_class))) {
8551 MonoProperty *prop = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionProperty, member), property);
8552 if (!(method = prop->get))
8553 method = prop->set;
8554 g_assert (method);
8555 } else {
8556 char *type_name = mono_type_get_full_name (member_class);
8557 mono_error_set_not_supported (error, "Custom modifiers on a ParamInfo with member %s are not supported", type_name);
8558 g_free (type_name);
8559 return NULL_HANDLE_ARRAY;
8562 image = m_class_get_image (method->klass);
8563 sig = mono_method_signature_internal (method);
8564 if (pos == -1)
8565 type = sig->ret;
8566 else
8567 type = sig->params [pos];
8569 return type_array_from_modifiers (image, type, optional, error);
8572 static MonoType*
8573 get_property_type (MonoProperty *prop)
8575 MonoMethodSignature *sig;
8576 if (prop->get) {
8577 sig = mono_method_signature_internal (prop->get);
8578 return sig->ret;
8579 } else if (prop->set) {
8580 sig = mono_method_signature_internal (prop->set);
8581 return sig->params [sig->param_count - 1];
8583 return NULL;
8586 MonoArrayHandle
8587 ves_icall_RuntimePropertyInfo_GetTypeModifiers (MonoReflectionPropertyHandle property, MonoBoolean optional, MonoError *error)
8589 error_init (error);
8590 MonoProperty *prop = MONO_HANDLE_GETVAL (property, property);
8591 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
8592 MonoType *type = get_property_type (prop);
8593 MonoImage *image = m_class_get_image (klass);
8595 if (!type)
8596 return NULL_HANDLE_ARRAY;
8597 return type_array_from_modifiers (image, type, optional, error);
8601 *Construct a MonoType suited to be used to decode a constant blob object.
8603 * @type is the target type which will be constructed
8604 * @blob_type is the blob type, for example, that comes from the constant table
8605 * @real_type is the expected constructed type.
8607 static void
8608 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
8610 type->type = blob_type;
8611 type->data.klass = NULL;
8612 if (blob_type == MONO_TYPE_CLASS)
8613 type->data.klass = mono_defaults.object_class;
8614 else if (real_type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (real_type->data.klass)) {
8615 /* For enums, we need to use the base type */
8616 type->type = MONO_TYPE_VALUETYPE;
8617 type->data.klass = mono_class_from_mono_type_internal (real_type);
8618 } else
8619 type->data.klass = mono_class_from_mono_type_internal (real_type);
8622 MonoObject*
8623 ves_icall_property_info_get_default_value (MonoReflectionProperty *property)
8625 ERROR_DECL (error);
8626 MonoType blob_type;
8627 MonoProperty *prop = property->property;
8628 MonoType *type = get_property_type (prop);
8629 MonoDomain *domain = mono_object_domain (property);
8630 MonoTypeEnum def_type;
8631 const char *def_value;
8632 MonoObject *o;
8634 mono_class_init_internal (prop->parent);
8636 if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT)) {
8637 mono_error_set_invalid_operation (error, NULL);
8638 mono_error_set_pending_exception (error);
8639 return NULL;
8642 def_value = mono_class_get_property_default_value (prop, &def_type);
8644 mono_type_from_blob_type (&blob_type, def_type, type);
8645 o = mono_get_object_from_blob (domain, &blob_type, def_value, error);
8647 mono_error_set_pending_exception (error);
8648 return o;
8651 MonoBoolean
8652 ves_icall_MonoCustomAttrs_IsDefinedInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, MonoError *error)
8654 error_init (error);
8655 MonoClass *attr_class = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (attr_type, type));
8657 mono_class_init_checked (attr_class, error);
8658 return_val_if_nok (error, FALSE);
8660 MonoCustomAttrInfo *cinfo = mono_reflection_get_custom_attrs_info_checked (obj, error);
8661 return_val_if_nok (error, FALSE);
8663 if (!cinfo)
8664 return FALSE;
8665 gboolean found = mono_custom_attrs_has_attr (cinfo, attr_class);
8666 if (!cinfo->cached)
8667 mono_custom_attrs_free (cinfo);
8668 return found;
8671 MonoArrayHandle
8672 ves_icall_MonoCustomAttrs_GetCustomAttributesInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, MonoBoolean pseudoattrs, MonoError *error)
8674 MonoClass *attr_class;
8675 if (MONO_HANDLE_IS_NULL (attr_type))
8676 attr_class = NULL;
8677 else
8678 attr_class = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (attr_type, type));
8680 if (attr_class) {
8681 mono_class_init_checked (attr_class, error);
8682 return_val_if_nok (error, NULL_HANDLE_ARRAY);
8685 return mono_reflection_get_custom_attrs_by_type_handle (obj, attr_class, error);
8688 MonoArrayHandle
8689 ves_icall_MonoCustomAttrs_GetCustomAttributesDataInternal (MonoObjectHandle obj, MonoError *error)
8691 error_init (error);
8692 return mono_reflection_get_custom_attrs_data_checked (obj, error);
8696 MonoStringHandle
8697 ves_icall_Mono_Runtime_GetDisplayName (MonoError *error)
8699 char *info;
8700 MonoStringHandle display_name;
8702 error_init (error);
8703 info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
8704 display_name = mono_string_new_handle (mono_domain_get (), info, error);
8705 g_free (info);
8706 return display_name;
8709 #ifndef HOST_WIN32
8710 static inline gint32
8711 mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
8713 return WAIT_TIMEOUT;
8715 #endif /* !HOST_WIN32 */
8717 #ifndef ENABLE_NETCORE
8718 gint32
8719 ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle (gpointer handle, gint32 milliseconds, MonoError *error)
8721 return mono_icall_wait_for_input_idle (handle, milliseconds);
8724 gint32
8725 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcessId (MonoError *error)
8727 return mono_process_current_pid ();
8730 MonoBoolean
8731 ves_icall_Mono_TlsProviderFactory_IsBtlsSupported (MonoError *error)
8733 #if HAVE_BTLS
8734 return TRUE;
8735 #else
8736 return FALSE;
8737 #endif
8739 #endif /* ENABLE_NETCORE */
8741 #ifndef DISABLE_COM
8744 ves_icall_System_Runtime_InteropServices_Marshal_GetHRForException_WinRT(MonoExceptionHandle ex, MonoError *error)
8746 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetHRForException_WinRT internal call is not implemented.");
8747 return 0;
8750 MonoObjectHandle
8751 ves_icall_System_Runtime_InteropServices_Marshal_GetNativeActivationFactory(MonoObjectHandle type, MonoError *error)
8753 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetNativeActivationFactory internal call is not implemented.");
8754 return NULL_HANDLE;
8757 void*
8758 ves_icall_System_Runtime_InteropServices_Marshal_GetRawIUnknownForComObjectNoAddRef(MonoObjectHandle obj, MonoError *error)
8760 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetRawIUnknownForComObjectNoAddRef internal call is not implemented.");
8761 return NULL;
8764 MonoObjectHandle
8765 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_GetRestrictedErrorInfo(MonoError *error)
8767 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.GetRestrictedErrorInfo internal call is not implemented.");
8768 return NULL_HANDLE;
8771 MonoBoolean
8772 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoOriginateLanguageException (int ierr, MonoStringHandle message, void* languageException, MonoError *error)
8774 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoOriginateLanguageException internal call is not implemented.");
8775 return FALSE;
8778 void
8779 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoReportUnhandledError (MonoObjectHandle oerr, MonoError *error)
8781 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoReportUnhandledError internal call is not implemented.");
8785 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsCreateString(MonoStringHandle sourceString, int length, void** hstring, MonoError *error)
8787 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString internal call is not implemented.");
8788 return 0;
8792 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsDeleteString(void* hstring, MonoError *error)
8794 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString internal call is not implemented.");
8795 return 0;
8798 mono_unichar2*
8799 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsGetStringRawBuffer(void* hstring, unsigned* length, MonoError *error)
8801 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsGetStringRawBuffer internal call is not implemented.");
8802 return NULL;
8805 #endif
8807 #if !ENABLE_NETCORE
8809 void
8810 ves_icall_System_IO_LogcatTextWriter_Log (const char *appname, gint32 level, const char *message)
8812 g_log (appname, (GLogLevelFlags)level, "%s", message);
8815 #endif
8817 static const MonoIcallTableCallbacks *icall_table;
8818 static mono_mutex_t icall_mutex;
8819 static GHashTable *icall_hash = NULL;
8821 typedef struct _MonoIcallHashTableValue {
8822 gconstpointer method;
8823 guint32 flags;
8824 } MonoIcallHashTableValue;
8826 void
8827 mono_install_icall_table_callbacks (const MonoIcallTableCallbacks *cb)
8829 g_assert (cb->version == MONO_ICALL_TABLE_CALLBACKS_VERSION);
8830 icall_table = cb;
8833 void
8834 mono_icall_init (void)
8836 #ifndef DISABLE_ICALL_TABLES
8837 mono_icall_table_init ();
8838 #endif
8839 icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
8840 mono_os_mutex_init (&icall_mutex);
8843 static void
8844 mono_icall_lock (void)
8846 mono_locks_os_acquire (&icall_mutex, IcallLock);
8849 static void
8850 mono_icall_unlock (void)
8852 mono_locks_os_release (&icall_mutex, IcallLock);
8855 void
8856 mono_icall_cleanup (void)
8858 g_hash_table_destroy (icall_hash);
8859 mono_os_mutex_destroy (&icall_mutex);
8862 static void
8863 add_internal_call_with_flags (const char *name, gconstpointer method, guint32 flags)
8865 char *key = g_strdup (name);
8866 MonoIcallHashTableValue *value = g_new (MonoIcallHashTableValue, 1);
8867 if (key && value) {
8868 value->method = method;
8869 value->flags = flags;
8871 mono_icall_lock ();
8872 g_hash_table_insert (icall_hash, key, (gpointer)value);
8873 mono_icall_unlock ();
8878 * mono_add_internal_call:
8879 * \param name method specification to surface to the managed world
8880 * \param method pointer to a C method to invoke when the method is called
8882 * This method surfaces the C function pointed by \p method as a method
8883 * that has been surfaced in managed code with the method specified in
8884 * \p name as an internal call.
8886 * Internal calls are surfaced to all app domains loaded and they are
8887 * accessibly by a type with the specified name.
8889 * You must provide a fully qualified type name, that is namespaces
8890 * and type name, followed by a colon and the method name, with an
8891 * optional signature to bind.
8893 * For example, the following are all valid declarations:
8895 * \c MyApp.Services.ScriptService:Accelerate
8897 * \c MyApp.Services.ScriptService:Slowdown(int,bool)
8899 * You use method parameters in cases where there might be more than
8900 * one surface method to managed code. That way you can register different
8901 * internal calls for different method overloads.
8903 * The internal calls are invoked with no marshalling. This means that .NET
8904 * types like \c System.String are exposed as \c MonoString* parameters. This is
8905 * different than the way that strings are surfaced in P/Invoke.
8907 * For more information on how the parameters are marshalled, see the
8908 * <a href="http://www.mono-project.com/docs/advanced/embedding/">Mono Embedding</a>
8909 * page.
8911 * See the <a href="mono-api-methods.html#method-desc">Method Description</a>
8912 * reference for more information on the format of method descriptions.
8914 void
8915 mono_add_internal_call (const char *name, gconstpointer method)
8917 mono_add_internal_call_with_flags (name, method, FALSE);
8921 * mono_dangerous_add_raw_internal_call:
8922 * \param name method specification to surface to the managed world
8923 * \param method pointer to a C method to invoke when the method is called
8925 * Similar to \c mono_add_internal_call but with more requirements for correct
8926 * operation.
8928 * A thread running a dangerous raw internal call will avoid a thread state
8929 * transition on entry and exit, but it must take responsiblity for cooperating
8930 * with the Mono runtime.
8932 * The \p method must NOT:
8934 * Run for an unbounded amount of time without calling the mono runtime.
8935 * Additionally, the method must switch to GC Safe mode to perform all blocking
8936 * operations: performing blocking I/O, taking locks, etc.
8939 void
8940 mono_dangerous_add_raw_internal_call (const char *name, gconstpointer method)
8942 mono_add_internal_call_with_flags (name, method, TRUE);
8946 * mono_add_internal_call_with_flags:
8947 * \param name method specification to surface to the managed world
8948 * \param method pointer to a C method to invoke when the method is called
8949 * \param cooperative if \c TRUE, run icall in GC Unsafe (cooperatively suspended) mode,
8950 * otherwise GC Safe (blocking)
8952 * Like \c mono_add_internal_call, but if \p cooperative is \c TRUE the added
8953 * icall promises that it will use the coopertive API to inform the runtime
8954 * when it is running blocking operations, that it will not run for unbounded
8955 * amounts of time without safepointing, and that it will not hold managed
8956 * object references across suspend safepoints.
8958 * If \p cooperative is \c FALSE, run the icall in GC Safe mode - the icall may
8959 * block. The icall must obey the GC Safe rules, e.g. it must not touch
8960 * unpinned managed memory.
8963 void
8964 mono_add_internal_call_with_flags (const char *name, gconstpointer method, gboolean cooperative)
8966 add_internal_call_with_flags (name, method, cooperative ? MONO_ICALL_FLAGS_COOPERATIVE : MONO_ICALL_FLAGS_FOREIGN);
8969 void
8970 mono_add_internal_call_internal (const char *name, gconstpointer method)
8972 mono_add_internal_call_with_flags (name, method, TRUE);
8976 * we should probably export this as an helper (handle nested types).
8977 * Returns the number of chars written in buf.
8979 static int
8980 concat_class_name (char *buf, int bufsize, MonoClass *klass)
8982 int nspacelen, cnamelen;
8983 nspacelen = strlen (m_class_get_name_space (klass));
8984 cnamelen = strlen (m_class_get_name (klass));
8985 if (nspacelen + cnamelen + 2 > bufsize)
8986 return 0;
8987 if (nspacelen) {
8988 memcpy (buf, m_class_get_name_space (klass), nspacelen);
8989 buf [nspacelen ++] = '.';
8991 memcpy (buf + nspacelen, m_class_get_name (klass), cnamelen);
8992 buf [nspacelen + cnamelen] = 0;
8993 return nspacelen + cnamelen;
8996 static void
8997 no_icall_table (void)
8999 g_assert_not_reached ();
9002 gconstpointer
9003 mono_lookup_internal_call_full_with_flags (MonoMethod *method, gboolean warn_on_missing, guint32 *flags)
9005 char *sigstart = NULL;
9006 char *tmpsig = NULL;
9007 char mname [2048];
9008 char *classname = NULL;
9009 int typelen = 0, mlen, siglen;
9010 gconstpointer res = NULL;
9011 gboolean locked = FALSE;
9013 g_assert (method != NULL);
9015 if (method->is_inflated)
9016 method = ((MonoMethodInflated *) method)->declaring;
9018 if (m_class_get_nested_in (method->klass)) {
9019 int pos = concat_class_name (mname, sizeof (mname)-2, m_class_get_nested_in (method->klass));
9020 if (!pos)
9021 goto exit;
9023 mname [pos++] = '/';
9024 mname [pos] = 0;
9026 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
9027 if (!typelen)
9028 goto exit;
9030 typelen += pos;
9031 } else {
9032 typelen = concat_class_name (mname, sizeof (mname), method->klass);
9033 if (!typelen)
9034 goto exit;
9037 classname = g_strdup (mname);
9039 mname [typelen] = ':';
9040 mname [typelen + 1] = ':';
9042 mlen = strlen (method->name);
9043 memcpy (mname + typelen + 2, method->name, mlen);
9044 sigstart = mname + typelen + 2 + mlen;
9045 *sigstart = 0;
9047 tmpsig = mono_signature_get_desc (mono_method_signature_internal (method), TRUE);
9048 siglen = strlen (tmpsig);
9049 if (typelen + mlen + siglen + 6 > sizeof (mname))
9050 goto exit;
9052 sigstart [0] = '(';
9053 memcpy (sigstart + 1, tmpsig, siglen);
9054 sigstart [siglen + 1] = ')';
9055 sigstart [siglen + 2] = 0;
9057 /* mono_marshal_get_native_wrapper () depends on this */
9058 if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor")) {
9059 res = (gconstpointer)ves_icall_System_String_ctor_RedirectToCreateString;
9060 goto exit;
9063 mono_icall_lock ();
9064 locked = TRUE;
9066 res = g_hash_table_lookup (icall_hash, mname);
9067 if (res) {
9068 MonoIcallHashTableValue *value = (MonoIcallHashTableValue *)res;
9069 if (flags)
9070 *flags = value->flags;
9071 res = value->method;
9072 goto exit;
9075 /* try without signature */
9076 *sigstart = 0;
9077 res = g_hash_table_lookup (icall_hash, mname);
9078 if (res) {
9079 MonoIcallHashTableValue *value = (MonoIcallHashTableValue *)res;
9080 if (flags)
9081 *flags = value->flags;
9082 res = value->method;
9083 goto exit;
9086 if (!icall_table) {
9087 /* Fail only when the result is actually used */
9088 res = (gconstpointer)no_icall_table;
9089 goto exit;
9090 } else {
9091 gboolean uses_handles = FALSE;
9092 g_assert (icall_table->lookup);
9093 res = icall_table->lookup (method, classname, sigstart - mlen, sigstart, &uses_handles);
9094 if (res && flags && uses_handles)
9095 *flags = *flags | MONO_ICALL_FLAGS_USES_HANDLES;
9096 mono_icall_unlock ();
9097 locked = FALSE;
9099 if (res)
9100 goto exit;
9102 if (warn_on_missing) {
9103 g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
9104 g_print ("\nYour mono runtime and class libraries are out of sync.\n");
9105 g_print ("The out of sync library is: %s\n", m_class_get_image (method->klass)->name);
9106 g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
9107 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");
9108 g_print ("If you see other errors or faults after this message they are probably related\n");
9109 g_print ("and you need to fix your mono install first.\n");
9112 res = NULL;
9115 exit:
9116 if (locked)
9117 mono_icall_unlock ();
9118 g_free (classname);
9119 g_free (tmpsig);
9120 return res;
9124 * mono_lookup_internal_call_full:
9125 * \param method the method to look up
9126 * \param uses_handles out argument if method needs handles around managed objects.
9127 * \returns a pointer to the icall code for the given method. If
9128 * \p uses_handles is not NULL, it will be set to TRUE if the method
9129 * needs managed objects wrapped using the infrastructure in handle.h
9131 * If the method is not found, warns and returns NULL.
9133 gconstpointer
9134 mono_lookup_internal_call_full (MonoMethod *method, gboolean warn_on_missing, mono_bool *uses_handles, mono_bool *foreign)
9136 if (uses_handles)
9137 *uses_handles = FALSE;
9138 if (foreign)
9139 *foreign = FALSE;
9141 guint32 flags = MONO_ICALL_FLAGS_NONE;
9142 gconstpointer addr = mono_lookup_internal_call_full_with_flags (method, warn_on_missing, &flags);
9144 if (uses_handles && (flags & MONO_ICALL_FLAGS_USES_HANDLES))
9145 *uses_handles = TRUE;
9146 if (foreign && (flags & MONO_ICALL_FLAGS_FOREIGN))
9147 *foreign = TRUE;
9148 return addr;
9152 * mono_lookup_internal_call:
9154 gpointer
9155 mono_lookup_internal_call (MonoMethod *method)
9157 return (gpointer)mono_lookup_internal_call_full (method, TRUE, NULL, NULL);
9161 * mono_lookup_icall_symbol:
9163 * Given the icall METHOD, returns its C symbol.
9165 const char*
9166 mono_lookup_icall_symbol (MonoMethod *m)
9168 if (!icall_table)
9169 return NULL;
9171 g_assert (icall_table->lookup_icall_symbol);
9172 gpointer func;
9173 func = (gpointer)mono_lookup_internal_call_full (m, FALSE, NULL, NULL);
9174 if (!func)
9175 return NULL;
9176 return icall_table->lookup_icall_symbol (func);
9179 #if defined(TARGET_WIN32) && defined(TARGET_X86)
9181 * Under windows, the default pinvoke calling convention is STDCALL but
9182 * we need CDECL.
9184 #define MONO_ICALL_SIGNATURE_CALL_CONVENTION MONO_CALL_C
9185 #else
9186 #define MONO_ICALL_SIGNATURE_CALL_CONVENTION 0
9187 #endif
9189 // Storage for these enums is pointer-sized as it gets replaced with MonoType*.
9191 // mono_create_icall_signatures depends on this order. Handle with care.
9192 // It is alphabetical.
9193 typedef enum ICallSigType {
9194 ICALL_SIG_TYPE_bool = 0x00,
9195 ICALL_SIG_TYPE_boolean = ICALL_SIG_TYPE_bool,
9196 ICALL_SIG_TYPE_double = 0x01,
9197 ICALL_SIG_TYPE_float = 0x02,
9198 ICALL_SIG_TYPE_int = 0x03,
9199 ICALL_SIG_TYPE_int16 = 0x04,
9200 ICALL_SIG_TYPE_int32 = 0x05,
9201 ICALL_SIG_TYPE_int8 = 0x06,
9202 ICALL_SIG_TYPE_long = 0x07,
9203 ICALL_SIG_TYPE_obj = 0x08,
9204 ICALL_SIG_TYPE_object = ICALL_SIG_TYPE_obj,
9205 ICALL_SIG_TYPE_ptr = ICALL_SIG_TYPE_int,
9206 ICALL_SIG_TYPE_ptrref = 0x09,
9207 ICALL_SIG_TYPE_string = 0x0A,
9208 ICALL_SIG_TYPE_uint16 = 0x0B,
9209 ICALL_SIG_TYPE_uint32 = 0x0C,
9210 ICALL_SIG_TYPE_uint8 = 0x0D,
9211 ICALL_SIG_TYPE_ulong = 0x0E,
9212 ICALL_SIG_TYPE_void = 0x0F,
9213 } ICallSigType;
9215 #define ICALL_SIG_TYPES_1(a) ICALL_SIG_TYPE_ ## a,
9216 #define ICALL_SIG_TYPES_2(a, b) ICALL_SIG_TYPES_1 (a ) ICALL_SIG_TYPES_1 (b)
9217 #define ICALL_SIG_TYPES_3(a, b, c) ICALL_SIG_TYPES_2 (a, b ) ICALL_SIG_TYPES_1 (c)
9218 #define ICALL_SIG_TYPES_4(a, b, c, d) ICALL_SIG_TYPES_3 (a, b, c ) ICALL_SIG_TYPES_1 (d)
9219 #define ICALL_SIG_TYPES_5(a, b, c, d, e) ICALL_SIG_TYPES_4 (a, b, c, d ) ICALL_SIG_TYPES_1 (e)
9220 #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)
9221 #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)
9222 #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)
9224 #define ICALL_SIG_TYPES(n, types) ICALL_SIG_TYPES_ ## n types
9226 // A scheme to make these const would be nice.
9227 static struct {
9228 #define ICALL_SIG(n, xtypes) \
9229 struct { \
9230 MonoMethodSignature sig; \
9231 gsize types [n]; \
9232 } ICALL_SIG_NAME (n, xtypes);
9233 ICALL_SIGS
9234 MonoMethodSignature end; // terminal zeroed element
9235 } mono_icall_signatures = {
9236 #undef ICALL_SIG
9237 #define ICALL_SIG(n, types) { { \
9238 0, /* ret */ \
9239 n, /* param_count */ \
9240 -1, /* sentinelpos */ \
9241 0, /* generic_param_count */ \
9242 MONO_ICALL_SIGNATURE_CALL_CONVENTION, \
9243 0, /* hasthis */ \
9244 0, /* explicit_this */ \
9245 1, /* pinvoke */ \
9246 0, /* is_inflated */ \
9247 0, /* has_type_parameters */ \
9248 }, /* possible gap here, depending on MONO_ZERO_LEN_ARRAY */ \
9249 { ICALL_SIG_TYPES (n, types) } }, /* params and ret */
9250 ICALL_SIGS
9253 #undef ICALL_SIG
9254 #define ICALL_SIG(n, types) MonoMethodSignature * const ICALL_SIG_NAME (n, types) = &mono_icall_signatures.ICALL_SIG_NAME (n, types).sig;
9255 ICALL_SIGS
9256 #undef ICALL_SIG
9258 void
9259 mono_create_icall_signatures (void)
9261 // Fixup the mostly statically initialized icall signatures.
9262 // x = m_class_get_byval_arg (x)
9263 // Initialize ret with params [0] and params [i] with params [i + 1].
9264 // ptrref is special
9266 // FIXME This is a bit obscure.
9268 typedef MonoMethodSignature G_MAY_ALIAS MonoMethodSignature_a;
9269 typedef gsize G_MAY_ALIAS gsize_a;
9271 MonoType * const lookup [ ] = {
9272 m_class_get_byval_arg (mono_defaults.boolean_class), // ICALL_SIG_TYPE_bool
9273 m_class_get_byval_arg (mono_defaults.double_class), // ICALL_SIG_TYPE_double
9274 m_class_get_byval_arg (mono_defaults.single_class), // ICALL_SIG_TYPE_float
9275 m_class_get_byval_arg (mono_defaults.int_class), // ICALL_SIG_TYPE_int
9276 m_class_get_byval_arg (mono_defaults.int16_class), // ICALL_SIG_TYPE_int16
9277 m_class_get_byval_arg (mono_defaults.int32_class), // ICALL_SIG_TYPE_int32
9278 m_class_get_byval_arg (mono_defaults.sbyte_class), // ICALL_SIG_TYPE_int8
9279 m_class_get_byval_arg (mono_defaults.int64_class), // ICALL_SIG_TYPE_long
9280 m_class_get_byval_arg (mono_defaults.object_class), // ICALL_SIG_TYPE_obj
9281 mono_class_get_byref_type (mono_defaults.int_class), // ICALL_SIG_TYPE_ptrref
9282 m_class_get_byval_arg (mono_defaults.string_class), // ICALL_SIG_TYPE_string
9283 m_class_get_byval_arg (mono_defaults.uint16_class), // ICALL_SIG_TYPE_uint16
9284 m_class_get_byval_arg (mono_defaults.uint32_class), // ICALL_SIG_TYPE_uint32
9285 m_class_get_byval_arg (mono_defaults.byte_class), // ICALL_SIG_TYPE_uint8
9286 m_class_get_byval_arg (mono_defaults.uint64_class), // ICALL_SIG_TYPE_ulong
9287 m_class_get_byval_arg (mono_defaults.void_class), // ICALL_SIG_TYPE_void
9290 MonoMethodSignature_a *sig = (MonoMethodSignature*)&mono_icall_signatures;
9291 int n;
9292 while ((n = sig->param_count)) {
9293 --sig->param_count; // remove ret
9294 gsize_a *types = (gsize*)(sig + 1);
9295 for (int i = 0; i < n; ++i) {
9296 gsize index = *types++;
9297 g_assert (index < G_N_ELEMENTS (lookup));
9298 // Casts on next line are attempt to follow strict aliasing rules,
9299 // to ensure reading from *types precedes writing
9300 // to params [].
9301 *(gsize*)(i ? &sig->params [i - 1] : &sig->ret) = (gsize)lookup [index];
9303 sig = (MonoMethodSignature*)types;
9307 void
9308 mono_register_jit_icall_info (MonoJitICallInfo *info, gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean avoid_wrapper, const char *c_symbol)
9310 // Duplicate initialization is allowed and racy, assuming it is equivalent.
9312 info->name = name;
9313 info->func = func;
9314 info->sig = sig;
9315 info->c_symbol = c_symbol;
9317 // Fill in wrapper ahead of time, to just be func, to avoid
9318 // later initializing it to anything else. So therefore, no wrapper.
9319 if (avoid_wrapper) {
9320 info->wrapper = func;
9321 } else {
9322 // Leave it alone in case of a race.
9327 ves_icall_System_GC_GetCollectionCount (int generation)
9329 return mono_gc_collection_count (generation);
9333 ves_icall_System_GC_GetGeneration (MonoObjectHandle object, MonoError *error)
9335 return mono_gc_get_generation (MONO_HANDLE_RAW (object));
9339 ves_icall_System_GC_GetMaxGeneration (void)
9341 return mono_gc_max_generation ();
9344 gint64
9345 ves_icall_System_GC_GetAllocatedBytesForCurrentThread (void)
9347 return mono_gc_get_allocated_bytes_for_current_thread ();
9350 void
9351 ves_icall_System_GC_RecordPressure (gint64 value)
9353 mono_gc_add_memory_pressure (value);
9356 gint64
9357 ves_icall_System_Diagnostics_Stopwatch_GetTimestamp (void)
9359 return mono_100ns_ticks ();
9362 gint64
9363 ves_icall_System_Threading_Timer_GetTimeMonotonic (void)
9365 return mono_100ns_ticks ();
9368 gint64
9369 ves_icall_System_DateTime_GetSystemTimeAsFileTime (void)
9371 return mono_100ns_datetime ();
9375 ves_icall_System_Threading_Thread_SystemMaxStackSize (void)
9377 return mono_thread_info_get_system_max_stack_size ();
9380 MonoBoolean
9381 ves_icall_System_Threading_Thread_YieldInternal (void)
9383 mono_threads_platform_yield ();
9384 return TRUE;
9387 gint32
9388 ves_icall_System_Environment_get_ProcessorCount (void)
9390 return mono_cpu_count ();
9393 #if defined(ENABLE_MONODROID)
9395 G_EXTERN_C gpointer CreateNLSocket (void);
9396 G_EXTERN_C gint32 ReadEvents (gpointer sock, gpointer buffer, gint32 count, gint32 size);
9397 G_EXTERN_C gpointer CloseNLSocket (gpointer sock);
9399 gpointer
9400 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CreateNLSocket (void)
9402 return CreateNLSocket ();
9405 gint32
9406 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_ReadEvents (gpointer sock, gpointer buffer, gint32 count, gint32 size)
9408 return ReadEvents (sock, buffer, count, size);
9411 gpointer
9412 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CloseNLSocket (gpointer sock)
9414 return CloseNLSocket (sock);
9417 #endif
9419 // Generate wrappers.
9421 #define ICALL_TYPE(id,name,first) /* nothing */
9422 #define ICALL(id,name,func) /* nothing */
9423 #define NOHANDLES(inner) /* nothing */
9425 #define MONO_HANDLE_REGISTER_ICALL(func, ret, nargs, argtypes) MONO_HANDLE_REGISTER_ICALL_IMPLEMENT (func, ret, nargs, argtypes)
9427 // Some native functions are exposed via multiple managed names.
9428 // Producing a wrapper for these results in duplicate wrappers with the same names,
9429 // which fails to compile. Do not produce such duplicate wrappers. Alternatively,
9430 // a one line native function with a different name that calls the main one could be used.
9431 // i.e. the wrapper would also have a different name.
9432 #define HANDLES_REUSE_WRAPPER(...) /* nothing */
9434 #define HANDLES(id, name, func, ret, nargs, argtypes) \
9435 MONO_HANDLE_DECLARE (id, name, func, ret, nargs, argtypes); \
9436 MONO_HANDLE_IMPLEMENT (id, name, func, ret, nargs, argtypes)
9438 #include "metadata/icall-def.h"
9440 #undef HANDLES
9441 #undef HANDLES_REUSE_WRAPPER
9442 #undef ICALL_TYPE
9443 #undef ICALL
9444 #undef NOHANDLES
9445 #undef MONO_HANDLE_REGISTER_ICALL