[corlib] Simplify RuntimeInformation by getting OS name from the runtime (#13164)
[mono-project.git] / mono / metadata / icall.c
blobd8a37befd773d11bea85b3e217e73f03de4ff577
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>
18 #include <glib.h>
19 #include <stdarg.h>
20 #include <string.h>
21 #include <ctype.h>
22 #ifdef HAVE_ALLOCA_H
23 #include <alloca.h>
24 #endif
25 #ifdef HAVE_SYS_TIME_H
26 #include <sys/time.h>
27 #endif
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #if defined (HAVE_WCHAR_H)
32 #include <wchar.h>
33 #endif
34 #include "mono/metadata/icall-internals.h"
35 #include "mono/utils/mono-membar.h"
36 #include <mono/metadata/object.h>
37 #include <mono/metadata/threads.h>
38 #include <mono/metadata/threads-types.h>
39 #include <mono/metadata/threadpool.h>
40 #include <mono/metadata/threadpool-io.h>
41 #include <mono/metadata/monitor.h>
42 #include <mono/metadata/reflection.h>
43 #include <mono/metadata/image-internals.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/assembly-internals.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/exception.h>
48 #include <mono/metadata/exception-internals.h>
49 #include <mono/metadata/w32file.h>
50 #include <mono/metadata/console-io.h>
51 #include <mono/metadata/mono-route.h>
52 #include <mono/metadata/w32socket.h>
53 #include <mono/metadata/mono-endian.h>
54 #include <mono/metadata/tokentype.h>
55 #include <mono/metadata/metadata-internals.h>
56 #include <mono/metadata/class-internals.h>
57 #include <mono/metadata/class-init.h>
58 #include <mono/metadata/reflection-internals.h>
59 #include <mono/metadata/marshal.h>
60 #include <mono/metadata/gc-internals.h>
61 #include <mono/metadata/mono-gc.h>
62 #include <mono/metadata/rand.h>
63 #include <mono/metadata/appdomain-icalls.h>
64 #include <mono/metadata/string-icalls.h>
65 #include <mono/metadata/debug-helpers.h>
66 #include <mono/metadata/w32process.h>
67 #include <mono/metadata/environment.h>
68 #include <mono/metadata/profiler-private.h>
69 #include <mono/metadata/locales.h>
70 #include <mono/metadata/filewatcher.h>
71 #include <mono/metadata/security.h>
72 #include <mono/metadata/mono-config.h>
73 #include <mono/metadata/cil-coff.h>
74 #include <mono/metadata/number-formatter.h>
75 #include <mono/metadata/security-manager.h>
76 #include <mono/metadata/security-core-clr.h>
77 #include <mono/metadata/mono-perfcounters.h>
78 #include <mono/metadata/mono-debug.h>
79 #include <mono/metadata/mono-ptr-array.h>
80 #include <mono/metadata/verify-internals.h>
81 #include <mono/metadata/runtime.h>
82 #include <mono/metadata/file-mmap.h>
83 #include <mono/metadata/seq-points-data.h>
84 #include <mono/metadata/icall-table.h>
85 #include <mono/metadata/handle.h>
86 #include <mono/metadata/w32mutex.h>
87 #include <mono/metadata/w32semaphore.h>
88 #include <mono/metadata/w32event.h>
89 #include <mono/metadata/abi-details.h>
90 #include <mono/metadata/loader-internals.h>
91 #include <mono/utils/monobitset.h>
92 #include <mono/utils/mono-time.h>
93 #include <mono/utils/mono-proclib.h>
94 #include <mono/utils/mono-string.h>
95 #include <mono/utils/mono-error-internals.h>
96 #include <mono/utils/mono-mmap.h>
97 #include <mono/utils/mono-io-portability.h>
98 #include <mono/utils/mono-digest.h>
99 #include <mono/utils/bsearch.h>
100 #include <mono/utils/mono-os-mutex.h>
101 #include <mono/utils/mono-threads.h>
102 #include <mono/metadata/w32error.h>
103 #include <mono/utils/w32api.h>
104 #include <mono/utils/mono-merp.h>
105 #include <mono/utils/mono-state.h>
106 #include <mono/utils/mono-logger-internals.h>
107 #if !defined(HOST_WIN32) && defined(HAVE_SYS_UTSNAME_H)
108 #include <sys/utsname.h>
109 #endif
110 #include "icall-decl.h"
111 #include "mono/utils/mono-threads-coop.h"
113 //#define MONO_DEBUG_ICALLARRAY
115 #ifdef MONO_DEBUG_ICALLARRAY
117 static char debug_icallarray; // 0:uninitialized 1:true 2:false
119 static gboolean
120 icallarray_print_enabled (void)
122 if (!debug_icallarray)
123 debug_icallarray = MONO_TRACE_IS_TRACED (G_LOG_LEVEL_DEBUG, MONO_TRACE_ICALLARRAY) ? 1 : 2;
124 return debug_icallarray == 1;
127 static void
128 icallarray_print (const char *format, ...)
130 if (!icallarray_print_enabled ())
131 return;
132 va_list args;
133 va_start (args, format);
134 g_printv (format, args);
135 va_end (args);
138 #else
139 #define icallarray_print_enabled() (FALSE)
140 #define icallarray_print(...) /* nothing */
141 #endif
143 /* Lazy class loading functions */
144 static GENERATE_GET_CLASS_WITH_CACHE (module, "System.Reflection", "Module")
146 static void
147 array_set_value_impl (MonoArrayHandle arr, MonoObjectHandle value, guint32 pos, MonoError *error);
149 static MonoArrayHandle
150 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error);
152 static inline MonoBoolean
153 is_generic_parameter (MonoType *type)
155 return !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR);
158 #ifndef HOST_WIN32
159 static inline void
160 mono_icall_make_platform_path (gchar *path)
162 return;
165 static inline const gchar *
166 mono_icall_get_file_path_prefix (const gchar *path)
168 return "file://";
170 #endif /* HOST_WIN32 */
172 MonoObjectHandle
173 ves_icall_System_Array_GetValueImpl (MonoArrayHandle array, guint32 pos, MonoError *error)
175 MonoClass * const array_class = mono_handle_class (array);
176 MonoClass * const element_class = m_class_get_element_class (array_class);
178 if (m_class_is_valuetype (element_class)) {
179 gsize element_size = mono_array_element_size (array_class);
180 gpointer element_address = mono_array_addr_with_size_fast (MONO_HANDLE_RAW (array), element_size, (gsize)pos);
181 return mono_value_box_handle (MONO_HANDLE_DOMAIN (array), element_class, element_address, error);
183 MonoObjectHandle result = mono_new_null ();
184 mono_handle_array_getref (result, array, pos);
185 return result;
188 MonoObjectHandle
189 ves_icall_System_Array_GetValue (MonoArrayHandle arr, MonoArrayHandle indices, MonoError *error)
191 MONO_CHECK_ARG_NULL_HANDLE (indices, NULL_HANDLE);
193 MonoClass * const indices_class = mono_handle_class (indices);
194 MonoClass * const array_class = mono_handle_class (arr);
196 g_assert (m_class_get_rank (indices_class) == 1);
198 if (MONO_HANDLE_GETVAL (indices, bounds) || MONO_HANDLE_GETVAL (indices, max_length) != m_class_get_rank (array_class)) {
199 mono_error_set_argument (error, NULL, NULL);
200 return NULL_HANDLE;
203 gint32 index = 0;
205 if (!MONO_HANDLE_GETVAL (arr, bounds)) {
206 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, 0);
207 if (index < 0 || index >= MONO_HANDLE_GETVAL (arr, max_length)) {
208 mono_error_set_index_out_of_range (error);
209 return NULL_HANDLE;
212 return ves_icall_System_Array_GetValueImpl (arr, index, error);
215 for (gint32 i = 0; i < m_class_get_rank (array_class); i++) {
216 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, i);
217 if ((index < MONO_HANDLE_GETVAL (arr, bounds [i].lower_bound)) ||
218 (index >= (mono_array_lower_bound_t)MONO_HANDLE_GETVAL (arr, bounds [i].length) + MONO_HANDLE_GETVAL (arr, bounds [i].lower_bound))) {
219 mono_error_set_index_out_of_range (error);
220 return NULL_HANDLE;
224 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, 0);
225 gint32 pos = index - MONO_HANDLE_GETVAL (arr, bounds [0].lower_bound);
226 for (gint32 i = 1; i < m_class_get_rank (array_class); i++) {
227 MONO_HANDLE_ARRAY_GETVAL (index, indices, gint32, i);
228 pos = pos * MONO_HANDLE_GETVAL (arr, bounds [i].length) + index -
229 MONO_HANDLE_GETVAL (arr, bounds [i].lower_bound);
232 return ves_icall_System_Array_GetValueImpl (arr, pos, error);
235 void
236 ves_icall_System_Array_SetValueImpl (MonoArrayHandle arr, MonoObjectHandle value, guint32 pos, MonoError *error)
238 array_set_value_impl (arr, value, pos, error);
241 static void
242 array_set_value_impl (MonoArrayHandle arr, MonoObjectHandle value, guint32 pos, MonoError *error)
244 MonoClass *ac, *vc, *ec;
245 gint32 esize, vsize;
246 gpointer *ea, *va;
248 guint64 u64 = 0;
249 gint64 i64 = 0;
250 gdouble r64 = 0;
252 uint32_t arr_gchandle = 0;
253 uint32_t value_gchandle = 0;
255 error_init (error);
257 if (!MONO_HANDLE_IS_NULL (value))
258 vc = mono_handle_class (value);
259 else
260 vc = NULL;
262 ac = mono_handle_class (arr);
263 ec = m_class_get_element_class (ac);
265 esize = mono_array_element_size (ac);
266 ea = (gpointer*)mono_array_handle_pin_with_size (arr, esize, pos, &arr_gchandle);
268 if (mono_class_is_nullable (ec)) {
269 mono_nullable_init_from_handle ((guint8*)ea, value, ec);
270 goto leave;
273 if (MONO_HANDLE_IS_NULL (value)) {
274 mono_gc_bzero_atomic (ea, esize);
275 goto leave;
278 #define NO_WIDENING_CONVERSION G_STMT_START{ \
279 mono_error_set_argument (error, "value", "not a widening conversion"); \
280 goto leave; \
281 }G_STMT_END
283 #define CHECK_WIDENING_CONVERSION(extra) G_STMT_START{ \
284 if (esize < vsize + (extra)) { \
285 mono_error_set_argument (error, "value", "not a widening conversion"); \
286 goto leave; \
288 }G_STMT_END
290 #define INVALID_CAST G_STMT_START{ \
291 mono_get_runtime_callbacks ()->set_cast_details (vc, ec); \
292 mono_error_set_invalid_cast (error); \
293 goto leave; \
294 }G_STMT_END
296 MonoTypeEnum et;
297 et = m_class_get_byval_arg (ec)->type;
298 MonoTypeEnum vt;
299 vt = m_class_get_byval_arg (vc)->type;
300 /* Check element (destination) type. */
301 switch (et) {
302 case MONO_TYPE_STRING:
303 switch (vt) {
304 case MONO_TYPE_STRING:
305 break;
306 default:
307 INVALID_CAST;
309 break;
310 case MONO_TYPE_BOOLEAN:
311 switch (vt) {
312 case MONO_TYPE_BOOLEAN:
313 break;
314 case MONO_TYPE_CHAR:
315 case MONO_TYPE_U1:
316 case MONO_TYPE_U2:
317 case MONO_TYPE_U4:
318 case MONO_TYPE_U8:
319 case MONO_TYPE_I1:
320 case MONO_TYPE_I2:
321 case MONO_TYPE_I4:
322 case MONO_TYPE_I8:
323 case MONO_TYPE_R4:
324 case MONO_TYPE_R8:
325 NO_WIDENING_CONVERSION;
326 default:
327 INVALID_CAST;
329 break;
330 default:
331 break;
334 MonoObjectHandle inst;
335 inst = mono_object_handle_isinst (value, ec, error);
336 goto_if_nok (error, leave);
337 gboolean castOk;
338 castOk = !MONO_HANDLE_IS_NULL (inst);
340 if (!m_class_is_valuetype (ec)) {
341 if (!castOk)
342 INVALID_CAST;
343 MONO_HANDLE_ARRAY_SETREF (arr, pos, value);
344 goto leave;
347 if (castOk) {
348 va = (gpointer*)mono_object_handle_pin_unbox (value, &value_gchandle);
349 if (m_class_has_references (ec))
350 mono_value_copy_internal (ea, va, ec);
351 else
352 mono_gc_memmove_atomic (ea, va, esize);
353 goto leave;
356 if (!m_class_is_valuetype (vc))
357 INVALID_CAST;
359 va = (gpointer*)mono_object_handle_pin_unbox (value, &value_gchandle);
361 vsize = mono_class_value_size (vc, NULL);
363 if (et == MONO_TYPE_VALUETYPE && m_class_is_enumtype (m_class_get_byval_arg (ec)->data.klass))
364 et = mono_class_enum_basetype_internal (m_class_get_byval_arg (ec)->data.klass)->type;
366 if (vt == MONO_TYPE_VALUETYPE && m_class_is_enumtype (m_class_get_byval_arg (vc)->data.klass))
367 vt = mono_class_enum_basetype_internal (m_class_get_byval_arg (vc)->data.klass)->type;
369 #define ASSIGN_UNSIGNED(etype) G_STMT_START{\
370 switch (vt) { \
371 case MONO_TYPE_U1: \
372 case MONO_TYPE_U2: \
373 case MONO_TYPE_U4: \
374 case MONO_TYPE_U8: \
375 case MONO_TYPE_CHAR: \
376 CHECK_WIDENING_CONVERSION(0); \
377 *(etype *) ea = (etype) u64; \
378 goto leave; \
379 /* You can't assign a signed value to an unsigned array. */ \
380 case MONO_TYPE_I1: \
381 case MONO_TYPE_I2: \
382 case MONO_TYPE_I4: \
383 case MONO_TYPE_I8: \
384 /* You can't assign a floating point number to an integer array. */ \
385 case MONO_TYPE_R4: \
386 case MONO_TYPE_R8: \
387 NO_WIDENING_CONVERSION; \
389 }G_STMT_END
391 #define ASSIGN_SIGNED(etype) G_STMT_START{\
392 switch (vt) { \
393 case MONO_TYPE_I1: \
394 case MONO_TYPE_I2: \
395 case MONO_TYPE_I4: \
396 case MONO_TYPE_I8: \
397 CHECK_WIDENING_CONVERSION(0); \
398 *(etype *) ea = (etype) i64; \
399 goto leave; \
400 /* You can assign an unsigned value to a signed array if the array's */ \
401 /* element size is larger than the value size. */ \
402 case MONO_TYPE_U1: \
403 case MONO_TYPE_U2: \
404 case MONO_TYPE_U4: \
405 case MONO_TYPE_U8: \
406 case MONO_TYPE_CHAR: \
407 CHECK_WIDENING_CONVERSION(1); \
408 *(etype *) ea = (etype) u64; \
409 goto leave; \
410 /* You can't assign a floating point number to an integer array. */ \
411 case MONO_TYPE_R4: \
412 case MONO_TYPE_R8: \
413 NO_WIDENING_CONVERSION; \
415 }G_STMT_END
417 #define ASSIGN_REAL(etype) G_STMT_START{\
418 switch (vt) { \
419 case MONO_TYPE_R4: \
420 case MONO_TYPE_R8: \
421 CHECK_WIDENING_CONVERSION(0); \
422 *(etype *) ea = (etype) r64; \
423 goto leave; \
424 /* All integer values fit into a floating point array, so we don't */ \
425 /* need to CHECK_WIDENING_CONVERSION here. */ \
426 case MONO_TYPE_I1: \
427 case MONO_TYPE_I2: \
428 case MONO_TYPE_I4: \
429 case MONO_TYPE_I8: \
430 *(etype *) ea = (etype) i64; \
431 goto leave; \
432 case MONO_TYPE_U1: \
433 case MONO_TYPE_U2: \
434 case MONO_TYPE_U4: \
435 case MONO_TYPE_U8: \
436 case MONO_TYPE_CHAR: \
437 *(etype *) ea = (etype) u64; \
438 goto leave; \
440 }G_STMT_END
442 switch (vt) {
443 case MONO_TYPE_U1:
444 u64 = *(guint8 *) va;
445 break;
446 case MONO_TYPE_U2:
447 u64 = *(guint16 *) va;
448 break;
449 case MONO_TYPE_U4:
450 u64 = *(guint32 *) va;
451 break;
452 case MONO_TYPE_U8:
453 u64 = *(guint64 *) va;
454 break;
455 case MONO_TYPE_I1:
456 i64 = *(gint8 *) va;
457 break;
458 case MONO_TYPE_I2:
459 i64 = *(gint16 *) va;
460 break;
461 case MONO_TYPE_I4:
462 i64 = *(gint32 *) va;
463 break;
464 case MONO_TYPE_I8:
465 i64 = *(gint64 *) va;
466 break;
467 case MONO_TYPE_R4:
468 r64 = *(gfloat *) va;
469 break;
470 case MONO_TYPE_R8:
471 r64 = *(gdouble *) va;
472 break;
473 case MONO_TYPE_CHAR:
474 u64 = *(guint16 *) va;
475 break;
476 case MONO_TYPE_BOOLEAN:
477 /* Boolean is only compatible with itself. */
478 switch (et) {
479 case MONO_TYPE_CHAR:
480 case MONO_TYPE_U1:
481 case MONO_TYPE_U2:
482 case MONO_TYPE_U4:
483 case MONO_TYPE_U8:
484 case MONO_TYPE_I1:
485 case MONO_TYPE_I2:
486 case MONO_TYPE_I4:
487 case MONO_TYPE_I8:
488 case MONO_TYPE_R4:
489 case MONO_TYPE_R8:
490 NO_WIDENING_CONVERSION;
491 default:
492 INVALID_CAST;
494 break;
497 /* If we can't do a direct copy, let's try a widening conversion. */
498 switch (et) {
499 case MONO_TYPE_CHAR:
500 ASSIGN_UNSIGNED (guint16);
501 case MONO_TYPE_U1:
502 ASSIGN_UNSIGNED (guint8);
503 case MONO_TYPE_U2:
504 ASSIGN_UNSIGNED (guint16);
505 case MONO_TYPE_U4:
506 ASSIGN_UNSIGNED (guint32);
507 case MONO_TYPE_U8:
508 ASSIGN_UNSIGNED (guint64);
509 case MONO_TYPE_I1:
510 ASSIGN_SIGNED (gint8);
511 case MONO_TYPE_I2:
512 ASSIGN_SIGNED (gint16);
513 case MONO_TYPE_I4:
514 ASSIGN_SIGNED (gint32);
515 case MONO_TYPE_I8:
516 ASSIGN_SIGNED (gint64);
517 case MONO_TYPE_R4:
518 ASSIGN_REAL (gfloat);
519 case MONO_TYPE_R8:
520 ASSIGN_REAL (gdouble);
523 INVALID_CAST;
524 /* Not reached, INVALID_CAST does fall thru. */
525 g_assert_not_reached ();
527 #undef INVALID_CAST
528 #undef NO_WIDENING_CONVERSION
529 #undef CHECK_WIDENING_CONVERSION
530 #undef ASSIGN_UNSIGNED
531 #undef ASSIGN_SIGNED
532 #undef ASSIGN_REAL
533 leave:
534 mono_gchandle_free_internal (arr_gchandle);
535 mono_gchandle_free_internal (value_gchandle);
536 return;
539 void
540 ves_icall_System_Array_SetValue (MonoArrayHandle arr, MonoObjectHandle value,
541 MonoArrayHandle idxs, MonoError *error)
543 icallarray_print ("%s\n", __func__);
545 MonoArrayBounds dim;
546 MonoClass *ac, *ic;
547 gint32 idx;
548 gint32 i, pos;
550 error_init (error);
552 if (MONO_HANDLE_IS_NULL (idxs)) {
553 mono_error_set_argument_null (error, "idxs", "");
554 return;
557 ic = mono_handle_class (idxs);
558 ac = mono_handle_class (arr);
560 g_assert (m_class_get_rank (ic) == 1);
561 if (mono_handle_array_has_bounds (idxs) || MONO_HANDLE_GETVAL (idxs, max_length) != m_class_get_rank (ac)) {
562 mono_error_set_argument (error, "idxs", "");
563 return;
566 if (!mono_handle_array_has_bounds (arr)) {
567 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, 0);
568 if (idx < 0 || idx >= MONO_HANDLE_GETVAL (arr, max_length)) {
569 mono_error_set_exception_instance (error, mono_get_exception_index_out_of_range ());
570 return;
573 array_set_value_impl (arr, value, idx, error);
574 return;
577 gint32 ac_rank = m_class_get_rank (ac);
578 for (i = 0; i < ac_rank; i++) {
579 mono_handle_array_get_bounds_dim (arr, i, &dim);
580 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, i);
581 if ((idx < dim.lower_bound) ||
582 (idx >= (mono_array_lower_bound_t)dim.length + dim.lower_bound)) {
583 mono_error_set_exception_instance (error, mono_get_exception_index_out_of_range ());
584 return;
588 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, 0);
589 mono_handle_array_get_bounds_dim (arr, 0, &dim);
590 pos = idx - dim.lower_bound;
591 for (i = 1; i < ac_rank; i++) {
592 mono_handle_array_get_bounds_dim (arr, i, &dim);
593 MONO_HANDLE_ARRAY_GETVAL (idx, idxs, gint32, i);
594 pos = pos * dim.length + idx - dim.lower_bound;
597 array_set_value_impl (arr, value, pos, error);
600 MonoArrayHandle
601 ves_icall_System_Array_CreateInstanceImpl (MonoReflectionTypeHandle type, MonoArrayHandle lengths, MonoArrayHandle bounds, MonoError *error)
603 // FIXME? fixed could be used for lengths, bounds.
605 icallarray_print ("%s type:%p length:%p bounds:%p\n", __func__, type, lengths, bounds);
607 MONO_CHECK_ARG_NULL_HANDLE (type, NULL_HANDLE_ARRAY);
608 MONO_CHECK_ARG_NULL_HANDLE (lengths, NULL_HANDLE_ARRAY);
610 MONO_CHECK_ARG (lengths, mono_array_handle_length (lengths) > 0, NULL_HANDLE_ARRAY);
611 if (!MONO_HANDLE_IS_NULL (bounds))
612 MONO_CHECK_ARG (bounds, mono_array_handle_length (lengths) == mono_array_handle_length (bounds), NULL_HANDLE_ARRAY);
614 for (uintptr_t i = 0; i < mono_array_handle_length (lengths); ++i) {
615 gint32 length = 0;
616 MONO_HANDLE_ARRAY_GETVAL (length, lengths, gint32, i);
617 if (length < 0) {
618 mono_error_set_argument_out_of_range (error, NULL);
619 return NULL_HANDLE_ARRAY;
623 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
624 if (!mono_class_init_checked (klass, error))
625 return NULL_HANDLE_ARRAY;
627 if (m_class_get_byval_arg (m_class_get_element_class (klass))->type == MONO_TYPE_VOID) {
628 mono_error_set_not_supported (error, "Arrays of System.Void are not supported.");
629 return NULL_HANDLE_ARRAY;
632 /* vectors are not the same as one dimensional arrays with non-zero bounds */
633 gboolean bounded = FALSE;
634 if (!MONO_HANDLE_IS_NULL (bounds) && mono_array_handle_length (bounds) == 1) {
635 gint32 bound0 = 0;
636 MONO_HANDLE_ARRAY_GETVAL (bound0, bounds, gint32, 0);
637 bounded = bound0 != 0;
640 MonoClass * const aklass = mono_class_create_bounded_array (klass, mono_array_handle_length (lengths), bounded);
641 uintptr_t const aklass_rank = m_class_get_rank (aklass);
642 uintptr_t * const sizes = g_newa (uintptr_t, aklass_rank);
643 intptr_t * const lower_bounds = g_newa (intptr_t, aklass_rank);
645 // Copy lengths and lower_bounds from gint32 to [u]intptr_t.
647 for (uintptr_t i = 0; i < aklass_rank; ++i) {
648 MONO_HANDLE_ARRAY_GETVAL (sizes [i], lengths, gint32, i);
649 if (!MONO_HANDLE_IS_NULL (bounds))
650 MONO_HANDLE_ARRAY_GETVAL (lower_bounds [i], bounds, gint32, i);
651 else
652 lower_bounds [i] = 0;
655 return mono_array_new_full_handle (MONO_HANDLE_DOMAIN (type), aklass, sizes, lower_bounds, error);
658 gint32
659 ves_icall_System_Array_GetRank (MonoObjectHandle arr, MonoError *error)
661 gint32 const result = m_class_get_rank (mono_handle_class (arr));
663 icallarray_print ("%s arr:%p res:%d\n", __func__, MONO_HANDLE_RAW (arr), result);
665 return result;
668 static mono_array_size_t
669 mono_array_get_length (MonoArrayHandle arr, gint32 dimension, MonoError *error)
671 if (dimension < 0 || dimension >= m_class_get_rank (mono_handle_class (arr))) {
672 mono_error_set_index_out_of_range (error);
673 return 0;
676 return MONO_HANDLE_GETVAL (arr, bounds) ? MONO_HANDLE_GETVAL (arr, bounds [dimension].length)
677 : MONO_HANDLE_GETVAL (arr, max_length);
680 gint32
681 ves_icall_System_Array_GetLength (MonoArrayHandle arr, gint32 dimension, MonoError *error)
683 icallarray_print ("%s arr:%p dimension:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)dimension);
685 mono_array_size_t const length = mono_array_get_length (arr, dimension, error);
686 if (length > G_MAXINT32) {
687 mono_error_set_overflow (error);
688 return 0;
690 return (gint32)length;
693 gint64
694 ves_icall_System_Array_GetLongLength (MonoArrayHandle arr, gint32 dimension, MonoError *error)
696 icallarray_print ("%s arr:%p dimension:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)dimension);
698 return (gint64)mono_array_get_length (arr, dimension, error);
701 gint32
702 ves_icall_System_Array_GetLowerBound (MonoArrayHandle arr, gint32 dimension, MonoError *error)
704 icallarray_print ("%s arr:%p dimension:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)dimension);
706 if (dimension < 0 || dimension >= m_class_get_rank (mono_handle_class (arr))) {
707 mono_error_set_index_out_of_range (error);
708 return 0;
711 return MONO_HANDLE_GETVAL (arr, bounds) ? MONO_HANDLE_GETVAL (arr, bounds [dimension].lower_bound)
712 : 0;
715 void
716 ves_icall_System_Array_ClearInternal (MonoArrayHandle arr, int idx, int length, MonoError *error)
718 icallarray_print ("%s arr:%p idx:%d len:%d\n", __func__, MONO_HANDLE_RAW (arr), (int)idx, (int)length);
720 int sz = mono_array_element_size (mono_handle_class (arr));
721 mono_gc_bzero_atomic (mono_array_addr_with_size_fast (MONO_HANDLE_RAW (arr), sz, idx), length * sz);
724 MonoBoolean
725 ves_icall_System_Array_FastCopy (MonoArrayHandle source, int source_idx, MonoArrayHandle dest, int dest_idx, int length, MonoError *error)
727 MonoVTable * const src_vtable = MONO_HANDLE_GETVAL (source, obj.vtable);
728 MonoVTable * const dest_vtable = MONO_HANDLE_GETVAL (dest, obj.vtable);
730 if (src_vtable->rank != dest_vtable->rank)
731 return FALSE;
733 MonoArrayBounds *source_bounds = MONO_HANDLE_GETVAL (source, bounds);
734 MonoArrayBounds *dest_bounds = MONO_HANDLE_GETVAL (dest, bounds);
736 for (int i = 0; i < src_vtable->rank; i++) {
737 if ((source_bounds && source_bounds [i].lower_bound > 0) ||
738 (dest_bounds && dest_bounds [i].lower_bound > 0))
739 return FALSE;
742 /* there's no integer overflow since mono_array_length_internal returns an unsigned integer */
743 if ((dest_idx + length > mono_array_handle_length (dest)) ||
744 (source_idx + length > mono_array_handle_length (source)))
745 return FALSE;
747 MonoClass * const src_class = m_class_get_element_class (src_vtable->klass);
748 MonoClass * const dest_class = m_class_get_element_class (dest_vtable->klass);
751 * Handle common cases.
754 /* Case1: object[] -> valuetype[] (ArrayList::ToArray)
755 We fallback to managed here since we need to typecheck each boxed valuetype before storing them in the dest array.
757 if (src_class == mono_defaults.object_class && m_class_is_valuetype (dest_class))
758 return FALSE;
760 /* Check if we're copying a char[] <==> (u)short[] */
761 if (src_class != dest_class) {
762 if (m_class_is_valuetype (dest_class) || m_class_is_enumtype (dest_class) ||
763 m_class_is_valuetype (src_class) || m_class_is_valuetype (src_class))
764 return FALSE;
766 /* 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. */
767 if (!mono_class_is_subclass_of (src_class, dest_class, FALSE))
768 return FALSE;
771 if (m_class_is_valuetype (dest_class)) {
772 gsize const element_size = mono_array_element_size (MONO_HANDLE_GETVAL (source, obj.vtable->klass));
774 MONO_ENTER_NO_SAFEPOINTS; // gchandle would also work here, is slow, breaks profiler tests.
776 gconstpointer const source_addr =
777 mono_array_addr_with_size_fast (MONO_HANDLE_RAW (source), element_size, source_idx);
778 if (m_class_has_references (dest_class)) {
779 mono_value_copy_array_handle (dest, dest_idx, source_addr, length);
780 } else {
781 gpointer const dest_addr =
782 mono_array_addr_with_size_fast (MONO_HANDLE_RAW (dest), element_size, dest_idx);
783 mono_gc_memmove_atomic (dest_addr, source_addr, element_size * length);
786 MONO_EXIT_NO_SAFEPOINTS;
788 } else {
789 mono_array_handle_memcpy_refs (dest, dest_idx, source, source_idx, length);
792 return TRUE;
795 void
796 ves_icall_System_Array_GetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
798 // FIXME?
799 // Generic ref/out parameters are not supported by HANDLES(), so NOHANDLES().
801 icallarray_print ("%s arr:%p pos:%u value:%p\n", __func__, arr, pos, value);
803 MONO_REQ_GC_UNSAFE_MODE; // because of gpointer value
805 MonoClass * const ac = mono_object_class (arr);
806 gsize const esize = mono_array_element_size (ac);
807 gconstpointer * const ea = (gconstpointer*)((char*)arr->vector + (pos * esize));
809 mono_gc_memmove_atomic (value, ea, esize);
812 void
813 ves_icall_System_Array_SetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
815 // FIXME?
816 // Generic ref/out parameters are not supported by HANDLES(), so NOHANDLES().
818 icallarray_print ("%s arr:%p pos:%u value:%p\n", __func__, arr, pos, value);
820 MONO_REQ_GC_UNSAFE_MODE; // because of gpointer value
823 MonoClass * const ac = mono_object_class (arr);
824 MonoClass * const ec = m_class_get_element_class (ac);
826 gsize const esize = mono_array_element_size (ac);
827 gpointer * const ea = (gpointer*)((char*)arr->vector + (pos * esize));
829 if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (ec))) {
830 g_assert (esize == sizeof (gpointer));
831 mono_gc_wbarrier_generic_store_internal (ea, *(MonoObject **)value);
832 } else {
833 g_assert (m_class_is_inited (ec));
834 g_assert (esize == mono_class_value_size (ec, NULL));
835 if (m_class_has_references (ec))
836 mono_gc_wbarrier_value_copy_internal (ea, value, 1, ec);
837 else
838 mono_gc_memmove_atomic (ea, value, esize);
842 void
843 ves_icall_System_Runtime_RuntimeImports_Memmove (guint8 *destination, guint8 *source, guint byte_count)
845 mono_gc_memmove_atomic (destination, source, byte_count);
848 void
849 ves_icall_System_Runtime_RuntimeImports_Memmove_wbarrier (guint8 *destination, guint8 *source, guint len, MonoType *type)
851 if (MONO_TYPE_IS_REFERENCE (type))
852 mono_gc_wbarrier_arrayref_copy_internal (destination, source, len);
853 else
854 mono_gc_wbarrier_value_copy_internal (destination, source, len, mono_class_from_mono_type_internal (type));
857 void
858 ves_icall_System_Runtime_RuntimeImports_ZeroMemory (guint8 *p, guint byte_length)
860 memset (p, 0, byte_length);
863 void
864 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArrayHandle array, MonoClassField *field_handle, MonoError *error)
866 MonoClass *klass = mono_handle_class (array);
867 guint32 size = mono_array_element_size (klass);
868 MonoType *type = mono_type_get_underlying_type (m_class_get_byval_arg (m_class_get_element_class (klass)));
869 int align;
870 const char *field_data;
872 if (MONO_TYPE_IS_REFERENCE (type) || type->type == MONO_TYPE_VALUETYPE) {
873 mono_error_set_argument (error, "array", "Cannot initialize array of non-primitive type");
874 return;
877 MonoType *field_type = mono_field_get_type_checked (field_handle, error);
878 if (!field_type)
879 return;
881 if (!(field_type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
882 mono_error_set_argument_format (error, "field_handle", "Field '%s' doesn't have an RVA", mono_field_get_name (field_handle));
883 return;
886 size *= MONO_HANDLE_GETVAL(array, max_length);
887 field_data = mono_field_get_data (field_handle);
889 if (size > mono_type_size (field_handle->type, &align)) {
890 mono_error_set_argument (error, "field_handle", "Field not large enough to fill array");
891 return;
894 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
895 #define SWAP(n) { \
896 guint ## n *data = (guint ## n *) mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0); \
897 guint ## n *src = (guint ## n *) field_data; \
898 int i, \
899 nEnt = (size / sizeof(guint ## n)); \
901 for (i = 0; i < nEnt; i++) { \
902 data[i] = read ## n (&src[i]); \
906 /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
908 switch (type->type) {
909 case MONO_TYPE_CHAR:
910 case MONO_TYPE_I2:
911 case MONO_TYPE_U2:
912 SWAP (16);
913 break;
914 case MONO_TYPE_I4:
915 case MONO_TYPE_U4:
916 case MONO_TYPE_R4:
917 SWAP (32);
918 break;
919 case MONO_TYPE_I8:
920 case MONO_TYPE_U8:
921 case MONO_TYPE_R8:
922 SWAP (64);
923 break;
924 default:
925 memcpy (mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0), field_data, size);
926 break;
928 #else
929 memcpy (mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0), field_data, size);
930 #endif
933 gint
934 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
936 return offsetof (MonoString, chars);
939 MonoObjectHandle
940 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObjectHandle obj, MonoError *error)
942 if (MONO_HANDLE_IS_NULL (obj) || !m_class_is_valuetype (mono_handle_class (obj)))
943 return obj;
945 return mono_object_clone_handle (obj, error);
948 void
949 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle, MonoError *error)
951 MonoClass *klass;
952 MonoVTable *vtable;
954 MONO_CHECK_ARG_NULL (handle,);
956 klass = mono_class_from_mono_type_internal (handle);
957 MONO_CHECK_ARG (handle, klass,);
959 if (mono_class_is_gtd (klass))
960 return;
962 vtable = mono_class_vtable_checked (mono_domain_get (), klass, error);
963 return_if_nok (error);
965 /* This will call the type constructor */
966 mono_runtime_class_init_full (vtable, error);
969 void
970 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (MonoImage *image, MonoError *error)
972 mono_image_check_for_module_cctor (image);
973 if (!image->has_module_cctor)
974 return;
976 MonoClass *module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, error);
977 return_if_nok (error);
979 MonoVTable * vtable = mono_class_vtable_checked (mono_domain_get (), module_klass, error);
980 return_if_nok (error);
982 mono_runtime_class_init_full (vtable, error);
985 MonoBoolean
986 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
988 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
989 // It does not work on win32
990 #elif defined(TARGET_ANDROID) || defined(__linux__)
991 // No need for now
992 #else
993 guint8 *stack_addr;
994 guint8 *current;
995 size_t stack_size;
996 int min_size;
997 MonoInternalThread *thread;
999 mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
1000 /* if we have no info we are optimistic and assume there is enough room */
1001 if (!stack_addr)
1002 return TRUE;
1004 thread = mono_thread_internal_current ();
1005 // .net seems to check that at least 50% of stack is available
1006 min_size = thread->stack_size / 2;
1008 // TODO: It's not always set
1009 if (!min_size)
1010 return TRUE;
1012 current = (guint8 *)&stack_addr;
1013 if (current > stack_addr) {
1014 if ((current - stack_addr) < min_size)
1015 return FALSE;
1016 } else {
1017 if (current - (stack_addr - stack_size) < min_size)
1018 return FALSE;
1020 #endif
1021 return TRUE;
1024 MonoObjectHandle
1025 ves_icall_System_Object_MemberwiseClone (MonoObjectHandle this_obj, MonoError *error)
1027 return mono_object_clone_handle (this_obj, error);
1030 gint32
1031 ves_icall_System_ValueType_InternalGetHashCode (MonoObject *this_obj, MonoArray **fields)
1033 ERROR_DECL (error);
1034 MonoClass *klass;
1035 MonoObject **values = NULL;
1036 MonoObject *o;
1037 int count = 0;
1038 gint32 result = (int)(gsize)mono_defaults.int32_class;
1039 MonoClassField* field;
1040 gpointer iter;
1042 klass = mono_object_class (this_obj);
1044 if (mono_class_num_fields (klass) == 0)
1045 return result;
1048 * Compute the starting value of the hashcode for fields of primitive
1049 * types, and return the remaining fields in an array to the managed side.
1050 * This way, we can avoid costly reflection operations in managed code.
1052 iter = NULL;
1053 while ((field = mono_class_get_fields_internal (klass, &iter))) {
1054 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1055 continue;
1056 if (mono_field_is_deleted (field))
1057 continue;
1058 /* FIXME: Add more types */
1059 switch (field->type->type) {
1060 case MONO_TYPE_I4:
1061 result ^= *(gint32*)((guint8*)this_obj + field->offset);
1062 break;
1063 case MONO_TYPE_PTR:
1064 result ^= mono_aligned_addr_hash (*(gpointer*)((guint8*)this_obj + field->offset));
1065 break;
1066 case MONO_TYPE_STRING: {
1067 MonoString *s;
1068 s = *(MonoString**)((guint8*)this_obj + field->offset);
1069 if (s != NULL)
1070 result ^= mono_string_hash_internal (s);
1071 break;
1073 default:
1074 if (!values)
1075 values = g_newa (MonoObject*, mono_class_num_fields (klass));
1076 o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, this_obj, error);
1077 if (!is_ok (error)) {
1078 mono_error_set_pending_exception (error);
1079 return 0;
1081 values [count++] = o;
1085 if (values) {
1086 int i;
1087 MonoArray *fields_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.object_class, count, error);
1088 if (mono_error_set_pending_exception (error))
1089 return 0;
1090 mono_gc_wbarrier_generic_store_internal (fields, (MonoObject*) fields_arr);
1091 for (i = 0; i < count; ++i)
1092 mono_array_setref_internal (*fields, i, values [i]);
1093 } else {
1094 *fields = NULL;
1096 return result;
1099 MonoBoolean
1100 ves_icall_System_ValueType_Equals (MonoObject *this_obj, MonoObject *that, MonoArray **fields)
1102 ERROR_DECL (error);
1103 MonoClass *klass;
1104 MonoObject **values = NULL;
1105 MonoObject *o;
1106 MonoClassField* field;
1107 gpointer iter;
1108 int count = 0;
1110 *fields = NULL;
1112 MONO_CHECK_ARG_NULL (that, FALSE);
1114 if (this_obj->vtable != that->vtable)
1115 return FALSE;
1117 klass = mono_object_class (this_obj);
1119 if (m_class_is_enumtype (klass) && mono_class_enum_basetype_internal (klass) && mono_class_enum_basetype_internal (klass)->type == MONO_TYPE_I4)
1120 return *(gint32*)mono_object_get_data (this_obj) == *(gint32*)mono_object_get_data (that);
1123 * Do the comparison for fields of primitive type and return a result if
1124 * possible. Otherwise, return the remaining fields in an array to the
1125 * managed side. This way, we can avoid costly reflection operations in
1126 * managed code.
1128 iter = NULL;
1129 while ((field = mono_class_get_fields_internal (klass, &iter))) {
1130 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1131 continue;
1132 if (mono_field_is_deleted (field))
1133 continue;
1134 guint8 *this_field = (guint8 *) this_obj + field->offset;
1135 guint8 *that_field = (guint8 *) that + field->offset;
1137 #define UNALIGNED_COMPARE(type) \
1138 do { \
1139 type left, right; \
1140 memcpy (&left, this_field, sizeof (type)); \
1141 memcpy (&right, that_field, sizeof (type)); \
1142 if (left != right) \
1143 return FALSE; \
1144 } while (0)
1146 /* FIXME: Add more types */
1147 switch (field->type->type) {
1148 case MONO_TYPE_U1:
1149 case MONO_TYPE_I1:
1150 case MONO_TYPE_BOOLEAN:
1151 if (*this_field != *that_field)
1152 return FALSE;
1153 break;
1154 case MONO_TYPE_U2:
1155 case MONO_TYPE_I2:
1156 case MONO_TYPE_CHAR:
1157 #ifdef NO_UNALIGNED_ACCESS
1158 if (G_UNLIKELY ((intptr_t) this_field & 1 || (intptr_t) that_field & 1))
1159 UNALIGNED_COMPARE (gint16);
1160 else
1161 #endif
1162 if (*(gint16 *) this_field != *(gint16 *) that_field)
1163 return FALSE;
1164 break;
1165 case MONO_TYPE_U4:
1166 case MONO_TYPE_I4:
1167 #ifdef NO_UNALIGNED_ACCESS
1168 if (G_UNLIKELY ((intptr_t) this_field & 3 || (intptr_t) that_field & 3))
1169 UNALIGNED_COMPARE (gint32);
1170 else
1171 #endif
1172 if (*(gint32 *) this_field != *(gint32 *) that_field)
1173 return FALSE;
1174 break;
1175 case MONO_TYPE_U8:
1176 case MONO_TYPE_I8:
1177 #ifdef NO_UNALIGNED_ACCESS
1178 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1179 UNALIGNED_COMPARE (gint64);
1180 else
1181 #endif
1182 if (*(gint64 *) this_field != *(gint64 *) that_field)
1183 return FALSE;
1184 break;
1186 case MONO_TYPE_R4:
1187 #ifdef NO_UNALIGNED_ACCESS
1188 if (G_UNLIKELY ((intptr_t) this_field & 3 || (intptr_t) that_field & 3))
1189 UNALIGNED_COMPARE (float);
1190 else
1191 #endif
1192 if (*(float *) this_field != *(float *) that_field)
1193 return FALSE;
1194 break;
1195 case MONO_TYPE_R8:
1196 #ifdef NO_UNALIGNED_ACCESS
1197 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1198 UNALIGNED_COMPARE (double);
1199 else
1200 #endif
1201 if (*(double *) this_field != *(double *) that_field)
1202 return FALSE;
1203 break;
1204 case MONO_TYPE_PTR:
1205 #ifdef NO_UNALIGNED_ACCESS
1206 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1207 UNALIGNED_COMPARE (gpointer);
1208 else
1209 #endif
1210 if (*(gpointer *) this_field != *(gpointer *) that_field)
1211 return FALSE;
1212 break;
1213 case MONO_TYPE_STRING: {
1214 MonoString *s1, *s2;
1215 guint32 s1len, s2len;
1216 s1 = *(MonoString**)((guint8*)this_obj + field->offset);
1217 s2 = *(MonoString**)((guint8*)that + field->offset);
1218 if (s1 == s2)
1219 break;
1220 if ((s1 == NULL) || (s2 == NULL))
1221 return FALSE;
1222 s1len = mono_string_length_internal (s1);
1223 s2len = mono_string_length_internal (s2);
1224 if (s1len != s2len)
1225 return FALSE;
1227 if (memcmp (mono_string_chars_internal (s1), mono_string_chars_internal (s2), s1len * sizeof (gunichar2)) != 0)
1228 return FALSE;
1229 break;
1231 default:
1232 if (!values)
1233 values = g_newa (MonoObject*, mono_class_num_fields (klass) * 2);
1234 o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, this_obj, error);
1235 if (!is_ok (error)) {
1236 mono_error_set_pending_exception (error);
1237 return FALSE;
1239 values [count++] = o;
1240 o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, that, error);
1241 if (!is_ok (error)) {
1242 mono_error_set_pending_exception (error);
1243 return FALSE;
1245 values [count++] = o;
1248 #undef UNALIGNED_COMPARE
1250 if (m_class_is_enumtype (klass))
1251 /* enums only have one non-static field */
1252 break;
1255 if (values) {
1256 int i;
1257 MonoArray *fields_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.object_class, count, error);
1258 if (mono_error_set_pending_exception (error))
1259 return FALSE;
1260 mono_gc_wbarrier_generic_store_internal (fields, (MonoObject*) fields_arr);
1261 for (i = 0; i < count; ++i)
1262 mono_array_setref_fast (*fields, i, values [i]);
1263 return FALSE;
1264 } else {
1265 return TRUE;
1269 MonoReflectionTypeHandle
1270 ves_icall_System_Object_GetType (MonoObjectHandle obj, MonoError *error)
1272 MonoDomain *domain = MONO_HANDLE_DOMAIN (obj);
1273 MonoClass *klass = mono_handle_class (obj);
1274 #ifndef DISABLE_REMOTING
1275 if (mono_class_is_transparent_proxy (klass)) {
1276 MonoTransparentProxyHandle proxy_obj = MONO_HANDLE_CAST (MonoTransparentProxy, obj);
1277 MonoRemoteClass *remote_class = MONO_HANDLE_GETVAL (proxy_obj, remote_class);
1278 /* If it's a transparent proxy for an interface, return the
1279 * interface type, not the unhelpful proxy_class class (which
1280 * is just MarshalByRefObject). */
1281 MonoType *proxy_type =
1282 mono_remote_class_is_interface_proxy (remote_class) ?
1283 m_class_get_byval_arg (remote_class->interfaces[0]) :
1284 m_class_get_byval_arg (remote_class->proxy_class);
1285 return mono_type_get_object_handle (domain, proxy_type, error);
1286 } else
1287 #endif
1288 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
1291 static gboolean
1292 get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1294 MonoMethod **dest = (MonoMethod **)data;
1296 /* skip unmanaged frames */
1297 if (!managed)
1298 return FALSE;
1300 if (!(*dest)) {
1301 if (!strcmp (m_class_get_name_space (m->klass), "System.Reflection"))
1302 return FALSE;
1303 *dest = m;
1304 return TRUE;
1306 return FALSE;
1309 static gboolean
1310 in_corlib_name_space (MonoClass *klass, const char *name_space)
1312 return m_class_get_image (klass) == mono_defaults.corlib &&
1313 !strcmp (m_class_get_name_space (klass), name_space);
1316 static gboolean
1317 get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1319 MonoMethod **dest = (MonoMethod **)data;
1321 /* skip unmanaged frames */
1322 if (!managed)
1323 return FALSE;
1325 if (m->wrapper_type != MONO_WRAPPER_NONE)
1326 return FALSE;
1328 if (m == *dest) {
1329 *dest = NULL;
1330 return FALSE;
1333 if (in_corlib_name_space (m->klass, "System.Reflection"))
1334 return FALSE;
1336 if (!(*dest)) {
1337 *dest = m;
1338 return TRUE;
1340 return FALSE;
1343 static gboolean
1344 get_caller_no_system_or_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1346 MonoMethod **dest = (MonoMethod **)data;
1348 /* skip unmanaged frames */
1349 if (!managed)
1350 return FALSE;
1352 if (m->wrapper_type != MONO_WRAPPER_NONE)
1353 return FALSE;
1355 if (m == *dest) {
1356 *dest = NULL;
1357 return FALSE;
1360 if (in_corlib_name_space (m->klass, "System.Reflection") || in_corlib_name_space (m->klass, "System"))
1361 return FALSE;
1363 if (!(*dest)) {
1364 *dest = m;
1365 return TRUE;
1367 return FALSE;
1371 * mono_runtime_get_caller_no_system_or_reflection:
1373 * Walk the stack of the current thread and find the first managed method that
1374 * is not in the mscorlib System or System.Reflection namespace. This skips
1375 * unmanaged callers and wrapper methods.
1377 * \returns a pointer to the \c MonoMethod or NULL if we walked past all the
1378 * callers.
1380 MonoMethod*
1381 mono_runtime_get_caller_no_system_or_reflection (void)
1383 MonoMethod *dest = NULL;
1384 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1385 return dest;
1389 * mono_runtime_get_caller_from_stack_mark:
1391 * Walk the stack and return the assembly of the method referenced
1392 * by the stack mark STACK_MARK.
1394 MonoAssembly*
1395 mono_runtime_get_caller_from_stack_mark (MonoStackCrawlMark *stack_mark)
1397 // FIXME: Use the stack mark
1398 MonoMethod *dest = NULL;
1399 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1400 if (dest)
1401 return m_class_get_image (dest->klass)->assembly;
1402 else
1403 return NULL;
1406 static MonoReflectionTypeHandle
1407 type_from_parsed_name (MonoTypeNameParse *info, MonoStackCrawlMark *stack_mark, MonoBoolean ignoreCase, MonoAssembly **caller_assembly, MonoError *error)
1409 MonoMethod *m;
1410 MonoType *type = NULL;
1411 MonoAssembly *assembly = NULL;
1412 gboolean type_resolve = FALSE;
1413 MonoImage *rootimage = NULL;
1415 error_init (error);
1418 * We must compute the calling assembly as type loading must happen under a metadata context.
1419 * For example. The main assembly is a.exe and Type.GetType is called from dir/b.dll. Without
1420 * the metadata context (basedir currently) set to dir/b.dll we won't be able to load a dir/c.dll.
1422 m = mono_method_get_last_managed ();
1423 if (m && m_class_get_image (m->klass) != mono_defaults.corlib) {
1424 /* Happens with inlining */
1425 assembly = m_class_get_image (m->klass)->assembly;
1426 } else {
1427 assembly = mono_runtime_get_caller_from_stack_mark (stack_mark);
1429 if (assembly) {
1430 type_resolve = TRUE;
1431 rootimage = assembly->image;
1432 } else {
1433 g_warning (G_STRLOC);
1435 *caller_assembly = assembly;
1437 if (info->assembly.name)
1438 assembly = mono_assembly_load (&info->assembly, assembly ? assembly->basedir : NULL, NULL);
1440 if (assembly) {
1441 /* When loading from the current assembly, AppDomain.TypeResolve will not be called yet */
1442 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
1443 goto_if_nok (error, fail);
1446 // XXXX - aleksey -
1447 // Say we're looking for System.Generic.Dict<int, Local>
1448 // we FAIL the get type above, because S.G.Dict isn't in assembly->image. So we drop down here.
1449 // but then we FAIL AGAIN because now we pass null as the image and the rootimage and everything
1450 // is messed up when we go to construct the Local as the type arg...
1452 // By contrast, if we started with Mine<System.Generic.Dict<int, Local>> we'd go in with assembly->image
1453 // as the root and then even the detour into generics would still not screw us when we went to load Local.
1454 if (!info->assembly.name && !type) {
1455 /* try mscorlib */
1456 type = mono_reflection_get_type_checked (rootimage, NULL, info, ignoreCase, &type_resolve, error);
1457 goto_if_nok (error, fail);
1459 if (assembly && !type && type_resolve) {
1460 type_resolve = FALSE; /* This will invoke TypeResolve if not done in the first 'if' */
1461 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
1462 goto_if_nok (error, fail);
1465 if (!type)
1466 goto fail;
1468 return mono_type_get_object_handle (mono_domain_get (), type, error);
1469 fail:
1470 return MONO_HANDLE_NEW (MonoReflectionType, NULL);
1473 MonoReflectionTypeHandle
1474 ves_icall_System_RuntimeTypeHandle_internal_from_name (MonoStringHandle name,
1475 MonoStackCrawlMark *stack_mark,
1476 MonoReflectionAssemblyHandle callerAssembly,
1477 MonoBoolean throwOnError,
1478 MonoBoolean ignoreCase,
1479 MonoBoolean reflectionOnly,
1480 MonoError *error)
1482 MonoTypeNameParse info;
1483 gboolean free_info = FALSE;
1484 MonoAssembly *caller_assembly;
1485 MonoReflectionTypeHandle type = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1487 /* The callerAssembly argument is unused for now */
1489 char *str = mono_string_handle_to_utf8 (name, error);
1490 goto_if_nok (error, leave);
1492 free_info = TRUE;
1493 if (!mono_reflection_parse_type_checked (str, &info, error))
1494 goto leave;
1496 /* mono_reflection_parse_type() mangles the string */
1498 MONO_HANDLE_ASSIGN (type, type_from_parsed_name (&info, (MonoStackCrawlMark*)stack_mark, ignoreCase, &caller_assembly, error));
1500 goto_if_nok (error, leave);
1502 if (MONO_HANDLE_IS_NULL (type)) {
1503 if (throwOnError) {
1504 char *tname = info.name_space ? g_strdup_printf ("%s.%s", info.name_space, info.name) : g_strdup (info.name);
1505 char *aname;
1506 if (info.assembly.name)
1507 aname = mono_stringify_assembly_name (&info.assembly);
1508 else if (caller_assembly)
1509 aname = mono_stringify_assembly_name (mono_assembly_get_name_internal (caller_assembly));
1510 else
1511 aname = g_strdup ("");
1512 mono_error_set_type_load_name (error, tname, aname, "");
1514 goto leave;
1517 leave:
1518 if (free_info)
1519 mono_reflection_free_type_info (&info);
1520 g_free (str);
1521 if (!is_ok (error)) {
1522 if (!throwOnError) {
1523 mono_error_cleanup (error);
1524 error_init (error);
1526 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
1527 } else
1528 return type;
1532 MonoReflectionTypeHandle
1533 ves_icall_System_Type_internal_from_handle (MonoType *handle, MonoError *error)
1535 MonoDomain *domain = mono_domain_get ();
1537 return mono_type_get_object_handle (domain, handle, error);
1540 MonoType*
1541 ves_icall_Mono_RuntimeClassHandle_GetTypeFromClass (MonoClass *klass, MonoError *error)
1543 return m_class_get_byval_arg (klass);
1546 void
1547 ves_icall_Mono_RuntimeGPtrArrayHandle_GPtrArrayFree (GPtrArray *ptr_array, MonoError *error)
1549 g_ptr_array_free (ptr_array, TRUE);
1552 void
1553 ves_icall_Mono_SafeStringMarshal_GFree (void *c_str, MonoError *error)
1555 g_free (c_str);
1558 char*
1559 ves_icall_Mono_SafeStringMarshal_StringToUtf8 (MonoStringHandle s, MonoError *error)
1561 return mono_string_handle_to_utf8 (s, error);
1564 /* System.TypeCode */
1565 typedef enum {
1566 TYPECODE_EMPTY,
1567 TYPECODE_OBJECT,
1568 TYPECODE_DBNULL,
1569 TYPECODE_BOOLEAN,
1570 TYPECODE_CHAR,
1571 TYPECODE_SBYTE,
1572 TYPECODE_BYTE,
1573 TYPECODE_INT16,
1574 TYPECODE_UINT16,
1575 TYPECODE_INT32,
1576 TYPECODE_UINT32,
1577 TYPECODE_INT64,
1578 TYPECODE_UINT64,
1579 TYPECODE_SINGLE,
1580 TYPECODE_DOUBLE,
1581 TYPECODE_DECIMAL,
1582 TYPECODE_DATETIME,
1583 TYPECODE_STRING = 18
1584 } TypeCode;
1586 guint32
1587 ves_icall_type_GetTypeCodeInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
1589 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1590 int t = type->type;
1592 if (type->byref)
1593 return TYPECODE_OBJECT;
1595 handle_enum:
1596 switch (t) {
1597 case MONO_TYPE_VOID:
1598 return TYPECODE_OBJECT;
1599 case MONO_TYPE_BOOLEAN:
1600 return TYPECODE_BOOLEAN;
1601 case MONO_TYPE_U1:
1602 return TYPECODE_BYTE;
1603 case MONO_TYPE_I1:
1604 return TYPECODE_SBYTE;
1605 case MONO_TYPE_U2:
1606 return TYPECODE_UINT16;
1607 case MONO_TYPE_I2:
1608 return TYPECODE_INT16;
1609 case MONO_TYPE_CHAR:
1610 return TYPECODE_CHAR;
1611 case MONO_TYPE_PTR:
1612 case MONO_TYPE_U:
1613 case MONO_TYPE_I:
1614 return TYPECODE_OBJECT;
1615 case MONO_TYPE_U4:
1616 return TYPECODE_UINT32;
1617 case MONO_TYPE_I4:
1618 return TYPECODE_INT32;
1619 case MONO_TYPE_U8:
1620 return TYPECODE_UINT64;
1621 case MONO_TYPE_I8:
1622 return TYPECODE_INT64;
1623 case MONO_TYPE_R4:
1624 return TYPECODE_SINGLE;
1625 case MONO_TYPE_R8:
1626 return TYPECODE_DOUBLE;
1627 case MONO_TYPE_VALUETYPE: {
1628 MonoClass *klass = type->data.klass;
1630 if (m_class_is_enumtype (klass)) {
1631 t = mono_class_enum_basetype_internal (klass)->type;
1632 goto handle_enum;
1633 } else if (mono_is_corlib_image (m_class_get_image (klass))) {
1634 if (strcmp (m_class_get_name_space (klass), "System") == 0) {
1635 if (strcmp (m_class_get_name (klass), "Decimal") == 0)
1636 return TYPECODE_DECIMAL;
1637 else if (strcmp (m_class_get_name (klass), "DateTime") == 0)
1638 return TYPECODE_DATETIME;
1641 return TYPECODE_OBJECT;
1643 case MONO_TYPE_STRING:
1644 return TYPECODE_STRING;
1645 case MONO_TYPE_SZARRAY:
1646 case MONO_TYPE_ARRAY:
1647 case MONO_TYPE_OBJECT:
1648 case MONO_TYPE_VAR:
1649 case MONO_TYPE_MVAR:
1650 case MONO_TYPE_TYPEDBYREF:
1651 return TYPECODE_OBJECT;
1652 case MONO_TYPE_CLASS:
1654 MonoClass *klass = type->data.klass;
1655 if (m_class_get_image (klass) == mono_defaults.corlib && strcmp (m_class_get_name_space (klass), "System") == 0) {
1656 if (strcmp (m_class_get_name (klass), "DBNull") == 0)
1657 return TYPECODE_DBNULL;
1660 return TYPECODE_OBJECT;
1661 case MONO_TYPE_GENERICINST:
1662 return TYPECODE_OBJECT;
1663 default:
1664 g_error ("type 0x%02x not handled in GetTypeCode()", t);
1666 return 0;
1669 static MonoType*
1670 mono_type_get_underlying_type_ignore_byref (MonoType *type)
1672 if (type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (type->data.klass))
1673 return mono_class_enum_basetype_internal (type->data.klass);
1674 if (type->type == MONO_TYPE_GENERICINST && m_class_is_enumtype (type->data.generic_class->container_class))
1675 return mono_class_enum_basetype_internal (type->data.generic_class->container_class);
1676 return type;
1679 guint32
1680 ves_icall_RuntimeTypeHandle_type_is_assignable_from (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_c, MonoError *error)
1682 g_assert (!MONO_HANDLE_IS_NULL (ref_type));
1684 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1685 MonoClass *klass = mono_class_from_mono_type_internal (type);
1686 MonoType *ctype = MONO_HANDLE_GETVAL (ref_c, type);
1687 MonoClass *klassc = mono_class_from_mono_type_internal (ctype);
1689 if (type->byref ^ ctype->byref)
1690 return FALSE;
1692 if (type->byref) {
1693 MonoType *t = mono_type_get_underlying_type_ignore_byref (type);
1694 MonoType *ot = mono_type_get_underlying_type_ignore_byref (ctype);
1696 klass = mono_class_from_mono_type_internal (t);
1697 klassc = mono_class_from_mono_type_internal (ot);
1699 if (mono_type_is_primitive (t)) {
1700 return mono_type_is_primitive (ot) && m_class_get_instance_size (klass) == m_class_get_instance_size (klassc);
1701 } else if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) {
1702 return t->type == ot->type && t->data.generic_param->num == ot->data.generic_param->num;
1703 } else if (t->type == MONO_TYPE_PTR || t->type == MONO_TYPE_FNPTR) {
1704 return t->type == ot->type;
1705 } else {
1706 if (ot->type == MONO_TYPE_VAR || ot->type == MONO_TYPE_MVAR)
1707 return FALSE;
1709 if (m_class_is_valuetype (klass))
1710 return klass == klassc;
1711 return m_class_is_valuetype (klass) == m_class_is_valuetype (klassc);
1714 return mono_class_is_assignable_from_internal (klass, klassc);
1717 MonoBoolean
1718 ves_icall_RuntimeTypeHandle_is_subclass_of (MonoType *childType, MonoType *baseType)
1720 ERROR_DECL (error);
1721 mono_bool result = FALSE;
1722 MonoClass *childClass;
1723 MonoClass *baseClass;
1725 childClass = mono_class_from_mono_type_internal (childType);
1726 baseClass = mono_class_from_mono_type_internal (baseType);
1728 if (G_UNLIKELY (childType->byref)) {
1729 result = !baseType->byref && baseClass == mono_defaults.object_class;
1730 goto done;
1733 if (G_UNLIKELY (baseType->byref)) {
1734 result = FALSE;
1735 goto done;
1738 if (childType == baseType) {
1739 /* .NET IsSubclassOf is not reflexive */
1740 result = FALSE;
1741 goto done;
1744 if (G_UNLIKELY (is_generic_parameter (childType))) {
1745 /* slow path: walk the type hierarchy looking at base types
1746 * until we see baseType. If the current type is not a gparam,
1747 * break out of the loop and use is_subclass_of.
1749 MonoClass *c = mono_generic_param_get_base_type (childClass);
1751 result = FALSE;
1752 while (c != NULL) {
1753 if (c == baseClass) {
1754 result = TRUE;
1755 break;
1757 if (!is_generic_parameter (m_class_get_byval_arg (c))) {
1758 result = mono_class_is_subclass_of (c, baseClass, FALSE);
1759 break;
1760 } else
1761 c = mono_generic_param_get_base_type (c);
1763 } else {
1764 result = mono_class_is_subclass_of (childClass, baseClass, FALSE);
1766 done:
1767 mono_error_set_pending_exception (error);
1768 return result;
1771 guint32
1772 ves_icall_RuntimeTypeHandle_IsInstanceOfType (MonoReflectionTypeHandle ref_type, MonoObjectHandle obj, MonoError *error)
1774 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1775 MonoClass *klass = mono_class_from_mono_type_internal (type);
1776 mono_class_init_checked (klass, error);
1777 return_val_if_nok (error, FALSE);
1778 MonoObjectHandle inst = mono_object_handle_isinst (obj, klass, error);
1779 return_val_if_nok (error, FALSE);
1780 return !MONO_HANDLE_IS_NULL (inst);
1783 guint32
1784 ves_icall_RuntimeTypeHandle_GetAttributes (MonoReflectionTypeHandle ref_type, MonoError *error)
1786 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1787 MonoClass *klass = mono_class_from_mono_type_internal (type);
1788 return mono_class_get_flags (klass);
1791 MonoReflectionMarshalAsAttributeHandle
1792 ves_icall_System_Reflection_FieldInfo_get_marshal_info (MonoReflectionFieldHandle field_h, MonoError *error)
1794 MonoDomain *domain = MONO_HANDLE_DOMAIN (field_h);
1795 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
1796 MonoClass *klass = field->parent;
1798 MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
1799 if (mono_class_is_gtd (klass) ||
1800 (gklass && gklass->context.class_inst->is_open))
1801 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1803 MonoType *ftype = mono_field_get_type_internal (field);
1804 if (ftype && !(ftype->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL))
1805 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1807 MonoMarshalType *info = mono_marshal_load_type_info (klass);
1809 for (int i = 0; i < info->num_fields; ++i) {
1810 if (info->fields [i].field == field) {
1811 if (!info->fields [i].mspec)
1812 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1813 else {
1814 return mono_reflection_marshal_as_attribute_from_marshal_spec (domain, klass, info->fields [i].mspec, error);
1819 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1822 MonoReflectionFieldHandle
1823 ves_icall_System_Reflection_FieldInfo_internal_from_handle_type (MonoClassField *handle, MonoType *type, MonoError *error)
1825 MonoClass *klass;
1827 g_assert (handle);
1829 if (!type) {
1830 klass = handle->parent;
1831 } else {
1832 klass = mono_class_from_mono_type_internal (type);
1834 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1836 if (!found)
1837 /* The managed code will throw the exception */
1838 return MONO_HANDLE_CAST (MonoReflectionField, NULL_HANDLE);
1841 return mono_field_get_object_handle (mono_domain_get (), klass, handle, error);
1844 MonoReflectionEventHandle
1845 ves_icall_System_Reflection_EventInfo_internal_from_handle_type (MonoEvent *handle, MonoType *type, MonoError *error)
1847 MonoClass *klass;
1849 g_assert (handle);
1851 if (!type) {
1852 klass = handle->parent;
1853 } else {
1854 klass = mono_class_from_mono_type_internal (type);
1856 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1857 if (!found)
1858 /* Managed code will throw an exception */
1859 return MONO_HANDLE_CAST (MonoReflectionEvent, NULL_HANDLE);
1862 return mono_event_get_object_handle (mono_domain_get (), klass, handle, error);
1866 MonoReflectionPropertyHandle
1867 ves_icall_System_Reflection_RuntimePropertyInfo_internal_from_handle_type (MonoProperty *handle, MonoType *type, MonoError *error)
1869 MonoClass *klass;
1871 g_assert (handle);
1873 if (!type) {
1874 klass = handle->parent;
1875 } else {
1876 klass = mono_class_from_mono_type_internal (type);
1878 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1879 if (!found)
1880 /* Managed code will throw an exception */
1881 return MONO_HANDLE_CAST (MonoReflectionProperty, NULL_HANDLE);
1884 return mono_property_get_object_handle (mono_domain_get (), klass, handle, error);
1887 MonoArrayHandle
1888 ves_icall_System_Reflection_FieldInfo_GetTypeModifiers (MonoReflectionFieldHandle field_h, MonoBoolean optional, MonoError *error)
1890 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
1892 MonoType *type = mono_field_get_type_checked (field, error);
1893 return_val_if_nok (error, NULL_HANDLE_ARRAY);
1895 return type_array_from_modifiers (m_class_get_image (field->parent), type, optional, error);
1899 ves_icall_get_method_attributes (MonoMethod *method)
1901 return method->flags;
1904 void
1905 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info, MonoError *error)
1907 MonoDomain *domain = mono_domain_get ();
1909 MonoMethodSignature* sig = mono_method_signature_checked (method, error);
1910 return_if_nok (error);
1912 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (method->klass), error);
1913 return_if_nok (error);
1915 MONO_STRUCT_SETREF_INTERNAL (info, parent, MONO_HANDLE_RAW (rt));
1917 MONO_HANDLE_ASSIGN (rt, mono_type_get_object_handle (domain, sig->ret, error));
1918 return_if_nok (error);
1920 MONO_STRUCT_SETREF_INTERNAL (info, ret, MONO_HANDLE_RAW (rt));
1922 info->attrs = method->flags;
1923 info->implattrs = method->iflags;
1924 guint32 callconv;
1925 if (sig->call_convention == MONO_CALL_DEFAULT)
1926 callconv = sig->sentinelpos >= 0 ? 2 : 1;
1927 else {
1928 if (sig->call_convention == MONO_CALL_VARARG || sig->sentinelpos >= 0)
1929 callconv = 2;
1930 else
1931 callconv = 1;
1933 callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6);
1934 info->callconv = callconv;
1937 MonoArrayHandle
1938 ves_icall_System_Reflection_MonoMethodInfo_get_parameter_info (MonoMethod *method, MonoReflectionMethodHandle member, MonoError *error)
1940 MonoDomain *domain = mono_domain_get ();
1942 MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1943 MONO_HANDLE_GET (reftype, member, reftype);
1944 MonoClass *klass = NULL;
1945 if (!MONO_HANDLE_IS_NULL (reftype))
1946 klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (reftype, type));
1947 return mono_param_get_objects_internal (domain, method, klass, error);
1950 MonoReflectionMarshalAsAttributeHandle
1951 ves_icall_System_MonoMethodInfo_get_retval_marshal (MonoMethod *method, MonoError *error)
1953 MonoDomain *domain = mono_domain_get ();
1954 MonoReflectionMarshalAsAttributeHandle res = MONO_HANDLE_NEW (MonoReflectionMarshalAsAttribute, NULL);
1956 MonoMarshalSpec **mspecs = g_new (MonoMarshalSpec*, mono_method_signature_internal (method)->param_count + 1);
1957 mono_method_get_marshal_info (method, mspecs);
1959 if (mspecs [0]) {
1960 MONO_HANDLE_ASSIGN (res, mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [0], error));
1961 goto_if_nok (error, leave);
1964 leave:
1965 for (int i = mono_method_signature_internal (method)->param_count; i >= 0; i--)
1966 if (mspecs [i])
1967 mono_metadata_free_marshal_spec (mspecs [i]);
1968 g_free (mspecs);
1970 return res;
1973 gint32
1974 ves_icall_RuntimeFieldInfo_GetFieldOffset (MonoReflectionFieldHandle field, MonoError *error)
1976 MonoClassField *class_field = MONO_HANDLE_GETVAL (field, field);
1977 mono_class_setup_fields (class_field->parent);
1979 return class_field->offset - MONO_ABI_SIZEOF (MonoObject);
1982 MonoReflectionTypeHandle
1983 ves_icall_RuntimeFieldInfo_GetParentType (MonoReflectionFieldHandle field, MonoBoolean declaring, MonoError *error)
1985 MonoDomain *domain = MONO_HANDLE_DOMAIN (field);
1986 MonoClass *parent;
1988 if (declaring) {
1989 MonoClassField *f = MONO_HANDLE_GETVAL (field, field);
1990 parent = f->parent;
1991 } else {
1992 parent = MONO_HANDLE_GETVAL (field, klass);
1995 return mono_type_get_object_handle (domain, m_class_get_byval_arg (parent), error);
1998 MonoObject *
1999 ves_icall_RuntimeFieldInfo_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
2001 ERROR_DECL (error);
2002 MonoClass *fklass = field->klass;
2003 MonoClassField *cf = field->field;
2004 MonoDomain *domain = mono_object_domain (field);
2006 if (mono_asmctx_get_kind (&m_class_get_image (fklass)->assembly->context) == MONO_ASMCTX_REFONLY) {
2007 mono_error_set_invalid_operation (error,
2008 "It is illegal to get the value on a field on a type loaded using the ReflectionOnly methods.");
2009 mono_error_set_pending_exception (error);
2010 return NULL;
2013 if (mono_security_core_clr_enabled () &&
2014 !mono_security_core_clr_ensure_reflection_access_field (cf, error)) {
2015 mono_error_set_pending_exception (error);
2016 return NULL;
2019 #ifndef DISABLE_REMOTING
2020 if (G_UNLIKELY (obj != NULL && mono_class_is_transparent_proxy (mono_object_class (obj)))) {
2021 /* We get here if someone used a
2022 * System.Reflection.FieldInfo:GetValue on a
2023 * ContextBoundObject's or cross-domain MarshalByRefObject's
2024 * transparent proxy. */
2025 MonoObject *result = mono_load_remote_field_new_checked (obj, fklass, cf, error);
2026 mono_error_set_pending_exception (error);
2027 return result;
2029 #endif
2031 MonoObject * result = mono_field_get_value_object_checked (domain, cf, obj, error);
2032 mono_error_set_pending_exception (error);
2033 return result;
2036 void
2037 ves_icall_RuntimeFieldInfo_SetValueInternal (MonoReflectionFieldHandle field, MonoObjectHandle obj, MonoObjectHandle value, MonoError *error)
2039 MonoClassField *cf = MONO_HANDLE_GETVAL (field, field);
2041 MonoClass *field_klass = MONO_HANDLE_GETVAL (field, klass);
2042 if (mono_asmctx_get_kind (&m_class_get_image (field_klass)->assembly->context) == MONO_ASMCTX_REFONLY) {
2043 mono_error_set_invalid_operation (error, "It is illegal to set the value on a field on a type loaded using the ReflectionOnly methods.");
2044 return;
2047 if (mono_security_core_clr_enabled () &&
2048 !mono_security_core_clr_ensure_reflection_access_field (cf, error)) {
2049 return;
2052 #ifndef DISABLE_REMOTING
2053 if (G_UNLIKELY (!MONO_HANDLE_IS_NULL (obj) && mono_class_is_transparent_proxy (mono_handle_class (obj)))) {
2054 /* We get here if someone used a
2055 * System.Reflection.FieldInfo:SetValue on a
2056 * ContextBoundObject's or cross-domain MarshalByRefObject's
2057 * transparent proxy. */
2058 /* FIXME: use handles for mono_store_remote_field_new_checked */
2059 MonoObject *v = MONO_HANDLE_RAW (value);
2060 MonoObject *o = MONO_HANDLE_RAW (obj);
2061 mono_store_remote_field_new_checked (o, field_klass, cf, v, error);
2062 return;
2064 #endif
2066 MonoType *type = mono_field_get_type_checked (cf, error);
2067 return_if_nok (error);
2069 gboolean isref = FALSE;
2070 uint32_t value_gchandle = 0;
2071 gchar *v = NULL;
2072 if (!type->byref) {
2073 switch (type->type) {
2074 case MONO_TYPE_U1:
2075 case MONO_TYPE_I1:
2076 case MONO_TYPE_BOOLEAN:
2077 case MONO_TYPE_U2:
2078 case MONO_TYPE_I2:
2079 case MONO_TYPE_CHAR:
2080 case MONO_TYPE_U:
2081 case MONO_TYPE_I:
2082 case MONO_TYPE_U4:
2083 case MONO_TYPE_I4:
2084 case MONO_TYPE_R4:
2085 case MONO_TYPE_U8:
2086 case MONO_TYPE_I8:
2087 case MONO_TYPE_R8:
2088 case MONO_TYPE_VALUETYPE:
2089 case MONO_TYPE_PTR:
2090 isref = FALSE;
2091 if (!MONO_HANDLE_IS_NULL (value))
2092 v = (char*)mono_object_handle_pin_unbox (value, &value_gchandle);
2093 break;
2094 case MONO_TYPE_STRING:
2095 case MONO_TYPE_OBJECT:
2096 case MONO_TYPE_CLASS:
2097 case MONO_TYPE_ARRAY:
2098 case MONO_TYPE_SZARRAY:
2099 /* Do nothing */
2100 isref = TRUE;
2101 break;
2102 case MONO_TYPE_GENERICINST: {
2103 MonoGenericClass *gclass = type->data.generic_class;
2104 g_assert (!gclass->context.class_inst->is_open);
2106 if (mono_class_is_nullable (mono_class_from_mono_type_internal (type))) {
2107 MonoClass *nklass = mono_class_from_mono_type_internal (type);
2110 * Convert the boxed vtype into a Nullable structure.
2111 * This is complicated by the fact that Nullables have
2112 * a variable structure.
2114 MonoObjectHandle nullable = mono_object_new_handle (mono_domain_get (), nklass, error);
2115 return_if_nok (error);
2117 uint32_t nullable_gchandle = 0;
2118 guint8 *nval = (guint8*)mono_object_handle_pin_unbox (nullable, &nullable_gchandle);
2119 mono_nullable_init_from_handle (nval, value, nklass);
2121 isref = FALSE;
2122 value_gchandle = nullable_gchandle;
2123 v = (gchar*)nval;
2125 else {
2126 isref = !m_class_is_valuetype (gclass->container_class);
2127 if (!isref && !MONO_HANDLE_IS_NULL (value)) {
2128 v = (char*)mono_object_handle_pin_unbox (value, &value_gchandle);
2131 break;
2133 default:
2134 g_error ("type 0x%x not handled in "
2135 "ves_icall_FieldInfo_SetValueInternal", type->type);
2136 return;
2140 /* either value is a reference type, or it's a value type and we pinned
2141 * it and v points to the payload. */
2142 g_assert ((isref && v == NULL && value_gchandle == 0) ||
2143 (!isref && v != NULL && value_gchandle != 0) ||
2144 (!isref && v == NULL && value_gchandle == 0));
2146 if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
2147 MonoVTable *vtable = mono_class_vtable_checked (MONO_HANDLE_DOMAIN (field), cf->parent, error);
2148 goto_if_nok (error, leave);
2150 if (!vtable->initialized) {
2151 if (!mono_runtime_class_init_full (vtable, error))
2152 goto leave;
2154 if (isref)
2155 mono_field_static_set_value_internal (vtable, cf, MONO_HANDLE_RAW (value)); /* FIXME make mono_field_static_set_value work with handles for value */
2156 else
2157 mono_field_static_set_value_internal (vtable, cf, v);
2158 } else {
2160 if (isref)
2161 MONO_HANDLE_SET_FIELD_REF (obj, cf, value);
2162 else
2163 mono_field_set_value_internal (MONO_HANDLE_RAW (obj), cf, v); /* FIXME: make mono_field_set_value take a handle for obj */
2165 leave:
2166 if (value_gchandle)
2167 mono_gchandle_free_internal (value_gchandle);
2170 static MonoObjectHandle
2171 typed_reference_to_object (MonoTypedRef *tref, MonoError *error)
2173 HANDLE_FUNCTION_ENTER ();
2174 MonoObjectHandle result;
2175 if (MONO_TYPE_IS_REFERENCE (tref->type)) {
2176 MonoObject** objp = (MonoObject **)tref->value;
2177 result = MONO_HANDLE_NEW (MonoObject, *objp);
2178 } else {
2179 result = mono_value_box_handle (mono_domain_get (), tref->klass, tref->value, error);
2181 HANDLE_FUNCTION_RETURN_REF (MonoObject, result);
2184 void
2185 ves_icall_System_RuntimeFieldHandle_SetValueDirect (MonoReflectionField *field, MonoReflectionType *field_type, MonoTypedRef *obj, MonoObject *value, MonoReflectionType *context_type)
2187 ICALL_ENTRY ();
2189 MonoClassField *f;
2191 g_assert (field);
2192 g_assert (obj);
2193 g_assert (value);
2195 f = field->field;
2196 if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (f->parent))) {
2197 MonoReflectionFieldHandle fieldHandle = MONO_HANDLE_NEW (MonoReflectionField, field);
2198 MonoObjectHandle objHandle = typed_reference_to_object (obj, error),
2199 valueHandle = MONO_HANDLE_NEW (MonoObject, value);
2200 goto_if_nok (error, leave);
2201 ves_icall_RuntimeFieldInfo_SetValueInternal (fieldHandle, objHandle, valueHandle, error);
2202 } else if (MONO_TYPE_IS_REFERENCE (f->type))
2203 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), value, FALSE);
2204 else
2205 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), mono_object_unbox_internal (value), FALSE);
2207 leave:
2208 ICALL_RETURN ();
2211 MonoObject *
2212 ves_icall_RuntimeFieldInfo_GetRawConstantValue (MonoReflectionField *rfield)
2214 MonoObject *o = NULL;
2215 MonoClassField *field = rfield->field;
2216 MonoClass *klass;
2217 MonoDomain *domain = mono_object_domain (rfield);
2218 gchar *v;
2219 MonoTypeEnum def_type;
2220 const char *def_value;
2221 MonoType *t;
2222 ERROR_DECL (error);
2224 mono_class_init_internal (field->parent);
2226 t = mono_field_get_type_checked (field, error);
2227 if (!is_ok (error)) {
2228 mono_error_set_pending_exception (error);
2229 return NULL;
2232 if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT)) {
2233 mono_error_set_invalid_operation (error, NULL);
2234 mono_error_set_pending_exception (error);
2235 return NULL;
2238 if (image_is_dynamic (m_class_get_image (field->parent))) {
2239 MonoClass *klass = field->parent;
2240 int fidx = field - m_class_get_fields (klass);
2241 MonoFieldDefaultValue *def_values = mono_class_get_field_def_values (klass);
2243 g_assert (def_values);
2244 def_type = def_values [fidx].def_type;
2245 def_value = def_values [fidx].data;
2247 if (def_type == MONO_TYPE_END) {
2248 mono_error_set_invalid_operation (error, NULL);
2249 mono_error_set_pending_exception (error);
2250 return NULL;
2252 } else {
2253 def_value = mono_class_get_field_default_value (field, &def_type);
2254 /* FIXME, maybe we should try to raise TLE if field->parent is broken */
2255 if (!def_value) {
2256 mono_error_set_invalid_operation (error, NULL);
2257 mono_error_set_pending_exception (error);
2258 return NULL;
2262 /*FIXME unify this with reflection.c:mono_get_object_from_blob*/
2263 switch (def_type) {
2264 case MONO_TYPE_U1:
2265 case MONO_TYPE_I1:
2266 case MONO_TYPE_BOOLEAN:
2267 case MONO_TYPE_U2:
2268 case MONO_TYPE_I2:
2269 case MONO_TYPE_CHAR:
2270 case MONO_TYPE_U:
2271 case MONO_TYPE_I:
2272 case MONO_TYPE_U4:
2273 case MONO_TYPE_I4:
2274 case MONO_TYPE_R4:
2275 case MONO_TYPE_U8:
2276 case MONO_TYPE_I8:
2277 case MONO_TYPE_R8: {
2278 MonoType *t;
2280 /* boxed value type */
2281 t = g_new0 (MonoType, 1);
2282 t->type = def_type;
2283 klass = mono_class_from_mono_type_internal (t);
2284 g_free (t);
2285 o = mono_object_new_checked (domain, klass, error);
2286 if (!is_ok (error)) {
2287 mono_error_set_pending_exception (error);
2288 return NULL;
2290 v = ((gchar *) o) + sizeof (MonoObject);
2291 mono_get_constant_value_from_blob (domain, def_type, def_value, v, error);
2292 if (mono_error_set_pending_exception (error))
2293 return NULL;
2294 break;
2296 case MONO_TYPE_STRING:
2297 case MONO_TYPE_CLASS:
2298 mono_get_constant_value_from_blob (domain, def_type, def_value, &o, error);
2299 if (mono_error_set_pending_exception (error))
2300 return NULL;
2301 break;
2302 default:
2303 g_assert_not_reached ();
2306 return o;
2309 MonoReflectionTypeHandle
2310 ves_icall_RuntimeFieldInfo_ResolveType (MonoReflectionFieldHandle ref_field, MonoError *error)
2312 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_field);
2313 MonoClassField *field = MONO_HANDLE_GETVAL (ref_field, field);
2314 MonoType *type = mono_field_get_type_checked (field, error);
2315 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
2316 return mono_type_get_object_handle (domain, type, error);
2319 void
2320 ves_icall_RuntimePropertyInfo_get_property_info (MonoReflectionPropertyHandle property, MonoPropertyInfo *info, PInfo req_info, MonoError *error)
2322 MonoDomain *domain = MONO_HANDLE_DOMAIN (property);
2323 const MonoProperty *pproperty = MONO_HANDLE_GETVAL (property, property);
2325 if ((req_info & PInfo_ReflectedType) != 0) {
2326 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
2327 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2328 return_if_nok (error);
2330 MONO_STRUCT_SETREF_INTERNAL (info, parent, MONO_HANDLE_RAW (rt));
2332 if ((req_info & PInfo_DeclaringType) != 0) {
2333 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (pproperty->parent), error);
2334 return_if_nok (error);
2336 MONO_STRUCT_SETREF_INTERNAL (info, declaring_type, MONO_HANDLE_RAW (rt));
2339 if ((req_info & PInfo_Name) != 0) {
2340 MonoStringHandle name = mono_string_new_handle (domain, pproperty->name, error);
2341 return_if_nok (error);
2343 MONO_STRUCT_SETREF_INTERNAL (info, name, MONO_HANDLE_RAW (name));
2346 if ((req_info & PInfo_Attributes) != 0)
2347 info->attrs = pproperty->attrs;
2349 if ((req_info & PInfo_GetMethod) != 0) {
2350 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2351 MonoReflectionMethodHandle rm;
2352 if (pproperty->get &&
2353 (((pproperty->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2354 pproperty->get->klass == property_klass)) {
2355 rm = mono_method_get_object_handle (domain, pproperty->get, property_klass, error);
2356 return_if_nok (error);
2357 } else {
2358 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2361 MONO_STRUCT_SETREF_INTERNAL (info, get, MONO_HANDLE_RAW (rm));
2363 if ((req_info & PInfo_SetMethod) != 0) {
2364 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2365 MonoReflectionMethodHandle rm;
2366 if (pproperty->set &&
2367 (((pproperty->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2368 pproperty->set->klass == property_klass)) {
2369 rm = mono_method_get_object_handle (domain, pproperty->set, property_klass, error);
2370 return_if_nok (error);
2371 } else {
2372 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2375 MONO_STRUCT_SETREF_INTERNAL (info, set, MONO_HANDLE_RAW (rm));
2378 * There may be other methods defined for properties, though, it seems they are not exposed
2379 * in the reflection API
2383 static gboolean
2384 add_event_other_methods_to_array (MonoDomain *domain, MonoMethod *m, MonoArrayHandle dest, int i, MonoError *error)
2386 HANDLE_FUNCTION_ENTER ();
2387 error_init (error);
2388 MonoReflectionMethodHandle rm = mono_method_get_object_handle (domain, m, NULL, error);
2389 goto_if_nok (error, leave);
2390 MONO_HANDLE_ARRAY_SETREF (dest, i, rm);
2391 leave:
2392 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2395 void
2396 ves_icall_RuntimeEventInfo_get_event_info (MonoReflectionMonoEventHandle ref_event, MonoEventInfo *info, MonoError *error)
2398 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_event);
2400 MonoClass *klass = MONO_HANDLE_GETVAL (ref_event, klass);
2401 MonoEvent *event = MONO_HANDLE_GETVAL (ref_event, event);
2403 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2404 return_if_nok (error);
2405 MONO_STRUCT_SETREF_INTERNAL (info, reflected_type, MONO_HANDLE_RAW (rt));
2407 rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (event->parent), error);
2408 return_if_nok (error);
2409 MONO_STRUCT_SETREF_INTERNAL (info, declaring_type, MONO_HANDLE_RAW (rt));
2411 MonoStringHandle ev_name = mono_string_new_handle (domain, event->name, error);
2412 return_if_nok (error);
2413 MONO_STRUCT_SETREF_INTERNAL (info, name, MONO_HANDLE_RAW (ev_name));
2415 info->attrs = event->attrs;
2417 MonoReflectionMethodHandle rm;
2418 if (event->add) {
2419 rm = mono_method_get_object_handle (domain, event->add, NULL, error);
2420 return_if_nok (error);
2421 } else {
2422 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2425 MONO_STRUCT_SETREF_INTERNAL (info, add_method, MONO_HANDLE_RAW (rm));
2427 if (event->remove) {
2428 rm = mono_method_get_object_handle (domain, event->remove, NULL, error);
2429 return_if_nok (error);
2430 } else {
2431 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2434 MONO_STRUCT_SETREF_INTERNAL (info, remove_method, MONO_HANDLE_RAW (rm));
2436 if (event->raise) {
2437 rm = mono_method_get_object_handle (domain, event->raise, NULL, error);
2438 return_if_nok (error);
2439 } else {
2440 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2443 MONO_STRUCT_SETREF_INTERNAL (info, raise_method, MONO_HANDLE_RAW (rm));
2445 #ifndef MONO_SMALL_CONFIG
2446 if (event->other) {
2447 int i, n = 0;
2448 while (event->other [n])
2449 n++;
2450 MonoArrayHandle info_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, n, error);
2451 return_if_nok (error);
2453 MONO_STRUCT_SETREF_INTERNAL (info, other_methods, MONO_HANDLE_RAW (info_arr));
2455 for (i = 0; i < n; i++)
2456 if (!add_event_other_methods_to_array (domain, event->other [i], info_arr, i, error))
2457 return;
2459 #endif
2462 static void
2463 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
2465 int i;
2466 MonoClass *ic;
2468 mono_class_setup_interfaces (klass, error);
2469 return_if_nok (error);
2471 int klass_interface_count = m_class_get_interface_count (klass);
2472 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
2473 for (i = 0; i < klass_interface_count; i++) {
2474 ic = klass_interfaces [i];
2475 g_hash_table_insert (ifaces, ic, ic);
2477 collect_interfaces (ic, ifaces, error);
2478 return_if_nok (error);
2482 typedef struct {
2483 MonoArrayHandle iface_array;
2484 MonoGenericContext *context;
2485 MonoError *error;
2486 MonoDomain *domain;
2487 int next_idx;
2488 } FillIfaceArrayData;
2490 static void
2491 fill_iface_array (gpointer key, gpointer value, gpointer user_data)
2493 HANDLE_FUNCTION_ENTER ();
2494 FillIfaceArrayData *data = (FillIfaceArrayData *)user_data;
2495 MonoClass *ic = (MonoClass *)key;
2496 MonoType *ret = m_class_get_byval_arg (ic), *inflated = NULL;
2497 MonoError *error = data->error;
2499 goto_if_nok (error, leave);
2501 if (data->context && mono_class_is_ginst (ic) && mono_class_get_generic_class (ic)->context.class_inst->is_open) {
2502 inflated = ret = mono_class_inflate_generic_type_checked (ret, data->context, error);
2503 goto_if_nok (error, leave);
2506 MonoReflectionTypeHandle rt;
2507 rt = mono_type_get_object_handle (data->domain, ret, error);
2508 goto_if_nok (error, leave);
2510 MONO_HANDLE_ARRAY_SETREF (data->iface_array, data->next_idx, rt);
2511 data->next_idx++;
2513 if (inflated)
2514 mono_metadata_free_type (inflated);
2515 leave:
2516 HANDLE_FUNCTION_RETURN ();
2519 static guint
2520 get_interfaces_hash (gconstpointer v1)
2522 MonoClass *k = (MonoClass*)v1;
2524 return m_class_get_type_token (k);
2527 MonoArrayHandle
2528 ves_icall_RuntimeType_GetInterfaces (MonoReflectionTypeHandle ref_type, MonoError *error)
2530 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2531 MonoClass *klass = mono_class_from_mono_type_internal (type);
2533 GHashTable *iface_hash = g_hash_table_new (get_interfaces_hash, NULL);
2535 MonoGenericContext *context = NULL;
2536 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open) {
2537 context = mono_class_get_context (klass);
2538 klass = mono_class_get_generic_class (klass)->container_class;
2541 for (MonoClass *parent = klass; parent; parent = m_class_get_parent (parent)) {
2542 mono_class_setup_interfaces (parent, error);
2543 goto_if_nok (error, fail);
2544 collect_interfaces (parent, iface_hash, error);
2545 goto_if_nok (error, fail);
2548 MonoDomain *domain;
2549 domain = MONO_HANDLE_DOMAIN (ref_type);
2551 int len;
2552 len = g_hash_table_size (iface_hash);
2553 if (len == 0) {
2554 g_hash_table_destroy (iface_hash);
2555 if (!domain->empty_types) {
2556 domain->empty_types = mono_array_new_cached (domain, mono_defaults.runtimetype_class, 0, error);
2557 goto_if_nok (error, fail);
2559 return MONO_HANDLE_NEW (MonoArray, domain->empty_types);
2562 FillIfaceArrayData data;
2563 data.iface_array = MONO_HANDLE_NEW (MonoArray, mono_array_new_cached (domain, mono_defaults.runtimetype_class, len, error));
2564 goto_if_nok (error, fail);
2565 data.context = context;
2566 data.error = error;
2567 data.domain = domain;
2568 data.next_idx = 0;
2570 g_hash_table_foreach (iface_hash, fill_iface_array, &data);
2572 goto_if_nok (error, fail);
2574 g_hash_table_destroy (iface_hash);
2575 return data.iface_array;
2577 fail:
2578 g_hash_table_destroy (iface_hash);
2579 return NULL_HANDLE_ARRAY;
2582 static gboolean
2583 set_interface_map_data_method_object (MonoDomain *domain, MonoMethod *method, MonoClass *iclass, int ioffset, MonoClass *klass, MonoArrayHandle targets, MonoArrayHandle methods, int i, MonoError *error)
2585 HANDLE_FUNCTION_ENTER ();
2586 error_init (error);
2587 MonoReflectionMethodHandle member = mono_method_get_object_handle (domain, method, iclass, error);
2588 goto_if_nok (error, leave);
2590 MONO_HANDLE_ARRAY_SETREF (methods, i, member);
2592 MONO_HANDLE_ASSIGN (member, mono_method_get_object_handle (domain, m_class_get_vtable (klass) [i + ioffset], klass, error));
2593 goto_if_nok (error, leave);
2595 MONO_HANDLE_ARRAY_SETREF (targets, i, member);
2597 leave:
2598 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2601 void
2602 ves_icall_RuntimeType_GetInterfaceMapData (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_iface, MonoArrayHandleOut targets, MonoArrayHandleOut methods, MonoError *error)
2604 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2605 MonoClass *klass = mono_class_from_mono_type_internal (type);
2606 MonoType *iface = MONO_HANDLE_GETVAL (ref_iface, type);
2607 MonoClass *iclass = mono_class_from_mono_type_internal (iface);
2609 mono_class_init_checked (klass, error);
2610 return_if_nok (error);
2611 mono_class_init_checked (iclass, error);
2612 return_if_nok (error);
2614 mono_class_setup_vtable (klass);
2616 gboolean variance_used;
2617 int ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
2618 if (ioffset == -1)
2619 return;
2621 int len = mono_class_num_methods (iclass);
2622 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2623 MonoArrayHandle targets_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
2624 return_if_nok (error);
2625 MONO_HANDLE_ASSIGN (targets, targets_arr);
2627 MonoArrayHandle methods_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
2628 return_if_nok (error);
2629 MONO_HANDLE_ASSIGN (methods, methods_arr);
2631 MonoMethod* method;
2632 int i = 0;
2633 gpointer iter = NULL;
2634 while ((method = mono_class_get_methods (iclass, &iter))) {
2635 if (!set_interface_map_data_method_object (domain, method, iclass, ioffset, klass, targets, methods, i, error))
2636 return;
2637 i ++;
2641 void
2642 ves_icall_RuntimeType_GetPacking (MonoReflectionTypeHandle ref_type, guint32 *packing, guint32 *size, MonoError *error)
2644 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2645 MonoClass *klass = mono_class_from_mono_type_internal (type);
2647 mono_class_init_checked (klass, error);
2648 return_if_nok (error);
2650 if (image_is_dynamic (m_class_get_image (klass))) {
2651 MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, ref_type);
2652 *packing = MONO_HANDLE_GETVAL (tb, packing_size);
2653 *size = MONO_HANDLE_GETVAL (tb, class_size);
2654 } else {
2655 mono_metadata_packing_from_typedef (m_class_get_image (klass), m_class_get_type_token (klass), packing, size);
2659 MonoReflectionTypeHandle
2660 ves_icall_RuntimeTypeHandle_GetElementType (MonoReflectionTypeHandle ref_type, MonoError *error)
2662 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2663 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2665 if (!type->byref && type->type == MONO_TYPE_SZARRAY) {
2666 return mono_type_get_object_handle (domain, m_class_get_byval_arg (type->data.klass), error);
2669 MonoClass *klass = mono_class_from_mono_type_internal (type);
2670 mono_class_init_checked (klass, error);
2671 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
2673 // GetElementType should only return a type for:
2674 // Array Pointer PassedByRef
2675 if (type->byref)
2676 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2677 else if (m_class_get_element_class (klass) && MONO_CLASS_IS_ARRAY (klass))
2678 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_element_class (klass)), error);
2679 else if (m_class_get_element_class (klass) && type->type == MONO_TYPE_PTR)
2680 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_element_class (klass)), error);
2681 else
2682 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2685 MonoReflectionTypeHandle
2686 ves_icall_RuntimeTypeHandle_GetBaseType (MonoReflectionTypeHandle ref_type, MonoError *error)
2688 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2689 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2691 if (type->byref)
2692 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2694 MonoClass *klass = mono_class_from_mono_type_internal (type);
2695 if (!m_class_get_parent (klass))
2696 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2698 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_parent (klass)), error);
2701 guint32
2702 ves_icall_RuntimeTypeHandle_GetCorElementType (MonoReflectionTypeHandle ref_type, MonoError *error)
2704 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2706 if (type->byref)
2707 return MONO_TYPE_BYREF;
2708 else
2709 return (guint32)type->type;
2712 MonoBoolean
2713 ves_icall_RuntimeTypeHandle_HasReferences (MonoReflectionTypeHandle ref_type, MonoError *error)
2715 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2716 MonoClass *klass;
2718 klass = mono_class_from_mono_type_internal (type);
2719 mono_class_init_internal (klass);
2720 return m_class_has_references (klass);
2723 MonoBoolean
2724 ves_icall_RuntimeTypeHandle_IsByRefLike (MonoReflectionTypeHandle ref_type, MonoError *error)
2726 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2727 /* .NET Core says byref types are not IsByRefLike */
2728 if (type->byref)
2729 return FALSE;
2730 MonoClass *klass = mono_class_from_mono_type_internal (type);
2731 return m_class_is_byreflike (klass);
2734 MonoBoolean
2735 ves_icall_RuntimeTypeHandle_IsComObject (MonoReflectionTypeHandle ref_type, MonoError *error)
2737 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2738 MonoClass *klass = mono_class_from_mono_type_internal (type);
2739 mono_class_init_checked (klass, error);
2740 return_val_if_nok (error, FALSE);
2742 return mono_class_is_com_object (klass);
2745 guint32
2746 ves_icall_reflection_get_token (MonoObjectHandle obj, MonoError *error)
2748 error_init (error);
2749 return mono_reflection_get_token_checked (obj, error);
2752 MonoReflectionModuleHandle
2753 ves_icall_RuntimeTypeHandle_GetModule (MonoReflectionTypeHandle type, MonoError *error)
2755 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
2756 MonoType *t = MONO_HANDLE_GETVAL (type, type);
2757 MonoClass *klass = mono_class_from_mono_type_internal (t);
2758 return mono_module_get_object_handle (domain, m_class_get_image (klass), error);
2761 MonoReflectionAssemblyHandle
2762 ves_icall_RuntimeTypeHandle_GetAssembly (MonoReflectionTypeHandle type, MonoError *error)
2764 MonoDomain *domain = mono_domain_get ();
2765 MonoType *t = MONO_HANDLE_GETVAL (type, type);
2766 MonoClass *klass = mono_class_from_mono_type_internal (t);
2767 return mono_assembly_get_object_handle (domain, m_class_get_image (klass)->assembly, error);
2770 MonoReflectionTypeHandle
2771 ves_icall_RuntimeType_get_DeclaringType (MonoReflectionTypeHandle ref_type, MonoError *error)
2773 MonoDomain *domain = mono_domain_get ();
2774 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2775 MonoClass *klass;
2777 if (type->byref)
2778 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2779 if (type->type == MONO_TYPE_VAR) {
2780 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
2781 klass = param ? param->owner.klass : NULL;
2782 } else if (type->type == MONO_TYPE_MVAR) {
2783 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
2784 klass = param ? param->owner.method->klass : NULL;
2785 } else {
2786 klass = m_class_get_nested_in (mono_class_from_mono_type_internal (type));
2789 if (!klass)
2790 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2792 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2795 MonoStringHandle
2796 ves_icall_RuntimeType_get_Name (MonoReflectionTypeHandle reftype, MonoError *error)
2798 MonoDomain *domain = mono_domain_get ();
2799 MonoType *type = MONO_HANDLE_RAW(reftype)->type;
2800 MonoClass *klass = mono_class_from_mono_type_internal (type);
2802 if (type->byref) {
2803 char *n = g_strdup_printf ("%s&", m_class_get_name (klass));
2804 MonoStringHandle res = mono_string_new_handle (domain, n, error);
2806 g_free (n);
2808 return res;
2809 } else {
2810 return mono_string_new_handle (domain, m_class_get_name (klass), error);
2814 MonoStringHandle
2815 ves_icall_RuntimeType_get_Namespace (MonoReflectionTypeHandle type, MonoError *error)
2817 MonoDomain *domain = mono_domain_get ();
2818 MonoClass *klass = mono_class_from_mono_type_handle (type);
2820 MonoClass *klass_nested_in;
2821 while ((klass_nested_in = m_class_get_nested_in (klass)))
2822 klass = klass_nested_in;
2824 if (m_class_get_name_space (klass) [0] == '\0')
2825 return NULL_HANDLE_STRING;
2826 else
2827 return mono_string_new_handle (domain, m_class_get_name_space (klass), error);
2830 gint32
2831 ves_icall_RuntimeTypeHandle_GetArrayRank (MonoReflectionTypeHandle ref_type, MonoError *error)
2833 error_init (error);
2834 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2836 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
2837 mono_error_set_argument (error, "type", "Type must be an array type");
2838 return 0;
2841 MonoClass *klass = mono_class_from_mono_type_internal (type);
2843 return m_class_get_rank (klass);
2846 static MonoArrayHandle
2847 create_type_array (MonoDomain *domain, MonoBoolean runtimeTypeArray, int count, MonoError *error)
2849 return mono_array_new_handle (domain, runtimeTypeArray ? mono_defaults.runtimetype_class : mono_defaults.systemtype_class, count, error);
2852 static gboolean
2853 set_type_object_in_array (MonoDomain *domain, MonoType *type, MonoArrayHandle dest, int i, MonoError *error)
2855 HANDLE_FUNCTION_ENTER();
2856 error_init (error);
2857 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, type, error);
2858 goto_if_nok (error, leave);
2860 MONO_HANDLE_ARRAY_SETREF (dest, i, rt);
2862 leave:
2863 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2866 MonoArrayHandle
2867 ves_icall_RuntimeType_GetGenericArguments (MonoReflectionTypeHandle ref_type, MonoBoolean runtimeTypeArray, MonoError *error)
2869 error_init (error);
2870 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2872 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2873 MonoClass *klass = mono_class_from_mono_type_internal (type);
2875 MonoArrayHandle res = MONO_HANDLE_NEW (MonoArray, NULL);
2876 if (mono_class_is_gtd (klass)) {
2877 MonoGenericContainer *container = mono_class_get_generic_container (klass);
2878 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, container->type_argc, error));
2879 goto_if_nok (error, leave);
2880 for (int i = 0; i < container->type_argc; ++i) {
2881 MonoClass *pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
2883 if (!set_type_object_in_array (domain, m_class_get_byval_arg (pklass), res, i, error))
2884 goto leave;
2887 } else if (mono_class_is_ginst (klass)) {
2888 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2889 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, inst->type_argc, error));
2890 goto_if_nok (error, leave);
2891 for (int i = 0; i < inst->type_argc; ++i) {
2892 if (!set_type_object_in_array (domain, inst->type_argv [i], res, i, error))
2893 goto leave;
2897 leave:
2898 return res;
2901 MonoBoolean
2902 ves_icall_RuntimeTypeHandle_IsGenericTypeDefinition (MonoReflectionTypeHandle ref_type, MonoError *error)
2904 error_init (error);
2906 if (!IS_MONOTYPE (MONO_HANDLE_RAW(ref_type)))
2907 return FALSE;
2909 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2910 if (type->byref)
2911 return FALSE;
2913 MonoClass *klass = mono_class_from_mono_type_internal (type);
2914 return mono_class_is_gtd (klass);
2917 MonoReflectionTypeHandle
2918 ves_icall_RuntimeTypeHandle_GetGenericTypeDefinition_impl (MonoReflectionTypeHandle ref_type, MonoError *error)
2920 error_init (error);
2921 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2923 MonoReflectionTypeHandle ret = MONO_HANDLE_NEW (MonoReflectionType, NULL);
2925 if (type->byref)
2926 goto leave;
2928 MonoClass *klass;
2929 klass = mono_class_from_mono_type_internal (type);
2931 if (mono_class_is_gtd (klass)) {
2932 /* check this one */
2933 MONO_HANDLE_ASSIGN (ret, ref_type);
2934 goto leave;
2936 if (mono_class_is_ginst (klass)) {
2937 MonoClass *generic_class = mono_class_get_generic_class (klass)->container_class;
2939 guint32 ref_info_handle = mono_class_get_ref_info_handle (generic_class);
2941 if (m_class_was_typebuilder (generic_class) && ref_info_handle) {
2942 MonoObjectHandle tb = mono_gchandle_get_target_handle (ref_info_handle);
2943 g_assert (!MONO_HANDLE_IS_NULL (tb));
2944 MONO_HANDLE_ASSIGN (ret, tb);
2945 } else {
2946 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2947 MONO_HANDLE_ASSIGN (ret, mono_type_get_object_handle (domain, m_class_get_byval_arg (generic_class), error));
2950 leave:
2951 return ret;
2954 MonoReflectionTypeHandle
2955 ves_icall_RuntimeType_MakeGenericType (MonoReflectionTypeHandle reftype, MonoArrayHandle type_array, MonoError *error)
2957 error_init (error);
2958 MonoDomain *domain = MONO_HANDLE_DOMAIN (reftype);
2960 g_assert (IS_MONOTYPE_HANDLE (reftype));
2961 MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
2962 mono_class_init_checked (mono_class_from_mono_type_internal (type), error);
2963 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
2965 int count = mono_array_handle_length (type_array);
2966 MonoType **types = g_new0 (MonoType *, count);
2968 MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
2969 for (int i = 0; i < count; i++) {
2970 MONO_HANDLE_ARRAY_GETREF (t, type_array, i);
2971 types [i] = MONO_HANDLE_GETVAL (t, type);
2974 MonoType *geninst = mono_reflection_bind_generic_parameters (reftype, count, types, error);
2975 g_free (types);
2976 if (!geninst) {
2977 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2980 MonoClass *klass = mono_class_from_mono_type_internal (geninst);
2982 /*we might inflate to the GTD*/
2983 if (mono_class_is_ginst (klass) && !mono_verifier_class_is_valid_generic_instantiation (klass)) {
2984 mono_error_set_argument (error, "typeArguments", "Invalid generic arguments");
2985 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2988 return mono_type_get_object_handle (domain, geninst, error);
2991 MonoBoolean
2992 ves_icall_RuntimeTypeHandle_HasInstantiation (MonoReflectionTypeHandle ref_type, MonoError *error)
2994 error_init (error);
2995 MonoClass *klass;
2997 if (!IS_MONOTYPE (MONO_HANDLE_RAW (ref_type)))
2998 return FALSE;
3000 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3001 if (type->byref)
3002 return FALSE;
3004 klass = mono_class_from_mono_type_internal (type);
3005 return mono_class_is_ginst (klass) || mono_class_is_gtd (klass);
3008 gint32
3009 ves_icall_RuntimeType_GetGenericParameterPosition (MonoReflectionTypeHandle ref_type, MonoError *error)
3011 error_init (error);
3012 if (!IS_MONOTYPE_HANDLE (ref_type))
3013 return -1;
3014 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3016 if (is_generic_parameter (type))
3017 return mono_type_get_generic_param_num (type);
3018 return -1;
3021 MonoGenericParamInfo *
3022 ves_icall_RuntimeTypeHandle_GetGenericParameterInfo (MonoReflectionTypeHandle ref_type, MonoError *error)
3024 error_init (error);
3025 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3026 return mono_generic_param_info (type->data.generic_param);
3029 MonoBoolean
3030 ves_icall_RuntimeTypeHandle_IsGenericVariable (MonoReflectionTypeHandle ref_type, MonoError *error)
3032 MonoType *type = MONO_HANDLE_GETVAL(ref_type, type);
3033 return is_generic_parameter (type);
3036 MonoReflectionMethodHandle
3037 ves_icall_RuntimeType_GetCorrespondingInflatedMethod (MonoReflectionTypeHandle ref_type,
3038 MonoReflectionMethodHandle generic,
3039 MonoError *error)
3041 error_init (error);
3042 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3043 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3044 MonoClass *klass = mono_class_from_mono_type_internal (type);
3046 mono_class_init_checked (klass, error);
3047 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3049 MonoMethod *generic_method = MONO_HANDLE_GETVAL (generic, method);
3051 MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3052 MonoMethod *method;
3053 gpointer iter = NULL;
3054 while ((method = mono_class_get_methods (klass, &iter))) {
3055 if (method->token == generic_method->token) {
3056 ret = mono_method_get_object_handle (domain, method, klass, error);
3057 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3061 return ret;
3064 MonoReflectionMethodHandle
3065 ves_icall_RuntimeType_get_DeclaringMethod (MonoReflectionTypeHandle ref_type, MonoError *error)
3067 error_init (error);
3068 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3069 MonoReflectionMethodHandle ret = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
3071 if (type->byref || (type->type != MONO_TYPE_MVAR && type->type != MONO_TYPE_VAR)) {
3072 mono_error_set_invalid_operation (error, "DeclaringMethod can only be used on generic arguments");
3073 goto leave;
3075 if (type->type == MONO_TYPE_VAR)
3076 goto leave;
3078 MonoMethod *method;
3079 method = mono_type_get_generic_param_owner (type)->owner.method;
3080 g_assert (method);
3082 MonoDomain *domain;
3083 domain = MONO_HANDLE_DOMAIN (ref_type);
3085 MONO_HANDLE_ASSIGN (ret, mono_method_get_object_handle (domain, method, method->klass, error));
3086 leave:
3087 return ret;
3090 MonoBoolean
3091 ves_icall_System_RuntimeType_IsTypeExportedToWindowsRuntime (MonoError *error)
3093 error_init (error);
3094 mono_error_set_not_implemented (error, "%s", "System.RuntimeType.IsTypeExportedToWindowsRuntime");
3095 return FALSE;
3098 MonoBoolean
3099 ves_icall_System_RuntimeType_IsWindowsRuntimeObjectType (MonoError *error)
3101 error_init (error);
3102 mono_error_set_not_implemented (error, "%s", "System.RuntimeType.IsWindowsRuntimeObjectType");
3103 return FALSE;
3106 void
3107 ves_icall_RuntimeMethodInfo_GetPInvoke (MonoReflectionMethodHandle ref_method, int* flags, MonoStringHandleOut entry_point, MonoStringHandleOut dll_name, MonoError *error)
3109 MonoDomain *domain = mono_domain_get ();
3110 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3111 MonoImage *image = m_class_get_image (method->klass);
3112 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
3113 MonoTableInfo *tables = image->tables;
3114 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3115 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3116 guint32 im_cols [MONO_IMPLMAP_SIZE];
3117 guint32 scope_token;
3118 const char *import = NULL;
3119 const char *scope = NULL;
3121 error_init (error);
3123 if (image_is_dynamic (image)) {
3124 MonoReflectionMethodAux *method_aux =
3125 (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)image)->method_aux_hash, method);
3126 if (method_aux) {
3127 import = method_aux->dllentry;
3128 scope = method_aux->dll;
3131 if (!import || !scope) {
3132 mono_error_set_argument (error, "method", "System.Refleciton.Emit method with invalid pinvoke information");
3133 return;
3136 else {
3137 if (piinfo->implmap_idx) {
3138 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3140 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
3141 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
3142 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
3143 scope = mono_metadata_string_heap (image, scope_token);
3147 *flags = piinfo->piflags;
3148 MONO_HANDLE_ASSIGN (entry_point, mono_string_new_handle (domain, import, error));
3149 return_if_nok (error);
3150 MONO_HANDLE_ASSIGN (dll_name, mono_string_new_handle (domain, scope, error));
3153 MonoReflectionMethodHandle
3154 ves_icall_RuntimeMethodInfo_GetGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *error)
3156 error_init (error);
3157 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3159 if (method->is_generic)
3160 return ref_method;
3162 if (!method->is_inflated)
3163 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3165 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
3167 MonoMethod *result = imethod->declaring;
3168 /* Not a generic method. */
3169 if (!result->is_generic)
3170 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3172 if (image_is_dynamic (m_class_get_image (method->klass))) {
3173 MonoDynamicImage *image = (MonoDynamicImage*)m_class_get_image (method->klass);
3176 * FIXME: Why is this stuff needed at all ? Why can't the code below work for
3177 * the dynamic case as well ?
3179 mono_image_lock ((MonoImage*)image);
3180 MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, (MonoReflectionMethod*)mono_g_hash_table_lookup (image->generic_def_objects, imethod));
3181 mono_image_unlock ((MonoImage*)image);
3183 if (!MONO_HANDLE_IS_NULL (res))
3184 return res;
3187 if (imethod->context.class_inst) {
3188 MonoClass *klass = ((MonoMethod *) imethod)->klass;
3189 /*Generic methods gets the context of the GTD.*/
3190 if (mono_class_get_context (klass)) {
3191 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
3192 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3196 return mono_method_get_object_handle (MONO_HANDLE_DOMAIN (ref_method), result, NULL, error);
3199 MonoBoolean
3200 ves_icall_RuntimeMethodInfo_get_IsGenericMethod (MonoReflectionMethodHandle ref_method, MonoError *erro)
3202 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3203 return mono_method_signature_internal (method)->generic_param_count != 0;
3206 MonoBoolean
3207 ves_icall_RuntimeMethodInfo_get_IsGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *Error)
3209 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3210 return method->is_generic;
3213 static gboolean
3214 set_array_generic_argument_handle_inflated (MonoDomain *domain, MonoGenericInst *inst, int i, MonoArrayHandle arr, MonoError *error)
3216 HANDLE_FUNCTION_ENTER ();
3217 error_init (error);
3218 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, inst->type_argv [i], error);
3219 goto_if_nok (error, leave);
3220 MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3221 leave:
3222 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3225 static gboolean
3226 set_array_generic_argument_handle_gparam (MonoDomain *domain, MonoGenericContainer *container, int i, MonoArrayHandle arr, MonoError *error)
3228 HANDLE_FUNCTION_ENTER ();
3229 error_init (error);
3230 MonoGenericParam *param = mono_generic_container_get_param (container, i);
3231 MonoClass *pklass = mono_class_create_generic_parameter (param);
3232 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (pklass), error);
3233 goto_if_nok (error, leave);
3234 MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3235 leave:
3236 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3239 MonoArrayHandle
3240 ves_icall_RuntimeMethodInfo_GetGenericArguments (MonoReflectionMethodHandle ref_method, MonoError *error)
3242 error_init (error);
3243 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_method);
3244 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3246 if (method->is_inflated) {
3247 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
3249 if (inst) {
3250 int count = inst->type_argc;
3251 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3252 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3254 for (int i = 0; i < count; i++) {
3255 if (!set_array_generic_argument_handle_inflated (domain, inst, i, res, error))
3256 break;
3258 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3259 return res;
3263 int count = mono_method_signature_internal (method)->generic_param_count;
3264 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3265 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3267 MonoGenericContainer *container = mono_method_get_generic_container (method);
3268 for (int i = 0; i < count; i++) {
3269 if (!set_array_generic_argument_handle_gparam (domain, container, i, res, error))
3270 break;
3272 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3273 return res;
3276 MonoObject *
3277 ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this_arg, MonoArray *params, MonoException **exc)
3279 ERROR_DECL (error);
3281 * Invoke from reflection is supposed to always be a virtual call (the API
3282 * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
3283 * greater flexibility.
3285 MonoMethod *m = method->method;
3286 MonoMethodSignature *sig = mono_method_signature_internal (m);
3287 MonoImage *image;
3288 int pcount;
3289 void *obj = this_arg;
3291 *exc = NULL;
3293 if (mono_security_core_clr_enabled () &&
3294 !mono_security_core_clr_ensure_reflection_access_method (m, error)) {
3295 mono_error_set_pending_exception (error);
3296 return NULL;
3299 if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
3300 if (!mono_class_vtable_checked (mono_object_domain (method), m->klass, error)) {
3301 mono_error_cleanup (error); /* FIXME does this make sense? */
3302 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_class_get_exception_for_failure (m->klass));
3303 return NULL;
3306 if (this_arg) {
3307 if (!mono_object_isinst_checked (this_arg, m->klass, error)) {
3308 if (!is_ok (error)) {
3309 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_error_convert_to_exception (error));
3310 return NULL;
3312 char *this_name = mono_type_get_full_name (mono_object_class (this_arg));
3313 char *target_name = mono_type_get_full_name (m->klass);
3314 char *msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
3315 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", msg));
3316 g_free (msg);
3317 g_free (target_name);
3318 g_free (this_name);
3319 return NULL;
3321 m = mono_object_get_virtual_method_internal (this_arg, m);
3322 /* must pass the pointer to the value for valuetype methods */
3323 if (m_class_is_valuetype (m->klass))
3324 obj = mono_object_unbox_internal (this_arg);
3325 } else if (strcmp (m->name, ".ctor") && !m->wrapper_type) {
3326 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Non-static method requires a target."));
3327 return NULL;
3331 if (sig->ret->byref) {
3332 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method returning ByRef type via reflection"));
3333 return NULL;
3336 pcount = params? mono_array_length_internal (params): 0;
3337 if (pcount != sig->param_count) {
3338 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetParameterCountException"));
3339 return NULL;
3342 if (mono_class_is_abstract (m->klass) && !strcmp (m->name, ".ctor") && !this_arg) {
3343 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Cannot invoke constructor of an abstract class."));
3344 return NULL;
3347 image = m_class_get_image (m->klass);
3348 if (mono_asmctx_get_kind (&image->assembly->context) == MONO_ASMCTX_REFONLY) {
3349 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_get_exception_invalid_operation ("It is illegal to invoke a method on a type loaded using the ReflectionOnly api."));
3350 return NULL;
3353 if (image_is_dynamic (image) && !((MonoDynamicImage*)image)->run) {
3354 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_get_exception_not_supported ("Cannot invoke a method in a dynamic assembly without run access."));
3355 return NULL;
3358 if (m_class_get_rank (m->klass) && !strcmp (m->name, ".ctor")) {
3359 MonoArray *arr;
3360 int i;
3361 uintptr_t *lengths;
3362 intptr_t *lower_bounds;
3363 pcount = mono_array_length_internal (params);
3364 lengths = g_newa (uintptr_t, pcount);
3365 /* Note: the synthetized array .ctors have int32 as argument type */
3366 for (i = 0; i < pcount; ++i)
3367 lengths [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, i) + sizeof (MonoObject));
3369 if (m_class_get_rank (m->klass) == 1 && sig->param_count == 2 && m_class_get_rank (m_class_get_element_class (m->klass))) {
3370 /* This is a ctor for jagged arrays. MS creates an array of arrays. */
3371 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, error);
3372 if (!is_ok (error)) {
3373 mono_error_set_pending_exception (error);
3374 return NULL;
3377 for (i = 0; i < mono_array_length_internal (arr); ++i) {
3378 MonoArray *subarray = mono_array_new_full_checked (mono_object_domain (params), m_class_get_element_class (m->klass), &lengths [1], NULL, error);
3379 if (!is_ok (error)) {
3380 mono_error_set_pending_exception (error);
3381 return NULL;
3383 mono_array_setref_fast (arr, i, subarray);
3385 return (MonoObject*)arr;
3388 if (m_class_get_rank (m->klass) == pcount) {
3389 /* Only lengths provided. */
3390 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, error);
3391 if (!is_ok (error)) {
3392 mono_error_set_pending_exception (error);
3393 return NULL;
3396 return (MonoObject*)arr;
3397 } else {
3398 g_assert (pcount == (m_class_get_rank (m->klass) * 2));
3399 /* The arguments are lower-bound-length pairs */
3400 lower_bounds = (intptr_t *)g_alloca (sizeof (intptr_t) * pcount);
3402 for (i = 0; i < pcount / 2; ++i) {
3403 lower_bounds [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, (i * 2)) + sizeof (MonoObject));
3404 lengths [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, (i * 2) + 1) + sizeof (MonoObject));
3407 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, lower_bounds, error);
3408 if (!is_ok (error)) {
3409 mono_error_set_pending_exception (error);
3410 return NULL;
3413 return (MonoObject*)arr;
3416 MonoObject *result = mono_runtime_invoke_array_checked (m, obj, params, error);
3417 mono_error_set_pending_exception (error);
3418 return result;
3421 #ifndef DISABLE_REMOTING
3422 static void
3423 internal_execute_field_getter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs, MonoError *error)
3425 error_init (error);
3426 MonoArray *out_args;
3427 MonoClass *k = mono_object_class (this_arg);
3428 MonoString *name;
3429 char *str;
3431 /* If this is a proxy, then it must be a CBO */
3432 if (mono_class_is_transparent_proxy (k)) {
3433 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
3434 this_arg = tp->rp->unwrapped_server;
3435 g_assert (this_arg);
3436 k = mono_object_class (this_arg);
3439 name = mono_array_get_internal (params, MonoString *, 1);
3440 str = mono_string_to_utf8_checked_internal (name, error);
3441 return_if_nok (error);
3443 do {
3444 MonoClassField* field = mono_class_get_field_from_name_full (k, str, NULL);
3445 if (field) {
3446 g_free (str);
3447 MonoClass *field_klass = mono_class_from_mono_type_internal (field->type);
3448 MonoObject *result;
3449 if (m_class_is_valuetype (field_klass)) {
3450 result = mono_value_box_checked (domain, field_klass, (char *)this_arg + field->offset, error);
3451 return_if_nok (error);
3452 } else
3453 result = (MonoObject *)*((gpointer *)((char *)this_arg + field->offset));
3455 out_args = mono_array_new_checked (domain, mono_defaults.object_class, 1, error);
3456 return_if_nok (error);
3457 mono_gc_wbarrier_generic_store_internal (outArgs, (MonoObject*) out_args);
3458 mono_array_setref_internal (out_args, 0, result);
3459 return;
3461 k = m_class_get_parent (k);
3462 } while (k);
3464 g_free (str);
3465 g_assert_not_reached ();
3468 static void
3469 internal_execute_field_setter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs, MonoError *error)
3471 error_init (error);
3472 MonoArray *out_args;
3473 MonoClass *k = mono_object_class (this_arg);
3474 MonoString *name;
3475 guint32 size;
3476 gint32 align;
3477 char *str;
3479 /* If this is a proxy, then it must be a CBO */
3480 if (mono_class_is_transparent_proxy (k)) {
3481 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
3482 this_arg = tp->rp->unwrapped_server;
3483 g_assert (this_arg);
3484 k = mono_object_class (this_arg);
3487 name = mono_array_get_internal (params, MonoString *, 1);
3488 str = mono_string_to_utf8_checked_internal (name, error);
3489 return_if_nok (error);
3491 do {
3492 MonoClassField* field = mono_class_get_field_from_name_full (k, str, NULL);
3493 if (field) {
3494 g_free (str);
3495 MonoClass *field_klass = mono_class_from_mono_type_internal (field->type);
3496 MonoObject *val = (MonoObject *)mono_array_get_internal (params, gpointer, 2);
3498 if (m_class_is_valuetype (field_klass)) {
3499 size = mono_type_size (field->type, &align);
3500 g_assert (size == mono_class_value_size (field_klass, NULL));
3501 mono_gc_wbarrier_value_copy_internal ((char *)this_arg + field->offset, (char*)val + sizeof (MonoObject), 1, field_klass);
3502 } else {
3503 mono_gc_wbarrier_set_field_internal (this_arg, (char*)this_arg + field->offset, val);
3506 out_args = mono_array_new_checked (domain, mono_defaults.object_class, 0, error);
3507 return_if_nok (error);
3508 mono_gc_wbarrier_generic_store_internal (outArgs, (MonoObject*) out_args);
3509 return;
3512 k = m_class_get_parent (k);
3513 } while (k);
3515 g_free (str);
3516 g_assert_not_reached ();
3519 MonoObject *
3520 ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs)
3522 ERROR_DECL (error);
3523 MonoDomain *domain = mono_object_domain (method);
3524 MonoMethod *m = method->method;
3525 MonoMethodSignature *sig = mono_method_signature_internal (m);
3526 MonoArray *out_args;
3527 MonoObject *result;
3528 int i, j, outarg_count = 0;
3530 if (m->klass == mono_defaults.object_class) {
3531 if (!strcmp (m->name, "FieldGetter")) {
3532 internal_execute_field_getter (domain, this_arg, params, outArgs, error);
3533 mono_error_set_pending_exception (error);
3534 return NULL;
3535 } else if (!strcmp (m->name, "FieldSetter")) {
3536 internal_execute_field_setter (domain, this_arg, params, outArgs, error);
3537 mono_error_set_pending_exception (error);
3538 return NULL;
3542 for (i = 0; i < mono_array_length_internal (params); i++) {
3543 if (sig->params [i]->byref)
3544 outarg_count++;
3547 out_args = mono_array_new_checked (domain, mono_defaults.object_class, outarg_count, error);
3548 if (mono_error_set_pending_exception (error))
3549 return NULL;
3551 /* handle constructors only for objects already allocated */
3552 if (!strcmp (method->method->name, ".ctor"))
3553 g_assert (this_arg);
3555 /* This can be called only on MBR objects, so no need to unbox for valuetypes. */
3556 g_assert (!m_class_is_valuetype (method->method->klass));
3557 result = mono_runtime_invoke_array_checked (method->method, this_arg, params, error);
3558 if (mono_error_set_pending_exception (error))
3559 return NULL;
3561 for (i = 0, j = 0; i < mono_array_length_internal (params); i++) {
3562 if (sig->params [i]->byref) {
3563 gpointer arg;
3564 arg = mono_array_get_internal (params, gpointer, i);
3565 mono_array_setref_internal (out_args, j, arg);
3566 j++;
3570 mono_gc_wbarrier_generic_store_internal (outArgs, (MonoObject*) out_args);
3572 return result;
3574 #endif
3576 static guint64
3577 read_enum_value (const char *mem, int type)
3579 switch (type) {
3580 case MONO_TYPE_BOOLEAN:
3581 case MONO_TYPE_U1:
3582 return *(guint8*)mem;
3583 case MONO_TYPE_I1:
3584 return *(gint8*)mem;
3585 case MONO_TYPE_CHAR:
3586 case MONO_TYPE_U2:
3587 return read16 (mem);
3588 case MONO_TYPE_I2:
3589 return (gint16) read16 (mem);
3590 case MONO_TYPE_U4:
3591 return read32 (mem);
3592 case MONO_TYPE_I4:
3593 return (gint32) read32 (mem);
3594 case MONO_TYPE_U8:
3595 case MONO_TYPE_I8:
3596 return read64 (mem);
3597 default:
3598 g_assert_not_reached ();
3600 return 0;
3603 static void
3604 write_enum_value (void *mem, int type, guint64 value)
3606 switch (type) {
3607 case MONO_TYPE_U1:
3608 case MONO_TYPE_I1: {
3609 guint8 *p = (guint8*)mem;
3610 *p = value;
3611 break;
3613 case MONO_TYPE_U2:
3614 case MONO_TYPE_I2:
3615 case MONO_TYPE_CHAR: {
3616 guint16 *p = (guint16 *)mem;
3617 *p = value;
3618 break;
3620 case MONO_TYPE_U4:
3621 case MONO_TYPE_I4: {
3622 guint32 *p = (guint32 *)mem;
3623 *p = value;
3624 break;
3626 case MONO_TYPE_U8:
3627 case MONO_TYPE_I8: {
3628 guint64 *p = (guint64 *)mem;
3629 *p = value;
3630 break;
3632 default:
3633 g_assert_not_reached ();
3635 return;
3638 MonoObjectHandle
3639 ves_icall_System_Enum_ToObject (MonoReflectionTypeHandle enumType, guint64 value, MonoError *error)
3641 MonoDomain *domain;
3642 MonoClass *enumc;
3643 MonoObjectHandle resultHandle;
3644 MonoType *etype;
3646 domain = MONO_HANDLE_DOMAIN (enumType);
3647 enumc = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (enumType, type));
3649 mono_class_init_checked (enumc, error);
3650 goto_if_nok (error, return_null);
3652 etype = mono_class_enum_basetype_internal (enumc);
3654 resultHandle = mono_object_new_handle (domain, enumc, error);
3655 goto_if_nok (error, return_null);
3657 write_enum_value (mono_handle_unbox_unsafe (resultHandle), etype->type, value);
3659 return resultHandle;
3661 return_null:
3662 return MONO_HANDLE_NEW (MonoObject, NULL);
3665 MonoBoolean
3666 ves_icall_System_Enum_InternalHasFlag (MonoObjectHandle a, MonoObjectHandle b, MonoError *error)
3668 int size = mono_class_value_size (mono_handle_class (a), NULL);
3669 guint64 a_val = 0, b_val = 0;
3671 memcpy (&a_val, mono_handle_unbox_unsafe (a), size);
3672 memcpy (&b_val, mono_handle_unbox_unsafe (b), size);
3674 return (a_val & b_val) == b_val;
3677 MonoObjectHandle
3678 ves_icall_System_Enum_get_value (MonoObjectHandle ehandle, MonoError *error)
3680 MonoObjectHandle resultHandle;
3681 MonoClass *enumc;
3682 int size;
3684 goto_if (MONO_HANDLE_IS_NULL (ehandle), return_null);
3686 g_assert (m_class_is_enumtype (mono_handle_class (ehandle)));
3688 enumc = mono_class_from_mono_type_internal (mono_class_enum_basetype_internal (mono_handle_class (ehandle)));
3690 resultHandle = mono_object_new_handle (MONO_HANDLE_DOMAIN (ehandle), enumc, error);
3691 goto_if_nok (error, return_null);
3692 size = mono_class_value_size (enumc, NULL);
3694 memcpy (mono_handle_unbox_unsafe (resultHandle), mono_handle_unbox_unsafe (ehandle), size);
3696 return resultHandle;
3697 return_null:
3698 return MONO_HANDLE_NEW (MonoObject, NULL);
3701 MonoReflectionTypeHandle
3702 ves_icall_System_Enum_get_underlying_type (MonoReflectionTypeHandle type, MonoError *error)
3704 MonoType *etype;
3705 MonoClass *klass;
3707 klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
3708 mono_class_init_checked (klass, error);
3709 goto_if_nok (error, return_null);
3711 etype = mono_class_enum_basetype_internal (klass);
3712 if (!etype) {
3713 mono_error_set_argument (error, "enumType", "Type provided must be an Enum.");
3714 goto return_null;
3717 return mono_type_get_object_handle (MONO_HANDLE_DOMAIN (type), etype, error);
3719 return_null:
3720 return MONO_HANDLE_NEW (MonoReflectionType, NULL);
3724 ves_icall_System_Enum_compare_value_to (MonoObjectHandle enumHandle, MonoObjectHandle otherHandle, MonoError *error)
3726 if (MONO_HANDLE_IS_NULL (otherHandle))
3727 return 1;
3729 if (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass != MONO_HANDLE_GETVAL (otherHandle, vtable)->klass)
3730 return 2;
3732 gpointer tdata = mono_handle_unbox_unsafe (enumHandle);
3733 gpointer odata = mono_handle_unbox_unsafe (otherHandle);
3734 MonoType *basetype = mono_class_enum_basetype_internal (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass);
3735 g_assert (basetype);
3737 #define COMPARE_ENUM_VALUES(ENUM_TYPE) do { \
3738 ENUM_TYPE me = *((ENUM_TYPE*)tdata); \
3739 ENUM_TYPE other = *((ENUM_TYPE*)odata); \
3740 if (me == other) \
3741 return 0; \
3742 return me > other ? 1 : -1; \
3743 } while (0)
3745 switch (basetype->type) {
3746 case MONO_TYPE_U1:
3747 COMPARE_ENUM_VALUES (guint8);
3748 case MONO_TYPE_I1:
3749 COMPARE_ENUM_VALUES (gint8);
3750 case MONO_TYPE_CHAR:
3751 case MONO_TYPE_U2:
3752 COMPARE_ENUM_VALUES (guint16);
3753 case MONO_TYPE_I2:
3754 COMPARE_ENUM_VALUES (gint16);
3755 case MONO_TYPE_U4:
3756 COMPARE_ENUM_VALUES (guint32);
3757 case MONO_TYPE_I4:
3758 COMPARE_ENUM_VALUES (gint32);
3759 case MONO_TYPE_U8:
3760 COMPARE_ENUM_VALUES (guint64);
3761 case MONO_TYPE_I8:
3762 COMPARE_ENUM_VALUES (gint64);
3764 #undef COMPARE_ENUM_VALUES
3765 /* indicates that the enum was of an unsupported underlying type */
3766 return 3;
3770 ves_icall_System_Enum_get_hashcode (MonoObjectHandle enumHandle, MonoError *error)
3772 gpointer data = mono_handle_unbox_unsafe (enumHandle);
3773 MonoType *basetype = mono_class_enum_basetype_internal (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass);
3774 g_assert (basetype);
3776 switch (basetype->type) {
3777 case MONO_TYPE_I1: {
3778 gint8 value = *((gint8*)data);
3779 return ((int)value ^ (int)value << 8);
3781 case MONO_TYPE_U1:
3782 return *((guint8*)data);
3783 case MONO_TYPE_CHAR:
3784 case MONO_TYPE_U2:
3785 return *((guint16*)data);
3787 case MONO_TYPE_I2: {
3788 gint16 value = *((gint16*)data);
3789 return ((int)(guint16)value | (((int)value) << 16));
3791 case MONO_TYPE_U4:
3792 return *((guint32*)data);
3793 case MONO_TYPE_I4:
3794 return *((gint32*)data);
3795 case MONO_TYPE_U8:
3796 case MONO_TYPE_I8: {
3797 gint64 value = *((gint64*)data);
3798 return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
3800 default:
3801 g_error ("Implement type 0x%02x in get_hashcode", basetype->type);
3803 return 0;
3806 static void
3807 get_enum_field (MonoDomain *domain, MonoArrayHandle names, MonoArrayHandle values, int base_type, MonoClassField *field, guint* j, guint64 *previous_value, gboolean *sorted, MonoError *error)
3809 error_init (error);
3810 HANDLE_FUNCTION_ENTER();
3811 guint64 field_value;
3812 const char *p;
3813 MonoTypeEnum def_type;
3815 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3816 goto leave;
3817 if (strcmp ("value__", mono_field_get_name (field)) == 0)
3818 goto leave;
3819 if (mono_field_is_deleted (field))
3820 goto leave;
3821 MonoStringHandle name;
3822 name = mono_string_new_handle (domain, mono_field_get_name (field), error);
3823 goto_if_nok (error, leave);
3824 MONO_HANDLE_ARRAY_SETREF (names, *j, name);
3826 p = mono_class_get_field_default_value (field, &def_type);
3827 /* len = */ mono_metadata_decode_blob_size (p, &p);
3829 field_value = read_enum_value (p, base_type);
3830 MONO_HANDLE_ARRAY_SETVAL (values, guint64, *j, field_value);
3832 if (*previous_value > field_value)
3833 *sorted = FALSE;
3835 *previous_value = field_value;
3836 (*j)++;
3837 leave:
3838 HANDLE_FUNCTION_RETURN();
3841 MonoBoolean
3842 ves_icall_System_Enum_GetEnumValuesAndNames (MonoReflectionTypeHandle type, MonoArrayHandleOut values, MonoArrayHandleOut names, MonoError *error)
3844 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
3845 MonoClass *enumc = mono_class_from_mono_type_internal (MONO_HANDLE_RAW(type)->type);
3846 guint j = 0, nvalues;
3847 gpointer iter;
3848 MonoClassField *field;
3849 int base_type;
3850 guint64 previous_value = 0;
3851 gboolean sorted = TRUE;
3853 error_init (error);
3854 mono_class_init_checked (enumc, error);
3855 return_val_if_nok (error, FALSE);
3857 if (!m_class_is_enumtype (enumc)) {
3858 mono_error_set_argument (error, "enumType", "Type provided must be an Enum.");
3859 return TRUE;
3862 base_type = mono_class_enum_basetype_internal (enumc)->type;
3864 nvalues = mono_class_num_fields (enumc) > 0 ? mono_class_num_fields (enumc) - 1 : 0;
3865 MONO_HANDLE_ASSIGN(names, mono_array_new_handle (domain, mono_defaults.string_class, nvalues, error));
3866 return_val_if_nok (error, FALSE);
3867 MONO_HANDLE_ASSIGN(values, mono_array_new_handle (domain, mono_defaults.uint64_class, nvalues, error));
3868 return_val_if_nok (error, FALSE);
3870 iter = NULL;
3871 while ((field = mono_class_get_fields_internal (enumc, &iter))) {
3872 get_enum_field(domain, names, values, base_type, field, &j, &previous_value, &sorted, error);
3873 if (!is_ok (error))
3874 break;
3876 return_val_if_nok (error, FALSE);
3878 return sorted;
3881 enum {
3882 BFLAGS_IgnoreCase = 1,
3883 BFLAGS_DeclaredOnly = 2,
3884 BFLAGS_Instance = 4,
3885 BFLAGS_Static = 8,
3886 BFLAGS_Public = 0x10,
3887 BFLAGS_NonPublic = 0x20,
3888 BFLAGS_FlattenHierarchy = 0x40,
3889 BFLAGS_InvokeMethod = 0x100,
3890 BFLAGS_CreateInstance = 0x200,
3891 BFLAGS_GetField = 0x400,
3892 BFLAGS_SetField = 0x800,
3893 BFLAGS_GetProperty = 0x1000,
3894 BFLAGS_SetProperty = 0x2000,
3895 BFLAGS_ExactBinding = 0x10000,
3896 BFLAGS_SuppressChangeType = 0x20000,
3897 BFLAGS_OptionalParamBinding = 0x40000
3900 enum {
3901 MLISTTYPE_All = 0,
3902 MLISTTYPE_CaseSensitive = 1,
3903 MLISTTYPE_CaseInsensitive = 2,
3904 MLISTTYPE_HandleToInfo = 3
3907 GPtrArray*
3908 ves_icall_RuntimeType_GetFields_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 bflags, guint32 mlisttype, MonoError *error)
3910 error_init (error);
3911 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3913 if (type->byref) {
3914 return g_ptr_array_new ();
3917 int (*compare_func) (const char *s1, const char *s2) = NULL;
3918 compare_func = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
3920 MonoClass *startklass, *klass;
3921 klass = startklass = mono_class_from_mono_type_internal (type);
3923 GPtrArray *ptr_array = g_ptr_array_sized_new (16);
3925 handle_parent:
3926 if (mono_class_has_failure (klass)) {
3927 mono_error_set_for_class_failure (error, klass);
3928 goto fail;
3931 MonoClassField *field;
3932 gpointer iter;
3933 iter = NULL;
3934 while ((field = mono_class_get_fields_lazy (klass, &iter))) {
3935 guint32 flags = mono_field_get_flags (field);
3936 int match = 0;
3937 if (mono_field_is_deleted_with_flags (field, flags))
3938 continue;
3939 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
3940 if (bflags & BFLAGS_Public)
3941 match++;
3942 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
3943 if (bflags & BFLAGS_NonPublic) {
3944 match++;
3947 if (!match)
3948 continue;
3949 match = 0;
3950 if (flags & FIELD_ATTRIBUTE_STATIC) {
3951 if (bflags & BFLAGS_Static)
3952 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3953 match++;
3954 } else {
3955 if (bflags & BFLAGS_Instance)
3956 match++;
3959 if (!match)
3960 continue;
3962 if (((mlisttype != MLISTTYPE_All) && (utf8_name != NULL)) && compare_func (mono_field_get_name (field), utf8_name))
3963 continue;
3965 g_ptr_array_add (ptr_array, field);
3967 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
3968 goto handle_parent;
3970 return ptr_array;
3972 fail:
3973 g_ptr_array_free (ptr_array, TRUE);
3974 return NULL;
3977 static gboolean
3978 method_nonpublic (MonoMethod* method, gboolean start_klass)
3980 switch (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) {
3981 case METHOD_ATTRIBUTE_ASSEM:
3982 return (start_klass || mono_defaults.generic_ilist_class);
3983 case METHOD_ATTRIBUTE_PRIVATE:
3984 return start_klass;
3985 case METHOD_ATTRIBUTE_PUBLIC:
3986 return FALSE;
3987 default:
3988 return TRUE;
3992 GPtrArray*
3993 mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, guint32 mlisttype, gboolean allow_ctors, MonoError *error)
3995 GPtrArray *array;
3996 MonoClass *startklass;
3997 MonoMethod *method;
3998 gpointer iter;
3999 int match, nslots;
4000 /*FIXME, use MonoBitSet*/
4001 guint32 method_slots_default [8];
4002 guint32 *method_slots = NULL;
4003 int (*compare_func) (const char *s1, const char *s2) = NULL;
4005 array = g_ptr_array_new ();
4006 startklass = klass;
4007 error_init (error);
4009 compare_func = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
4011 /* An optimization for calls made from Delegate:CreateDelegate () */
4012 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))) {
4013 method = mono_get_delegate_invoke_internal (klass);
4014 g_assert (method);
4016 g_ptr_array_add (array, method);
4017 return array;
4020 mono_class_setup_methods (klass);
4021 mono_class_setup_vtable (klass);
4022 if (mono_class_has_failure (klass))
4023 goto loader_error;
4025 if (is_generic_parameter (m_class_get_byval_arg (klass)))
4026 nslots = mono_class_get_vtable_size (m_class_get_parent (klass));
4027 else
4028 nslots = MONO_CLASS_IS_INTERFACE_INTERNAL (klass) ? mono_class_num_methods (klass) : mono_class_get_vtable_size (klass);
4029 if (nslots >= sizeof (method_slots_default) * 8) {
4030 method_slots = g_new0 (guint32, nslots / 32 + 1);
4031 } else {
4032 method_slots = method_slots_default;
4033 memset (method_slots, 0, sizeof (method_slots_default));
4035 handle_parent:
4036 mono_class_setup_methods (klass);
4037 mono_class_setup_vtable (klass);
4038 if (mono_class_has_failure (klass))
4039 goto loader_error;
4041 iter = NULL;
4042 while ((method = mono_class_get_methods (klass, &iter))) {
4043 match = 0;
4044 if (method->slot != -1) {
4045 g_assert (method->slot < nslots);
4046 if (method_slots [method->slot >> 5] & (1 << (method->slot & 0x1f)))
4047 continue;
4048 if (!(method->flags & METHOD_ATTRIBUTE_NEW_SLOT))
4049 method_slots [method->slot >> 5] |= 1 << (method->slot & 0x1f);
4052 if (!allow_ctors && method->name [0] == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0))
4053 continue;
4054 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4055 if (bflags & BFLAGS_Public)
4056 match++;
4057 } else if ((bflags & BFLAGS_NonPublic) && method_nonpublic (method, (klass == startklass))) {
4058 match++;
4060 if (!match)
4061 continue;
4062 match = 0;
4063 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4064 if (bflags & BFLAGS_Static)
4065 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4066 match++;
4067 } else {
4068 if (bflags & BFLAGS_Instance)
4069 match++;
4072 if (!match)
4073 continue;
4075 if ((mlisttype != MLISTTYPE_All) && (name != NULL)) {
4076 if (compare_func (name, method->name))
4077 continue;
4080 match = 0;
4081 g_ptr_array_add (array, method);
4083 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
4084 goto handle_parent;
4085 if (method_slots != method_slots_default)
4086 g_free (method_slots);
4088 return array;
4090 loader_error:
4091 if (method_slots != method_slots_default)
4092 g_free (method_slots);
4093 g_ptr_array_free (array, TRUE);
4095 g_assert (mono_class_has_failure (klass));
4096 mono_error_set_for_class_failure (error, klass);
4097 return NULL;
4100 GPtrArray*
4101 ves_icall_RuntimeType_GetMethodsByName_native (MonoReflectionTypeHandle ref_type, const char *mname, guint32 bflags, guint32 mlisttype, MonoError *error)
4103 error_init (error);
4104 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4106 MonoClass *klass = mono_class_from_mono_type_internal (type);
4107 if (type->byref) {
4108 return g_ptr_array_new ();
4111 return mono_class_get_methods_by_name (klass, mname, bflags, mlisttype, FALSE, error);
4114 GPtrArray*
4115 ves_icall_RuntimeType_GetConstructors_native (MonoReflectionTypeHandle ref_type, guint32 bflags, MonoError *error)
4117 error_init (error);
4118 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4119 if (type->byref) {
4120 return g_ptr_array_new ();
4123 MonoClass *startklass, *klass;
4124 klass = startklass = mono_class_from_mono_type_internal (type);
4126 mono_class_setup_methods (klass);
4127 if (mono_class_has_failure (klass)) {
4128 mono_error_set_for_class_failure (error, klass);
4129 return NULL;
4133 GPtrArray *res_array = g_ptr_array_sized_new (4); /* FIXME, guestimating */
4135 MonoMethod *method;
4136 gpointer iter = NULL;
4137 while ((method = mono_class_get_methods (klass, &iter))) {
4138 int match = 0;
4139 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
4140 continue;
4141 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4142 if (bflags & BFLAGS_Public)
4143 match++;
4144 } else {
4145 if (bflags & BFLAGS_NonPublic)
4146 match++;
4148 if (!match)
4149 continue;
4150 match = 0;
4151 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4152 if (bflags & BFLAGS_Static)
4153 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4154 match++;
4155 } else {
4156 if (bflags & BFLAGS_Instance)
4157 match++;
4160 if (!match)
4161 continue;
4162 g_ptr_array_add (res_array, method);
4165 return res_array;
4168 static guint
4169 property_hash (gconstpointer data)
4171 MonoProperty *prop = (MonoProperty*)data;
4173 return g_str_hash (prop->name);
4176 static gboolean
4177 property_accessor_override (MonoMethod *method1, MonoMethod *method2)
4179 if (method1->slot != -1 && method1->slot == method2->slot)
4180 return TRUE;
4182 if (mono_class_get_generic_type_definition (method1->klass) == mono_class_get_generic_type_definition (method2->klass)) {
4183 if (method1->is_inflated)
4184 method1 = ((MonoMethodInflated*) method1)->declaring;
4185 if (method2->is_inflated)
4186 method2 = ((MonoMethodInflated*) method2)->declaring;
4189 return mono_metadata_signature_equal (mono_method_signature_internal (method1), mono_method_signature_internal (method2));
4192 static gboolean
4193 property_equal (MonoProperty *prop1, MonoProperty *prop2)
4195 // Properties are hide-by-name-and-signature
4196 if (!g_str_equal (prop1->name, prop2->name))
4197 return FALSE;
4199 /* If we see a property in a generic method, we want to
4200 compare the generic signatures, not the inflated signatures
4201 because we might conflate two properties that were
4202 distinct:
4204 class Foo<T,U> {
4205 public T this[T t] { getter { return t; } } // method 1
4206 public U this[U u] { getter { return u; } } // method 2
4209 If we see int Foo<int,int>::Item[int] we need to know if
4210 the indexer came from method 1 or from method 2, and we
4211 shouldn't conflate them. (Bugzilla 36283)
4213 if (prop1->get && prop2->get && !property_accessor_override (prop1->get, prop2->get))
4214 return FALSE;
4216 if (prop1->set && prop2->set && !property_accessor_override (prop1->set, prop2->set))
4217 return FALSE;
4219 return TRUE;
4222 static gboolean
4223 property_accessor_nonpublic (MonoMethod* accessor, gboolean start_klass)
4225 if (!accessor)
4226 return FALSE;
4228 return method_nonpublic (accessor, start_klass);
4231 GPtrArray*
4232 ves_icall_RuntimeType_GetPropertiesByName_native (MonoReflectionTypeHandle ref_type, gchar *propname, guint32 bflags, guint32 mlisttype, MonoError *error)
4234 error_init (error);
4235 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4238 if (type->byref) {
4239 return g_ptr_array_new ();
4243 MonoClass *startklass, *klass;
4244 klass = startklass = mono_class_from_mono_type_internal (type);
4246 int (*compare_func) (const char *s1, const char *s2) = (mlisttype == MLISTTYPE_CaseInsensitive) ? mono_utf8_strcasecmp : strcmp;
4248 GPtrArray *res_array = g_ptr_array_sized_new (8); /*This the average for ASP.NET types*/
4250 GHashTable *properties = g_hash_table_new (property_hash, (GEqualFunc)property_equal);
4252 handle_parent:
4253 mono_class_setup_methods (klass);
4254 mono_class_setup_vtable (klass);
4255 if (mono_class_has_failure (klass)) {
4256 mono_error_set_for_class_failure (error, klass);
4257 goto loader_error;
4260 MonoProperty *prop;
4261 gpointer iter;
4262 iter = NULL;
4263 while ((prop = mono_class_get_properties (klass, &iter))) {
4264 int match = 0;
4265 MonoMethod *method = prop->get;
4266 if (!method)
4267 method = prop->set;
4268 guint32 flags = 0;
4269 if (method)
4270 flags = method->flags;
4271 if ((prop->get && ((prop->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)) ||
4272 (prop->set && ((prop->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC))) {
4273 if (bflags & BFLAGS_Public)
4274 match++;
4275 } else if (bflags & BFLAGS_NonPublic) {
4276 if (property_accessor_nonpublic(prop->get, startklass == klass) ||
4277 property_accessor_nonpublic(prop->set, startklass == klass)) {
4278 match++;
4281 if (!match)
4282 continue;
4283 match = 0;
4284 if (flags & METHOD_ATTRIBUTE_STATIC) {
4285 if (bflags & BFLAGS_Static)
4286 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4287 match++;
4288 } else {
4289 if (bflags & BFLAGS_Instance)
4290 match++;
4293 if (!match)
4294 continue;
4295 match = 0;
4297 if ((mlisttype != MLISTTYPE_All) && (propname != NULL) && compare_func (propname, prop->name))
4298 continue;
4300 if (g_hash_table_lookup (properties, prop))
4301 continue;
4303 g_ptr_array_add (res_array, prop);
4305 g_hash_table_insert (properties, prop, prop);
4307 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
4308 goto handle_parent;
4310 g_hash_table_destroy (properties);
4312 return res_array;
4315 loader_error:
4316 if (properties)
4317 g_hash_table_destroy (properties);
4318 g_ptr_array_free (res_array, TRUE);
4320 return NULL;
4323 static guint
4324 event_hash (gconstpointer data)
4326 MonoEvent *event = (MonoEvent*)data;
4328 return g_str_hash (event->name);
4331 static gboolean
4332 event_equal (MonoEvent *event1, MonoEvent *event2)
4334 // Events are hide-by-name
4335 return g_str_equal (event1->name, event2->name);
4338 GPtrArray*
4339 ves_icall_RuntimeType_GetEvents_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 mlisttype, MonoError *error)
4341 error_init (error);
4342 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4344 if (type->byref) {
4345 return g_ptr_array_new ();
4348 int (*compare_func) (const char *s1, const char *s2) = (mlisttype == MLISTTYPE_CaseInsensitive) ? mono_utf8_strcasecmp : strcmp;
4350 GPtrArray *res_array = g_ptr_array_sized_new (4);
4352 MonoClass *startklass, *klass;
4353 klass = startklass = mono_class_from_mono_type_internal (type);
4355 GHashTable *events = g_hash_table_new (event_hash, (GEqualFunc)event_equal);
4356 handle_parent:
4357 mono_class_setup_methods (klass);
4358 mono_class_setup_vtable (klass);
4359 if (mono_class_has_failure (klass)) {
4360 mono_error_set_for_class_failure (error, klass);
4361 goto failure;
4364 MonoEvent *event;
4365 gpointer iter;
4366 iter = NULL;
4367 while ((event = mono_class_get_events (klass, &iter))) {
4369 // Remove inherited privates and inherited
4370 // without add/remove/raise methods
4371 if (klass != startklass)
4373 MonoMethod *method = event->add;
4374 if (!method)
4375 method = event->remove;
4376 if (!method)
4377 method = event->raise;
4378 if (!method)
4379 continue;
4380 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PRIVATE)
4381 continue;
4384 if ((mlisttype != MLISTTYPE_All) && (utf8_name != NULL) && compare_func (event->name, utf8_name))
4385 continue;
4387 if (g_hash_table_lookup (events, event))
4388 continue;
4390 g_ptr_array_add (res_array, event);
4392 g_hash_table_insert (events, event, event);
4394 if ((klass = m_class_get_parent (klass)))
4395 goto handle_parent;
4397 g_hash_table_destroy (events);
4399 return res_array;
4401 failure:
4402 if (events != NULL)
4403 g_hash_table_destroy (events);
4405 g_ptr_array_free (res_array, TRUE);
4407 return NULL;
4410 GPtrArray *
4411 ves_icall_RuntimeType_GetNestedTypes_native (MonoReflectionTypeHandle ref_type, char *str, guint32 bflags, guint32 mlisttype, MonoError *error)
4413 error_init (error);
4414 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4416 if (type->byref) {
4417 return g_ptr_array_new ();
4420 int (*compare_func) (const char *s1, const char *s2) = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
4422 MonoClass *klass = mono_class_from_mono_type_internal (type);
4425 * If a nested type is generic, return its generic type definition.
4426 * Note that this means that the return value is essentially the set
4427 * of nested types of the generic type definition of @klass.
4429 * A note in MSDN claims that a generic type definition can have
4430 * nested types that aren't generic. In any case, the container of that
4431 * nested type would be the generic type definition.
4433 if (mono_class_is_ginst (klass))
4434 klass = mono_class_get_generic_class (klass)->container_class;
4436 GPtrArray *res_array = g_ptr_array_new ();
4438 MonoClass *nested;
4439 gpointer iter = NULL;
4440 while ((nested = mono_class_get_nested_types (klass, &iter))) {
4441 int match = 0;
4442 if ((mono_class_get_flags (nested) & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
4443 if (bflags & BFLAGS_Public)
4444 match++;
4445 } else {
4446 if (bflags & BFLAGS_NonPublic)
4447 match++;
4449 if (!match)
4450 continue;
4452 if ((mlisttype != MLISTTYPE_All) && (str != NULL) && compare_func (m_class_get_name (nested), str))
4453 continue;
4455 g_ptr_array_add (res_array, m_class_get_byval_arg (nested));
4458 return res_array;
4461 static MonoType*
4462 get_type_from_module_builder_module (MonoArrayHandle modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
4464 HANDLE_FUNCTION_ENTER ();
4465 error_init (error);
4466 MonoType *type = NULL;
4467 MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW (MonoReflectionModuleBuilder, NULL);
4468 MONO_HANDLE_ARRAY_GETREF (mb, modules, i);
4469 MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
4470 type = mono_reflection_get_type_checked (&dynamic_image->image, &dynamic_image->image, info, ignoreCase, type_resolve, error);
4471 HANDLE_FUNCTION_RETURN_VAL (type);
4474 static MonoType*
4475 get_type_from_module_builder_loaded_modules (MonoArrayHandle loaded_modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
4477 HANDLE_FUNCTION_ENTER ();
4478 error_init (error);
4479 MonoType *type = NULL;
4480 MonoReflectionModuleHandle mod = MONO_HANDLE_NEW (MonoReflectionModule, NULL);
4481 MONO_HANDLE_ARRAY_GETREF (mod, loaded_modules, i);
4482 MonoImage *image = MONO_HANDLE_GETVAL (mod, image);
4483 type = mono_reflection_get_type_checked (image, image, info, ignoreCase, type_resolve, error);
4484 HANDLE_FUNCTION_RETURN_VAL (type);
4487 MonoReflectionTypeHandle
4488 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssemblyHandle assembly_h, MonoReflectionModuleHandle module, MonoStringHandle name, MonoBoolean throwOnError, MonoBoolean ignoreCase, MonoError *error)
4490 error_init (error);
4491 ERROR_DECL (parse_error);
4493 MonoTypeNameParse info;
4494 gboolean type_resolve;
4496 /* On MS.NET, this does not fire a TypeResolve event */
4497 type_resolve = TRUE;
4498 char *str = mono_string_handle_to_utf8 (name, error);
4499 goto_if_nok (error, fail);
4501 /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
4502 if (!mono_reflection_parse_type_checked (str, &info, parse_error)) {
4503 g_free (str);
4504 mono_reflection_free_type_info (&info);
4505 mono_error_cleanup (parse_error);
4506 if (throwOnError) {
4507 mono_error_set_argument (error, "typeName", "failed to parse the type");
4508 goto fail;
4510 /*g_print ("failed parse\n");*/
4511 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4514 if (info.assembly.name) {
4515 g_free (str);
4516 mono_reflection_free_type_info (&info);
4517 if (throwOnError) {
4518 /* 1.0 and 2.0 throw different exceptions */
4519 if (mono_defaults.generic_ilist_class)
4520 mono_error_set_argument (error, NULL, "Type names passed to Assembly.GetType() must not specify an assembly.");
4521 else
4522 mono_error_set_type_load_name (error, g_strdup (""), g_strdup (""), "Type names passed to Assembly.GetType() must not specify an assembly.");
4523 goto fail;
4525 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4528 MonoType *type;
4529 type = NULL;
4530 if (!MONO_HANDLE_IS_NULL (module)) {
4531 MonoImage *image = MONO_HANDLE_GETVAL (module, image);
4532 if (image) {
4533 type = mono_reflection_get_type_checked (image, image, &info, ignoreCase, &type_resolve, error);
4534 if (!is_ok (error)) {
4535 g_free (str);
4536 mono_reflection_free_type_info (&info);
4537 goto fail;
4541 else {
4542 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4543 if (assembly_is_dynamic (assembly)) {
4544 /* Enumerate all modules */
4545 MonoReflectionAssemblyBuilderHandle abuilder = MONO_HANDLE_NEW (MonoReflectionAssemblyBuilder, NULL);
4546 MONO_HANDLE_ASSIGN (abuilder, assembly_h);
4547 int i;
4549 MonoArrayHandle modules = MONO_HANDLE_NEW (MonoArray, NULL);
4550 MONO_HANDLE_GET (modules, abuilder, modules);
4551 if (!MONO_HANDLE_IS_NULL (modules)) {
4552 int n = mono_array_handle_length (modules);
4553 for (i = 0; i < n; ++i) {
4554 type = get_type_from_module_builder_module (modules, i, &info, ignoreCase, &type_resolve, error);
4555 if (!is_ok (error)) {
4556 g_free (str);
4557 mono_reflection_free_type_info (&info);
4558 goto fail;
4560 if (type)
4561 break;
4565 MonoArrayHandle loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL);
4566 MONO_HANDLE_GET (loaded_modules, abuilder, loaded_modules);
4567 if (!type && !MONO_HANDLE_IS_NULL (loaded_modules)) {
4568 int n = mono_array_handle_length (loaded_modules);
4569 for (i = 0; i < n; ++i) {
4570 type = get_type_from_module_builder_loaded_modules (loaded_modules, i, &info, ignoreCase, &type_resolve, error);
4572 if (!is_ok (error)) {
4573 g_free (str);
4574 mono_reflection_free_type_info (&info);
4575 goto fail;
4577 if (type)
4578 break;
4582 else {
4583 type = mono_reflection_get_type_checked (assembly->image, assembly->image, &info, ignoreCase, &type_resolve, error);
4584 if (!is_ok (error)) {
4585 g_free (str);
4586 mono_reflection_free_type_info (&info);
4587 goto fail;
4591 g_free (str);
4592 mono_reflection_free_type_info (&info);
4594 if (!type) {
4595 if (throwOnError) {
4596 ERROR_DECL (inner_error);
4597 char *type_name = mono_string_handle_to_utf8 (name, inner_error);
4598 mono_error_assert_ok (inner_error);
4599 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4600 char *assmname = mono_stringify_assembly_name (&assembly->aname);
4601 mono_error_set_type_load_name (error, type_name, assmname, "%s", "");
4602 goto fail;
4605 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4608 if (type->type == MONO_TYPE_CLASS) {
4609 MonoClass *klass = mono_type_get_class (type);
4611 /* need to report exceptions ? */
4612 if (throwOnError && mono_class_has_failure (klass)) {
4613 /* report SecurityException (or others) that occured when loading the assembly */
4614 mono_error_set_for_class_failure (error, klass);
4615 goto fail;
4619 /* g_print ("got it\n"); */
4620 return mono_type_get_object_handle (MONO_HANDLE_DOMAIN (assembly_h), type, error);
4621 fail:
4622 g_assert (!is_ok (error));
4623 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4626 static gboolean
4627 replace_shadow_path (MonoDomain *domain, gchar *dirname, gchar **filename)
4629 gchar *content;
4630 gchar *shadow_ini_file;
4631 gsize len;
4633 /* Check for shadow-copied assembly */
4634 if (mono_is_shadow_copy_enabled (domain, dirname)) {
4635 shadow_ini_file = g_build_filename (dirname, "__AssemblyInfo__.ini", NULL);
4636 content = NULL;
4637 if (!g_file_get_contents (shadow_ini_file, &content, &len, NULL) ||
4638 !g_file_test (content, G_FILE_TEST_IS_REGULAR)) {
4639 g_free (content);
4640 content = NULL;
4642 g_free (shadow_ini_file);
4643 if (content != NULL) {
4644 g_free (*filename);
4645 *filename = content;
4646 return TRUE;
4649 return FALSE;
4652 MonoStringHandle
4653 ves_icall_System_Reflection_RuntimeAssembly_get_code_base (MonoReflectionAssemblyHandle assembly, MonoBoolean escaped, MonoError *error)
4655 error_init (error);
4656 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
4657 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
4658 gchar *absolute;
4659 gchar *dirname;
4661 if (g_path_is_absolute (mass->image->name)) {
4662 absolute = g_strdup (mass->image->name);
4663 dirname = g_path_get_dirname (absolute);
4664 } else {
4665 absolute = g_build_filename (mass->basedir, mass->image->name, NULL);
4666 dirname = g_strdup (mass->basedir);
4669 replace_shadow_path (domain, dirname, &absolute);
4670 g_free (dirname);
4672 mono_icall_make_platform_path (absolute);
4674 gchar *uri;
4675 if (escaped) {
4676 uri = g_filename_to_uri (absolute, NULL, NULL);
4677 } else {
4678 const gchar *prepend = mono_icall_get_file_path_prefix (absolute);
4679 uri = g_strconcat (prepend, absolute, NULL);
4682 g_free (absolute);
4684 MonoStringHandle res;
4685 if (uri) {
4686 res = mono_string_new_handle (domain, uri, error);
4687 g_free (uri);
4688 } else {
4689 res = MONO_HANDLE_NEW (MonoString, NULL);
4691 return res;
4694 MonoBoolean
4695 ves_icall_System_Reflection_RuntimeAssembly_get_global_assembly_cache (MonoReflectionAssemblyHandle assembly, MonoError *error)
4697 error_init (error);
4698 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly,assembly);
4700 return mass->in_gac;
4703 MonoReflectionAssemblyHandle
4704 ves_icall_System_Reflection_Assembly_load_with_partial_name (MonoStringHandle mname, MonoObjectHandle evidence, MonoError *error)
4706 gchar *name;
4707 MonoImageOpenStatus status;
4708 MonoReflectionAssemblyHandle result = MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
4710 name = mono_string_handle_to_utf8 (mname, error);
4711 goto_if_nok (error, leave);
4712 MonoAssembly *res;
4713 res = mono_assembly_load_with_partial_name_internal (name, &status);
4715 g_free (name);
4717 if (res == NULL)
4718 goto leave;
4719 result = mono_assembly_get_object_handle (mono_domain_get (), res, error);
4720 leave:
4721 return result;
4724 MonoStringHandle
4725 ves_icall_System_Reflection_RuntimeAssembly_get_location (MonoReflectionAssemblyHandle refassembly, MonoError *error)
4727 MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
4728 MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
4729 return mono_string_new_handle (domain, mono_image_get_filename (assembly->image), error);
4732 MonoBoolean
4733 ves_icall_System_Reflection_RuntimeAssembly_get_ReflectionOnly (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
4735 error_init (error);
4736 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4737 return mono_asmctx_get_kind (&assembly->context) == MONO_ASMCTX_REFONLY;
4740 MonoStringHandle
4741 ves_icall_System_Reflection_RuntimeAssembly_InternalImageRuntimeVersion (MonoReflectionAssemblyHandle refassembly, MonoError *error)
4743 MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
4744 MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
4746 return mono_string_new_handle (domain, assembly->image->version, error);
4749 MonoReflectionMethodHandle
4750 ves_icall_System_Reflection_RuntimeAssembly_get_EntryPoint (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
4752 error_init (error);
4753 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4754 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4755 MonoMethod *method;
4757 MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
4758 guint32 token = mono_image_get_entry_point (assembly->image);
4760 if (!token)
4761 goto leave;
4762 method = mono_get_method_checked (assembly->image, token, NULL, NULL, error);
4763 goto_if_nok (error, leave);
4765 MONO_HANDLE_ASSIGN (res, mono_method_get_object_handle (domain, method, NULL, error));
4766 leave:
4767 return res;
4770 MonoReflectionModuleHandle
4771 ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAssemblyHandle assembly, MonoError *error)
4773 error_init (error);
4774 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
4775 MonoAssembly *a = MONO_HANDLE_GETVAL (assembly, assembly);
4776 return mono_module_get_object_handle (domain, a->image, error);
4779 static gboolean
4780 add_manifest_resource_name_to_array (MonoDomain *domain, MonoImage *image, MonoTableInfo *table, int i, MonoArrayHandle dest, MonoError *error)
4782 HANDLE_FUNCTION_ENTER ();
4783 error_init (error);
4784 const char *val = mono_metadata_string_heap (image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
4785 MonoStringHandle str = mono_string_new_handle (domain, val, error);
4786 goto_if_nok (error, leave);
4787 MONO_HANDLE_ARRAY_SETREF (dest, i, str);
4788 leave:
4789 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
4792 MonoArrayHandle
4793 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceNames (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
4795 error_init (error);
4796 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4797 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4798 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4799 MonoArrayHandle result = mono_array_new_handle (domain, mono_defaults.string_class, table->rows, error);
4800 goto_if_nok (error, fail);
4801 int i;
4803 for (i = 0; i < table->rows; ++i) {
4804 if (!add_manifest_resource_name_to_array (domain, assembly->image, table, i, result, error))
4805 goto fail;
4807 return result;
4808 fail:
4809 return NULL_HANDLE_ARRAY;
4812 MonoStringHandle
4813 ves_icall_System_Reflection_RuntimeAssembly_GetAotId (MonoError *error)
4815 char *guid = mono_runtime_get_aotid ();
4816 if (guid == NULL)
4817 return MONO_HANDLE_CAST (MonoString, mono_new_null ());
4818 MonoStringHandle res = mono_string_new_handle (mono_domain_get (), guid, error);
4819 g_free (guid);
4820 return res;
4823 static MonoAssemblyName*
4824 create_referenced_assembly_name (MonoDomain *domain, MonoImage *image, MonoTableInfo *t, int i, MonoError *error)
4826 error_init (error);
4827 MonoAssemblyName *aname = g_new0 (MonoAssemblyName, 1);
4829 mono_assembly_get_assemblyref_checked (image, i, aname, error);
4830 return_val_if_nok (error, NULL);
4831 aname->hash_alg = ASSEMBLY_HASH_SHA1 /* SHA1 (default) */;
4832 /* name and culture are pointers into the image tables, but we need
4833 * real malloc'd strings (so that we can g_free() them later from
4834 * Mono.RuntimeMarshal.FreeAssemblyName) */
4835 aname->name = g_strdup (aname->name);
4836 aname->culture = g_strdup (aname->culture);
4837 /* Don't need the hash value in managed */
4838 aname->hash_value = NULL;
4839 aname->hash_len = 0;
4840 g_assert (aname->public_key == NULL);
4842 /* note: this function doesn't return the codebase on purpose (i.e. it can
4843 be used under partial trust as path information isn't present). */
4844 return aname;
4847 GPtrArray*
4848 ves_icall_System_Reflection_Assembly_InternalGetReferencedAssemblies (MonoReflectionAssemblyHandle assembly, MonoError *error)
4850 error_init (error);
4851 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
4852 MonoAssembly *ass = MONO_HANDLE_GETVAL(assembly, assembly);
4853 MonoImage *image = ass->image;
4855 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
4856 int count = t->rows;
4858 GPtrArray *result = g_ptr_array_sized_new (count);
4860 for (int i = 0; i < count; i++) {
4861 MonoAssemblyName *aname = create_referenced_assembly_name (domain, image, t, i, error);
4862 if (!is_ok (error))
4863 break;
4864 g_ptr_array_add (result, aname);
4866 return result;
4869 /* move this in some file in mono/util/ */
4870 static char *
4871 g_concat_dir_and_file (const char *dir, const char *file)
4873 g_return_val_if_fail (dir != NULL, NULL);
4874 g_return_val_if_fail (file != NULL, NULL);
4877 * If the directory name doesn't have a / on the end, we need
4878 * to add one so we get a proper path to the file
4880 if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
4881 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
4882 else
4883 return g_strconcat (dir, file, NULL);
4886 void *
4887 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, gint32 *size, MonoReflectionModuleHandleOut ref_module, MonoError *error)
4889 error_init (error);
4890 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4891 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4892 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4893 guint32 i;
4894 guint32 cols [MONO_MANIFEST_SIZE];
4895 guint32 impl, file_idx;
4896 const char *val;
4897 MonoImage *module;
4899 char *n = mono_string_handle_to_utf8 (name, error);
4900 return_val_if_nok (error, NULL);
4902 for (i = 0; i < table->rows; ++i) {
4903 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4904 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
4905 if (strcmp (val, n) == 0)
4906 break;
4908 g_free (n);
4909 if (i == table->rows)
4910 return NULL;
4911 /* FIXME */
4912 impl = cols [MONO_MANIFEST_IMPLEMENTATION];
4913 if (impl) {
4915 * this code should only be called after obtaining the
4916 * ResourceInfo and handling the other cases.
4918 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
4919 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
4921 module = mono_image_load_file_for_image_checked (assembly->image, file_idx, error);
4922 if (!is_ok (error) || !module)
4923 return NULL;
4925 else
4926 module = assembly->image;
4929 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
4930 return_val_if_nok (error, NULL);
4931 MONO_HANDLE_ASSIGN (ref_module, rm);
4933 return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
4936 static gboolean
4937 get_manifest_resource_info_internal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info, MonoError *error)
4939 HANDLE_FUNCTION_ENTER ();
4940 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4941 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4942 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4943 int i;
4944 guint32 cols [MONO_MANIFEST_SIZE];
4945 guint32 file_cols [MONO_FILE_SIZE];
4946 const char *val;
4947 char *n;
4949 gboolean result = FALSE;
4951 n = mono_string_handle_to_utf8 (name, error);
4952 goto_if_nok (error, leave);
4954 for (i = 0; i < table->rows; ++i) {
4955 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4956 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
4957 if (strcmp (val, n) == 0)
4958 break;
4960 g_free (n);
4961 if (i == table->rows)
4962 goto leave;
4964 if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
4965 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST);
4967 else {
4968 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
4969 case MONO_IMPLEMENTATION_FILE:
4970 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4971 table = &assembly->image->tables [MONO_TABLE_FILE];
4972 mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
4973 val = mono_metadata_string_heap (assembly->image, file_cols [MONO_FILE_NAME]);
4974 MONO_HANDLE_SET (info, filename, mono_string_new_handle (domain, val, error));
4975 if (file_cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA)
4976 MONO_HANDLE_SETVAL (info, location, guint32, 0);
4977 else
4978 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED);
4979 break;
4981 case MONO_IMPLEMENTATION_ASSEMBLYREF:
4982 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4983 mono_assembly_load_reference (assembly->image, i - 1);
4984 if (assembly->image->references [i - 1] == REFERENCE_MISSING) {
4985 mono_error_set_file_not_found (error, NULL, "Assembly %d referenced from assembly %s not found ", i - 1, assembly->image->name);
4986 goto leave;
4988 MonoReflectionAssemblyHandle assm_obj;
4989 assm_obj = mono_assembly_get_object_handle (mono_domain_get (), assembly->image->references [i - 1], error);
4990 goto_if_nok (error, leave);
4991 MONO_HANDLE_SET (info, assembly, assm_obj);
4993 /* Obtain info recursively */
4994 get_manifest_resource_info_internal (assm_obj, name, info, error);
4995 goto_if_nok (error, leave);
4996 guint32 location;
4997 location = MONO_HANDLE_GETVAL (info, location);
4998 location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
4999 MONO_HANDLE_SETVAL (info, location, guint32, location);
5000 break;
5002 case MONO_IMPLEMENTATION_EXP_TYPE:
5003 g_assert_not_reached ();
5004 break;
5008 result = TRUE;
5009 leave:
5010 HANDLE_FUNCTION_RETURN_VAL (result);
5013 MonoBoolean
5014 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInfoInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info_h, MonoError *error)
5016 error_init (error);
5017 return get_manifest_resource_info_internal (assembly_h, name, info_h, error);
5020 static gboolean
5021 add_filename_to_files_array (MonoDomain *domain, MonoAssembly * assembly, MonoTableInfo *table, int i, MonoArrayHandle dest, int dest_idx, MonoError *error)
5023 HANDLE_FUNCTION_ENTER();
5024 error_init (error);
5025 const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
5026 char *n = g_concat_dir_and_file (assembly->basedir, val);
5027 MonoStringHandle str = mono_string_new_handle (domain, n, error);
5028 g_free (n);
5029 goto_if_nok (error, leave);
5030 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, str);
5031 leave:
5032 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5035 MonoObjectHandle
5036 ves_icall_System_Reflection_RuntimeAssembly_GetFilesInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoBoolean resource_modules, MonoError *error)
5038 error_init (error);
5039 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5040 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5041 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_FILE];
5042 int i, count;
5044 /* check hash if needed */
5045 if (!MONO_HANDLE_IS_NULL(name)) {
5046 char *n = mono_string_handle_to_utf8 (name, error);
5047 goto_if_nok (error, fail);
5049 for (i = 0; i < table->rows; ++i) {
5050 const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
5051 if (strcmp (val, n) == 0) {
5052 g_free (n);
5053 n = g_concat_dir_and_file (assembly->basedir, val);
5054 MonoStringHandle fn = mono_string_new_handle (domain, n, error);
5055 g_free (n);
5056 goto_if_nok (error, fail);
5057 return MONO_HANDLE_CAST (MonoObject, fn);
5060 g_free (n);
5061 return NULL_HANDLE;
5064 count = 0;
5065 for (i = 0; i < table->rows; ++i) {
5066 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA))
5067 count ++;
5070 MonoArrayHandle result;
5071 result = mono_array_new_handle (domain, mono_defaults.string_class, count, error);
5072 goto_if_nok (error, fail);
5074 count = 0;
5075 for (i = 0; i < table->rows; ++i) {
5076 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
5077 if (!add_filename_to_files_array (domain, assembly, table, i, result, count, error))
5078 goto fail;
5079 count++;
5082 return MONO_HANDLE_CAST (MonoObject, result);
5083 fail:
5084 return NULL_HANDLE;
5087 static gboolean
5088 add_module_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int *dest_idx, MonoImage* module, MonoError *error)
5090 HANDLE_FUNCTION_ENTER ();
5091 error_init (error);
5092 if (module) {
5093 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
5094 goto_if_nok (error, leave);
5096 MONO_HANDLE_ARRAY_SETREF (dest, *dest_idx, rm);
5097 ++(*dest_idx);
5100 leave:
5101 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5104 static gboolean
5105 add_file_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int dest_idx, MonoImage *image, MonoTableInfo *table, int table_idx, MonoError *error)
5107 HANDLE_FUNCTION_ENTER ();
5108 error_init (error);
5110 guint32 cols [MONO_FILE_SIZE];
5111 mono_metadata_decode_row (table, table_idx, cols, MONO_FILE_SIZE);
5112 if (cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA) {
5113 MonoReflectionModuleHandle rm = mono_module_file_get_object_handle (domain, image, table_idx, error);
5114 goto_if_nok (error, leave);
5115 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5116 } else {
5117 MonoImage *m = mono_image_load_file_for_image_checked (image, table_idx + 1, error);
5118 goto_if_nok (error, leave);
5119 if (!m) {
5120 const char *filename = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
5121 mono_error_set_file_not_found (error, filename, "%s", "");
5122 goto leave;
5124 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, m, error);
5125 goto_if_nok (error, leave);
5126 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5129 leave:
5130 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5133 MonoArrayHandle
5134 ves_icall_System_Reflection_RuntimeAssembly_GetModulesInternal (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5136 error_init (error);
5137 MonoDomain *domain = mono_domain_get();
5138 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5139 MonoClass *klass;
5140 int i, j, file_count = 0;
5141 MonoImage **modules;
5142 guint32 module_count, real_module_count;
5143 MonoTableInfo *table;
5144 MonoImage *image = assembly->image;
5146 g_assert (image != NULL);
5147 g_assert (!assembly_is_dynamic (assembly));
5149 table = &image->tables [MONO_TABLE_FILE];
5150 file_count = table->rows;
5152 modules = image->modules;
5153 module_count = image->module_count;
5155 real_module_count = 0;
5156 for (i = 0; i < module_count; ++i)
5157 if (modules [i])
5158 real_module_count ++;
5160 klass = mono_class_get_module_class ();
5161 MonoArrayHandle res = mono_array_new_handle (domain, klass, 1 + real_module_count + file_count, error);
5162 goto_if_nok (error, fail);
5164 MonoReflectionModuleHandle image_obj;
5165 image_obj = mono_module_get_object_handle (domain, image, error);
5166 goto_if_nok (error, fail);
5168 MONO_HANDLE_ARRAY_SETREF (res, 0, image_obj);
5170 j = 1;
5171 for (i = 0; i < module_count; ++i)
5172 if (!add_module_to_modules_array (domain, res, &j, modules[i], error))
5173 goto fail;
5175 for (i = 0; i < file_count; ++i, ++j) {
5176 if (!add_file_to_modules_array (domain, res, j, image, table, i, error))
5177 goto fail;
5180 return res;
5181 fail:
5182 return NULL_HANDLE_ARRAY;
5185 MonoReflectionMethodHandle
5186 ves_icall_GetCurrentMethod (MonoError *error)
5188 error_init (error);
5190 MonoMethod *m = mono_method_get_last_managed ();
5192 if (!m) {
5193 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5194 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5197 while (m->is_inflated)
5198 m = ((MonoMethodInflated*)m)->declaring;
5200 return mono_method_get_object_handle (mono_domain_get (), m, NULL, error);
5204 static MonoMethod*
5205 mono_method_get_equivalent_method (MonoMethod *method, MonoClass *klass)
5207 int offset = -1, i;
5208 if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) {
5209 ERROR_DECL (error);
5210 MonoMethod *result;
5211 MonoMethodInflated *inflated = (MonoMethodInflated*)method;
5212 //method is inflated, we should inflate it on the other class
5213 MonoGenericContext ctx;
5214 ctx.method_inst = inflated->context.method_inst;
5215 ctx.class_inst = inflated->context.class_inst;
5216 if (mono_class_is_ginst (klass))
5217 ctx.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
5218 else if (mono_class_is_gtd (klass))
5219 ctx.class_inst = mono_class_get_generic_container (klass)->context.class_inst;
5220 result = mono_class_inflate_generic_method_full_checked (inflated->declaring, klass, &ctx, error);
5221 g_assert (is_ok (error)); /* FIXME don't swallow the error */
5222 return result;
5225 mono_class_setup_methods (method->klass);
5226 if (mono_class_has_failure (method->klass))
5227 return NULL;
5228 int mcount = mono_class_get_method_count (method->klass);
5229 MonoMethod **method_klass_methods = m_class_get_methods (method->klass);
5230 for (i = 0; i < mcount; ++i) {
5231 if (method_klass_methods [i] == method) {
5232 offset = i;
5233 break;
5236 mono_class_setup_methods (klass);
5237 if (mono_class_has_failure (klass))
5238 return NULL;
5239 g_assert (offset >= 0 && offset < mono_class_get_method_count (klass));
5240 return m_class_get_methods (klass) [offset];
5243 MonoReflectionMethodHandle
5244 ves_icall_System_Reflection_RuntimeMethodInfo_GetMethodFromHandleInternalType_native (MonoMethod *method, MonoType *type, MonoBoolean generic_check, MonoError *error)
5246 error_init (error);
5247 MonoClass *klass;
5248 if (type && generic_check) {
5249 klass = mono_class_from_mono_type_internal (type);
5250 if (mono_class_get_generic_type_definition (method->klass) != mono_class_get_generic_type_definition (klass))
5251 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5253 if (method->klass != klass) {
5254 method = mono_method_get_equivalent_method (method, klass);
5255 if (!method)
5256 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5258 } else if (type)
5259 klass = mono_class_from_mono_type_internal (type);
5260 else
5261 klass = method->klass;
5262 return mono_method_get_object_handle (mono_domain_get (), method, klass, error);
5265 MonoReflectionMethodBodyHandle
5266 ves_icall_System_Reflection_RuntimeMethodInfo_GetMethodBodyInternal (MonoMethod *method, MonoError *error)
5268 error_init (error);
5269 return mono_method_body_get_object_handle (mono_domain_get (), method, error);
5272 MonoReflectionAssemblyHandle
5273 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (MonoError *error)
5275 error_init (error);
5277 MonoMethod *dest = NULL;
5278 mono_stack_walk_no_il (get_executing, &dest);
5279 g_assert (dest);
5280 return mono_assembly_get_object_handle (mono_domain_get (), m_class_get_image (dest->klass)->assembly, error);
5284 MonoReflectionAssemblyHandle
5285 ves_icall_System_Reflection_Assembly_GetEntryAssembly (MonoError *error)
5287 error_init (error);
5289 MonoDomain* domain = mono_domain_get ();
5291 if (!domain->entry_assembly)
5292 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5294 return mono_assembly_get_object_handle (domain, domain->entry_assembly, error);
5297 MonoReflectionAssemblyHandle
5298 ves_icall_System_Reflection_Assembly_GetCallingAssembly (MonoError *error)
5300 error_init (error);
5301 MonoMethod *m;
5302 MonoMethod *dest;
5304 dest = NULL;
5305 mono_stack_walk_no_il (get_executing, &dest);
5306 m = dest;
5307 mono_stack_walk_no_il (get_caller_no_reflection, &dest);
5308 if (!dest)
5309 dest = m;
5310 if (!m) {
5311 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5312 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5314 return mono_assembly_get_object_handle (mono_domain_get (), m_class_get_image (dest->klass)->assembly, error);
5317 MonoStringHandle
5318 ves_icall_System_RuntimeType_getFullName (MonoReflectionTypeHandle object, MonoBoolean full_name,
5319 MonoBoolean assembly_qualified, MonoError *error)
5321 MonoDomain *domain = mono_object_domain (MONO_HANDLE_RAW (object));
5322 MonoType *type = MONO_HANDLE_RAW (object)->type;
5323 MonoTypeNameFormat format;
5324 MonoStringHandle res;
5325 gchar *name;
5327 if (full_name)
5328 format = assembly_qualified ?
5329 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED :
5330 MONO_TYPE_NAME_FORMAT_FULL_NAME;
5331 else
5332 format = MONO_TYPE_NAME_FORMAT_REFLECTION;
5334 name = mono_type_get_name_full (type, format);
5335 if (!name)
5336 return NULL_HANDLE_STRING;
5338 if (full_name && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
5339 g_free (name);
5340 return NULL_HANDLE_STRING;
5343 res = mono_string_new_handle (domain, name, error);
5344 g_free (name);
5346 return res;
5350 ves_icall_RuntimeType_get_core_clr_security_level (MonoReflectionTypeHandle rfield, MonoError *error)
5352 error_init (error);
5353 MonoType *type = MONO_HANDLE_GETVAL (rfield, type);
5354 MonoClass *klass = mono_class_from_mono_type_internal (type);
5356 mono_class_init_checked (klass, error);
5357 return_val_if_nok (error, -1);
5358 return mono_security_core_clr_class_level (klass);
5362 ves_icall_RuntimeFieldInfo_get_core_clr_security_level (MonoReflectionFieldHandle rfield, MonoError *error)
5364 MonoClassField *field = MONO_HANDLE_GETVAL (rfield, field);
5365 return mono_security_core_clr_field_level (field, TRUE);
5369 ves_icall_RuntimeMethodInfo_get_core_clr_security_level (MonoReflectionMethodHandle rfield, MonoError *error)
5371 MonoMethod *method = MONO_HANDLE_GETVAL (rfield, method);
5372 return mono_security_core_clr_method_level (method, TRUE);
5375 MonoStringHandle
5376 ves_icall_System_Reflection_RuntimeAssembly_get_fullname (MonoReflectionAssemblyHandle assembly, MonoError *error)
5378 error_init (error);
5379 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5380 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
5381 gchar *name;
5383 name = mono_stringify_assembly_name (&mass->aname);
5384 MonoStringHandle res = mono_string_new_handle (domain, name, error);
5385 g_free (name);
5386 return res;
5389 MonoAssemblyName *
5390 ves_icall_System_Reflection_AssemblyName_GetNativeName (MonoAssembly *mass)
5392 return &mass->aname;
5395 void
5396 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoStringHandle fname, MonoAssemblyName *name, MonoStringHandleOut normalized_codebase, MonoError *error)
5398 char *filename;
5399 MonoImageOpenStatus status = MONO_IMAGE_OK;
5400 char *codebase = NULL;
5401 gboolean res;
5402 MonoImage *image;
5403 char *dirname;
5405 error_init (error);
5407 filename = mono_string_handle_to_utf8 (fname, error);
5408 return_if_nok (error);
5410 dirname = g_path_get_dirname (filename);
5411 replace_shadow_path (mono_domain_get (), dirname, &filename);
5412 g_free (dirname);
5414 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "InternalGetAssemblyName (\"%s\")", filename);
5416 image = mono_image_open_full (filename, &status, TRUE);
5418 if (!image){
5419 if (status == MONO_IMAGE_IMAGE_INVALID)
5420 mono_error_set_bad_image_by_name (error, filename, "Invalid Image");
5421 else
5422 mono_error_set_file_not_found (error, filename, "%s", "");
5423 g_free (filename);
5424 return;
5427 res = mono_assembly_fill_assembly_name_full (image, name, TRUE);
5428 if (!res) {
5429 mono_image_close (image);
5430 g_free (filename);
5431 mono_error_set_argument (error, "assemblyFile", "The file does not contain a manifest");
5432 return;
5435 if (filename != NULL && *filename != '\0') {
5436 gchar *result;
5438 codebase = g_strdup (filename);
5440 mono_icall_make_platform_path (codebase);
5442 const gchar *prepend = mono_icall_get_file_path_prefix (codebase);
5444 result = g_strconcat (prepend, codebase, NULL);
5445 g_free (codebase);
5446 codebase = result;
5448 MONO_HANDLE_ASSIGN (normalized_codebase, mono_string_new_handle (mono_domain_get (), codebase, error));
5449 g_free (codebase);
5451 mono_image_close (image);
5452 g_free (filename);
5455 MonoBoolean
5456 ves_icall_System_Reflection_RuntimeAssembly_LoadPermissions (MonoReflectionAssemblyHandle assembly_h,
5457 char **minimum, guint32 *minLength, char **optional, guint32 *optLength, char **refused, guint32 *refLength, MonoError *error)
5459 error_init (error);
5460 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5461 MonoBoolean result = FALSE;
5462 MonoDeclSecurityEntry entry;
5464 /* SecurityAction.RequestMinimum */
5465 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQMIN, &entry)) {
5466 *minimum = entry.blob;
5467 *minLength = entry.size;
5468 result = TRUE;
5470 /* SecurityAction.RequestOptional */
5471 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQOPT, &entry)) {
5472 *optional = entry.blob;
5473 *optLength = entry.size;
5474 result = TRUE;
5476 /* SecurityAction.RequestRefuse */
5477 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQREFUSE, &entry)) {
5478 *refused = entry.blob;
5479 *refLength = entry.size;
5480 result = TRUE;
5483 return result;
5486 static gboolean
5487 mono_module_type_is_visible (MonoTableInfo *tdef, MonoImage *image, int type)
5489 guint32 attrs, visibility;
5490 do {
5491 attrs = mono_metadata_decode_row_col (tdef, type - 1, MONO_TYPEDEF_FLAGS);
5492 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5493 if (visibility != TYPE_ATTRIBUTE_PUBLIC && visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC)
5494 return FALSE;
5496 } while ((type = mono_metadata_token_index (mono_metadata_nested_in_typedef (image, type))));
5498 return TRUE;
5501 static void
5502 image_get_type (MonoDomain *domain, MonoImage *image, MonoTableInfo *tdef, int table_idx, int count, MonoArrayHandle res, MonoArrayHandle exceptions, MonoBoolean exportedOnly, MonoError *error)
5504 error_init (error);
5505 HANDLE_FUNCTION_ENTER ();
5506 ERROR_DECL (klass_error);
5507 MonoClass *klass = mono_class_get_checked (image, table_idx | MONO_TOKEN_TYPE_DEF, klass_error);
5509 if (klass) {
5510 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
5511 return_if_nok (error);
5513 MONO_HANDLE_ARRAY_SETREF (res, count, rt);
5514 } else {
5515 MonoExceptionHandle ex = mono_error_convert_to_exception_handle (klass_error);
5516 MONO_HANDLE_ARRAY_SETREF (exceptions, count, ex);
5518 HANDLE_FUNCTION_RETURN ();
5521 static MonoArrayHandle
5522 mono_module_get_types (MonoDomain *domain, MonoImage *image, MonoArrayHandleOut exceptions, MonoBoolean exportedOnly, MonoError *error)
5524 MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
5525 int i, count;
5527 error_init (error);
5529 /* we start the count from 1 because we skip the special type <Module> */
5530 if (exportedOnly) {
5531 count = 0;
5532 for (i = 1; i < tdef->rows; ++i) {
5533 if (mono_module_type_is_visible (tdef, image, i + 1))
5534 count++;
5536 } else {
5537 count = tdef->rows - 1;
5539 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.runtimetype_class, count, error);
5540 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5541 MONO_HANDLE_ASSIGN (exceptions, mono_array_new_handle (domain, mono_defaults.exception_class, count, error));
5542 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5543 count = 0;
5544 for (i = 1; i < tdef->rows; ++i) {
5545 if (!exportedOnly || mono_module_type_is_visible (tdef, image, i+1)) {
5546 image_get_type (domain, image, tdef, i + 1, count, res, exceptions, exportedOnly, error);
5547 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5548 count++;
5552 return res;
5555 static void
5556 append_module_types (MonoDomain *domain, MonoArrayHandleOut res, MonoArrayHandleOut exceptions, MonoImage *image, MonoBoolean exportedOnly, MonoError *error)
5558 HANDLE_FUNCTION_ENTER ();
5559 error_init (error);
5560 MonoArrayHandle ex2 = MONO_HANDLE_NEW (MonoArray, NULL);
5561 MonoArrayHandle res2 = mono_module_get_types (domain, image, ex2, exportedOnly, error);
5562 goto_if_nok (error, leave);
5564 /* Append the new types to the end of the array */
5565 if (mono_array_handle_length (res2) > 0) {
5566 guint32 len1, len2;
5568 len1 = mono_array_handle_length (res);
5569 len2 = mono_array_handle_length (res2);
5571 MonoArrayHandle res3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
5572 goto_if_nok (error, leave);
5574 mono_array_handle_memcpy_refs (res3, 0, res, 0, len1);
5575 mono_array_handle_memcpy_refs (res3, len1, res2, 0, len2);
5576 MONO_HANDLE_ASSIGN (res, res3);
5578 MonoArrayHandle ex3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
5579 goto_if_nok (error, leave);
5581 mono_array_handle_memcpy_refs (ex3, 0, exceptions, 0, len1);
5582 mono_array_handle_memcpy_refs (ex3, len1, ex2, 0, len2);
5583 MONO_HANDLE_ASSIGN (exceptions, ex3);
5585 leave:
5586 HANDLE_FUNCTION_RETURN ();
5589 static void
5590 set_class_failure_in_array (MonoArrayHandle exl, int i, MonoClass *klass)
5592 HANDLE_FUNCTION_ENTER ();
5593 ERROR_DECL (unboxed_error);
5594 mono_error_set_for_class_failure (unboxed_error, klass);
5596 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, mono_error_convert_to_exception (unboxed_error));
5597 MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
5598 HANDLE_FUNCTION_RETURN ();
5601 MonoArrayHandle
5602 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssemblyHandle assembly_handle, MonoBoolean exportedOnly, MonoError *error)
5604 MonoArrayHandle exceptions = MONO_HANDLE_NEW(MonoArray, NULL);
5605 int i;
5607 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_handle);
5608 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_handle, assembly);
5610 g_assert (!assembly_is_dynamic (assembly));
5611 MonoImage *image = assembly->image;
5612 MonoTableInfo *table = &image->tables [MONO_TABLE_FILE];
5613 MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, exportedOnly, error);
5614 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5616 /* Append data from all modules in the assembly */
5617 for (i = 0; i < table->rows; ++i) {
5618 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
5619 MonoImage *loaded_image = mono_assembly_load_module_checked (image->assembly, i + 1, error);
5620 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5622 if (loaded_image) {
5623 append_module_types (domain, res, exceptions, loaded_image, exportedOnly, error);
5624 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5629 /* the ReflectionTypeLoadException must have all the types (Types property),
5630 * NULL replacing types which throws an exception. The LoaderException must
5631 * contain all exceptions for NULL items.
5634 int len = mono_array_handle_length (res);
5636 int ex_count = 0;
5637 GList *list = NULL;
5638 MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
5639 for (i = 0; i < len; i++) {
5640 MONO_HANDLE_ARRAY_GETREF (t, res, i);
5642 if (!MONO_HANDLE_IS_NULL (t)) {
5643 MonoClass *klass = mono_type_get_class (MONO_HANDLE_GETVAL (t, type));
5644 if ((klass != NULL) && mono_class_has_failure (klass)) {
5645 /* keep the class in the list */
5646 list = g_list_append (list, klass);
5647 /* and replace Type with NULL */
5648 MONO_HANDLE_ARRAY_SETREF (res, i, NULL_HANDLE);
5650 } else {
5651 ex_count ++;
5655 if (list || ex_count) {
5656 GList *tmp = NULL;
5657 int j, length = g_list_length (list) + ex_count;
5659 MonoArrayHandle exl = mono_array_new_handle (domain, mono_defaults.exception_class, length, error);
5660 if (!is_ok (error)) {
5661 g_list_free (list);
5662 return NULL_HANDLE_ARRAY;
5664 /* Types for which mono_class_get_checked () succeeded */
5665 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5666 for (i = 0, tmp = list; tmp; i++, tmp = tmp->next) {
5667 set_class_failure_in_array (exl, i, (MonoClass*)tmp->data);
5669 /* Types for which it don't */
5670 for (j = 0; j < mono_array_handle_length (exceptions); ++j) {
5671 MONO_HANDLE_ARRAY_GETREF (exc, exceptions, j);
5672 if (!MONO_HANDLE_IS_NULL (exc)) {
5673 g_assert (i < length);
5674 MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
5675 i ++;
5678 g_list_free (list);
5679 list = NULL;
5681 MONO_HANDLE_ASSIGN (exc, mono_get_exception_reflection_type_load_checked (res, exl, error));
5682 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5683 mono_error_set_exception_handle (error, exc);
5684 return NULL_HANDLE_ARRAY;
5687 return res;
5690 #if ENABLE_NETCORE
5691 MonoArrayHandle
5692 ves_icall_System_Reflection_RuntimeAssembly_GetExportedTypes (MonoReflectionAssemblyHandle assembly_handle, MonoError *error)
5694 return ves_icall_System_Reflection_Assembly_GetTypes (assembly_handle, TRUE, error);
5696 #endif
5698 void
5699 ves_icall_Mono_RuntimeMarshal_FreeAssemblyName (MonoAssemblyName *aname, MonoBoolean free_struct, MonoError *error)
5701 mono_assembly_name_free (aname);
5702 if (free_struct)
5703 g_free (aname);
5706 void
5707 ves_icall_Mono_Runtime_DisableMicrosoftTelemetry (MonoError *error)
5709 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
5710 mono_merp_disable ();
5711 #else
5712 // Icall has platform check in managed too.
5713 g_assert_not_reached ();
5714 #endif
5717 void
5718 ves_icall_Mono_Runtime_AnnotateMicrosoftTelemetry (const char *key, const char *value, MonoError *error)
5720 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
5721 if (!mono_merp_enabled ())
5722 g_error ("Cannot add attributes to telemetry without enabling subsystem");
5723 mono_merp_add_annotation (key, value);
5724 #else
5725 // Icall has platform check in managed too.
5726 g_assert_not_reached ();
5727 #endif
5730 void
5731 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)
5733 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
5734 mono_merp_enable (appBundleID, appSignature, appVersion, merpGUIPath, eventType, appPath, configDir);
5736 mono_get_runtime_callbacks ()->install_state_summarizer ();
5737 #else
5738 // Icall has platform check in managed too.
5739 g_assert_not_reached ();
5740 #endif
5743 // Number derived from trials on relevant hardware.
5744 // If it seems large, please confirm it's safe to shrink
5745 // before doing so.
5746 #define MONO_MAX_SUMMARY_LEN_ICALL 500000
5748 MonoStringHandle
5749 ves_icall_Mono_Runtime_ExceptionToState (MonoExceptionHandle exc_handle, guint64 *portable_hash_out, guint64 *unportable_hash_out, MonoError *error)
5751 MonoStringHandle result;
5753 #ifndef DISABLE_CRASH_REPORTING
5754 if (mono_get_eh_callbacks ()->mono_summarize_exception) {
5755 // FIXME: Push handles down into mini/mini-exceptions.c
5756 MonoException *exc = MONO_HANDLE_RAW (exc_handle);
5757 MonoThreadSummary out;
5758 mono_get_eh_callbacks ()->mono_summarize_exception (exc, &out);
5760 *portable_hash_out = (guint64) out.hashes.offset_free_hash;
5761 *unportable_hash_out = (guint64) out.hashes.offset_rich_hash;
5763 MonoStateWriter writer;
5764 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
5765 mono_state_writer_init (&writer, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
5766 mono_native_state_init (&writer);
5767 gboolean first_thread_added = TRUE;
5768 mono_native_state_add_thread (&writer, &out, NULL, first_thread_added, TRUE);
5769 char *output = mono_native_state_free (&writer, FALSE);
5770 result = mono_string_new_handle (mono_domain_get (), output, error);
5771 g_free (output);
5772 g_free (scratch);
5773 return result;
5775 #endif
5777 *portable_hash_out = 0;
5778 *unportable_hash_out = 0;
5779 result = mono_string_new_handle (mono_domain_get (), "", error);
5780 return result;
5783 void
5784 ves_icall_Mono_Runtime_SendMicrosoftTelemetry (const char *payload, guint64 portable_hash, guint64 unportable_hash, MonoError *error)
5786 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
5787 if (!mono_merp_enabled ())
5788 g_error ("Cannot send telemetry without registering parameters first");
5790 pid_t crashed_pid = getpid ();
5792 MonoStackHash hashes;
5793 memset (&hashes, 0, sizeof (MonoStackHash));
5794 hashes.offset_free_hash = portable_hash;
5795 hashes.offset_rich_hash = unportable_hash;
5797 // Tells mono that we want to send the HANG EXC_TYPE.
5798 const char *signal = "SIGTERM";
5800 gboolean success = mono_merp_invoke (crashed_pid, signal, payload, &hashes);
5801 if (!success) {
5802 //g_assert_not_reached ();
5803 mono_error_set_generic_error (error, "System", "Exception", "We were unable to start the Microsoft Error Reporting client.");
5805 #else
5806 // Icall has platform check in managed too.
5807 g_assert_not_reached ();
5808 #endif
5811 void
5812 ves_icall_Mono_Runtime_DumpTelemetry (const char *payload, guint64 portable_hash, guint64 unportable_hash, MonoError *error)
5814 #ifndef DISABLE_CRASH_REPORTING
5815 MonoStackHash hashes;
5816 memset (&hashes, 0, sizeof (MonoStackHash));
5817 hashes.offset_free_hash = portable_hash;
5818 hashes.offset_rich_hash = unportable_hash;
5819 mono_crash_dump (payload, &hashes);
5820 #else
5821 return;
5822 #endif
5825 MonoStringHandle
5826 ves_icall_Mono_Runtime_DumpStateSingle (guint64 *portable_hash, guint64 *unportable_hash, MonoError *error)
5828 MonoStringHandle result;
5830 #ifndef DISABLE_CRASH_REPORTING
5831 MonoStackHash hashes;
5832 memset (&hashes, 0, sizeof (MonoStackHash));
5833 MonoContext *ctx = NULL;
5835 MonoThreadSummary this_thread;
5836 if (!mono_threads_summarize_one (&this_thread, ctx))
5837 return mono_string_new_handle (mono_domain_get (), "", error);
5839 *portable_hash = (guint64) this_thread.hashes.offset_free_hash;
5840 *unportable_hash = (guint64) this_thread.hashes.offset_rich_hash;
5842 MonoStateWriter writer;
5843 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
5844 mono_state_writer_init (&writer, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
5845 mono_native_state_init (&writer);
5846 gboolean first_thread_added = TRUE;
5847 mono_native_state_add_thread (&writer, &this_thread, NULL, first_thread_added, TRUE);
5848 char *output = mono_native_state_free (&writer, FALSE);
5849 result = mono_string_new_handle (mono_domain_get (), output, error);
5850 g_free (output);
5851 g_free (scratch);
5852 #else
5853 *portable_hash = 0;
5854 *unportable_hash = 0;
5855 result = mono_string_new_handle (mono_domain_get (), "", error);
5856 #endif
5858 return result;
5862 void
5863 ves_icall_Mono_Runtime_RegisterReportingForNativeLib (const char *path_suffix, const char *module_name)
5865 #ifndef DISABLE_CRASH_REPORTING
5866 if (mono_get_eh_callbacks ()->mono_register_native_library)
5867 mono_get_eh_callbacks ()->mono_register_native_library (path_suffix, module_name);
5868 #endif
5871 void
5872 ves_icall_Mono_Runtime_EnableCrashReportingLog (const char *directory, MonoError *error)
5874 #ifndef DISABLE_CRASH_REPORTING
5875 mono_summarize_set_timeline_dir (directory);
5876 #endif
5880 ves_icall_Mono_Runtime_CheckCrashReportingLog (const char *directory, MonoBoolean clear, MonoError *error)
5882 int ret;
5883 #ifndef DISABLE_CRASH_REPORTING
5884 ret = (int) mono_summarize_timeline_read_level (directory, clear != 0);
5885 #else
5886 ret = 0;
5887 #endif
5888 return ret;
5891 MonoStringHandle
5892 ves_icall_Mono_Runtime_DumpStateTotal (guint64 *portable_hash, guint64 *unportable_hash, MonoError *error)
5894 MonoStringHandle result;
5896 #ifndef DISABLE_CRASH_REPORTING
5897 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
5899 char *out;
5900 MonoStackHash hashes;
5901 memset (&hashes, 0, sizeof (MonoStackHash));
5902 MonoContext *ctx = NULL;
5904 mono_get_runtime_callbacks ()->install_state_summarizer ();
5906 mono_summarize_timeline_start ();
5908 gboolean success = mono_threads_summarize (ctx, &out, &hashes, TRUE, FALSE, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
5909 mono_summarize_timeline_phase_log (MonoSummaryCleanup);
5911 if (!success)
5912 return mono_string_new_handle (mono_domain_get (), "", error);
5914 *portable_hash = (guint64) hashes.offset_free_hash;
5915 *unportable_hash = (guint64) hashes.offset_rich_hash;
5916 result = mono_string_new_handle (mono_domain_get (), out, error);
5918 // out is now a pointer into garbage memory
5919 g_free (scratch);
5921 mono_summarize_timeline_phase_log (MonoSummaryDone);
5922 #else
5923 *portable_hash = 0;
5924 *unportable_hash = 0;
5925 result = mono_string_new_handle (mono_domain_get (), "", error);
5926 #endif
5928 return result;
5931 MonoBoolean
5932 ves_icall_System_Reflection_AssemblyName_ParseAssemblyName (const char *name, MonoAssemblyName *aname, MonoBoolean *is_version_defined_arg, MonoBoolean *is_token_defined_arg)
5934 gboolean is_version_defined = FALSE;
5935 gboolean is_token_defined = FALSE;
5936 gboolean result = FALSE;
5938 result = mono_assembly_name_parse_full (name, aname, TRUE, &is_version_defined, &is_token_defined);
5940 *is_version_defined_arg = (MonoBoolean)is_version_defined;
5941 *is_token_defined_arg = (MonoBoolean)is_token_defined;
5943 return result;
5946 MonoReflectionTypeHandle
5947 ves_icall_System_Reflection_RuntimeModule_GetGlobalType (MonoImage *image, MonoError *error)
5949 MonoDomain *domain = mono_domain_get ();
5950 MonoClass *klass;
5952 g_assert (image);
5954 MonoReflectionTypeHandle ret = MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
5956 if (image_is_dynamic (image) && ((MonoDynamicImage*)image)->initial_image)
5957 /* These images do not have a global type */
5958 goto leave;
5960 klass = mono_class_get_checked (image, 1 | MONO_TOKEN_TYPE_DEF, error);
5961 goto_if_nok (error, leave);
5963 ret = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
5964 leave:
5965 return ret;
5968 MonoStringHandle
5969 ves_icall_System_Reflection_RuntimeModule_GetGuidInternal (MonoImage *image, MonoError *error)
5971 MonoDomain *domain = mono_domain_get ();
5973 return mono_string_new_handle (domain, image->guid, error);
5976 #ifndef HOST_WIN32
5977 static inline gpointer
5978 mono_icall_module_get_hinstance (MonoImage *image)
5980 return (gpointer) (-1);
5982 #endif /* HOST_WIN32 */
5984 gpointer
5985 ves_icall_System_Reflection_RuntimeModule_GetHINSTANCE (MonoImage *image, MonoError *error)
5987 return mono_icall_module_get_hinstance (image);
5990 void
5991 ves_icall_System_Reflection_RuntimeModule_GetPEKind (MonoImage *image, gint32 *pe_kind, gint32 *machine, MonoError *error)
5993 if (image_is_dynamic (image)) {
5994 MonoDynamicImage *dyn = (MonoDynamicImage*)image;
5995 *pe_kind = dyn->pe_kind;
5996 *machine = dyn->machine;
5998 else {
5999 *pe_kind = (image->image_info->cli_cli_header.ch_flags & 0x3);
6000 *machine = image->image_info->cli_header.coff.coff_machine;
6004 gint32
6005 ves_icall_System_Reflection_RuntimeModule_GetMDStreamVersion (MonoImage *image, MonoError *error)
6007 return (image->md_version_major << 16) | (image->md_version_minor);
6010 MonoArrayHandle
6011 ves_icall_System_Reflection_RuntimeModule_InternalGetTypes (MonoImage *image, MonoError *error)
6013 error_init (error);
6015 MonoDomain *domain = mono_domain_get ();
6017 if (!image) {
6018 MonoArrayHandle arr = mono_array_new_handle (domain, mono_defaults.runtimetype_class, 0, error);
6019 return arr;
6020 } else {
6021 MonoArrayHandle exceptions = MONO_HANDLE_NEW (MonoArray, NULL);
6022 MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, FALSE, error);
6023 return_val_if_nok (error, MONO_HANDLE_CAST(MonoArray, NULL_HANDLE));
6025 int n = mono_array_handle_length (exceptions);
6026 MonoExceptionHandle ex = MONO_HANDLE_NEW (MonoException, NULL);
6027 for (int i = 0; i < n; ++i) {
6028 MONO_HANDLE_ARRAY_GETREF(ex, exceptions, i);
6029 if (!MONO_HANDLE_IS_NULL (ex)) {
6030 mono_error_set_exception_handle (error, ex);
6031 return MONO_HANDLE_CAST(MonoArray, NULL_HANDLE);
6034 return res;
6038 static gboolean
6039 mono_memberref_is_method (MonoImage *image, guint32 token)
6041 if (!image_is_dynamic (image)) {
6042 guint32 cols [MONO_MEMBERREF_SIZE];
6043 const char *sig;
6044 const MonoTableInfo *table = &image->tables [MONO_TABLE_MEMBERREF];
6045 int idx = mono_metadata_token_index (token) - 1;
6046 if (idx < 0 || table->rows <= idx) {
6047 return FALSE;
6049 mono_metadata_decode_row (table, idx, cols, MONO_MEMBERREF_SIZE);
6050 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6051 mono_metadata_decode_blob_size (sig, &sig);
6052 return (*sig != 0x6);
6053 } else {
6054 ERROR_DECL (error);
6055 MonoClass *handle_class;
6057 if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL, error)) {
6058 mono_error_cleanup (error); /* just probing, ignore error */
6059 return FALSE;
6062 return mono_defaults.methodhandle_class == handle_class;
6066 static MonoGenericInst *
6067 get_generic_inst_from_array_handle (MonoArrayHandle type_args)
6069 int type_argc = mono_array_handle_length (type_args);
6070 int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *);
6072 MonoGenericInst *ginst = (MonoGenericInst *)g_alloca (size);
6073 memset (ginst, 0, sizeof (MonoGenericInst));
6074 ginst->type_argc = type_argc;
6075 for (int i = 0; i < type_argc; i++) {
6076 MONO_HANDLE_ARRAY_GETVAL (ginst->type_argv[i], type_args, MonoType*, i);
6078 ginst->is_open = FALSE;
6079 for (int i = 0; i < type_argc; i++) {
6080 if (mono_class_is_open_constructed_type (ginst->type_argv[i])) {
6081 ginst->is_open = TRUE;
6082 break;
6086 return mono_metadata_get_canonical_generic_inst (ginst);
6089 static void
6090 init_generic_context_from_args_handles (MonoGenericContext *context, MonoArrayHandle type_args, MonoArrayHandle method_args)
6092 if (!MONO_HANDLE_IS_NULL (type_args)) {
6093 context->class_inst = get_generic_inst_from_array_handle (type_args);
6094 } else {
6095 context->class_inst = NULL;
6097 if (!MONO_HANDLE_IS_NULL (method_args)) {
6098 context->method_inst = get_generic_inst_from_array_handle (method_args);
6099 } else {
6100 context->method_inst = NULL;
6105 static MonoType*
6106 module_resolve_type_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6108 HANDLE_FUNCTION_ENTER ();
6109 error_init (error);
6110 MonoType *result = NULL;
6111 MonoClass *klass;
6112 int table = mono_metadata_token_table (token);
6113 int index = mono_metadata_token_index (token);
6114 MonoGenericContext context;
6116 *resolve_error = ResolveTokenError_Other;
6118 /* Validate token */
6119 if ((table != MONO_TABLE_TYPEDEF) && (table != MONO_TABLE_TYPEREF) &&
6120 (table != MONO_TABLE_TYPESPEC)) {
6121 *resolve_error = ResolveTokenError_BadTable;
6122 goto leave;
6125 if (image_is_dynamic (image)) {
6126 if ((table == MONO_TABLE_TYPEDEF) || (table == MONO_TABLE_TYPEREF)) {
6127 ERROR_DECL (inner_error);
6128 klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6129 mono_error_cleanup (inner_error);
6130 result = klass ? m_class_get_byval_arg (klass) : NULL;
6131 goto leave;
6134 init_generic_context_from_args_handles (&context, type_args, method_args);
6135 ERROR_DECL (inner_error);
6136 klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6137 mono_error_cleanup (inner_error);
6138 result = klass ? m_class_get_byval_arg (klass) : NULL;
6139 goto leave;
6142 if ((index <= 0) || (index > image->tables [table].rows)) {
6143 *resolve_error = ResolveTokenError_OutOfRange;
6144 goto leave;
6147 init_generic_context_from_args_handles (&context, type_args, method_args);
6148 klass = mono_class_get_checked (image, token, error);
6149 if (klass)
6150 klass = mono_class_inflate_generic_class_checked (klass, &context, error);
6151 goto_if_nok (error, leave);
6153 if (klass)
6154 result = m_class_get_byval_arg (klass);
6155 leave:
6156 HANDLE_FUNCTION_RETURN_VAL (result);
6159 MonoType*
6160 ves_icall_System_Reflection_RuntimeModule_ResolveTypeToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6162 return module_resolve_type_token (image, token, type_args, method_args, resolve_error, error);
6165 static MonoMethod*
6166 module_resolve_method_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6168 HANDLE_FUNCTION_ENTER ();
6169 error_init (error);
6170 MonoMethod *method = NULL;
6171 int table = mono_metadata_token_table (token);
6172 int index = mono_metadata_token_index (token);
6173 MonoGenericContext context;
6175 *resolve_error = ResolveTokenError_Other;
6177 /* Validate token */
6178 if ((table != MONO_TABLE_METHOD) && (table != MONO_TABLE_METHODSPEC) &&
6179 (table != MONO_TABLE_MEMBERREF)) {
6180 *resolve_error = ResolveTokenError_BadTable;
6181 goto leave;
6184 if (image_is_dynamic (image)) {
6185 if (table == MONO_TABLE_METHOD) {
6186 ERROR_DECL (inner_error);
6187 method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6188 mono_error_cleanup (inner_error);
6189 goto leave;
6192 if ((table == MONO_TABLE_MEMBERREF) && !(mono_memberref_is_method (image, token))) {
6193 *resolve_error = ResolveTokenError_BadTable;
6194 goto leave;
6197 init_generic_context_from_args_handles (&context, type_args, method_args);
6198 ERROR_DECL (inner_error);
6199 method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6200 mono_error_cleanup (inner_error);
6201 goto leave;
6204 if ((index <= 0) || (index > image->tables [table].rows)) {
6205 *resolve_error = ResolveTokenError_OutOfRange;
6206 goto leave;
6208 if ((table == MONO_TABLE_MEMBERREF) && (!mono_memberref_is_method (image, token))) {
6209 *resolve_error = ResolveTokenError_BadTable;
6210 goto leave;
6213 init_generic_context_from_args_handles (&context, type_args, method_args);
6214 method = mono_get_method_checked (image, token, NULL, &context, error);
6216 leave:
6217 HANDLE_FUNCTION_RETURN_VAL (method);
6220 MonoMethod*
6221 ves_icall_System_Reflection_RuntimeModule_ResolveMethodToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6223 return module_resolve_method_token (image, token, type_args, method_args, resolve_error, error);
6226 MonoStringHandle
6227 ves_icall_System_Reflection_RuntimeModule_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error, MonoError *error)
6229 int index = mono_metadata_token_index (token);
6231 *resolve_error = ResolveTokenError_Other;
6233 /* Validate token */
6234 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
6235 *resolve_error = ResolveTokenError_BadTable;
6236 return NULL_HANDLE_STRING;
6239 if (image_is_dynamic (image)) {
6240 ERROR_DECL (ignore_inner_error);
6241 // FIXME ignoring error
6242 // FIXME Push MONO_HANDLE_NEW to lower layers.
6243 MonoStringHandle result = MONO_HANDLE_NEW (MonoString, (MonoString*)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, ignore_inner_error));
6244 mono_error_cleanup (ignore_inner_error);
6245 return result;
6248 if ((index <= 0) || (index >= image->heap_us.size)) {
6249 *resolve_error = ResolveTokenError_OutOfRange;
6250 return NULL_HANDLE_STRING;
6253 /* FIXME: What to do if the index points into the middle of a string ? */
6254 return mono_ldstr_handle (mono_domain_get (), image, index, error);
6257 static MonoClassField*
6258 module_resolve_field_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6260 HANDLE_FUNCTION_ENTER ();
6261 MonoClass *klass;
6262 int table = mono_metadata_token_table (token);
6263 int index = mono_metadata_token_index (token);
6264 MonoGenericContext context;
6265 MonoClassField *field = NULL;
6267 error_init (error);
6268 *resolve_error = ResolveTokenError_Other;
6270 /* Validate token */
6271 if ((table != MONO_TABLE_FIELD) && (table != MONO_TABLE_MEMBERREF)) {
6272 *resolve_error = ResolveTokenError_BadTable;
6273 goto leave;
6276 if (image_is_dynamic (image)) {
6277 if (table == MONO_TABLE_FIELD) {
6278 ERROR_DECL (inner_error);
6279 field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6280 mono_error_cleanup (inner_error);
6281 goto leave;
6284 if (mono_memberref_is_method (image, token)) {
6285 *resolve_error = ResolveTokenError_BadTable;
6286 goto leave;
6289 init_generic_context_from_args_handles (&context, type_args, method_args);
6290 ERROR_DECL (inner_error);
6291 field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6292 mono_error_cleanup (inner_error);
6293 goto leave;
6296 if ((index <= 0) || (index > image->tables [table].rows)) {
6297 *resolve_error = ResolveTokenError_OutOfRange;
6298 goto leave;
6300 if ((table == MONO_TABLE_MEMBERREF) && (mono_memberref_is_method (image, token))) {
6301 *resolve_error = ResolveTokenError_BadTable;
6302 goto leave;
6305 init_generic_context_from_args_handles (&context, type_args, method_args);
6306 field = mono_field_from_token_checked (image, token, &klass, &context, error);
6308 leave:
6309 HANDLE_FUNCTION_RETURN_VAL (field);
6312 MonoClassField*
6313 ves_icall_System_Reflection_RuntimeModule_ResolveFieldToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6315 return module_resolve_field_token (image, token, type_args, method_args, resolve_error, error);
6318 MonoObjectHandle
6319 ves_icall_System_Reflection_RuntimeModule_ResolveMemberToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *error, MonoError *merror)
6321 int table = mono_metadata_token_table (token);
6323 error_init (merror);
6324 *error = ResolveTokenError_Other;
6326 switch (table) {
6327 case MONO_TABLE_TYPEDEF:
6328 case MONO_TABLE_TYPEREF:
6329 case MONO_TABLE_TYPESPEC: {
6330 MonoType *t = module_resolve_type_token (image, token, type_args, method_args, error, merror);
6331 if (t) {
6332 return MONO_HANDLE_CAST (MonoObject, mono_type_get_object_handle (mono_domain_get (), t, merror));
6334 else
6335 return NULL_HANDLE;
6337 case MONO_TABLE_METHOD:
6338 case MONO_TABLE_METHODSPEC: {
6339 MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
6340 if (m) {
6341 return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
6342 } else
6343 return NULL_HANDLE;
6345 case MONO_TABLE_FIELD: {
6346 MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
6347 if (f) {
6348 return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
6350 else
6351 return NULL_HANDLE;
6353 case MONO_TABLE_MEMBERREF:
6354 if (mono_memberref_is_method (image, token)) {
6355 MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
6356 if (m) {
6357 return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
6358 } else
6359 return NULL_HANDLE;
6361 else {
6362 MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
6363 if (f) {
6364 return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
6366 else
6367 return NULL_HANDLE;
6369 break;
6371 default:
6372 *error = ResolveTokenError_BadTable;
6375 return NULL_HANDLE;
6378 MonoArrayHandle
6379 ves_icall_System_Reflection_RuntimeModule_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error, MonoError *error)
6381 error_init (error);
6382 int table = mono_metadata_token_table (token);
6383 int idx = mono_metadata_token_index (token);
6384 MonoTableInfo *tables = image->tables;
6385 guint32 sig, len;
6386 const char *ptr;
6388 *resolve_error = ResolveTokenError_OutOfRange;
6390 /* FIXME: Support other tables ? */
6391 if (table != MONO_TABLE_STANDALONESIG)
6392 return NULL_HANDLE_ARRAY;
6394 if (image_is_dynamic (image))
6395 return NULL_HANDLE_ARRAY;
6397 if ((idx == 0) || (idx > tables [MONO_TABLE_STANDALONESIG].rows))
6398 return NULL_HANDLE_ARRAY;
6400 sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
6402 ptr = mono_metadata_blob_heap (image, sig);
6403 len = mono_metadata_decode_blob_size (ptr, &ptr);
6405 MonoArrayHandle res = mono_array_new_handle (mono_domain_get (), mono_defaults.byte_class, len, error);
6406 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6407 uint32_t h;
6408 gpointer array_base = MONO_ARRAY_HANDLE_PIN (res, guint8, 0, &h);
6409 memcpy (array_base, ptr, len);
6410 mono_gchandle_free_internal (h);
6411 return res;
6414 static void
6415 check_for_invalid_type (MonoClass *klass, MonoError *error)
6417 char *name;
6419 error_init (error);
6421 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_TYPEDBYREF)
6422 return;
6424 name = mono_type_get_full_name (klass);
6425 mono_error_set_type_load_name (error, name, g_strdup (""), "");
6428 MonoReflectionTypeHandle
6429 ves_icall_RuntimeType_make_array_type (MonoReflectionTypeHandle ref_type, int rank, MonoError *error)
6431 error_init (error);
6432 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6434 MonoClass *klass = mono_class_from_mono_type_internal (type);
6435 check_for_invalid_type (klass, error);
6436 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6438 MonoClass *aklass;
6439 if (rank == 0) //single dimension array
6440 aklass = mono_class_create_array (klass, 1);
6441 else
6442 aklass = mono_class_create_bounded_array (klass, rank, TRUE);
6444 if (mono_class_has_failure (aklass)) {
6445 mono_error_set_for_class_failure (error, aklass);
6446 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6449 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6450 return mono_type_get_object_handle (domain, m_class_get_byval_arg (aklass), error);
6453 MonoReflectionTypeHandle
6454 ves_icall_RuntimeType_make_byref_type (MonoReflectionTypeHandle ref_type, MonoError *error)
6456 error_init (error);
6457 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6459 MonoClass *klass = mono_class_from_mono_type_internal (type);
6460 mono_class_init_checked (klass, error);
6461 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6463 check_for_invalid_type (klass, error);
6464 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6466 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6467 return mono_type_get_object_handle (domain, m_class_get_this_arg (klass), error);
6470 MonoReflectionTypeHandle
6471 ves_icall_RuntimeType_MakePointerType (MonoReflectionTypeHandle ref_type, MonoError *error)
6473 error_init (error);
6474 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6475 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6476 MonoClass *klass = mono_class_from_mono_type_internal (type);
6477 mono_class_init_checked (klass, error);
6478 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6480 check_for_invalid_type (klass, error);
6481 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6483 MonoClass *pklass = mono_class_create_ptr (type);
6485 return mono_type_get_object_handle (domain, m_class_get_byval_arg (pklass), error);
6488 MonoObjectHandle
6489 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionTypeHandle ref_type, MonoObjectHandle target,
6490 MonoReflectionMethodHandle info, MonoBoolean throwOnBindFailure, MonoError *error)
6492 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6493 MonoClass *delegate_class = mono_class_from_mono_type_internal (type);
6494 MonoMethod *method = MONO_HANDLE_GETVAL (info, method);
6495 MonoMethodSignature *sig = mono_method_signature_internal (method);
6497 mono_class_init_checked (delegate_class, error);
6498 return_val_if_nok (error, NULL_HANDLE);
6500 if (!(m_class_get_parent (delegate_class) == mono_defaults.multicastdelegate_class)) {
6501 /* FIXME improve this exception message */
6502 mono_error_set_execution_engine (error, "file %s: line %d (%s): assertion failed: (%s)", __FILE__, __LINE__,
6503 __func__,
6504 "delegate_class->parent == mono_defaults.multicastdelegate_class");
6505 return NULL_HANDLE;
6508 if (mono_security_core_clr_enabled ()) {
6509 ERROR_DECL (security_error);
6510 if (!mono_security_core_clr_ensure_delegate_creation (method, security_error)) {
6511 if (throwOnBindFailure)
6512 mono_error_move (error, security_error);
6513 else
6514 mono_error_cleanup (security_error);
6515 return NULL_HANDLE;
6519 if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
6520 if (!method->is_inflated) {
6521 mono_error_set_argument (error, "method", " Cannot bind to the target method because its signature differs from that of the delegate type");
6522 return NULL_HANDLE;
6526 MonoObjectHandle delegate = mono_object_new_handle (MONO_HANDLE_DOMAIN (ref_type), delegate_class, error);
6527 return_val_if_nok (error, NULL_HANDLE);
6529 if (!method_is_dynamic (method) && (!MONO_HANDLE_IS_NULL (target) && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass != mono_handle_class (target))) {
6530 method = mono_object_handle_get_virtual_method (target, method, error);
6531 return_val_if_nok (error, NULL_HANDLE);
6534 mono_delegate_ctor_with_method (delegate, target, NULL, method, error);
6535 return_val_if_nok (error, NULL_HANDLE);
6536 return delegate;
6539 MonoMulticastDelegateHandle
6540 ves_icall_System_Delegate_AllocDelegateLike_internal (MonoDelegateHandle delegate, MonoError *error)
6542 error_init (error);
6544 MonoClass *klass = mono_handle_class (delegate);
6545 g_assert (mono_class_has_parent (klass, mono_defaults.multicastdelegate_class));
6547 MonoMulticastDelegateHandle ret = MONO_HANDLE_CAST (MonoMulticastDelegate, mono_object_new_handle (MONO_HANDLE_DOMAIN (delegate), klass, error));
6548 return_val_if_nok (error, MONO_HANDLE_CAST (MonoMulticastDelegate, NULL_HANDLE));
6550 MONO_HANDLE_SETVAL (MONO_HANDLE_CAST (MonoDelegate, ret), invoke_impl, gpointer, mono_runtime_create_delegate_trampoline (klass));
6552 return ret;
6555 MonoReflectionMethodHandle
6556 ves_icall_System_Delegate_GetVirtualMethod_internal (MonoDelegateHandle delegate, MonoError *error)
6558 error_init (error);
6560 MonoObjectHandle delegate_target = MONO_HANDLE_NEW_GET (MonoObject, delegate, target);
6561 MonoMethod *m = mono_object_handle_get_virtual_method (delegate_target, MONO_HANDLE_GETVAL (delegate, method), error);
6562 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
6563 return mono_method_get_object_handle (mono_domain_get (), m, m->klass, error);
6566 /* System.Buffer */
6568 static inline gint32
6569 mono_array_get_byte_length (MonoArray *array)
6571 MonoClass *klass;
6572 int length;
6573 int i;
6575 klass = array->obj.vtable->klass;
6577 if (array->bounds == NULL)
6578 length = array->max_length;
6579 else {
6580 length = 1;
6581 int klass_rank = m_class_get_rank (klass);
6582 for (i = 0; i < klass_rank; ++ i)
6583 length *= array->bounds [i].length;
6586 switch (m_class_get_byval_arg (m_class_get_element_class (klass))->type) {
6587 case MONO_TYPE_I1:
6588 case MONO_TYPE_U1:
6589 case MONO_TYPE_BOOLEAN:
6590 return length;
6591 case MONO_TYPE_I2:
6592 case MONO_TYPE_U2:
6593 case MONO_TYPE_CHAR:
6594 return length << 1;
6595 case MONO_TYPE_I4:
6596 case MONO_TYPE_U4:
6597 case MONO_TYPE_R4:
6598 return length << 2;
6599 case MONO_TYPE_I:
6600 case MONO_TYPE_U:
6601 return length * sizeof (gpointer);
6602 case MONO_TYPE_I8:
6603 case MONO_TYPE_U8:
6604 case MONO_TYPE_R8:
6605 return length << 3;
6606 default:
6607 return -1;
6611 gint32
6612 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array)
6614 return mono_array_get_byte_length (array);
6617 gint8
6618 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx)
6620 return mono_array_get_internal (array, gint8, idx);
6623 void
6624 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value)
6626 mono_array_set_internal (array, gint8, idx, value);
6629 void
6630 ves_icall_System_Buffer_MemcpyInternal (gpointer dest, gconstpointer src, gint32 count)
6632 memcpy (dest, src, count);
6635 MonoBoolean
6636 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count)
6638 guint8 *src_buf, *dest_buf;
6640 if (count < 0) {
6641 ERROR_DECL (error);
6642 mono_error_set_argument (error, "count", "is negative");
6643 mono_error_set_pending_exception (error);
6644 return FALSE;
6647 g_assert (count >= 0);
6649 /* This is called directly from the class libraries without going through the managed wrapper */
6650 MONO_CHECK_ARG_NULL (src, FALSE);
6651 MONO_CHECK_ARG_NULL (dest, FALSE);
6653 /* watch out for integer overflow */
6654 if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
6655 return FALSE;
6657 src_buf = (guint8 *)src->vector + src_offset;
6658 dest_buf = (guint8 *)dest->vector + dest_offset;
6660 if (src != dest)
6661 memcpy (dest_buf, src_buf, count);
6662 else
6663 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
6665 return TRUE;
6668 #ifndef DISABLE_REMOTING
6669 MonoObjectHandle
6670 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObjectHandle this_obj, MonoStringHandle class_name, MonoError *error)
6672 error_init (error);
6673 MonoDomain *domain = MONO_HANDLE_DOMAIN (this_obj);
6674 MonoRealProxyHandle rp = MONO_HANDLE_CAST (MonoRealProxy, this_obj);
6676 MonoObjectHandle res = mono_object_new_handle (domain, mono_defaults.transparent_proxy_class, error);
6677 return_val_if_nok (error, NULL_HANDLE);
6679 MonoTransparentProxyHandle tp = MONO_HANDLE_CAST (MonoTransparentProxy, res);
6681 MONO_HANDLE_SET (tp, rp, rp);
6683 MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
6684 MONO_HANDLE_GET (reftype, rp, class_to_proxy);
6685 MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
6686 MonoClass *klass = mono_class_from_mono_type_internal (type);
6688 // mono_remote_class_vtable cannot handle errors well, so force any loading error to occur early
6689 mono_class_setup_vtable (klass);
6690 if (mono_class_has_failure (klass)) {
6691 mono_error_set_for_class_failure (error, klass);
6692 return NULL_HANDLE;
6695 MonoObjectHandle remoting_obj = mono_object_handle_isinst (this_obj, mono_defaults.iremotingtypeinfo_class, error);
6696 return_val_if_nok (error, NULL_HANDLE);
6697 MONO_HANDLE_SETVAL (tp, custom_type_info, MonoBoolean, !MONO_HANDLE_IS_NULL (remoting_obj));
6699 MonoRemoteClass *remote_class = (MonoRemoteClass*)mono_remote_class (domain, class_name, klass, error);
6700 return_val_if_nok (error, NULL_HANDLE);
6701 MONO_HANDLE_SETVAL (tp, remote_class, MonoRemoteClass*, remote_class);
6703 MONO_HANDLE_SETVAL (res, vtable, MonoVTable*, (MonoVTable*)mono_remote_class_vtable (domain, remote_class, rp, error));
6704 return_val_if_nok (error, NULL_HANDLE);
6705 return res;
6708 MonoReflectionType *
6709 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
6711 ERROR_DECL (error);
6712 g_assert (tp != NULL && mono_object_class (tp) == mono_defaults.transparent_proxy_class);
6713 g_assert (tp->remote_class != NULL && tp->remote_class->proxy_class != NULL);
6714 MonoReflectionType *ret = mono_type_get_object_checked (mono_object_domain (tp), m_class_get_byval_arg (tp->remote_class->proxy_class), error);
6715 mono_error_set_pending_exception (error);
6717 return ret;
6719 #endif
6721 /* System.Environment */
6723 MonoStringHandle
6724 ves_icall_System_Environment_get_UserName (MonoError *error)
6726 error_init (error);
6727 /* using glib is more portable */
6728 const gchar *user_name = g_get_user_name ();
6729 if (user_name != NULL)
6730 return mono_string_new_handle (mono_domain_get (), user_name, error);
6731 else
6732 return NULL_HANDLE_STRING;
6735 #ifndef HOST_WIN32
6736 static MonoStringHandle
6737 mono_icall_get_machine_name (MonoError *error)
6739 error_init (error);
6740 #if !defined(DISABLE_SOCKETS)
6741 MonoStringHandle result;
6742 char *buf;
6743 int n, i;
6744 #if defined _SC_HOST_NAME_MAX
6745 n = sysconf (_SC_HOST_NAME_MAX);
6746 if (n == -1)
6747 #endif
6748 n = 512;
6749 buf = (char*)g_malloc (n + 1);
6751 #if defined(HAVE_GETHOSTNAME)
6752 if (gethostname (buf, n) == 0){
6753 buf [n] = 0;
6754 // try truncating the string at the first dot
6755 for (i = 0; i < n; i++) {
6756 if (buf [i] == '.') {
6757 buf [i] = 0;
6758 break;
6761 result = mono_string_new_handle (mono_domain_get (), buf, error);
6762 } else
6763 #endif
6764 result = MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
6766 g_free (buf);
6768 return result;
6769 #else
6770 return mono_string_new_handle (mono_domain_get (), "mono", error);
6771 #endif
6773 #endif /* !HOST_WIN32 */
6775 MonoStringHandle
6776 ves_icall_System_Environment_get_MachineName (MonoError *error)
6778 error_init (error);
6779 return mono_icall_get_machine_name (error);
6782 #ifndef HOST_WIN32
6783 static inline int
6784 mono_icall_get_platform (void)
6786 #if defined(__MACH__)
6787 /* OSX */
6789 // Notice that the value is hidden from user code, and only exposed
6790 // to mscorlib. This is due to Mono's Unix/MacOS code predating the
6791 // define and making assumptions based on Unix/128/4 values before there
6792 // was a MacOS define. Lots of code would assume that not-Unix meant
6793 // Windows, but in this case, it would be OSX.
6795 return 6;
6796 #else
6797 /* Unix */
6798 return 4;
6799 #endif
6801 #endif /* !HOST_WIN32 */
6804 ves_icall_System_Environment_get_Platform (void)
6806 return mono_icall_get_platform ();
6809 #ifndef HOST_WIN32
6810 static inline MonoStringHandle
6811 mono_icall_get_new_line (MonoError *error)
6813 error_init (error);
6814 return mono_string_new_handle (mono_domain_get (), "\n", error);
6816 #endif /* !HOST_WIN32 */
6818 MonoStringHandle
6819 ves_icall_System_Environment_get_NewLine (MonoError *error)
6821 return mono_icall_get_new_line (error);
6824 #ifndef HOST_WIN32
6825 static inline MonoBoolean
6826 mono_icall_is_64bit_os (void)
6828 #if SIZEOF_VOID_P == 8
6829 return TRUE;
6830 #else
6831 #if defined(HAVE_SYS_UTSNAME_H)
6832 struct utsname name;
6834 if (uname (&name) >= 0) {
6835 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;
6837 #endif
6838 return FALSE;
6839 #endif
6841 #endif /* !HOST_WIN32 */
6843 MonoBoolean
6844 ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
6846 return mono_icall_is_64bit_os ();
6849 MonoStringHandle
6850 ves_icall_System_Environment_GetEnvironmentVariable_native (const gchar *utf8_name, MonoError *error)
6852 gchar *value;
6854 if (utf8_name == NULL)
6855 return NULL_HANDLE_STRING;
6857 value = g_getenv (utf8_name);
6859 if (value == 0)
6860 return NULL_HANDLE_STRING;
6862 MonoStringHandle res = mono_string_new_handle (mono_domain_get (), value, error);
6863 g_free (value);
6864 return res;
6868 * There is no standard way to get at environ.
6870 #ifndef _MSC_VER
6871 #ifndef __MINGW32_VERSION
6872 #if defined(__APPLE__)
6873 #if defined (TARGET_OSX)
6874 /* Apple defines this in crt_externs.h but doesn't provide that header for
6875 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
6876 * in fact exist on all implementations (so far)
6878 G_BEGIN_DECLS
6879 gchar ***_NSGetEnviron(void);
6880 G_END_DECLS
6881 #define environ (*_NSGetEnviron())
6882 #else
6883 static char *mono_environ[1] = { NULL };
6884 #define environ mono_environ
6885 #endif /* defined (TARGET_OSX) */
6886 #else
6887 G_BEGIN_DECLS
6888 extern
6889 char **environ;
6890 G_END_DECLS
6891 #endif
6892 #endif
6893 #endif
6895 MonoArrayHandle
6896 ves_icall_System_Environment_GetCommandLineArgs (MonoError *error)
6898 error_init (error);
6899 MonoArrayHandle result = mono_runtime_get_main_args_handle (error);
6900 return result;
6903 #ifndef HOST_WIN32
6904 static MonoArray *
6905 mono_icall_get_environment_variable_names (MonoError *error)
6907 MonoArray *names;
6908 MonoDomain *domain;
6909 MonoString *str;
6910 gchar **e, **parts;
6911 int n;
6913 error_init (error);
6914 n = 0;
6915 for (e = environ; *e != 0; ++ e)
6916 ++ n;
6918 domain = mono_domain_get ();
6919 names = mono_array_new_checked (domain, mono_defaults.string_class, n, error);
6920 return_val_if_nok (error, NULL);
6922 n = 0;
6923 for (e = environ; *e != 0; ++ e) {
6924 parts = g_strsplit (*e, "=", 2);
6925 if (*parts != 0) {
6926 str = mono_string_new_checked (domain, *parts, error);
6927 if (!is_ok (error)) {
6928 g_strfreev (parts);
6929 return NULL;
6931 mono_array_setref_internal (names, n, str);
6934 g_strfreev (parts);
6936 ++ n;
6939 return names;
6941 #endif /* !HOST_WIN32 */
6943 MonoArray *
6944 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
6946 ERROR_DECL (error);
6947 MonoArray *result = mono_icall_get_environment_variable_names (error);
6948 mono_error_set_pending_exception (error);
6949 return result;
6952 void
6953 ves_icall_System_Environment_InternalSetEnvironmentVariable (const gunichar2 *name, gint32 name_length,
6954 const gunichar2 *value, gint32 value_length, MonoError *error)
6956 #ifdef HOST_WIN32
6957 if (!value || !value_length || !value [0])
6958 value = NULL;
6960 SetEnvironmentVariableW (name, value);
6961 #else
6962 char *utf8_name = NULL;
6963 char *utf8_value = NULL;
6965 utf8_name = mono_utf16_to_utf8 (name, name_length, error); // FIXME: this should be ascii
6966 goto_if_nok (error, exit);
6968 if (!value || !value_length || !value [0]) {
6969 g_unsetenv (utf8_name);
6970 goto exit;
6973 utf8_value = mono_utf16_to_utf8 (value, value_length, error);
6974 goto_if_nok (error, exit);
6976 g_setenv (utf8_name, utf8_value, TRUE);
6977 exit:
6978 g_free (utf8_name);
6979 g_free (utf8_value);
6980 #endif
6983 void
6984 ves_icall_System_Environment_Exit (int result)
6986 mono_environment_exitcode_set (result);
6988 if (!mono_runtime_try_shutdown ())
6989 mono_thread_exit ();
6991 /* Suspend all managed threads since the runtime is going away */
6992 mono_thread_suspend_all_other_threads ();
6994 mono_runtime_quit ();
6996 /* we may need to do some cleanup here... */
6997 exit (result);
7000 MonoStringHandle
7001 ves_icall_System_Environment_GetGacPath (MonoError *error)
7003 return mono_string_new_handle (mono_domain_get (), mono_assembly_getrootdir (), error);
7006 #ifndef HOST_WIN32
7007 static inline MonoStringHandle
7008 mono_icall_get_windows_folder_path (int folder, MonoError *error)
7010 error_init (error);
7011 g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
7012 return mono_string_new_handle (mono_domain_get (), "", error);
7014 #endif /* !HOST_WIN32 */
7016 MonoStringHandle
7017 ves_icall_System_Environment_GetWindowsFolderPath (int folder, MonoError *error)
7019 return mono_icall_get_windows_folder_path (folder, error);
7022 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
7023 static MonoArray *
7024 mono_icall_get_logical_drives (void)
7026 ERROR_DECL (error);
7027 gunichar2 buf [256], *ptr, *dname;
7028 gunichar2 *u16;
7029 guint initial_size = 127, size = 128;
7030 gint ndrives;
7031 MonoArray *result;
7032 MonoString *drivestr;
7033 MonoDomain *domain = mono_domain_get ();
7034 gint len;
7036 buf [0] = '\0';
7037 ptr = buf;
7039 while (size > initial_size) {
7040 size = (guint) mono_w32file_get_logical_drive (initial_size, ptr);
7041 if (size > initial_size) {
7042 if (ptr != buf)
7043 g_free (ptr);
7044 ptr = (gunichar2 *)g_malloc0 ((size + 1) * sizeof (gunichar2));
7045 initial_size = size;
7046 size++;
7050 /* Count strings */
7051 dname = ptr;
7052 ndrives = 0;
7053 do {
7054 while (*dname++);
7055 ndrives++;
7056 } while (*dname);
7058 dname = ptr;
7059 result = mono_array_new_checked (domain, mono_defaults.string_class, ndrives, error);
7060 if (mono_error_set_pending_exception (error))
7061 goto leave;
7063 ndrives = 0;
7064 do {
7065 len = 0;
7066 u16 = dname;
7067 while (*u16) { u16++; len ++; }
7068 drivestr = mono_string_new_utf16_checked (domain, dname, len, error);
7069 if (mono_error_set_pending_exception (error))
7070 goto leave;
7072 mono_array_setref_internal (result, ndrives++, drivestr);
7073 while (*dname++);
7074 } while (*dname);
7076 leave:
7077 if (ptr != buf)
7078 g_free (ptr);
7080 return result;
7082 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
7084 MonoArray *
7085 ves_icall_System_Environment_GetLogicalDrives (void)
7087 return mono_icall_get_logical_drives ();
7090 MonoStringHandle
7091 ves_icall_System_IO_DriveInfo_GetDriveFormat (const gunichar2 *path, gint32 path_length, MonoError *error)
7093 gunichar2 volume_name [MAX_PATH + 1];
7095 if (mono_w32file_get_file_system_type (path, volume_name, MAX_PATH + 1) == FALSE)
7096 return NULL_HANDLE_STRING;
7097 return mono_string_new_utf16_handle (mono_domain_get (), volume_name, g_utf16_len (volume_name), error);
7100 MonoStringHandle
7101 ves_icall_System_Environment_InternalGetHome (MonoError *error)
7103 const gchar *home_dir = g_get_home_dir ();
7104 if (home_dir != NULL)
7105 return mono_string_new_handle (mono_domain_get (), home_dir, error);
7106 else
7107 return NULL_HANDLE_STRING;
7110 static const char * const encodings [] = {
7111 (char *) 1,
7112 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
7113 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
7114 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
7115 (char *) 2,
7116 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
7117 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
7118 "x_unicode_2_0_utf_7",
7119 (char *) 3,
7120 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
7121 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
7122 (char *) 4,
7123 "utf_16", "UTF_16LE", "ucs_2", "unicode",
7124 "iso_10646_ucs2",
7125 (char *) 5,
7126 "unicodefffe", "utf_16be",
7127 (char *) 6,
7128 "iso_8859_1",
7129 (char *) 0
7133 * Returns the internal codepage, if the value of "int_code_page" is
7134 * 1 at entry, and we can not compute a suitable code page number,
7135 * returns the code page as a string
7137 MonoStringHandle
7138 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page, MonoError *error)
7140 error_init (error);
7141 const char *cset;
7142 const char *p;
7143 char *c;
7144 char *codepage = NULL;
7145 int code;
7146 int want_name = *int_code_page;
7147 int i;
7149 *int_code_page = -1;
7151 g_get_charset (&cset);
7152 c = codepage = g_strdup (cset);
7153 for (c = codepage; *c; c++){
7154 if (isascii (*c) && isalpha (*c))
7155 *c = tolower (*c);
7156 if (*c == '-')
7157 *c = '_';
7159 /* g_print ("charset: %s\n", cset); */
7161 /* handle some common aliases */
7162 p = encodings [0];
7163 code = 0;
7164 for (i = 0; p != 0; ){
7165 if ((gsize) p < 7){
7166 code = (gssize) p;
7167 p = encodings [++i];
7168 continue;
7170 if (strcmp (p, codepage) == 0){
7171 *int_code_page = code;
7172 break;
7174 p = encodings [++i];
7177 if (strstr (codepage, "utf_8") != NULL)
7178 *int_code_page |= 0x10000000;
7179 g_free (codepage);
7181 if (want_name && *int_code_page == -1)
7182 return mono_string_new_handle (mono_domain_get (), cset, error);
7183 return NULL_HANDLE_STRING;
7186 MonoBoolean
7187 ves_icall_System_Environment_get_HasShutdownStarted (void)
7189 return mono_runtime_is_shutting_down () || mono_domain_is_unloading (mono_domain_get ());
7192 #ifndef HOST_WIN32
7194 void
7195 ves_icall_System_Environment_BroadcastSettingChange (MonoError *error)
7199 #endif
7201 gint32
7202 ves_icall_System_Environment_get_TickCount (void)
7204 /* this will overflow after ~24 days */
7205 return (gint32) (mono_msec_boottime () & 0xffffffff);
7208 gint32
7209 ves_icall_System_Runtime_Versioning_VersioningHelper_GetRuntimeId (MonoError *error)
7211 return 9;
7214 #ifndef DISABLE_REMOTING
7215 MonoBoolean
7216 ves_icall_IsTransparentProxy (MonoObjectHandle proxy, MonoError *error)
7218 if (MONO_HANDLE_IS_NULL (proxy))
7219 return 0;
7221 if (mono_class_is_transparent_proxy (mono_handle_class (proxy)))
7222 return 1;
7224 return 0;
7227 MonoReflectionMethodHandle
7228 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
7229 MonoReflectionTypeHandle rtype, MonoReflectionMethodHandle rmethod, MonoError *error)
7231 MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
7233 if (MONO_HANDLE_IS_NULL (rtype)) {
7234 mono_error_set_argument_null (error, "type", "");
7235 return ret;
7237 if (MONO_HANDLE_IS_NULL (rmethod)) {
7238 mono_error_set_argument_null (error, "method", "");
7239 return ret;
7242 MonoMethod *method = MONO_HANDLE_GETVAL (rmethod, method);
7243 MonoType *type = MONO_HANDLE_GETVAL (rtype, type);
7244 MonoClass *klass = mono_class_from_mono_type_internal (type);
7245 mono_class_init_checked (klass, error);
7246 return_val_if_nok (error, ret);
7248 if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass))
7249 return ret;
7251 if (method->flags & METHOD_ATTRIBUTE_STATIC)
7252 return ret;
7254 if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
7255 if (klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE))
7256 ret = rmethod;
7257 return ret;
7260 mono_class_setup_vtable (klass);
7261 MonoMethod **vtable = m_class_get_vtable (klass);
7263 MonoMethod *res = NULL;
7264 if (mono_class_is_interface (method->klass)) {
7265 gboolean variance_used = FALSE;
7266 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
7267 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
7268 if (offs >= 0)
7269 res = vtable [offs + method->slot];
7270 } else {
7271 if (!(klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE)))
7272 return ret;
7274 if (method->slot != -1)
7275 res = vtable [method->slot];
7278 if (!res)
7279 return ret;
7281 ret = mono_method_get_object_handle (mono_domain_get (), res, NULL, error);
7282 return ret;
7285 void
7286 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
7288 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
7289 MonoVTable *vtable = mono_class_vtable_checked (mono_domain_get (), klass, error);
7290 return_if_nok (error);
7292 mono_vtable_set_is_remote (vtable, enable);
7295 #else /* DISABLE_REMOTING */
7297 void
7298 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
7300 g_assert_not_reached ();
7303 #endif
7305 MonoObjectHandle
7306 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionTypeHandle type, MonoError *error)
7308 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
7309 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
7310 mono_class_init_checked (klass, error);
7311 return_val_if_nok (error, NULL_HANDLE);
7313 if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || mono_class_is_abstract (klass)) {
7314 mono_error_set_argument (error, "type", "Type cannot be instantiated");
7315 return NULL_HANDLE;
7318 if (m_class_get_rank (klass) >= 1) {
7319 g_assert (m_class_get_rank (klass) == 1);
7320 return MONO_HANDLE_CAST (MonoObject, mono_array_new_handle (domain, m_class_get_element_class (klass), 0, error));
7321 } else {
7322 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
7323 return_val_if_nok (error, NULL_HANDLE);
7325 /* Bypass remoting object creation check */
7326 return MONO_HANDLE_NEW (MonoObject, mono_object_new_alloc_specific_checked (vtable, error));
7330 MonoStringHandle
7331 ves_icall_System_IO_get_temp_path (MonoError *error)
7333 return mono_string_new_handle (mono_domain_get (), g_get_tmp_dir (), error);
7336 #if defined(ENABLE_MONODROID) || defined(ENABLE_MONOTOUCH)
7338 G_EXTERN_C gpointer CreateZStream (gint32 compress, MonoBoolean gzip, gpointer feeder, gpointer data);
7339 G_EXTERN_C gint32 CloseZStream (gpointer stream);
7340 G_EXTERN_C gint32 Flush (gpointer stream);
7341 G_EXTERN_C gint32 ReadZStream (gpointer stream, gpointer buffer, gint32 length);
7342 G_EXTERN_C gint32 WriteZStream (gpointer stream, gpointer buffer, gint32 length);
7344 gpointer
7345 ves_icall_System_IO_Compression_DeflateStreamNative_CreateZStream (gint32 compress, MonoBoolean gzip, gpointer feeder, gpointer data)
7347 #ifdef MONO_CROSS_COMPILE
7348 return NULL;
7349 #else
7350 return CreateZStream (compress, gzip, feeder, data);
7351 #endif
7354 gint32
7355 ves_icall_System_IO_Compression_DeflateStreamNative_CloseZStream (gpointer stream)
7357 #ifdef MONO_CROSS_COMPILE
7358 return 0;
7359 #else
7360 return CloseZStream (stream);
7361 #endif
7364 gint32
7365 ves_icall_System_IO_Compression_DeflateStreamNative_Flush (gpointer stream)
7367 #ifdef MONO_CROSS_COMPILE
7368 return 0;
7369 #else
7370 return Flush (stream);
7371 #endif
7374 gint32
7375 ves_icall_System_IO_Compression_DeflateStreamNative_ReadZStream (gpointer stream, gpointer buffer, gint32 length)
7377 #ifdef MONO_CROSS_COMPILE
7378 return 0;
7379 #else
7380 return ReadZStream (stream, buffer, length);
7381 #endif
7384 gint32
7385 ves_icall_System_IO_Compression_DeflateStreamNative_WriteZStream (gpointer stream, gpointer buffer, gint32 length)
7387 #ifdef MONO_CROSS_COMPILE
7388 return 0;
7389 #else
7390 return WriteZStream (stream, buffer, length);
7391 #endif
7394 #endif
7396 #ifndef PLATFORM_NO_DRIVEINFO
7397 MonoBoolean
7398 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (const gunichar2 *path_name, gint32 path_name_length, guint64 *free_bytes_avail,
7399 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
7400 gint32 *error)
7402 g_assert (error);
7403 g_assert (free_bytes_avail);
7404 g_assert (total_number_of_bytes);
7405 g_assert (total_number_of_free_bytes);
7407 // FIXME check for embedded nuls here or managed
7409 *error = ERROR_SUCCESS;
7410 *free_bytes_avail = (guint64)-1;
7411 *total_number_of_bytes = (guint64)-1;
7412 *total_number_of_free_bytes = (guint64)-1;
7414 gboolean result = mono_w32file_get_disk_free_space (path_name, free_bytes_avail, total_number_of_bytes, total_number_of_free_bytes);
7415 if (!result)
7416 *error = mono_w32error_get_last ();
7418 return result;
7420 #endif /* PLATFORM_NO_DRIVEINFO */
7422 gpointer
7423 ves_icall_RuntimeMethodHandle_GetFunctionPointer (MonoMethod *method, MonoError *error)
7425 return mono_compile_method_checked (method, error);
7428 MonoStringHandle
7429 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (MonoError *error)
7431 gchar *path;
7433 const char *mono_cfg_dir = mono_get_config_dir ();
7434 if (!mono_cfg_dir)
7435 return mono_string_new_handle (mono_domain_get (), "", error);
7437 path = g_build_path (G_DIR_SEPARATOR_S, mono_cfg_dir, "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
7439 mono_icall_make_platform_path (path);
7441 MonoStringHandle mcpath = mono_string_new_handle (mono_domain_get (), path, error);
7442 g_free (path);
7444 mono_error_assert_ok (error);
7446 return mcpath;
7449 MonoStringHandle
7450 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_app_config (MonoError *error)
7452 const gchar *app_config;
7453 MonoDomain *domain;
7454 gchar *config_file_name, *config_file_path;
7455 gsize len, config_file_path_length, config_ext_length;
7456 gchar *module;
7458 domain = mono_domain_get ();
7459 MonoStringHandle file = MONO_HANDLE_NEW (MonoString, domain->setup->configuration_file);
7460 if (MONO_HANDLE_IS_NULL (file) || MONO_HANDLE_GETVAL (file, length) == 0)
7461 return MONO_HANDLE_CAST (MonoString, mono_new_null ());
7463 // Retrieve config file and remove the extension
7464 config_file_name = mono_string_handle_to_utf8 (file, error);
7465 return_val_if_nok (error, MONO_HANDLE_CAST (MonoString, NULL_HANDLE));
7467 config_file_path = mono_portability_find_file (config_file_name, TRUE);
7468 if (!config_file_path)
7469 config_file_path = config_file_name;
7471 config_file_path_length = strlen (config_file_path);
7472 config_ext_length = strlen (".config");
7473 if (config_file_path_length <= config_ext_length) {
7474 if (config_file_name != config_file_path)
7475 g_free (config_file_name);
7476 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
7479 len = config_file_path_length - config_ext_length;
7480 module = (gchar *)g_malloc0 (len + 1);
7481 memcpy (module, config_file_path, len);
7482 // Get the config file from the module name
7483 app_config = mono_config_string_for_assembly_file (module);
7484 // Clean-up
7485 g_free (module);
7486 if (config_file_name != config_file_path)
7487 g_free (config_file_name);
7488 g_free (config_file_path);
7490 if (!app_config)
7491 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
7493 return mono_string_new_handle (mono_domain_get (), app_config, error);
7496 static MonoStringHandle
7497 get_bundled_machine_config (MonoError *error)
7499 const gchar *machine_config;
7501 machine_config = mono_get_machine_config ();
7503 if (!machine_config)
7504 return NULL_HANDLE_STRING;
7506 return mono_string_new_handle (mono_domain_get (), machine_config, error);
7509 MonoStringHandle
7510 ves_icall_System_Environment_get_bundled_machine_config (MonoError *error)
7512 return get_bundled_machine_config (error);
7516 MonoStringHandle
7517 ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
7519 return get_bundled_machine_config (error);
7522 MonoStringHandle
7523 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
7525 return get_bundled_machine_config (error);
7529 MonoStringHandle
7530 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (MonoError *error)
7532 const char *mono_cfg_dir = mono_get_config_dir ();
7533 if (!mono_cfg_dir)
7534 return mono_string_new_handle (mono_domain_get (), "", error);
7536 char *path = g_path_get_dirname (mono_cfg_dir);
7538 mono_icall_make_platform_path (path);
7540 MonoStringHandle ipath = mono_string_new_handle (mono_domain_get (), path, error);
7541 g_free (path);
7543 return ipath;
7546 MonoBoolean
7547 ves_icall_get_resources_ptr (MonoReflectionAssemblyHandle assembly, gpointer *result, gint32 *size, MonoError *error)
7549 MonoPEResourceDataEntry *entry;
7550 MonoImage *image;
7552 if (MONO_HANDLE_IS_NULL (assembly) || !result || !size)
7553 return FALSE;
7555 *result = NULL;
7556 *size = 0;
7557 MonoAssembly *assm = MONO_HANDLE_GETVAL (assembly, assembly);
7558 image = assm->image;
7559 entry = (MonoPEResourceDataEntry *)mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
7560 if (!entry)
7561 return FALSE;
7563 *result = mono_image_rva_map (image, entry->rde_data_offset);
7564 if (!(*result)) {
7565 g_free (entry);
7566 return FALSE;
7568 *size = entry->rde_size;
7569 g_free (entry);
7570 return TRUE;
7573 MonoBoolean
7574 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (MonoError *error)
7576 return mono_is_debugger_attached ();
7579 MonoBoolean
7580 ves_icall_System_Diagnostics_Debugger_IsLogging (MonoError *error)
7582 return mono_get_runtime_callbacks ()->debug_log_is_enabled
7583 && mono_get_runtime_callbacks ()->debug_log_is_enabled ();
7586 void
7587 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoStringHandle category, MonoStringHandle message, MonoError *error)
7589 if (mono_get_runtime_callbacks ()->debug_log)
7590 mono_get_runtime_callbacks ()->debug_log (level, category, message);
7593 #ifndef HOST_WIN32
7594 static inline void
7595 mono_icall_write_windows_debug_string (const gunichar2 *message)
7597 g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
7599 #endif /* !HOST_WIN32 */
7601 void
7602 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (const gunichar2 *message, MonoError *error)
7604 mono_icall_write_windows_debug_string (message);
7607 /* Only used for value types */
7608 MonoObjectHandle
7609 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
7611 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
7612 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7613 MonoClass *klass = mono_class_from_mono_type_internal (type);
7615 mono_class_init_checked (klass, error);
7616 return_val_if_nok (error, NULL_HANDLE);
7618 if (mono_class_is_nullable (klass))
7619 /* No arguments -> null */
7620 return NULL_HANDLE;
7622 return mono_object_new_handle (domain, klass, error);
7625 MonoReflectionMethodHandle
7626 ves_icall_RuntimeMethodInfo_get_base_method (MonoReflectionMethodHandle m, MonoBoolean definition, MonoError *error)
7628 MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
7630 MonoMethod *base = mono_method_get_base_method (method, definition, error);
7631 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
7632 if (base == method) {
7633 /* we want to short-circuit and return 'm' here. But we should
7634 return the same method object that
7635 mono_method_get_object_handle, below would return. Since
7636 that call takes NULL for the reftype argument, it will take
7637 base->klass as the reflected type for the MonoMethod. So we
7638 need to check that m also has base->klass as the reflected
7639 type. */
7640 MonoReflectionTypeHandle orig_reftype = MONO_HANDLE_NEW_GET (MonoReflectionType, m, reftype);
7641 MonoClass *orig_klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (orig_reftype, type));
7642 if (base->klass == orig_klass)
7643 return m;
7645 return mono_method_get_object_handle (mono_domain_get (), base, NULL, error);
7648 MonoStringHandle
7649 ves_icall_RuntimeMethodInfo_get_name (MonoReflectionMethodHandle m, MonoError *error)
7651 MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
7653 MonoStringHandle s = mono_string_new_handle (MONO_HANDLE_DOMAIN (m), method->name, error);
7654 return_val_if_nok (error, NULL_HANDLE_STRING);
7655 MONO_HANDLE_SET (m, name, s);
7656 return s;
7659 void
7660 ves_icall_System_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
7662 iter->sig = *(MonoMethodSignature**)argsp;
7664 g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
7665 g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
7667 iter->next_arg = 0;
7668 /* FIXME: it's not documented what start is exactly... */
7669 if (start) {
7670 iter->args = start;
7671 } else {
7672 iter->args = argsp + sizeof (gpointer);
7674 iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
7676 /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
7679 void
7680 ves_icall_System_ArgIterator_IntGetNextArg (MonoArgIterator *iter, MonoTypedRef *res)
7682 guint32 i, arg_size;
7683 gint32 align;
7685 i = iter->sig->sentinelpos + iter->next_arg;
7687 g_assert (i < iter->sig->param_count);
7689 res->type = iter->sig->params [i];
7690 res->klass = mono_class_from_mono_type_internal (res->type);
7691 arg_size = mono_type_stack_size (res->type, &align);
7692 #if defined(__arm__) || defined(__mips__)
7693 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7694 #endif
7695 res->value = iter->args;
7696 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
7697 if (arg_size <= sizeof (gpointer)) {
7698 int dummy;
7699 int padding = arg_size - mono_type_size (res->type, &dummy);
7700 res->value = (guint8*)res->value + padding;
7702 #endif
7703 iter->args = (char*)iter->args + arg_size;
7704 iter->next_arg++;
7706 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res->type->type, arg_size, res->value); */
7709 void
7710 ves_icall_System_ArgIterator_IntGetNextArgWithType (MonoArgIterator *iter, MonoTypedRef *res, MonoType *type)
7712 guint32 i, arg_size;
7713 gint32 align;
7715 i = iter->sig->sentinelpos + iter->next_arg;
7717 g_assert (i < iter->sig->param_count);
7719 while (i < iter->sig->param_count) {
7720 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
7721 continue;
7722 res->type = iter->sig->params [i];
7723 res->klass = mono_class_from_mono_type_internal (res->type);
7724 /* FIXME: endianess issue... */
7725 arg_size = mono_type_stack_size (res->type, &align);
7726 #if defined(__arm__) || defined(__mips__)
7727 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7728 #endif
7729 res->value = iter->args;
7730 iter->args = (char*)iter->args + arg_size;
7731 iter->next_arg++;
7732 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7733 return;
7735 /* g_print ("arg type 0x%02x not found\n", res.type->type); */
7737 memset (res, 0, sizeof (MonoTypedRef));
7740 MonoType*
7741 ves_icall_System_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
7743 gint i;
7745 i = iter->sig->sentinelpos + iter->next_arg;
7747 g_assert (i < iter->sig->param_count);
7749 return iter->sig->params [i];
7752 MonoObjectHandle
7753 ves_icall_System_TypedReference_ToObject (MonoTypedRef* tref, MonoError *error)
7755 return typed_reference_to_object (tref, error);
7758 void
7759 ves_icall_System_TypedReference_InternalMakeTypedReference (MonoTypedRef *res, MonoObjectHandle target, MonoArrayHandle fields, MonoReflectionTypeHandle last_field, MonoError *error)
7761 MonoClass *klass;
7762 MonoType *ftype = NULL;
7763 int i;
7765 memset (res, 0, sizeof (MonoTypedRef));
7767 g_assert (mono_array_handle_length (fields) > 0);
7769 klass = mono_handle_class (target);
7771 int offset = 0;
7772 for (i = 0; i < mono_array_handle_length (fields); ++i) {
7773 MonoClassField *f;
7774 MONO_HANDLE_ARRAY_GETVAL (f, fields, MonoClassField*, i);
7776 g_assert (f);
7778 if (i == 0)
7779 offset = f->offset;
7780 else
7781 offset += f->offset - sizeof (MonoObject);
7782 klass = mono_class_from_mono_type_internal (f->type);
7783 ftype = f->type;
7786 res->type = ftype;
7787 res->klass = mono_class_from_mono_type_internal (ftype);
7788 res->value = (guint8*)MONO_HANDLE_RAW (target) + offset;
7791 static void
7792 prelink_method (MonoMethod *method, MonoError *error)
7794 error_init (error);
7795 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7796 return;
7797 mono_lookup_pinvoke_call_internal (method, error);
7798 /* create the wrapper, too? */
7801 void
7802 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethodHandle method, MonoError *error)
7804 error_init (error);
7806 prelink_method (MONO_HANDLE_GETVAL (method, method), error);
7809 void
7810 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionTypeHandle type, MonoError *error)
7812 error_init (error);
7813 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
7814 MonoMethod* m;
7815 gpointer iter = NULL;
7817 mono_class_init_checked (klass, error);
7818 return_if_nok (error);
7820 while ((m = mono_class_get_methods (klass, &iter))) {
7821 prelink_method (m, error);
7822 return_if_nok (error);
7827 * used by System.Runtime.InteropServices.RuntimeInformation.(OS|Process)Architecture;
7828 * which use them in different ways for filling in an enum
7830 MonoStringHandle
7831 ves_icall_System_Runtime_InteropServices_RuntimeInformation_GetRuntimeArchitecture (MonoError *error)
7833 error_init (error);
7834 return mono_string_new_handle (mono_domain_get (), mono_config_get_cpu (), error);
7838 * used by System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform
7840 MonoStringHandle
7841 ves_icall_System_Runtime_InteropServices_RuntimeInformation_GetOSName (MonoError *error)
7843 error_init (error);
7844 return mono_string_new_handle (mono_domain_get (), mono_config_get_os (), error);
7848 ves_icall_Interop_Sys_DoubleToString(double value, char *format, char *buffer, int bufferLength)
7850 #if defined(TARGET_ARM)
7851 /* workaround for faulty vcmp.f64 implementation on some 32bit ARM CPUs */
7852 guint64 bits = *(guint64 *) &value;
7853 if (bits == 0x1) { /* 4.9406564584124654E-324 */
7854 g_assert (!strcmp (format, "%.40e"));
7855 return snprintf (buffer, bufferLength, "%s", "4.9406564584124654417656879286822137236506e-324");
7856 } else if (bits == 0x4) { /* 2E-323 */
7857 g_assert (!strcmp (format, "%.40e"));
7858 return snprintf (buffer, bufferLength, "%s", "1.9762625833649861767062751714728854894602e-323");
7860 #endif
7862 return snprintf(buffer, bufferLength, format, value);
7865 void
7866 ves_icall_System_Runtime_RuntimeImports_ecvt_s(char *buffer, size_t sizeInBytes, double value, int count, int* dec, int* sign)
7868 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
7869 _ecvt_s(buffer, sizeInBytes, value, count, dec, sign);
7870 #endif
7874 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
7875 void
7876 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
7877 gint32 const **exponents,
7878 gunichar2 const **digitLowerTable,
7879 gunichar2 const **digitUpperTable,
7880 gint64 const **tenPowersList,
7881 gint32 const **decHexDigits)
7883 *mantissas = Formatter_MantissaBitsTable;
7884 *exponents = Formatter_TensExponentTable;
7885 *digitLowerTable = Formatter_DigitLowerTable;
7886 *digitUpperTable = Formatter_DigitUpperTable;
7887 *tenPowersList = Formatter_TenPowersList;
7888 *decHexDigits = Formatter_DecHexDigits;
7891 static gboolean
7892 add_modifier_to_array (MonoDomain *domain, MonoImage *image, MonoCustomMod *modifier, MonoArrayHandle dest, int dest_idx, MonoError *error)
7894 HANDLE_FUNCTION_ENTER ();
7895 error_init (error);
7896 MonoClass *klass = mono_class_get_checked (image, modifier->token, error);
7897 goto_if_nok (error, leave);
7899 MonoReflectionTypeHandle rt;
7900 rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
7901 goto_if_nok (error, leave);
7903 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rt);
7904 leave:
7905 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
7909 * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
7910 * and avoid useless allocations.
7912 static MonoArrayHandle
7913 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error)
7915 int i, count = 0;
7916 MonoDomain *domain = mono_domain_get ();
7918 MonoCustomModContainer *cmods = mono_type_get_cmods (type);
7919 if (!cmods)
7920 goto fail;
7922 error_init (error);
7923 for (i = 0; i < cmods->count; ++i) {
7924 if ((optional && !cmods->modifiers [i].required) || (!optional && cmods->modifiers [i].required))
7925 count++;
7927 if (!count)
7928 goto fail;
7930 MonoArrayHandle res;
7931 res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
7932 goto_if_nok (error, fail);
7933 count = 0;
7934 for (i = cmods->count - 1; i >= 0; --i) {
7935 if ((optional && !cmods->modifiers [i].required) || (!optional && cmods->modifiers [i].required)) {
7936 if (!add_modifier_to_array (domain, image, &cmods->modifiers [i], res, count , error))
7937 goto fail;
7938 count++;
7941 return res;
7942 fail:
7943 return MONO_HANDLE_NEW (MonoArray, NULL);
7946 MonoArrayHandle
7947 ves_icall_RuntimeParameterInfo_GetTypeModifiers (MonoReflectionTypeHandle rt, MonoObjectHandle member, int pos, MonoBoolean optional, MonoError *error)
7949 error_init (error);
7950 MonoType *type = MONO_HANDLE_GETVAL (rt, type);
7951 MonoClass *member_class = mono_handle_class (member);
7952 MonoMethod *method = NULL;
7953 MonoImage *image;
7954 MonoMethodSignature *sig;
7956 if (mono_class_is_reflection_method_or_constructor (member_class)) {
7957 method = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionMethod, member), method);
7958 } else if (m_class_get_image (member_class) == mono_defaults.corlib && !strcmp ("RuntimePropertyInfo", m_class_get_name (member_class))) {
7959 MonoProperty *prop = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionProperty, member), property);
7960 if (!(method = prop->get))
7961 method = prop->set;
7962 g_assert (method);
7963 } else {
7964 char *type_name = mono_type_get_full_name (member_class);
7965 mono_error_set_not_supported (error, "Custom modifiers on a ParamInfo with member %s are not supported", type_name);
7966 g_free (type_name);
7967 return NULL_HANDLE_ARRAY;
7970 image = m_class_get_image (method->klass);
7971 sig = mono_method_signature_internal (method);
7972 if (pos == -1)
7973 type = sig->ret;
7974 else
7975 type = sig->params [pos];
7977 return type_array_from_modifiers (image, type, optional, error);
7980 static MonoType*
7981 get_property_type (MonoProperty *prop)
7983 MonoMethodSignature *sig;
7984 if (prop->get) {
7985 sig = mono_method_signature_internal (prop->get);
7986 return sig->ret;
7987 } else if (prop->set) {
7988 sig = mono_method_signature_internal (prop->set);
7989 return sig->params [sig->param_count - 1];
7991 return NULL;
7994 MonoArrayHandle
7995 ves_icall_RuntimePropertyInfo_GetTypeModifiers (MonoReflectionPropertyHandle property, MonoBoolean optional, MonoError *error)
7997 error_init (error);
7998 MonoProperty *prop = MONO_HANDLE_GETVAL (property, property);
7999 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
8000 MonoType *type = get_property_type (prop);
8001 MonoImage *image = m_class_get_image (klass);
8003 if (!type)
8004 return NULL_HANDLE_ARRAY;
8005 return type_array_from_modifiers (image, type, optional, error);
8009 *Construct a MonoType suited to be used to decode a constant blob object.
8011 * @type is the target type which will be constructed
8012 * @blob_type is the blob type, for example, that comes from the constant table
8013 * @real_type is the expected constructed type.
8015 static void
8016 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
8018 type->type = blob_type;
8019 type->data.klass = NULL;
8020 if (blob_type == MONO_TYPE_CLASS)
8021 type->data.klass = mono_defaults.object_class;
8022 else if (real_type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (real_type->data.klass)) {
8023 /* For enums, we need to use the base type */
8024 type->type = MONO_TYPE_VALUETYPE;
8025 type->data.klass = mono_class_from_mono_type_internal (real_type);
8026 } else
8027 type->data.klass = mono_class_from_mono_type_internal (real_type);
8030 MonoObject*
8031 ves_icall_property_info_get_default_value (MonoReflectionProperty *property)
8033 ERROR_DECL (error);
8034 MonoType blob_type;
8035 MonoProperty *prop = property->property;
8036 MonoType *type = get_property_type (prop);
8037 MonoDomain *domain = mono_object_domain (property);
8038 MonoTypeEnum def_type;
8039 const char *def_value;
8040 MonoObject *o;
8042 mono_class_init_internal (prop->parent);
8044 if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT)) {
8045 mono_error_set_invalid_operation (error, NULL);
8046 mono_error_set_pending_exception (error);
8047 return NULL;
8050 def_value = mono_class_get_property_default_value (prop, &def_type);
8052 mono_type_from_blob_type (&blob_type, def_type, type);
8053 o = mono_get_object_from_blob (domain, &blob_type, def_value, error);
8055 mono_error_set_pending_exception (error);
8056 return o;
8059 MonoBoolean
8060 ves_icall_MonoCustomAttrs_IsDefinedInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, MonoError *error)
8062 error_init (error);
8063 MonoClass *attr_class = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (attr_type, type));
8065 mono_class_init_checked (attr_class, error);
8066 return_val_if_nok (error, FALSE);
8068 MonoCustomAttrInfo *cinfo = mono_reflection_get_custom_attrs_info_checked (obj, error);
8069 return_val_if_nok (error, FALSE);
8071 if (!cinfo)
8072 return FALSE;
8073 gboolean found = mono_custom_attrs_has_attr (cinfo, attr_class);
8074 if (!cinfo->cached)
8075 mono_custom_attrs_free (cinfo);
8076 return found;
8079 MonoArrayHandle
8080 ves_icall_MonoCustomAttrs_GetCustomAttributesInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, MonoBoolean pseudoattrs, MonoError *error)
8082 MonoClass *attr_class;
8083 if (MONO_HANDLE_IS_NULL (attr_type))
8084 attr_class = NULL;
8085 else
8086 attr_class = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (attr_type, type));
8088 if (attr_class) {
8089 mono_class_init_checked (attr_class, error);
8090 return_val_if_nok (error, NULL_HANDLE_ARRAY);
8093 return mono_reflection_get_custom_attrs_by_type_handle (obj, attr_class, error);
8096 MonoArrayHandle
8097 ves_icall_MonoCustomAttrs_GetCustomAttributesDataInternal (MonoObjectHandle obj, MonoError *error)
8099 error_init (error);
8100 return mono_reflection_get_custom_attrs_data_checked (obj, error);
8104 MonoStringHandle
8105 ves_icall_Mono_Runtime_GetDisplayName (MonoError *error)
8107 char *info;
8108 MonoStringHandle display_name;
8110 error_init (error);
8111 info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
8112 display_name = mono_string_new_handle (mono_domain_get (), info, error);
8113 g_free (info);
8114 return display_name;
8117 #ifndef HOST_WIN32
8118 static inline gint32
8119 mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
8121 return WAIT_TIMEOUT;
8123 #endif /* !HOST_WIN32 */
8125 gint32
8126 ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle (gpointer handle, gint32 milliseconds, MonoError *error)
8128 return mono_icall_wait_for_input_idle (handle, milliseconds);
8131 gint32
8132 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcessId (MonoError *error)
8134 return mono_process_current_pid ();
8137 MonoBoolean
8138 ves_icall_Mono_TlsProviderFactory_IsBtlsSupported (MonoError *error)
8140 #if HAVE_BTLS
8141 return TRUE;
8142 #else
8143 return FALSE;
8144 #endif
8147 #ifndef DISABLE_COM
8150 ves_icall_System_Runtime_InteropServices_Marshal_GetHRForException_WinRT(MonoExceptionHandle ex, MonoError *error)
8152 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetHRForException_WinRT internal call is not implemented.");
8153 return 0;
8156 MonoObjectHandle
8157 ves_icall_System_Runtime_InteropServices_Marshal_GetNativeActivationFactory(MonoObjectHandle type, MonoError *error)
8159 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetNativeActivationFactory internal call is not implemented.");
8160 return NULL_HANDLE;
8163 void*
8164 ves_icall_System_Runtime_InteropServices_Marshal_GetRawIUnknownForComObjectNoAddRef(MonoObjectHandle obj, MonoError *error)
8166 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetRawIUnknownForComObjectNoAddRef internal call is not implemented.");
8167 return NULL;
8170 MonoObjectHandle
8171 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_GetRestrictedErrorInfo(MonoError *error)
8173 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.GetRestrictedErrorInfo internal call is not implemented.");
8174 return NULL_HANDLE;
8177 MonoBoolean
8178 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoOriginateLanguageException (int ierr, MonoStringHandle message, void* languageException, MonoError *error)
8180 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoOriginateLanguageException internal call is not implemented.");
8181 return FALSE;
8184 void
8185 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoReportUnhandledError (MonoObjectHandle oerr, MonoError *error)
8187 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoReportUnhandledError internal call is not implemented.");
8191 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsCreateString(MonoStringHandle sourceString, int length, void** hstring, MonoError *error)
8193 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString internal call is not implemented.");
8194 return 0;
8198 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsDeleteString(void* hstring, MonoError *error)
8200 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString internal call is not implemented.");
8201 return 0;
8204 mono_unichar2*
8205 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsGetStringRawBuffer(void* hstring, unsigned* length, MonoError *error)
8207 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsGetStringRawBuffer internal call is not implemented.");
8208 return NULL;
8211 #endif
8213 void
8214 ves_icall_System_IO_LogcatTextWriter_Log (const char *appname, gint32 level, const char *message)
8216 g_log (appname, (GLogLevelFlags)level, "%s", message);
8219 static MonoIcallTableCallbacks icall_table;
8220 static mono_mutex_t icall_mutex;
8221 static GHashTable *icall_hash = NULL;
8222 static GHashTable *icall_hash_foreign = NULL;
8223 static GHashTable *jit_icall_hash_name = NULL;
8224 static GHashTable *jit_icall_hash_addr = NULL;
8226 void
8227 mono_install_icall_table_callbacks (MonoIcallTableCallbacks *cb)
8229 g_assert (cb->version == MONO_ICALL_TABLE_CALLBACKS_VERSION);
8230 memcpy (&icall_table, cb, sizeof (MonoIcallTableCallbacks));
8233 void
8234 mono_icall_init (void)
8236 #ifndef DISABLE_ICALL_TABLES
8237 mono_icall_table_init ();
8238 #endif
8239 icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8240 icall_hash_foreign = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8241 mono_os_mutex_init (&icall_mutex);
8244 static void
8245 mono_icall_lock (void)
8247 mono_locks_os_acquire (&icall_mutex, IcallLock);
8250 static void
8251 mono_icall_unlock (void)
8253 mono_locks_os_release (&icall_mutex, IcallLock);
8256 void
8257 mono_icall_cleanup (void)
8259 g_hash_table_destroy (icall_hash);
8260 g_hash_table_destroy (icall_hash_foreign);
8261 g_hash_table_destroy (jit_icall_hash_name);
8262 g_hash_table_destroy (jit_icall_hash_addr);
8263 mono_os_mutex_destroy (&icall_mutex);
8267 * mono_add_internal_call:
8268 * \param name method specification to surface to the managed world
8269 * \param method pointer to a C method to invoke when the method is called
8271 * This method surfaces the C function pointed by \p method as a method
8272 * that has been surfaced in managed code with the method specified in
8273 * \p name as an internal call.
8275 * Internal calls are surfaced to all app domains loaded and they are
8276 * accessibly by a type with the specified name.
8278 * You must provide a fully qualified type name, that is namespaces
8279 * and type name, followed by a colon and the method name, with an
8280 * optional signature to bind.
8282 * For example, the following are all valid declarations:
8284 * \c MyApp.Services.ScriptService:Accelerate
8286 * \c MyApp.Services.ScriptService:Slowdown(int,bool)
8288 * You use method parameters in cases where there might be more than
8289 * one surface method to managed code. That way you can register different
8290 * internal calls for different method overloads.
8292 * The internal calls are invoked with no marshalling. This means that .NET
8293 * types like \c System.String are exposed as \c MonoString* parameters. This is
8294 * different than the way that strings are surfaced in P/Invoke.
8296 * For more information on how the parameters are marshalled, see the
8297 * <a href="http://www.mono-project.com/docs/advanced/embedding/">Mono Embedding</a>
8298 * page.
8300 * See the <a href="mono-api-methods.html#method-desc">Method Description</a>
8301 * reference for more information on the format of method descriptions.
8303 void
8304 mono_add_internal_call (const char *name, gconstpointer method)
8306 mono_add_internal_call_with_flags (name, method, FALSE);
8310 * mono_dangerous_add_raw_internal_call:
8311 * \param name method specification to surface to the managed world
8312 * \param method pointer to a C method to invoke when the method is called
8314 * Similar to \c mono_add_internal_call but with more requirements for correct
8315 * operation.
8317 * A thread running a dangerous raw internal call will avoid a thread state
8318 * transition on entry and exit, but it must take responsiblity for cooperating
8319 * with the Mono runtime.
8321 * The \p method must NOT:
8323 * Run for an unbounded amount of time without calling the mono runtime.
8324 * Additionally, the method must switch to GC Safe mode to perform all blocking
8325 * operations: performing blocking I/O, taking locks, etc.
8328 void
8329 mono_dangerous_add_raw_internal_call (const char *name, gconstpointer method)
8331 mono_add_internal_call_with_flags (name, method, TRUE);
8335 * mono_add_internal_call_with_flags:
8336 * \param name method specification to surface to the managed world
8337 * \param method pointer to a C method to invoke when the method is called
8338 * \param cooperative if \c TRUE, run icall in GC Unsafe (cooperatively suspended) mode,
8339 * otherwise GC Safe (blocking)
8341 * Like \c mono_add_internal_call, but if \p cooperative is \c TRUE the added
8342 * icall promises that it will use the coopertive API to inform the runtime
8343 * when it is running blocking operations, that it will not run for unbounded
8344 * amounts of time without safepointing, and that it will not hold managed
8345 * object references across suspend safepoints.
8347 * If \p cooperative is \c FALSE, run the icall in GC Safe mode - the icall may
8348 * block. The icall must obey the GC Safe rules, e.g. it must not touch
8349 * unpinned managed memory.
8352 void
8353 mono_add_internal_call_with_flags (const char *name, gconstpointer method, gboolean cooperative)
8355 mono_icall_lock ();
8357 g_hash_table_insert (cooperative ? icall_hash : icall_hash_foreign , g_strdup (name), (gpointer) method);
8359 mono_icall_unlock ();
8362 void
8363 mono_add_internal_call_internal (const char *name, gconstpointer method)
8365 mono_add_internal_call_with_flags (name, method, TRUE);
8369 * we should probably export this as an helper (handle nested types).
8370 * Returns the number of chars written in buf.
8372 static int
8373 concat_class_name (char *buf, int bufsize, MonoClass *klass)
8375 int nspacelen, cnamelen;
8376 nspacelen = strlen (m_class_get_name_space (klass));
8377 cnamelen = strlen (m_class_get_name (klass));
8378 if (nspacelen + cnamelen + 2 > bufsize)
8379 return 0;
8380 if (nspacelen) {
8381 memcpy (buf, m_class_get_name_space (klass), nspacelen);
8382 buf [nspacelen ++] = '.';
8384 memcpy (buf + nspacelen, m_class_get_name (klass), cnamelen);
8385 buf [nspacelen + cnamelen] = 0;
8386 return nspacelen + cnamelen;
8389 static void
8390 no_icall_table (void)
8392 g_assert_not_reached ();
8396 * mono_lookup_internal_call_full:
8397 * \param method the method to look up
8398 * \param uses_handles out argument if method needs handles around managed objects.
8399 * \returns a pointer to the icall code for the given method. If
8400 * \p uses_handles is not NULL, it will be set to TRUE if the method
8401 * needs managed objects wrapped using the infrastructure in handle.h
8403 * If the method is not found, warns and returns NULL.
8405 gpointer
8406 mono_lookup_internal_call_full (MonoMethod *method, gboolean warn_on_missing, mono_bool *uses_handles, mono_bool *foreign)
8408 char *sigstart;
8409 char *tmpsig;
8410 char mname [2048];
8411 char *classname;
8412 int typelen = 0, mlen, siglen;
8413 gpointer res;
8415 if (uses_handles)
8416 *uses_handles = FALSE;
8417 if (foreign)
8418 *foreign = FALSE;
8420 g_assert (method != NULL);
8422 if (method->is_inflated)
8423 method = ((MonoMethodInflated *) method)->declaring;
8425 if (m_class_get_nested_in (method->klass)) {
8426 int pos = concat_class_name (mname, sizeof (mname)-2, m_class_get_nested_in (method->klass));
8427 if (!pos)
8428 return NULL;
8430 mname [pos++] = '/';
8431 mname [pos] = 0;
8433 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
8434 if (!typelen)
8435 return NULL;
8437 typelen += pos;
8438 } else {
8439 typelen = concat_class_name (mname, sizeof (mname), method->klass);
8440 if (!typelen)
8441 return NULL;
8444 classname = g_strdup (mname);
8446 mname [typelen] = ':';
8447 mname [typelen + 1] = ':';
8449 mlen = strlen (method->name);
8450 memcpy (mname + typelen + 2, method->name, mlen);
8451 sigstart = mname + typelen + 2 + mlen;
8452 *sigstart = 0;
8454 tmpsig = mono_signature_get_desc (mono_method_signature_internal (method), TRUE);
8455 siglen = strlen (tmpsig);
8456 if (typelen + mlen + siglen + 6 > sizeof (mname)) {
8457 g_free (classname);
8458 return NULL;
8460 sigstart [0] = '(';
8461 memcpy (sigstart + 1, tmpsig, siglen);
8462 sigstart [siglen + 1] = ')';
8463 sigstart [siglen + 2] = 0;
8464 g_free (tmpsig);
8466 /* mono_marshal_get_native_wrapper () depends on this */
8467 if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor"))
8468 return (gpointer)ves_icall_System_String_ctor_RedirectToCreateString;
8470 mono_icall_lock ();
8472 res = g_hash_table_lookup (icall_hash, mname);
8473 if (res) {
8474 g_free (classname);
8475 mono_icall_unlock ();
8476 return res;
8478 res = g_hash_table_lookup (icall_hash_foreign, mname);
8479 if (res) {
8480 if (foreign)
8481 *foreign = TRUE;
8482 g_free (classname);
8483 mono_icall_unlock ();
8484 return res;
8487 /* try without signature */
8488 *sigstart = 0;
8489 res = g_hash_table_lookup (icall_hash, mname);
8490 if (res) {
8491 g_free (classname);
8492 mono_icall_unlock ();
8493 return res;
8495 res = g_hash_table_lookup (icall_hash_foreign, mname);
8496 if (res) {
8497 if (foreign)
8498 *foreign = TRUE;
8499 g_free (classname);
8500 mono_icall_unlock ();
8501 return res;
8504 if (!icall_table.lookup) {
8505 mono_icall_unlock ();
8506 g_free (classname);
8507 /* Fail only when the result is actually used */
8508 return (gpointer)no_icall_table;
8509 } else {
8510 res = icall_table.lookup (method, classname, sigstart - mlen, sigstart, uses_handles);
8511 g_free (classname);
8513 mono_icall_unlock ();
8515 if (res)
8516 return res;
8518 if (warn_on_missing) {
8519 g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
8520 g_print ("\nYour mono runtime and class libraries are out of sync.\n");
8521 g_print ("The out of sync library is: %s\n", m_class_get_image (method->klass)->name);
8522 g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
8523 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");
8524 g_print ("If you see other errors or faults after this message they are probably related\n");
8525 g_print ("and you need to fix your mono install first.\n");
8528 return NULL;
8533 * mono_lookup_internal_call:
8535 gpointer
8536 mono_lookup_internal_call (MonoMethod *method)
8538 return mono_lookup_internal_call_full (method, TRUE, NULL, NULL);
8542 * mono_lookup_icall_symbol:
8544 * Given the icall METHOD, returns its C symbol.
8546 const char*
8547 mono_lookup_icall_symbol (MonoMethod *m)
8549 if (!icall_table.lookup_icall_symbol)
8550 return NULL;
8552 gpointer func;
8553 func = mono_lookup_internal_call_full (m, FALSE, NULL, NULL);
8554 if (!func)
8555 return NULL;
8556 return icall_table.lookup_icall_symbol (func);
8559 static MonoType*
8560 type_from_typename (char *type_name)
8562 MonoClass *klass = NULL; /* assignment to shut GCC warning up */
8564 if (!strcmp (type_name, "int"))
8565 klass = mono_defaults.int_class;
8566 else if (!strcmp (type_name, "ptr&"))
8567 return mono_class_get_byref_type (mono_defaults.int_class);
8568 else if (!strcmp (type_name, "ptr"))
8569 klass = mono_defaults.int_class;
8570 else if (!strcmp (type_name, "void"))
8571 klass = mono_defaults.void_class;
8572 else if (!strcmp (type_name, "int32"))
8573 klass = mono_defaults.int32_class;
8574 else if (!strcmp (type_name, "uint32"))
8575 klass = mono_defaults.uint32_class;
8576 else if (!strcmp (type_name, "int8"))
8577 klass = mono_defaults.sbyte_class;
8578 else if (!strcmp (type_name, "uint8"))
8579 klass = mono_defaults.byte_class;
8580 else if (!strcmp (type_name, "int16"))
8581 klass = mono_defaults.int16_class;
8582 else if (!strcmp (type_name, "uint16"))
8583 klass = mono_defaults.uint16_class;
8584 else if (!strcmp (type_name, "long"))
8585 klass = mono_defaults.int64_class;
8586 else if (!strcmp (type_name, "ulong"))
8587 klass = mono_defaults.uint64_class;
8588 else if (!strcmp (type_name, "float"))
8589 klass = mono_defaults.single_class;
8590 else if (!strcmp (type_name, "double"))
8591 klass = mono_defaults.double_class;
8592 else if (!strcmp (type_name, "object"))
8593 klass = mono_defaults.object_class;
8594 else if (!strcmp (type_name, "obj"))
8595 klass = mono_defaults.object_class;
8596 else if (!strcmp (type_name, "string"))
8597 klass = mono_defaults.string_class;
8598 else if (!strcmp (type_name, "bool"))
8599 klass = mono_defaults.boolean_class;
8600 else if (!strcmp (type_name, "boolean"))
8601 klass = mono_defaults.boolean_class;
8602 else {
8603 g_error ("%s", type_name);
8604 g_assert_not_reached ();
8606 return m_class_get_byval_arg (klass);
8610 * LOCKING: Take the corlib image lock.
8612 MonoMethodSignature*
8613 mono_create_icall_signature (const char *sigstr)
8615 gchar **parts;
8616 int i, len;
8617 gchar **tmp;
8618 MonoMethodSignature *res, *res2;
8619 MonoImage *corlib = mono_defaults.corlib;
8621 mono_image_lock (corlib);
8622 res = (MonoMethodSignature *)g_hash_table_lookup (corlib->helper_signatures, sigstr);
8623 mono_image_unlock (corlib);
8625 if (res)
8626 return res;
8628 parts = g_strsplit (sigstr, " ", 256);
8630 tmp = parts;
8631 len = 0;
8632 while (*tmp) {
8633 len ++;
8634 tmp ++;
8637 res = mono_metadata_signature_alloc (corlib, len - 1);
8638 res->pinvoke = 1;
8640 #if defined(TARGET_WIN32) && defined(TARGET_X86)
8642 * Under windows, the default pinvoke calling convention is STDCALL but
8643 * we need CDECL.
8645 res->call_convention = MONO_CALL_C;
8646 #endif
8648 res->ret = type_from_typename (parts [0]);
8649 for (i = 1; i < len; ++i) {
8650 res->params [i - 1] = type_from_typename (parts [i]);
8653 g_strfreev (parts);
8655 mono_image_lock (corlib);
8656 res2 = (MonoMethodSignature *)g_hash_table_lookup (corlib->helper_signatures, sigstr);
8657 if (res2)
8658 res = res2; /*Value is allocated in the image pool*/
8659 else
8660 g_hash_table_insert (corlib->helper_signatures, (gpointer)sigstr, res);
8661 mono_image_unlock (corlib);
8663 return res;
8666 MonoJitICallInfo *
8667 mono_find_jit_icall_by_name (const char *name)
8669 MonoJitICallInfo *info;
8670 g_assert (jit_icall_hash_name);
8672 mono_icall_lock ();
8673 info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name);
8674 mono_icall_unlock ();
8675 return info;
8678 MonoJitICallInfo *
8679 mono_find_jit_icall_by_addr (gconstpointer addr)
8681 MonoJitICallInfo *info;
8682 g_assert (jit_icall_hash_addr);
8684 mono_icall_lock ();
8685 info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
8686 mono_icall_unlock ();
8688 return info;
8692 * mono_get_jit_icall_info:
8694 * Return the hashtable mapping JIT icall names to MonoJitICallInfo structures. The
8695 * caller should access it while holding the icall lock.
8697 GHashTable*
8698 mono_get_jit_icall_info (void)
8700 return jit_icall_hash_name;
8704 * mono_lookup_jit_icall_symbol:
8706 * Given the jit icall NAME, returns its C symbol if possible, or NULL.
8708 const char*
8709 mono_lookup_jit_icall_symbol (const char *name)
8711 MonoJitICallInfo *info;
8712 const char *res = NULL;
8714 mono_icall_lock ();
8715 info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name);
8716 if (info)
8717 res = info->c_symbol;
8718 mono_icall_unlock ();
8719 return res;
8722 void
8723 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
8725 mono_icall_lock ();
8726 g_hash_table_insert (jit_icall_hash_addr, (gpointer)wrapper, info);
8727 mono_icall_unlock ();
8730 MonoJitICallInfo *
8731 mono_register_jit_icall_full (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean avoid_wrapper, const char *c_symbol)
8733 MonoJitICallInfo *info;
8735 g_assert (func);
8736 g_assert (name);
8738 mono_icall_lock ();
8740 if (!jit_icall_hash_name) {
8741 jit_icall_hash_name = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
8742 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
8745 if ((info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name))) {
8746 g_warning ("jit icall already defined \"%s\" \"%s\" %p %p\n", name, info->name, func, info->func);
8747 g_assert_not_reached ();
8750 info = g_new0 (MonoJitICallInfo, 1);
8752 info->name = name;
8753 info->func = func;
8754 info->sig = sig;
8755 info->c_symbol = c_symbol;
8757 if (avoid_wrapper) {
8758 info->wrapper = func;
8759 } else {
8760 info->wrapper = NULL;
8763 g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
8764 g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
8766 mono_icall_unlock ();
8767 return info;
8770 MonoJitICallInfo *
8771 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean no_wrapper)
8773 return mono_register_jit_icall_full (func, name, sig, no_wrapper, NULL);
8777 ves_icall_System_GC_GetCollectionCount (int generation)
8779 return mono_gc_collection_count (generation);
8783 ves_icall_System_GC_GetGeneration (MonoObjectHandle object, MonoError *error)
8785 return mono_gc_get_generation (MONO_HANDLE_RAW (object));
8789 ves_icall_System_GC_GetMaxGeneration (void)
8791 return mono_gc_max_generation ();
8794 gint64
8795 ves_icall_System_GC_GetAllocatedBytesForCurrentThread (void)
8797 return 0; // TODO: implement https://github.com/mono/mono/issues/8397
8800 void
8801 ves_icall_System_GC_RecordPressure (gint64 value)
8803 mono_gc_add_memory_pressure (value);
8806 gint64
8807 ves_icall_System_Diagnostics_Stopwatch_GetTimestamp (void)
8809 return mono_100ns_ticks ();
8812 gint64
8813 ves_icall_System_Threading_Timer_GetTimeMonotonic (void)
8815 return mono_100ns_ticks ();
8818 gint64
8819 ves_icall_System_DateTime_GetSystemTimeAsFileTime (void)
8821 return mono_100ns_datetime ();
8825 ves_icall_System_Threading_Thread_SystemMaxStackSize (void)
8827 return mono_thread_info_get_system_max_stack_size ();
8830 MonoBoolean
8831 ves_icall_System_Threading_Thread_YieldInternal (void)
8833 mono_threads_platform_yield ();
8834 return TRUE;
8837 gint32
8838 ves_icall_System_Environment_get_ProcessorCount (void)
8840 return mono_cpu_count ();
8843 #if defined(ENABLE_MONODROID)
8845 G_EXTERN_C gint32 CreateNLSocket (void);
8846 G_EXTERN_C gint32 ReadEvents (gpointer sock, gpointer buffer, gint32 count, gint32 size);
8847 G_EXTERN_C gint32 CloseNLSocket (gpointer sock);
8849 gint32
8850 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CreateNLSocket (void)
8852 return CreateNLSocket ();
8855 gint32
8856 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_ReadEvents (gpointer sock, gpointer buffer, gint32 count, gint32 size)
8858 return ReadEvents (sock, buffer, count, size);
8861 gint32
8862 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CloseNLSocket (gpointer sock)
8864 return CloseNLSocket (sock);
8867 #endif
8869 // Generate wrappers.
8871 #define ICALL_TYPE(id,name,first) /* nothing */
8872 #define ICALL(id,name,func) /* nothing */
8873 #define NOHANDLES(inner) /* nothing */
8875 #define MONO_HANDLE_REGISTER_ICALL(func, ret, nargs, argtypes) MONO_HANDLE_REGISTER_ICALL_IMPLEMENT (func, ret, nargs, argtypes)
8877 // Some native functions are exposed via multiple managed names.
8878 // Producing a wrapper for these results in duplicate wrappers with the same names,
8879 // which fails to compile. Do not produce such duplicate wrappers. Alternatively,
8880 // a one line native function with a different name that calls the main one could be used.
8881 // i.e. the wrapper would also have a different name.
8882 #define HANDLES_REUSE_WRAPPER(...) /* nothing */
8884 #define HANDLES(id, name, func, ret, nargs, argtypes) \
8885 MONO_HANDLE_DECLARE (id, name, func, ret, nargs, argtypes); \
8886 MONO_HANDLE_IMPLEMENT (id, name, func, ret, nargs, argtypes)
8888 #include "metadata/icall-def.h"
8890 #undef HANDLES
8891 #undef HANDLES_REUSE_WRAPPER
8892 #undef ICALL_TYPE
8893 #undef ICALL
8894 #undef NOHANDLES
8895 #undef MONO_HANDLE_REGISTER_ICALL