[corlib] Move the implementations of virtual methods from Assembly to RuntimeAssembly...
[mono-project.git] / mono / metadata / icall.c
blobdaccd81b9e8013586b1458ed504c8c7736a45d30
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 if (MONO_HANDLE_GETVAL (source, bounds) || MONO_HANDLE_GETVAL (dest, bounds))
734 return FALSE;
736 /* there's no integer overflow since mono_array_length_internal returns an unsigned integer */
737 if ((dest_idx + length > mono_array_handle_length (dest)) ||
738 (source_idx + length > mono_array_handle_length (source)))
739 return FALSE;
741 MonoClass * const src_class = m_class_get_element_class (src_vtable->klass);
742 MonoClass * const dest_class = m_class_get_element_class (dest_vtable->klass);
745 * Handle common cases.
748 /* Case1: object[] -> valuetype[] (ArrayList::ToArray)
749 We fallback to managed here since we need to typecheck each boxed valuetype before storing them in the dest array.
751 if (src_class == mono_defaults.object_class && m_class_is_valuetype (dest_class))
752 return FALSE;
754 /* Check if we're copying a char[] <==> (u)short[] */
755 if (src_class != dest_class) {
756 if (m_class_is_valuetype (dest_class) || m_class_is_enumtype (dest_class) ||
757 m_class_is_valuetype (src_class) || m_class_is_valuetype (src_class))
758 return FALSE;
760 /* 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. */
761 if (!mono_class_is_subclass_of (src_class, dest_class, FALSE))
762 return FALSE;
765 if (m_class_is_valuetype (dest_class)) {
766 gsize const element_size = mono_array_element_size (MONO_HANDLE_GETVAL (source, obj.vtable->klass));
768 MONO_ENTER_NO_SAFEPOINTS; // gchandle would also work here, is slow, breaks profiler tests.
770 gconstpointer const source_addr =
771 mono_array_addr_with_size_fast (MONO_HANDLE_RAW (source), element_size, source_idx);
772 if (m_class_has_references (dest_class)) {
773 mono_value_copy_array_handle (dest, dest_idx, source_addr, length);
774 } else {
775 gpointer const dest_addr =
776 mono_array_addr_with_size_fast (MONO_HANDLE_RAW (dest), element_size, dest_idx);
777 mono_gc_memmove_atomic (dest_addr, source_addr, element_size * length);
780 MONO_EXIT_NO_SAFEPOINTS;
782 } else {
783 mono_array_handle_memcpy_refs (dest, dest_idx, source, source_idx, length);
786 return TRUE;
789 void
790 ves_icall_System_Array_GetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
792 // FIXME?
793 // Generic ref/out parameters are not supported by HANDLES(), so NOHANDLES().
795 icallarray_print ("%s arr:%p pos:%u value:%p\n", __func__, arr, pos, value);
797 MONO_REQ_GC_UNSAFE_MODE; // because of gpointer value
799 MonoClass * const ac = mono_object_class (arr);
800 gsize const esize = mono_array_element_size (ac);
801 gconstpointer * const ea = (gconstpointer*)((char*)arr->vector + (pos * esize));
803 mono_gc_memmove_atomic (value, ea, esize);
806 void
807 ves_icall_System_Array_SetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
809 // FIXME?
810 // Generic ref/out parameters are not supported by HANDLES(), so NOHANDLES().
812 icallarray_print ("%s arr:%p pos:%u value:%p\n", __func__, arr, pos, value);
814 MONO_REQ_GC_UNSAFE_MODE; // because of gpointer value
817 MonoClass * const ac = mono_object_class (arr);
818 MonoClass * const ec = m_class_get_element_class (ac);
820 gsize const esize = mono_array_element_size (ac);
821 gpointer * const ea = (gpointer*)((char*)arr->vector + (pos * esize));
823 if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (ec))) {
824 g_assert (esize == sizeof (gpointer));
825 mono_gc_wbarrier_generic_store_internal (ea, *(MonoObject **)value);
826 } else {
827 g_assert (m_class_is_inited (ec));
828 g_assert (esize == mono_class_value_size (ec, NULL));
829 if (m_class_has_references (ec))
830 mono_gc_wbarrier_value_copy_internal (ea, value, 1, ec);
831 else
832 mono_gc_memmove_atomic (ea, value, esize);
836 void
837 ves_icall_System_Runtime_RuntimeImports_Memmove (guint8 *destination, guint8 *source, guint byte_count)
839 mono_gc_memmove_atomic (destination, source, byte_count);
842 void
843 ves_icall_System_Runtime_RuntimeImports_Memmove_wbarrier (guint8 *destination, guint8 *source, guint len, MonoType *type)
845 if (MONO_TYPE_IS_REFERENCE (type))
846 mono_gc_wbarrier_arrayref_copy_internal (destination, source, len);
847 else
848 mono_gc_wbarrier_value_copy_internal (destination, source, len, mono_class_from_mono_type_internal (type));
851 void
852 ves_icall_System_Runtime_RuntimeImports_ZeroMemory (guint8 *p, guint byte_length)
854 memset (p, 0, byte_length);
857 void
858 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArrayHandle array, MonoClassField *field_handle, MonoError *error)
860 MonoClass *klass = mono_handle_class (array);
861 guint32 size = mono_array_element_size (klass);
862 MonoType *type = mono_type_get_underlying_type (m_class_get_byval_arg (m_class_get_element_class (klass)));
863 int align;
864 const char *field_data;
866 if (MONO_TYPE_IS_REFERENCE (type) || type->type == MONO_TYPE_VALUETYPE) {
867 mono_error_set_argument (error, "array", "Cannot initialize array of non-primitive type");
868 return;
871 MonoType *field_type = mono_field_get_type_checked (field_handle, error);
872 if (!field_type)
873 return;
875 if (!(field_type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
876 mono_error_set_argument_format (error, "field_handle", "Field '%s' doesn't have an RVA", mono_field_get_name (field_handle));
877 return;
880 size *= MONO_HANDLE_GETVAL(array, max_length);
881 field_data = mono_field_get_data (field_handle);
883 if (size > mono_type_size (field_handle->type, &align)) {
884 mono_error_set_argument (error, "field_handle", "Field not large enough to fill array");
885 return;
888 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
889 #define SWAP(n) { \
890 guint ## n *data = (guint ## n *) mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0); \
891 guint ## n *src = (guint ## n *) field_data; \
892 int i, \
893 nEnt = (size / sizeof(guint ## n)); \
895 for (i = 0; i < nEnt; i++) { \
896 data[i] = read ## n (&src[i]); \
900 /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
902 switch (type->type) {
903 case MONO_TYPE_CHAR:
904 case MONO_TYPE_I2:
905 case MONO_TYPE_U2:
906 SWAP (16);
907 break;
908 case MONO_TYPE_I4:
909 case MONO_TYPE_U4:
910 case MONO_TYPE_R4:
911 SWAP (32);
912 break;
913 case MONO_TYPE_I8:
914 case MONO_TYPE_U8:
915 case MONO_TYPE_R8:
916 SWAP (64);
917 break;
918 default:
919 memcpy (mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0), field_data, size);
920 break;
922 #else
923 memcpy (mono_array_addr_internal (MONO_HANDLE_RAW(array), char, 0), field_data, size);
924 #endif
927 gint
928 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
930 return offsetof (MonoString, chars);
933 MonoObjectHandle
934 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObjectHandle obj, MonoError *error)
936 if (MONO_HANDLE_IS_NULL (obj) || !m_class_is_valuetype (mono_handle_class (obj)))
937 return obj;
939 return mono_object_clone_handle (obj, error);
942 void
943 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle, MonoError *error)
945 MonoClass *klass;
946 MonoVTable *vtable;
948 MONO_CHECK_ARG_NULL (handle,);
950 klass = mono_class_from_mono_type_internal (handle);
951 MONO_CHECK_ARG (handle, klass,);
953 if (mono_class_is_gtd (klass))
954 return;
956 vtable = mono_class_vtable_checked (mono_domain_get (), klass, error);
957 return_if_nok (error);
959 /* This will call the type constructor */
960 mono_runtime_class_init_full (vtable, error);
963 void
964 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (MonoImage *image, MonoError *error)
966 mono_image_check_for_module_cctor (image);
967 if (!image->has_module_cctor)
968 return;
970 MonoClass *module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, error);
971 return_if_nok (error);
973 MonoVTable * vtable = mono_class_vtable_checked (mono_domain_get (), module_klass, error);
974 return_if_nok (error);
976 mono_runtime_class_init_full (vtable, error);
979 MonoBoolean
980 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
982 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
983 // It does not work on win32
984 #elif defined(TARGET_ANDROID) || defined(__linux__)
985 // No need for now
986 #else
987 guint8 *stack_addr;
988 guint8 *current;
989 size_t stack_size;
990 int min_size;
991 MonoInternalThread *thread;
993 mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
994 /* if we have no info we are optimistic and assume there is enough room */
995 if (!stack_addr)
996 return TRUE;
998 thread = mono_thread_internal_current ();
999 // .net seems to check that at least 50% of stack is available
1000 min_size = thread->stack_size / 2;
1002 // TODO: It's not always set
1003 if (!min_size)
1004 return TRUE;
1006 current = (guint8 *)&stack_addr;
1007 if (current > stack_addr) {
1008 if ((current - stack_addr) < min_size)
1009 return FALSE;
1010 } else {
1011 if (current - (stack_addr - stack_size) < min_size)
1012 return FALSE;
1014 #endif
1015 return TRUE;
1018 MonoObjectHandle
1019 ves_icall_System_Object_MemberwiseClone (MonoObjectHandle this_obj, MonoError *error)
1021 return mono_object_clone_handle (this_obj, error);
1024 gint32
1025 ves_icall_System_ValueType_InternalGetHashCode (MonoObject *this_obj, MonoArray **fields)
1027 ERROR_DECL (error);
1028 MonoClass *klass;
1029 MonoObject **values = NULL;
1030 MonoObject *o;
1031 int count = 0;
1032 gint32 result = (int)(gsize)mono_defaults.int32_class;
1033 MonoClassField* field;
1034 gpointer iter;
1036 klass = mono_object_class (this_obj);
1038 if (mono_class_num_fields (klass) == 0)
1039 return result;
1042 * Compute the starting value of the hashcode for fields of primitive
1043 * types, and return the remaining fields in an array to the managed side.
1044 * This way, we can avoid costly reflection operations in managed code.
1046 iter = NULL;
1047 while ((field = mono_class_get_fields_internal (klass, &iter))) {
1048 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1049 continue;
1050 if (mono_field_is_deleted (field))
1051 continue;
1052 /* FIXME: Add more types */
1053 switch (field->type->type) {
1054 case MONO_TYPE_I4:
1055 result ^= *(gint32*)((guint8*)this_obj + field->offset);
1056 break;
1057 case MONO_TYPE_PTR:
1058 result ^= mono_aligned_addr_hash (*(gpointer*)((guint8*)this_obj + field->offset));
1059 break;
1060 case MONO_TYPE_STRING: {
1061 MonoString *s;
1062 s = *(MonoString**)((guint8*)this_obj + field->offset);
1063 if (s != NULL)
1064 result ^= mono_string_hash_internal (s);
1065 break;
1067 default:
1068 if (!values)
1069 values = g_newa (MonoObject*, mono_class_num_fields (klass));
1070 o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, this_obj, error);
1071 if (!is_ok (error)) {
1072 mono_error_set_pending_exception (error);
1073 return 0;
1075 values [count++] = o;
1079 if (values) {
1080 int i;
1081 MonoArray *fields_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.object_class, count, error);
1082 if (mono_error_set_pending_exception (error))
1083 return 0;
1084 mono_gc_wbarrier_generic_store_internal (fields, (MonoObject*) fields_arr);
1085 for (i = 0; i < count; ++i)
1086 mono_array_setref_internal (*fields, i, values [i]);
1087 } else {
1088 *fields = NULL;
1090 return result;
1093 MonoBoolean
1094 ves_icall_System_ValueType_Equals (MonoObject *this_obj, MonoObject *that, MonoArray **fields)
1096 ERROR_DECL (error);
1097 MonoClass *klass;
1098 MonoObject **values = NULL;
1099 MonoObject *o;
1100 MonoClassField* field;
1101 gpointer iter;
1102 int count = 0;
1104 *fields = NULL;
1106 MONO_CHECK_ARG_NULL (that, FALSE);
1108 if (this_obj->vtable != that->vtable)
1109 return FALSE;
1111 klass = mono_object_class (this_obj);
1113 if (m_class_is_enumtype (klass) && mono_class_enum_basetype_internal (klass) && mono_class_enum_basetype_internal (klass)->type == MONO_TYPE_I4)
1114 return *(gint32*)mono_object_get_data (this_obj) == *(gint32*)mono_object_get_data (that);
1117 * Do the comparison for fields of primitive type and return a result if
1118 * possible. Otherwise, return the remaining fields in an array to the
1119 * managed side. This way, we can avoid costly reflection operations in
1120 * managed code.
1122 iter = NULL;
1123 while ((field = mono_class_get_fields_internal (klass, &iter))) {
1124 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1125 continue;
1126 if (mono_field_is_deleted (field))
1127 continue;
1128 guint8 *this_field = (guint8 *) this_obj + field->offset;
1129 guint8 *that_field = (guint8 *) that + field->offset;
1131 #define UNALIGNED_COMPARE(type) \
1132 do { \
1133 type left, right; \
1134 memcpy (&left, this_field, sizeof (type)); \
1135 memcpy (&right, that_field, sizeof (type)); \
1136 if (left != right) \
1137 return FALSE; \
1138 } while (0)
1140 /* FIXME: Add more types */
1141 switch (field->type->type) {
1142 case MONO_TYPE_U1:
1143 case MONO_TYPE_I1:
1144 case MONO_TYPE_BOOLEAN:
1145 if (*this_field != *that_field)
1146 return FALSE;
1147 break;
1148 case MONO_TYPE_U2:
1149 case MONO_TYPE_I2:
1150 case MONO_TYPE_CHAR:
1151 #ifdef NO_UNALIGNED_ACCESS
1152 if (G_UNLIKELY ((intptr_t) this_field & 1 || (intptr_t) that_field & 1))
1153 UNALIGNED_COMPARE (gint16);
1154 else
1155 #endif
1156 if (*(gint16 *) this_field != *(gint16 *) that_field)
1157 return FALSE;
1158 break;
1159 case MONO_TYPE_U4:
1160 case MONO_TYPE_I4:
1161 #ifdef NO_UNALIGNED_ACCESS
1162 if (G_UNLIKELY ((intptr_t) this_field & 3 || (intptr_t) that_field & 3))
1163 UNALIGNED_COMPARE (gint32);
1164 else
1165 #endif
1166 if (*(gint32 *) this_field != *(gint32 *) that_field)
1167 return FALSE;
1168 break;
1169 case MONO_TYPE_U8:
1170 case MONO_TYPE_I8:
1171 #ifdef NO_UNALIGNED_ACCESS
1172 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1173 UNALIGNED_COMPARE (gint64);
1174 else
1175 #endif
1176 if (*(gint64 *) this_field != *(gint64 *) that_field)
1177 return FALSE;
1178 break;
1180 case MONO_TYPE_R4:
1181 #ifdef NO_UNALIGNED_ACCESS
1182 if (G_UNLIKELY ((intptr_t) this_field & 3 || (intptr_t) that_field & 3))
1183 UNALIGNED_COMPARE (float);
1184 else
1185 #endif
1186 if (*(float *) this_field != *(float *) that_field)
1187 return FALSE;
1188 break;
1189 case MONO_TYPE_R8:
1190 #ifdef NO_UNALIGNED_ACCESS
1191 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1192 UNALIGNED_COMPARE (double);
1193 else
1194 #endif
1195 if (*(double *) this_field != *(double *) that_field)
1196 return FALSE;
1197 break;
1198 case MONO_TYPE_PTR:
1199 #ifdef NO_UNALIGNED_ACCESS
1200 if (G_UNLIKELY ((intptr_t) this_field & 7 || (intptr_t) that_field & 7))
1201 UNALIGNED_COMPARE (gpointer);
1202 else
1203 #endif
1204 if (*(gpointer *) this_field != *(gpointer *) that_field)
1205 return FALSE;
1206 break;
1207 case MONO_TYPE_STRING: {
1208 MonoString *s1, *s2;
1209 guint32 s1len, s2len;
1210 s1 = *(MonoString**)((guint8*)this_obj + field->offset);
1211 s2 = *(MonoString**)((guint8*)that + field->offset);
1212 if (s1 == s2)
1213 break;
1214 if ((s1 == NULL) || (s2 == NULL))
1215 return FALSE;
1216 s1len = mono_string_length_internal (s1);
1217 s2len = mono_string_length_internal (s2);
1218 if (s1len != s2len)
1219 return FALSE;
1221 if (memcmp (mono_string_chars_internal (s1), mono_string_chars_internal (s2), s1len * sizeof (gunichar2)) != 0)
1222 return FALSE;
1223 break;
1225 default:
1226 if (!values)
1227 values = g_newa (MonoObject*, mono_class_num_fields (klass) * 2);
1228 o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, this_obj, error);
1229 if (!is_ok (error)) {
1230 mono_error_set_pending_exception (error);
1231 return FALSE;
1233 values [count++] = o;
1234 o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, that, error);
1235 if (!is_ok (error)) {
1236 mono_error_set_pending_exception (error);
1237 return FALSE;
1239 values [count++] = o;
1242 #undef UNALIGNED_COMPARE
1244 if (m_class_is_enumtype (klass))
1245 /* enums only have one non-static field */
1246 break;
1249 if (values) {
1250 int i;
1251 MonoArray *fields_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.object_class, count, error);
1252 if (mono_error_set_pending_exception (error))
1253 return FALSE;
1254 mono_gc_wbarrier_generic_store_internal (fields, (MonoObject*) fields_arr);
1255 for (i = 0; i < count; ++i)
1256 mono_array_setref_fast (*fields, i, values [i]);
1257 return FALSE;
1258 } else {
1259 return TRUE;
1263 MonoReflectionTypeHandle
1264 ves_icall_System_Object_GetType (MonoObjectHandle obj, MonoError *error)
1266 MonoDomain *domain = MONO_HANDLE_DOMAIN (obj);
1267 MonoClass *klass = mono_handle_class (obj);
1268 #ifndef DISABLE_REMOTING
1269 if (mono_class_is_transparent_proxy (klass)) {
1270 MonoTransparentProxyHandle proxy_obj = MONO_HANDLE_CAST (MonoTransparentProxy, obj);
1271 MonoRemoteClass *remote_class = MONO_HANDLE_GETVAL (proxy_obj, remote_class);
1272 /* If it's a transparent proxy for an interface, return the
1273 * interface type, not the unhelpful proxy_class class (which
1274 * is just MarshalByRefObject). */
1275 MonoType *proxy_type =
1276 mono_remote_class_is_interface_proxy (remote_class) ?
1277 m_class_get_byval_arg (remote_class->interfaces[0]) :
1278 m_class_get_byval_arg (remote_class->proxy_class);
1279 return mono_type_get_object_handle (domain, proxy_type, error);
1280 } else
1281 #endif
1282 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
1285 static gboolean
1286 get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1288 MonoMethod **dest = (MonoMethod **)data;
1290 /* skip unmanaged frames */
1291 if (!managed)
1292 return FALSE;
1294 if (!(*dest)) {
1295 if (!strcmp (m_class_get_name_space (m->klass), "System.Reflection"))
1296 return FALSE;
1297 *dest = m;
1298 return TRUE;
1300 return FALSE;
1303 static gboolean
1304 in_corlib_name_space (MonoClass *klass, const char *name_space)
1306 return m_class_get_image (klass) == mono_defaults.corlib &&
1307 !strcmp (m_class_get_name_space (klass), name_space);
1310 static gboolean
1311 get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1313 MonoMethod **dest = (MonoMethod **)data;
1315 /* skip unmanaged frames */
1316 if (!managed)
1317 return FALSE;
1319 if (m->wrapper_type != MONO_WRAPPER_NONE)
1320 return FALSE;
1322 if (m == *dest) {
1323 *dest = NULL;
1324 return FALSE;
1327 if (in_corlib_name_space (m->klass, "System.Reflection"))
1328 return FALSE;
1330 if (!(*dest)) {
1331 *dest = m;
1332 return TRUE;
1334 return FALSE;
1337 static gboolean
1338 get_caller_no_system_or_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1340 MonoMethod **dest = (MonoMethod **)data;
1342 /* skip unmanaged frames */
1343 if (!managed)
1344 return FALSE;
1346 if (m->wrapper_type != MONO_WRAPPER_NONE)
1347 return FALSE;
1349 if (m == *dest) {
1350 *dest = NULL;
1351 return FALSE;
1354 if (in_corlib_name_space (m->klass, "System.Reflection") || in_corlib_name_space (m->klass, "System"))
1355 return FALSE;
1357 if (!(*dest)) {
1358 *dest = m;
1359 return TRUE;
1361 return FALSE;
1365 * mono_runtime_get_caller_no_system_or_reflection:
1367 * Walk the stack of the current thread and find the first managed method that
1368 * is not in the mscorlib System or System.Reflection namespace. This skips
1369 * unmanaged callers and wrapper methods.
1371 * \returns a pointer to the \c MonoMethod or NULL if we walked past all the
1372 * callers.
1374 MonoMethod*
1375 mono_runtime_get_caller_no_system_or_reflection (void)
1377 MonoMethod *dest = NULL;
1378 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1379 return dest;
1383 * mono_runtime_get_caller_from_stack_mark:
1385 * Walk the stack and return the assembly of the method referenced
1386 * by the stack mark STACK_MARK.
1388 MonoAssembly*
1389 mono_runtime_get_caller_from_stack_mark (MonoStackCrawlMark *stack_mark)
1391 // FIXME: Use the stack mark
1392 MonoMethod *dest = NULL;
1393 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1394 if (dest)
1395 return m_class_get_image (dest->klass)->assembly;
1396 else
1397 return NULL;
1400 static MonoReflectionTypeHandle
1401 type_from_parsed_name (MonoTypeNameParse *info, MonoStackCrawlMark *stack_mark, MonoBoolean ignoreCase, MonoAssembly **caller_assembly, MonoError *error)
1403 MonoMethod *m;
1404 MonoType *type = NULL;
1405 MonoAssembly *assembly = NULL;
1406 gboolean type_resolve = FALSE;
1407 MonoImage *rootimage = NULL;
1409 error_init (error);
1412 * We must compute the calling assembly as type loading must happen under a metadata context.
1413 * For example. The main assembly is a.exe and Type.GetType is called from dir/b.dll. Without
1414 * the metadata context (basedir currently) set to dir/b.dll we won't be able to load a dir/c.dll.
1416 m = mono_method_get_last_managed ();
1417 if (m && m_class_get_image (m->klass) != mono_defaults.corlib) {
1418 /* Happens with inlining */
1419 assembly = m_class_get_image (m->klass)->assembly;
1420 } else {
1421 assembly = mono_runtime_get_caller_from_stack_mark (stack_mark);
1423 if (assembly) {
1424 type_resolve = TRUE;
1425 rootimage = assembly->image;
1426 } else {
1427 g_warning (G_STRLOC);
1429 *caller_assembly = assembly;
1431 if (info->assembly.name)
1432 assembly = mono_assembly_load (&info->assembly, assembly ? assembly->basedir : NULL, NULL);
1434 if (assembly) {
1435 /* When loading from the current assembly, AppDomain.TypeResolve will not be called yet */
1436 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
1437 goto_if_nok (error, fail);
1440 // XXXX - aleksey -
1441 // Say we're looking for System.Generic.Dict<int, Local>
1442 // we FAIL the get type above, because S.G.Dict isn't in assembly->image. So we drop down here.
1443 // but then we FAIL AGAIN because now we pass null as the image and the rootimage and everything
1444 // is messed up when we go to construct the Local as the type arg...
1446 // By contrast, if we started with Mine<System.Generic.Dict<int, Local>> we'd go in with assembly->image
1447 // as the root and then even the detour into generics would still not screw us when we went to load Local.
1448 if (!info->assembly.name && !type) {
1449 /* try mscorlib */
1450 type = mono_reflection_get_type_checked (rootimage, NULL, info, ignoreCase, &type_resolve, error);
1451 goto_if_nok (error, fail);
1453 if (assembly && !type && type_resolve) {
1454 type_resolve = FALSE; /* This will invoke TypeResolve if not done in the first 'if' */
1455 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
1456 goto_if_nok (error, fail);
1459 if (!type)
1460 goto fail;
1462 return mono_type_get_object_handle (mono_domain_get (), type, error);
1463 fail:
1464 return MONO_HANDLE_NEW (MonoReflectionType, NULL);
1467 MonoReflectionTypeHandle
1468 ves_icall_System_RuntimeTypeHandle_internal_from_name (MonoStringHandle name,
1469 MonoStackCrawlMark *stack_mark,
1470 MonoReflectionAssemblyHandle callerAssembly,
1471 MonoBoolean throwOnError,
1472 MonoBoolean ignoreCase,
1473 MonoBoolean reflectionOnly,
1474 MonoError *error)
1476 MonoTypeNameParse info;
1477 gboolean free_info = FALSE;
1478 MonoAssembly *caller_assembly;
1479 MonoReflectionTypeHandle type = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1481 /* The callerAssembly argument is unused for now */
1483 char *str = mono_string_handle_to_utf8 (name, error);
1484 goto_if_nok (error, leave);
1486 free_info = TRUE;
1487 if (!mono_reflection_parse_type_checked (str, &info, error))
1488 goto leave;
1490 /* mono_reflection_parse_type() mangles the string */
1492 MONO_HANDLE_ASSIGN (type, type_from_parsed_name (&info, (MonoStackCrawlMark*)stack_mark, ignoreCase, &caller_assembly, error));
1494 goto_if_nok (error, leave);
1496 if (MONO_HANDLE_IS_NULL (type)) {
1497 if (throwOnError) {
1498 char *tname = info.name_space ? g_strdup_printf ("%s.%s", info.name_space, info.name) : g_strdup (info.name);
1499 char *aname;
1500 if (info.assembly.name)
1501 aname = mono_stringify_assembly_name (&info.assembly);
1502 else if (caller_assembly)
1503 aname = mono_stringify_assembly_name (mono_assembly_get_name_internal (caller_assembly));
1504 else
1505 aname = g_strdup ("");
1506 mono_error_set_type_load_name (error, tname, aname, "");
1508 goto leave;
1511 leave:
1512 if (free_info)
1513 mono_reflection_free_type_info (&info);
1514 g_free (str);
1515 if (!is_ok (error)) {
1516 if (!throwOnError) {
1517 mono_error_cleanup (error);
1518 error_init (error);
1520 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
1521 } else
1522 return type;
1526 MonoReflectionTypeHandle
1527 ves_icall_System_Type_internal_from_handle (MonoType *handle, MonoError *error)
1529 MonoDomain *domain = mono_domain_get ();
1531 return mono_type_get_object_handle (domain, handle, error);
1534 MonoType*
1535 ves_icall_Mono_RuntimeClassHandle_GetTypeFromClass (MonoClass *klass, MonoError *error)
1537 return m_class_get_byval_arg (klass);
1540 void
1541 ves_icall_Mono_RuntimeGPtrArrayHandle_GPtrArrayFree (GPtrArray *ptr_array, MonoError *error)
1543 g_ptr_array_free (ptr_array, TRUE);
1546 void
1547 ves_icall_Mono_SafeStringMarshal_GFree (void *c_str, MonoError *error)
1549 g_free (c_str);
1552 char*
1553 ves_icall_Mono_SafeStringMarshal_StringToUtf8 (MonoStringHandle s, MonoError *error)
1555 return mono_string_handle_to_utf8 (s, error);
1558 /* System.TypeCode */
1559 typedef enum {
1560 TYPECODE_EMPTY,
1561 TYPECODE_OBJECT,
1562 TYPECODE_DBNULL,
1563 TYPECODE_BOOLEAN,
1564 TYPECODE_CHAR,
1565 TYPECODE_SBYTE,
1566 TYPECODE_BYTE,
1567 TYPECODE_INT16,
1568 TYPECODE_UINT16,
1569 TYPECODE_INT32,
1570 TYPECODE_UINT32,
1571 TYPECODE_INT64,
1572 TYPECODE_UINT64,
1573 TYPECODE_SINGLE,
1574 TYPECODE_DOUBLE,
1575 TYPECODE_DECIMAL,
1576 TYPECODE_DATETIME,
1577 TYPECODE_STRING = 18
1578 } TypeCode;
1580 guint32
1581 ves_icall_type_GetTypeCodeInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
1583 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1584 int t = type->type;
1586 if (type->byref)
1587 return TYPECODE_OBJECT;
1589 handle_enum:
1590 switch (t) {
1591 case MONO_TYPE_VOID:
1592 return TYPECODE_OBJECT;
1593 case MONO_TYPE_BOOLEAN:
1594 return TYPECODE_BOOLEAN;
1595 case MONO_TYPE_U1:
1596 return TYPECODE_BYTE;
1597 case MONO_TYPE_I1:
1598 return TYPECODE_SBYTE;
1599 case MONO_TYPE_U2:
1600 return TYPECODE_UINT16;
1601 case MONO_TYPE_I2:
1602 return TYPECODE_INT16;
1603 case MONO_TYPE_CHAR:
1604 return TYPECODE_CHAR;
1605 case MONO_TYPE_PTR:
1606 case MONO_TYPE_U:
1607 case MONO_TYPE_I:
1608 return TYPECODE_OBJECT;
1609 case MONO_TYPE_U4:
1610 return TYPECODE_UINT32;
1611 case MONO_TYPE_I4:
1612 return TYPECODE_INT32;
1613 case MONO_TYPE_U8:
1614 return TYPECODE_UINT64;
1615 case MONO_TYPE_I8:
1616 return TYPECODE_INT64;
1617 case MONO_TYPE_R4:
1618 return TYPECODE_SINGLE;
1619 case MONO_TYPE_R8:
1620 return TYPECODE_DOUBLE;
1621 case MONO_TYPE_VALUETYPE: {
1622 MonoClass *klass = type->data.klass;
1624 if (m_class_is_enumtype (klass)) {
1625 t = mono_class_enum_basetype_internal (klass)->type;
1626 goto handle_enum;
1627 } else if (mono_is_corlib_image (m_class_get_image (klass))) {
1628 if (strcmp (m_class_get_name_space (klass), "System") == 0) {
1629 if (strcmp (m_class_get_name (klass), "Decimal") == 0)
1630 return TYPECODE_DECIMAL;
1631 else if (strcmp (m_class_get_name (klass), "DateTime") == 0)
1632 return TYPECODE_DATETIME;
1635 return TYPECODE_OBJECT;
1637 case MONO_TYPE_STRING:
1638 return TYPECODE_STRING;
1639 case MONO_TYPE_SZARRAY:
1640 case MONO_TYPE_ARRAY:
1641 case MONO_TYPE_OBJECT:
1642 case MONO_TYPE_VAR:
1643 case MONO_TYPE_MVAR:
1644 case MONO_TYPE_TYPEDBYREF:
1645 return TYPECODE_OBJECT;
1646 case MONO_TYPE_CLASS:
1648 MonoClass *klass = type->data.klass;
1649 if (m_class_get_image (klass) == mono_defaults.corlib && strcmp (m_class_get_name_space (klass), "System") == 0) {
1650 if (strcmp (m_class_get_name (klass), "DBNull") == 0)
1651 return TYPECODE_DBNULL;
1654 return TYPECODE_OBJECT;
1655 case MONO_TYPE_GENERICINST:
1656 return TYPECODE_OBJECT;
1657 default:
1658 g_error ("type 0x%02x not handled in GetTypeCode()", t);
1660 return 0;
1663 static MonoType*
1664 mono_type_get_underlying_type_ignore_byref (MonoType *type)
1666 if (type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (type->data.klass))
1667 return mono_class_enum_basetype_internal (type->data.klass);
1668 if (type->type == MONO_TYPE_GENERICINST && m_class_is_enumtype (type->data.generic_class->container_class))
1669 return mono_class_enum_basetype_internal (type->data.generic_class->container_class);
1670 return type;
1673 guint32
1674 ves_icall_RuntimeTypeHandle_type_is_assignable_from (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_c, MonoError *error)
1676 g_assert (!MONO_HANDLE_IS_NULL (ref_type));
1678 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1679 MonoClass *klass = mono_class_from_mono_type_internal (type);
1680 MonoType *ctype = MONO_HANDLE_GETVAL (ref_c, type);
1681 MonoClass *klassc = mono_class_from_mono_type_internal (ctype);
1683 if (type->byref ^ ctype->byref)
1684 return FALSE;
1686 if (type->byref) {
1687 MonoType *t = mono_type_get_underlying_type_ignore_byref (type);
1688 MonoType *ot = mono_type_get_underlying_type_ignore_byref (ctype);
1690 klass = mono_class_from_mono_type_internal (t);
1691 klassc = mono_class_from_mono_type_internal (ot);
1693 if (mono_type_is_primitive (t)) {
1694 return mono_type_is_primitive (ot) && m_class_get_instance_size (klass) == m_class_get_instance_size (klassc);
1695 } else if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) {
1696 return t->type == ot->type && t->data.generic_param->num == ot->data.generic_param->num;
1697 } else if (t->type == MONO_TYPE_PTR || t->type == MONO_TYPE_FNPTR) {
1698 return t->type == ot->type;
1699 } else {
1700 if (ot->type == MONO_TYPE_VAR || ot->type == MONO_TYPE_MVAR)
1701 return FALSE;
1703 if (m_class_is_valuetype (klass))
1704 return klass == klassc;
1705 return m_class_is_valuetype (klass) == m_class_is_valuetype (klassc);
1708 return mono_class_is_assignable_from_internal (klass, klassc);
1711 MonoBoolean
1712 ves_icall_RuntimeTypeHandle_is_subclass_of (MonoType *childType, MonoType *baseType)
1714 ERROR_DECL (error);
1715 mono_bool result = FALSE;
1716 MonoClass *childClass;
1717 MonoClass *baseClass;
1719 childClass = mono_class_from_mono_type_internal (childType);
1720 baseClass = mono_class_from_mono_type_internal (baseType);
1722 if (G_UNLIKELY (childType->byref)) {
1723 result = !baseType->byref && baseClass == mono_defaults.object_class;
1724 goto done;
1727 if (G_UNLIKELY (baseType->byref)) {
1728 result = FALSE;
1729 goto done;
1732 if (childType == baseType) {
1733 /* .NET IsSubclassOf is not reflexive */
1734 result = FALSE;
1735 goto done;
1738 if (G_UNLIKELY (is_generic_parameter (childType))) {
1739 /* slow path: walk the type hierarchy looking at base types
1740 * until we see baseType. If the current type is not a gparam,
1741 * break out of the loop and use is_subclass_of.
1743 MonoClass *c = mono_generic_param_get_base_type (childClass);
1745 result = FALSE;
1746 while (c != NULL) {
1747 if (c == baseClass) {
1748 result = TRUE;
1749 break;
1751 if (!is_generic_parameter (m_class_get_byval_arg (c))) {
1752 result = mono_class_is_subclass_of (c, baseClass, FALSE);
1753 break;
1754 } else
1755 c = mono_generic_param_get_base_type (c);
1757 } else {
1758 result = mono_class_is_subclass_of (childClass, baseClass, FALSE);
1760 done:
1761 mono_error_set_pending_exception (error);
1762 return result;
1765 guint32
1766 ves_icall_RuntimeTypeHandle_IsInstanceOfType (MonoReflectionTypeHandle ref_type, MonoObjectHandle obj, MonoError *error)
1768 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1769 MonoClass *klass = mono_class_from_mono_type_internal (type);
1770 mono_class_init_checked (klass, error);
1771 return_val_if_nok (error, FALSE);
1772 MonoObjectHandle inst = mono_object_handle_isinst (obj, klass, error);
1773 return_val_if_nok (error, FALSE);
1774 return !MONO_HANDLE_IS_NULL (inst);
1777 guint32
1778 ves_icall_RuntimeTypeHandle_GetAttributes (MonoReflectionTypeHandle ref_type, MonoError *error)
1780 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1781 MonoClass *klass = mono_class_from_mono_type_internal (type);
1782 return mono_class_get_flags (klass);
1785 MonoReflectionMarshalAsAttributeHandle
1786 ves_icall_System_Reflection_FieldInfo_get_marshal_info (MonoReflectionFieldHandle field_h, MonoError *error)
1788 MonoDomain *domain = MONO_HANDLE_DOMAIN (field_h);
1789 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
1790 MonoClass *klass = field->parent;
1792 MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
1793 if (mono_class_is_gtd (klass) ||
1794 (gklass && gklass->context.class_inst->is_open))
1795 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1797 MonoType *ftype = mono_field_get_type_internal (field);
1798 if (ftype && !(ftype->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL))
1799 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1801 MonoMarshalType *info = mono_marshal_load_type_info (klass);
1803 for (int i = 0; i < info->num_fields; ++i) {
1804 if (info->fields [i].field == field) {
1805 if (!info->fields [i].mspec)
1806 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1807 else {
1808 return mono_reflection_marshal_as_attribute_from_marshal_spec (domain, klass, info->fields [i].mspec, error);
1813 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1816 MonoReflectionFieldHandle
1817 ves_icall_System_Reflection_FieldInfo_internal_from_handle_type (MonoClassField *handle, MonoType *type, MonoError *error)
1819 MonoClass *klass;
1821 g_assert (handle);
1823 if (!type) {
1824 klass = handle->parent;
1825 } else {
1826 klass = mono_class_from_mono_type_internal (type);
1828 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1830 if (!found)
1831 /* The managed code will throw the exception */
1832 return MONO_HANDLE_CAST (MonoReflectionField, NULL_HANDLE);
1835 return mono_field_get_object_handle (mono_domain_get (), klass, handle, error);
1838 MonoReflectionEventHandle
1839 ves_icall_System_Reflection_EventInfo_internal_from_handle_type (MonoEvent *handle, MonoType *type, MonoError *error)
1841 MonoClass *klass;
1843 g_assert (handle);
1845 if (!type) {
1846 klass = handle->parent;
1847 } else {
1848 klass = mono_class_from_mono_type_internal (type);
1850 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1851 if (!found)
1852 /* Managed code will throw an exception */
1853 return MONO_HANDLE_CAST (MonoReflectionEvent, NULL_HANDLE);
1856 return mono_event_get_object_handle (mono_domain_get (), klass, handle, error);
1860 MonoReflectionPropertyHandle
1861 ves_icall_System_Reflection_RuntimePropertyInfo_internal_from_handle_type (MonoProperty *handle, MonoType *type, MonoError *error)
1863 MonoClass *klass;
1865 g_assert (handle);
1867 if (!type) {
1868 klass = handle->parent;
1869 } else {
1870 klass = mono_class_from_mono_type_internal (type);
1872 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1873 if (!found)
1874 /* Managed code will throw an exception */
1875 return MONO_HANDLE_CAST (MonoReflectionProperty, NULL_HANDLE);
1878 return mono_property_get_object_handle (mono_domain_get (), klass, handle, error);
1881 MonoArrayHandle
1882 ves_icall_System_Reflection_FieldInfo_GetTypeModifiers (MonoReflectionFieldHandle field_h, MonoBoolean optional, MonoError *error)
1884 MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
1886 MonoType *type = mono_field_get_type_checked (field, error);
1887 return_val_if_nok (error, NULL_HANDLE_ARRAY);
1889 return type_array_from_modifiers (m_class_get_image (field->parent), type, optional, error);
1893 ves_icall_get_method_attributes (MonoMethod *method)
1895 return method->flags;
1898 void
1899 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info, MonoError *error)
1901 MonoDomain *domain = mono_domain_get ();
1903 MonoMethodSignature* sig = mono_method_signature_checked (method, error);
1904 return_if_nok (error);
1906 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (method->klass), error);
1907 return_if_nok (error);
1909 MONO_STRUCT_SETREF_INTERNAL (info, parent, MONO_HANDLE_RAW (rt));
1911 MONO_HANDLE_ASSIGN (rt, mono_type_get_object_handle (domain, sig->ret, error));
1912 return_if_nok (error);
1914 MONO_STRUCT_SETREF_INTERNAL (info, ret, MONO_HANDLE_RAW (rt));
1916 info->attrs = method->flags;
1917 info->implattrs = method->iflags;
1918 guint32 callconv;
1919 if (sig->call_convention == MONO_CALL_DEFAULT)
1920 callconv = sig->sentinelpos >= 0 ? 2 : 1;
1921 else {
1922 if (sig->call_convention == MONO_CALL_VARARG || sig->sentinelpos >= 0)
1923 callconv = 2;
1924 else
1925 callconv = 1;
1927 callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6);
1928 info->callconv = callconv;
1931 MonoArrayHandle
1932 ves_icall_System_Reflection_MonoMethodInfo_get_parameter_info (MonoMethod *method, MonoReflectionMethodHandle member, MonoError *error)
1934 MonoDomain *domain = mono_domain_get ();
1936 MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1937 MONO_HANDLE_GET (reftype, member, reftype);
1938 MonoClass *klass = NULL;
1939 if (!MONO_HANDLE_IS_NULL (reftype))
1940 klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (reftype, type));
1941 return mono_param_get_objects_internal (domain, method, klass, error);
1944 MonoReflectionMarshalAsAttributeHandle
1945 ves_icall_System_MonoMethodInfo_get_retval_marshal (MonoMethod *method, MonoError *error)
1947 MonoDomain *domain = mono_domain_get ();
1948 MonoReflectionMarshalAsAttributeHandle res = MONO_HANDLE_NEW (MonoReflectionMarshalAsAttribute, NULL);
1950 MonoMarshalSpec **mspecs = g_new (MonoMarshalSpec*, mono_method_signature_internal (method)->param_count + 1);
1951 mono_method_get_marshal_info (method, mspecs);
1953 if (mspecs [0]) {
1954 MONO_HANDLE_ASSIGN (res, mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [0], error));
1955 goto_if_nok (error, leave);
1958 leave:
1959 for (int i = mono_method_signature_internal (method)->param_count; i >= 0; i--)
1960 if (mspecs [i])
1961 mono_metadata_free_marshal_spec (mspecs [i]);
1962 g_free (mspecs);
1964 return res;
1967 gint32
1968 ves_icall_RuntimeFieldInfo_GetFieldOffset (MonoReflectionFieldHandle field, MonoError *error)
1970 MonoClassField *class_field = MONO_HANDLE_GETVAL (field, field);
1971 mono_class_setup_fields (class_field->parent);
1973 return class_field->offset - MONO_ABI_SIZEOF (MonoObject);
1976 MonoReflectionTypeHandle
1977 ves_icall_RuntimeFieldInfo_GetParentType (MonoReflectionFieldHandle field, MonoBoolean declaring, MonoError *error)
1979 MonoDomain *domain = MONO_HANDLE_DOMAIN (field);
1980 MonoClass *parent;
1982 if (declaring) {
1983 MonoClassField *f = MONO_HANDLE_GETVAL (field, field);
1984 parent = f->parent;
1985 } else {
1986 parent = MONO_HANDLE_GETVAL (field, klass);
1989 return mono_type_get_object_handle (domain, m_class_get_byval_arg (parent), error);
1992 MonoObject *
1993 ves_icall_RuntimeFieldInfo_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
1995 ERROR_DECL (error);
1996 MonoClass *fklass = field->klass;
1997 MonoClassField *cf = field->field;
1998 MonoDomain *domain = mono_object_domain (field);
2000 if (mono_asmctx_get_kind (&m_class_get_image (fklass)->assembly->context) == MONO_ASMCTX_REFONLY) {
2001 mono_error_set_invalid_operation (error,
2002 "It is illegal to get the value on a field on a type loaded using the ReflectionOnly methods.");
2003 mono_error_set_pending_exception (error);
2004 return NULL;
2007 if (mono_security_core_clr_enabled () &&
2008 !mono_security_core_clr_ensure_reflection_access_field (cf, error)) {
2009 mono_error_set_pending_exception (error);
2010 return NULL;
2013 #ifndef DISABLE_REMOTING
2014 if (G_UNLIKELY (obj != NULL && mono_class_is_transparent_proxy (mono_object_class (obj)))) {
2015 /* We get here if someone used a
2016 * System.Reflection.FieldInfo:GetValue on a
2017 * ContextBoundObject's or cross-domain MarshalByRefObject's
2018 * transparent proxy. */
2019 MonoObject *result = mono_load_remote_field_new_checked (obj, fklass, cf, error);
2020 mono_error_set_pending_exception (error);
2021 return result;
2023 #endif
2025 MonoObject * result = mono_field_get_value_object_checked (domain, cf, obj, error);
2026 mono_error_set_pending_exception (error);
2027 return result;
2030 void
2031 ves_icall_RuntimeFieldInfo_SetValueInternal (MonoReflectionFieldHandle field, MonoObjectHandle obj, MonoObjectHandle value, MonoError *error)
2033 MonoClassField *cf = MONO_HANDLE_GETVAL (field, field);
2035 MonoClass *field_klass = MONO_HANDLE_GETVAL (field, klass);
2036 if (mono_asmctx_get_kind (&m_class_get_image (field_klass)->assembly->context) == MONO_ASMCTX_REFONLY) {
2037 mono_error_set_invalid_operation (error, "It is illegal to set the value on a field on a type loaded using the ReflectionOnly methods.");
2038 return;
2041 if (mono_security_core_clr_enabled () &&
2042 !mono_security_core_clr_ensure_reflection_access_field (cf, error)) {
2043 return;
2046 #ifndef DISABLE_REMOTING
2047 if (G_UNLIKELY (!MONO_HANDLE_IS_NULL (obj) && mono_class_is_transparent_proxy (mono_handle_class (obj)))) {
2048 /* We get here if someone used a
2049 * System.Reflection.FieldInfo:SetValue on a
2050 * ContextBoundObject's or cross-domain MarshalByRefObject's
2051 * transparent proxy. */
2052 /* FIXME: use handles for mono_store_remote_field_new_checked */
2053 MonoObject *v = MONO_HANDLE_RAW (value);
2054 MonoObject *o = MONO_HANDLE_RAW (obj);
2055 mono_store_remote_field_new_checked (o, field_klass, cf, v, error);
2056 return;
2058 #endif
2060 MonoType *type = mono_field_get_type_checked (cf, error);
2061 return_if_nok (error);
2063 gboolean isref = FALSE;
2064 uint32_t value_gchandle = 0;
2065 gchar *v = NULL;
2066 if (!type->byref) {
2067 switch (type->type) {
2068 case MONO_TYPE_U1:
2069 case MONO_TYPE_I1:
2070 case MONO_TYPE_BOOLEAN:
2071 case MONO_TYPE_U2:
2072 case MONO_TYPE_I2:
2073 case MONO_TYPE_CHAR:
2074 case MONO_TYPE_U:
2075 case MONO_TYPE_I:
2076 case MONO_TYPE_U4:
2077 case MONO_TYPE_I4:
2078 case MONO_TYPE_R4:
2079 case MONO_TYPE_U8:
2080 case MONO_TYPE_I8:
2081 case MONO_TYPE_R8:
2082 case MONO_TYPE_VALUETYPE:
2083 case MONO_TYPE_PTR:
2084 isref = FALSE;
2085 if (!MONO_HANDLE_IS_NULL (value))
2086 v = (char*)mono_object_handle_pin_unbox (value, &value_gchandle);
2087 break;
2088 case MONO_TYPE_STRING:
2089 case MONO_TYPE_OBJECT:
2090 case MONO_TYPE_CLASS:
2091 case MONO_TYPE_ARRAY:
2092 case MONO_TYPE_SZARRAY:
2093 /* Do nothing */
2094 isref = TRUE;
2095 break;
2096 case MONO_TYPE_GENERICINST: {
2097 MonoGenericClass *gclass = type->data.generic_class;
2098 g_assert (!gclass->context.class_inst->is_open);
2100 if (mono_class_is_nullable (mono_class_from_mono_type_internal (type))) {
2101 MonoClass *nklass = mono_class_from_mono_type_internal (type);
2104 * Convert the boxed vtype into a Nullable structure.
2105 * This is complicated by the fact that Nullables have
2106 * a variable structure.
2108 MonoObjectHandle nullable = mono_object_new_handle (mono_domain_get (), nklass, error);
2109 return_if_nok (error);
2111 uint32_t nullable_gchandle = 0;
2112 guint8 *nval = (guint8*)mono_object_handle_pin_unbox (nullable, &nullable_gchandle);
2113 mono_nullable_init_from_handle (nval, value, nklass);
2115 isref = FALSE;
2116 value_gchandle = nullable_gchandle;
2117 v = (gchar*)nval;
2119 else {
2120 isref = !m_class_is_valuetype (gclass->container_class);
2121 if (!isref && !MONO_HANDLE_IS_NULL (value)) {
2122 v = (char*)mono_object_handle_pin_unbox (value, &value_gchandle);
2125 break;
2127 default:
2128 g_error ("type 0x%x not handled in "
2129 "ves_icall_FieldInfo_SetValueInternal", type->type);
2130 return;
2134 /* either value is a reference type, or it's a value type and we pinned
2135 * it and v points to the payload. */
2136 g_assert ((isref && v == NULL && value_gchandle == 0) ||
2137 (!isref && v != NULL && value_gchandle != 0) ||
2138 (!isref && v == NULL && value_gchandle == 0));
2140 if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
2141 MonoVTable *vtable = mono_class_vtable_checked (MONO_HANDLE_DOMAIN (field), cf->parent, error);
2142 goto_if_nok (error, leave);
2144 if (!vtable->initialized) {
2145 if (!mono_runtime_class_init_full (vtable, error))
2146 goto leave;
2148 if (isref)
2149 mono_field_static_set_value_internal (vtable, cf, MONO_HANDLE_RAW (value)); /* FIXME make mono_field_static_set_value work with handles for value */
2150 else
2151 mono_field_static_set_value_internal (vtable, cf, v);
2152 } else {
2154 if (isref)
2155 MONO_HANDLE_SET_FIELD_REF (obj, cf, value);
2156 else
2157 mono_field_set_value_internal (MONO_HANDLE_RAW (obj), cf, v); /* FIXME: make mono_field_set_value take a handle for obj */
2159 leave:
2160 if (value_gchandle)
2161 mono_gchandle_free_internal (value_gchandle);
2164 static MonoObjectHandle
2165 typed_reference_to_object (MonoTypedRef *tref, MonoError *error)
2167 HANDLE_FUNCTION_ENTER ();
2168 MonoObjectHandle result;
2169 if (MONO_TYPE_IS_REFERENCE (tref->type)) {
2170 MonoObject** objp = (MonoObject **)tref->value;
2171 result = MONO_HANDLE_NEW (MonoObject, *objp);
2172 } else {
2173 result = mono_value_box_handle (mono_domain_get (), tref->klass, tref->value, error);
2175 HANDLE_FUNCTION_RETURN_REF (MonoObject, result);
2178 void
2179 ves_icall_System_RuntimeFieldHandle_SetValueDirect (MonoReflectionField *field, MonoReflectionType *field_type, MonoTypedRef *obj, MonoObject *value, MonoReflectionType *context_type)
2181 ICALL_ENTRY ();
2183 MonoClassField *f;
2185 g_assert (field);
2186 g_assert (obj);
2187 g_assert (value);
2189 f = field->field;
2190 if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (f->parent))) {
2191 MonoReflectionFieldHandle fieldHandle = MONO_HANDLE_NEW (MonoReflectionField, field);
2192 MonoObjectHandle objHandle = typed_reference_to_object (obj, error),
2193 valueHandle = MONO_HANDLE_NEW (MonoObject, value);
2194 goto_if_nok (error, leave);
2195 ves_icall_RuntimeFieldInfo_SetValueInternal (fieldHandle, objHandle, valueHandle, error);
2196 } else if (MONO_TYPE_IS_REFERENCE (f->type))
2197 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), value, FALSE);
2198 else
2199 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), mono_object_unbox_internal (value), FALSE);
2201 leave:
2202 ICALL_RETURN ();
2205 MonoObject *
2206 ves_icall_RuntimeFieldInfo_GetRawConstantValue (MonoReflectionField *rfield)
2208 MonoObject *o = NULL;
2209 MonoClassField *field = rfield->field;
2210 MonoClass *klass;
2211 MonoDomain *domain = mono_object_domain (rfield);
2212 gchar *v;
2213 MonoTypeEnum def_type;
2214 const char *def_value;
2215 MonoType *t;
2216 ERROR_DECL (error);
2218 mono_class_init_internal (field->parent);
2220 t = mono_field_get_type_checked (field, error);
2221 if (!is_ok (error)) {
2222 mono_error_set_pending_exception (error);
2223 return NULL;
2226 if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT)) {
2227 mono_error_set_invalid_operation (error, NULL);
2228 mono_error_set_pending_exception (error);
2229 return NULL;
2232 if (image_is_dynamic (m_class_get_image (field->parent))) {
2233 MonoClass *klass = field->parent;
2234 int fidx = field - m_class_get_fields (klass);
2235 MonoFieldDefaultValue *def_values = mono_class_get_field_def_values (klass);
2237 g_assert (def_values);
2238 def_type = def_values [fidx].def_type;
2239 def_value = def_values [fidx].data;
2241 if (def_type == MONO_TYPE_END) {
2242 mono_error_set_invalid_operation (error, NULL);
2243 mono_error_set_pending_exception (error);
2244 return NULL;
2246 } else {
2247 def_value = mono_class_get_field_default_value (field, &def_type);
2248 /* FIXME, maybe we should try to raise TLE if field->parent is broken */
2249 if (!def_value) {
2250 mono_error_set_invalid_operation (error, NULL);
2251 mono_error_set_pending_exception (error);
2252 return NULL;
2256 /*FIXME unify this with reflection.c:mono_get_object_from_blob*/
2257 switch (def_type) {
2258 case MONO_TYPE_U1:
2259 case MONO_TYPE_I1:
2260 case MONO_TYPE_BOOLEAN:
2261 case MONO_TYPE_U2:
2262 case MONO_TYPE_I2:
2263 case MONO_TYPE_CHAR:
2264 case MONO_TYPE_U:
2265 case MONO_TYPE_I:
2266 case MONO_TYPE_U4:
2267 case MONO_TYPE_I4:
2268 case MONO_TYPE_R4:
2269 case MONO_TYPE_U8:
2270 case MONO_TYPE_I8:
2271 case MONO_TYPE_R8: {
2272 MonoType *t;
2274 /* boxed value type */
2275 t = g_new0 (MonoType, 1);
2276 t->type = def_type;
2277 klass = mono_class_from_mono_type_internal (t);
2278 g_free (t);
2279 o = mono_object_new_checked (domain, klass, error);
2280 if (!is_ok (error)) {
2281 mono_error_set_pending_exception (error);
2282 return NULL;
2284 v = ((gchar *) o) + sizeof (MonoObject);
2285 mono_get_constant_value_from_blob (domain, def_type, def_value, v, error);
2286 if (mono_error_set_pending_exception (error))
2287 return NULL;
2288 break;
2290 case MONO_TYPE_STRING:
2291 case MONO_TYPE_CLASS:
2292 mono_get_constant_value_from_blob (domain, def_type, def_value, &o, error);
2293 if (mono_error_set_pending_exception (error))
2294 return NULL;
2295 break;
2296 default:
2297 g_assert_not_reached ();
2300 return o;
2303 MonoReflectionTypeHandle
2304 ves_icall_RuntimeFieldInfo_ResolveType (MonoReflectionFieldHandle ref_field, MonoError *error)
2306 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_field);
2307 MonoClassField *field = MONO_HANDLE_GETVAL (ref_field, field);
2308 MonoType *type = mono_field_get_type_checked (field, error);
2309 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
2310 return mono_type_get_object_handle (domain, type, error);
2313 void
2314 ves_icall_RuntimePropertyInfo_get_property_info (MonoReflectionPropertyHandle property, MonoPropertyInfo *info, PInfo req_info, MonoError *error)
2316 MonoDomain *domain = MONO_HANDLE_DOMAIN (property);
2317 const MonoProperty *pproperty = MONO_HANDLE_GETVAL (property, property);
2319 if ((req_info & PInfo_ReflectedType) != 0) {
2320 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
2321 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2322 return_if_nok (error);
2324 MONO_STRUCT_SETREF_INTERNAL (info, parent, MONO_HANDLE_RAW (rt));
2326 if ((req_info & PInfo_DeclaringType) != 0) {
2327 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (pproperty->parent), error);
2328 return_if_nok (error);
2330 MONO_STRUCT_SETREF_INTERNAL (info, declaring_type, MONO_HANDLE_RAW (rt));
2333 if ((req_info & PInfo_Name) != 0) {
2334 MonoStringHandle name = mono_string_new_handle (domain, pproperty->name, error);
2335 return_if_nok (error);
2337 MONO_STRUCT_SETREF_INTERNAL (info, name, MONO_HANDLE_RAW (name));
2340 if ((req_info & PInfo_Attributes) != 0)
2341 info->attrs = pproperty->attrs;
2343 if ((req_info & PInfo_GetMethod) != 0) {
2344 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2345 MonoReflectionMethodHandle rm;
2346 if (pproperty->get &&
2347 (((pproperty->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2348 pproperty->get->klass == property_klass)) {
2349 rm = mono_method_get_object_handle (domain, pproperty->get, property_klass, error);
2350 return_if_nok (error);
2351 } else {
2352 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2355 MONO_STRUCT_SETREF_INTERNAL (info, get, MONO_HANDLE_RAW (rm));
2357 if ((req_info & PInfo_SetMethod) != 0) {
2358 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2359 MonoReflectionMethodHandle rm;
2360 if (pproperty->set &&
2361 (((pproperty->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2362 pproperty->set->klass == property_klass)) {
2363 rm = mono_method_get_object_handle (domain, pproperty->set, property_klass, error);
2364 return_if_nok (error);
2365 } else {
2366 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2369 MONO_STRUCT_SETREF_INTERNAL (info, set, MONO_HANDLE_RAW (rm));
2372 * There may be other methods defined for properties, though, it seems they are not exposed
2373 * in the reflection API
2377 static gboolean
2378 add_event_other_methods_to_array (MonoDomain *domain, MonoMethod *m, MonoArrayHandle dest, int i, MonoError *error)
2380 HANDLE_FUNCTION_ENTER ();
2381 error_init (error);
2382 MonoReflectionMethodHandle rm = mono_method_get_object_handle (domain, m, NULL, error);
2383 goto_if_nok (error, leave);
2384 MONO_HANDLE_ARRAY_SETREF (dest, i, rm);
2385 leave:
2386 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2389 void
2390 ves_icall_RuntimeEventInfo_get_event_info (MonoReflectionMonoEventHandle ref_event, MonoEventInfo *info, MonoError *error)
2392 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_event);
2394 MonoClass *klass = MONO_HANDLE_GETVAL (ref_event, klass);
2395 MonoEvent *event = MONO_HANDLE_GETVAL (ref_event, event);
2397 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2398 return_if_nok (error);
2399 MONO_STRUCT_SETREF_INTERNAL (info, reflected_type, MONO_HANDLE_RAW (rt));
2401 rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (event->parent), error);
2402 return_if_nok (error);
2403 MONO_STRUCT_SETREF_INTERNAL (info, declaring_type, MONO_HANDLE_RAW (rt));
2405 MonoStringHandle ev_name = mono_string_new_handle (domain, event->name, error);
2406 return_if_nok (error);
2407 MONO_STRUCT_SETREF_INTERNAL (info, name, MONO_HANDLE_RAW (ev_name));
2409 info->attrs = event->attrs;
2411 MonoReflectionMethodHandle rm;
2412 if (event->add) {
2413 rm = mono_method_get_object_handle (domain, event->add, NULL, error);
2414 return_if_nok (error);
2415 } else {
2416 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2419 MONO_STRUCT_SETREF_INTERNAL (info, add_method, MONO_HANDLE_RAW (rm));
2421 if (event->remove) {
2422 rm = mono_method_get_object_handle (domain, event->remove, NULL, error);
2423 return_if_nok (error);
2424 } else {
2425 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2428 MONO_STRUCT_SETREF_INTERNAL (info, remove_method, MONO_HANDLE_RAW (rm));
2430 if (event->raise) {
2431 rm = mono_method_get_object_handle (domain, event->raise, NULL, error);
2432 return_if_nok (error);
2433 } else {
2434 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2437 MONO_STRUCT_SETREF_INTERNAL (info, raise_method, MONO_HANDLE_RAW (rm));
2439 #ifndef MONO_SMALL_CONFIG
2440 if (event->other) {
2441 int i, n = 0;
2442 while (event->other [n])
2443 n++;
2444 MonoArrayHandle info_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, n, error);
2445 return_if_nok (error);
2447 MONO_STRUCT_SETREF_INTERNAL (info, other_methods, MONO_HANDLE_RAW (info_arr));
2449 for (i = 0; i < n; i++)
2450 if (!add_event_other_methods_to_array (domain, event->other [i], info_arr, i, error))
2451 return;
2453 #endif
2456 static void
2457 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
2459 int i;
2460 MonoClass *ic;
2462 mono_class_setup_interfaces (klass, error);
2463 return_if_nok (error);
2465 int klass_interface_count = m_class_get_interface_count (klass);
2466 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
2467 for (i = 0; i < klass_interface_count; i++) {
2468 ic = klass_interfaces [i];
2469 g_hash_table_insert (ifaces, ic, ic);
2471 collect_interfaces (ic, ifaces, error);
2472 return_if_nok (error);
2476 typedef struct {
2477 MonoArrayHandle iface_array;
2478 MonoGenericContext *context;
2479 MonoError *error;
2480 MonoDomain *domain;
2481 int next_idx;
2482 } FillIfaceArrayData;
2484 static void
2485 fill_iface_array (gpointer key, gpointer value, gpointer user_data)
2487 HANDLE_FUNCTION_ENTER ();
2488 FillIfaceArrayData *data = (FillIfaceArrayData *)user_data;
2489 MonoClass *ic = (MonoClass *)key;
2490 MonoType *ret = m_class_get_byval_arg (ic), *inflated = NULL;
2491 MonoError *error = data->error;
2493 goto_if_nok (error, leave);
2495 if (data->context && mono_class_is_ginst (ic) && mono_class_get_generic_class (ic)->context.class_inst->is_open) {
2496 inflated = ret = mono_class_inflate_generic_type_checked (ret, data->context, error);
2497 goto_if_nok (error, leave);
2500 MonoReflectionTypeHandle rt;
2501 rt = mono_type_get_object_handle (data->domain, ret, error);
2502 goto_if_nok (error, leave);
2504 MONO_HANDLE_ARRAY_SETREF (data->iface_array, data->next_idx, rt);
2505 data->next_idx++;
2507 if (inflated)
2508 mono_metadata_free_type (inflated);
2509 leave:
2510 HANDLE_FUNCTION_RETURN ();
2513 static guint
2514 get_interfaces_hash (gconstpointer v1)
2516 MonoClass *k = (MonoClass*)v1;
2518 return m_class_get_type_token (k);
2521 MonoArrayHandle
2522 ves_icall_RuntimeType_GetInterfaces (MonoReflectionTypeHandle ref_type, MonoError *error)
2524 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2525 MonoClass *klass = mono_class_from_mono_type_internal (type);
2527 GHashTable *iface_hash = g_hash_table_new (get_interfaces_hash, NULL);
2529 MonoGenericContext *context = NULL;
2530 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open) {
2531 context = mono_class_get_context (klass);
2532 klass = mono_class_get_generic_class (klass)->container_class;
2535 for (MonoClass *parent = klass; parent; parent = m_class_get_parent (parent)) {
2536 mono_class_setup_interfaces (parent, error);
2537 goto_if_nok (error, fail);
2538 collect_interfaces (parent, iface_hash, error);
2539 goto_if_nok (error, fail);
2542 MonoDomain *domain;
2543 domain = MONO_HANDLE_DOMAIN (ref_type);
2545 int len;
2546 len = g_hash_table_size (iface_hash);
2547 if (len == 0) {
2548 g_hash_table_destroy (iface_hash);
2549 if (!domain->empty_types) {
2550 domain->empty_types = mono_array_new_cached (domain, mono_defaults.runtimetype_class, 0, error);
2551 goto_if_nok (error, fail);
2553 return MONO_HANDLE_NEW (MonoArray, domain->empty_types);
2556 FillIfaceArrayData data;
2557 data.iface_array = MONO_HANDLE_NEW (MonoArray, mono_array_new_cached (domain, mono_defaults.runtimetype_class, len, error));
2558 goto_if_nok (error, fail);
2559 data.context = context;
2560 data.error = error;
2561 data.domain = domain;
2562 data.next_idx = 0;
2564 g_hash_table_foreach (iface_hash, fill_iface_array, &data);
2566 goto_if_nok (error, fail);
2568 g_hash_table_destroy (iface_hash);
2569 return data.iface_array;
2571 fail:
2572 g_hash_table_destroy (iface_hash);
2573 return NULL_HANDLE_ARRAY;
2576 static gboolean
2577 set_interface_map_data_method_object (MonoDomain *domain, MonoMethod *method, MonoClass *iclass, int ioffset, MonoClass *klass, MonoArrayHandle targets, MonoArrayHandle methods, int i, MonoError *error)
2579 HANDLE_FUNCTION_ENTER ();
2580 error_init (error);
2581 MonoReflectionMethodHandle member = mono_method_get_object_handle (domain, method, iclass, error);
2582 goto_if_nok (error, leave);
2584 MONO_HANDLE_ARRAY_SETREF (methods, i, member);
2586 MONO_HANDLE_ASSIGN (member, mono_method_get_object_handle (domain, m_class_get_vtable (klass) [i + ioffset], klass, error));
2587 goto_if_nok (error, leave);
2589 MONO_HANDLE_ARRAY_SETREF (targets, i, member);
2591 leave:
2592 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2595 void
2596 ves_icall_RuntimeType_GetInterfaceMapData (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_iface, MonoArrayHandleOut targets, MonoArrayHandleOut methods, MonoError *error)
2598 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2599 MonoClass *klass = mono_class_from_mono_type_internal (type);
2600 MonoType *iface = MONO_HANDLE_GETVAL (ref_iface, type);
2601 MonoClass *iclass = mono_class_from_mono_type_internal (iface);
2603 mono_class_init_checked (klass, error);
2604 return_if_nok (error);
2605 mono_class_init_checked (iclass, error);
2606 return_if_nok (error);
2608 mono_class_setup_vtable (klass);
2610 gboolean variance_used;
2611 int ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
2612 if (ioffset == -1)
2613 return;
2615 int len = mono_class_num_methods (iclass);
2616 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2617 MonoArrayHandle targets_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
2618 return_if_nok (error);
2619 MONO_HANDLE_ASSIGN (targets, targets_arr);
2621 MonoArrayHandle methods_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
2622 return_if_nok (error);
2623 MONO_HANDLE_ASSIGN (methods, methods_arr);
2625 MonoMethod* method;
2626 int i = 0;
2627 gpointer iter = NULL;
2628 while ((method = mono_class_get_methods (iclass, &iter))) {
2629 if (!set_interface_map_data_method_object (domain, method, iclass, ioffset, klass, targets, methods, i, error))
2630 return;
2631 i ++;
2635 void
2636 ves_icall_RuntimeType_GetPacking (MonoReflectionTypeHandle ref_type, guint32 *packing, guint32 *size, MonoError *error)
2638 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2639 MonoClass *klass = mono_class_from_mono_type_internal (type);
2641 mono_class_init_checked (klass, error);
2642 return_if_nok (error);
2644 if (image_is_dynamic (m_class_get_image (klass))) {
2645 MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, ref_type);
2646 *packing = MONO_HANDLE_GETVAL (tb, packing_size);
2647 *size = MONO_HANDLE_GETVAL (tb, class_size);
2648 } else {
2649 mono_metadata_packing_from_typedef (m_class_get_image (klass), m_class_get_type_token (klass), packing, size);
2653 MonoReflectionTypeHandle
2654 ves_icall_RuntimeTypeHandle_GetElementType (MonoReflectionTypeHandle ref_type, MonoError *error)
2656 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2657 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2659 if (!type->byref && type->type == MONO_TYPE_SZARRAY) {
2660 return mono_type_get_object_handle (domain, m_class_get_byval_arg (type->data.klass), error);
2663 MonoClass *klass = mono_class_from_mono_type_internal (type);
2664 mono_class_init_checked (klass, error);
2665 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
2667 // GetElementType should only return a type for:
2668 // Array Pointer PassedByRef
2669 if (type->byref)
2670 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2671 else if (m_class_get_element_class (klass) && MONO_CLASS_IS_ARRAY (klass))
2672 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_element_class (klass)), error);
2673 else if (m_class_get_element_class (klass) && type->type == MONO_TYPE_PTR)
2674 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_element_class (klass)), error);
2675 else
2676 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2679 MonoReflectionTypeHandle
2680 ves_icall_RuntimeTypeHandle_GetBaseType (MonoReflectionTypeHandle ref_type, MonoError *error)
2682 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2683 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2685 if (type->byref)
2686 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2688 MonoClass *klass = mono_class_from_mono_type_internal (type);
2689 if (!m_class_get_parent (klass))
2690 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2692 return mono_type_get_object_handle (domain, m_class_get_byval_arg (m_class_get_parent (klass)), error);
2695 MonoBoolean
2696 ves_icall_RuntimeTypeHandle_IsPointer (MonoReflectionTypeHandle ref_type, MonoError *error)
2698 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2699 return type->type == MONO_TYPE_PTR;
2702 MonoBoolean
2703 ves_icall_RuntimeTypeHandle_IsPrimitive (MonoReflectionTypeHandle ref_type, MonoError *error)
2705 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2706 return (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)));
2709 MonoBoolean
2710 ves_icall_RuntimeTypeHandle_HasReferences (MonoReflectionTypeHandle ref_type, MonoError *error)
2712 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2713 MonoClass *klass;
2715 klass = mono_class_from_mono_type_internal (type);
2716 mono_class_init_internal (klass);
2717 return m_class_has_references (klass);
2720 MonoBoolean
2721 ves_icall_RuntimeTypeHandle_IsByRef (MonoReflectionTypeHandle ref_type, MonoError *error)
2723 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2724 return type->byref;
2727 MonoBoolean
2728 ves_icall_RuntimeTypeHandle_IsByRefLike (MonoReflectionTypeHandle ref_type, MonoError *error)
2730 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2731 /* .NET Core says byref types are not IsByRefLike */
2732 if (type->byref)
2733 return FALSE;
2734 MonoClass *klass = mono_class_from_mono_type_internal (type);
2735 return m_class_is_byreflike (klass);
2738 MonoBoolean
2739 ves_icall_RuntimeTypeHandle_IsComObject (MonoReflectionTypeHandle ref_type, MonoError *error)
2741 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2742 MonoClass *klass = mono_class_from_mono_type_internal (type);
2743 mono_class_init_checked (klass, error);
2744 return_val_if_nok (error, FALSE);
2746 return mono_class_is_com_object (klass);
2749 guint32
2750 ves_icall_reflection_get_token (MonoObjectHandle obj, MonoError *error)
2752 error_init (error);
2753 return mono_reflection_get_token_checked (obj, error);
2756 MonoReflectionModuleHandle
2757 ves_icall_RuntimeTypeHandle_GetModule (MonoReflectionTypeHandle type, MonoError *error)
2759 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
2760 MonoType *t = MONO_HANDLE_GETVAL (type, type);
2761 MonoClass *klass = mono_class_from_mono_type_internal (t);
2762 return mono_module_get_object_handle (domain, m_class_get_image (klass), error);
2765 MonoReflectionAssemblyHandle
2766 ves_icall_RuntimeTypeHandle_GetAssembly (MonoReflectionTypeHandle type, MonoError *error)
2768 MonoDomain *domain = mono_domain_get ();
2769 MonoType *t = MONO_HANDLE_GETVAL (type, type);
2770 MonoClass *klass = mono_class_from_mono_type_internal (t);
2771 return mono_assembly_get_object_handle (domain, m_class_get_image (klass)->assembly, error);
2774 MonoReflectionTypeHandle
2775 ves_icall_RuntimeType_get_DeclaringType (MonoReflectionTypeHandle ref_type, MonoError *error)
2777 MonoDomain *domain = mono_domain_get ();
2778 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2779 MonoClass *klass;
2781 if (type->byref)
2782 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2783 if (type->type == MONO_TYPE_VAR) {
2784 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
2785 klass = param ? param->owner.klass : NULL;
2786 } else if (type->type == MONO_TYPE_MVAR) {
2787 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
2788 klass = param ? param->owner.method->klass : NULL;
2789 } else {
2790 klass = m_class_get_nested_in (mono_class_from_mono_type_internal (type));
2793 if (!klass)
2794 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2796 return mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
2799 MonoStringHandle
2800 ves_icall_RuntimeType_get_Name (MonoReflectionTypeHandle reftype, MonoError *error)
2802 MonoDomain *domain = mono_domain_get ();
2803 MonoType *type = MONO_HANDLE_RAW(reftype)->type;
2804 MonoClass *klass = mono_class_from_mono_type_internal (type);
2806 if (type->byref) {
2807 char *n = g_strdup_printf ("%s&", m_class_get_name (klass));
2808 MonoStringHandle res = mono_string_new_handle (domain, n, error);
2810 g_free (n);
2812 return res;
2813 } else {
2814 return mono_string_new_handle (domain, m_class_get_name (klass), error);
2818 MonoStringHandle
2819 ves_icall_RuntimeType_get_Namespace (MonoReflectionTypeHandle type, MonoError *error)
2821 MonoDomain *domain = mono_domain_get ();
2822 MonoClass *klass = mono_class_from_mono_type_handle (type);
2824 MonoClass *klass_nested_in;
2825 while ((klass_nested_in = m_class_get_nested_in (klass)))
2826 klass = klass_nested_in;
2828 if (m_class_get_name_space (klass) [0] == '\0')
2829 return NULL_HANDLE_STRING;
2830 else
2831 return mono_string_new_handle (domain, m_class_get_name_space (klass), error);
2834 gint32
2835 ves_icall_RuntimeTypeHandle_GetArrayRank (MonoReflectionTypeHandle ref_type, MonoError *error)
2837 error_init (error);
2838 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2840 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
2841 mono_error_set_argument (error, "type", "Type must be an array type");
2842 return 0;
2845 MonoClass *klass = mono_class_from_mono_type_internal (type);
2847 return m_class_get_rank (klass);
2850 static MonoArrayHandle
2851 create_type_array (MonoDomain *domain, MonoBoolean runtimeTypeArray, int count, MonoError *error)
2853 return mono_array_new_handle (domain, runtimeTypeArray ? mono_defaults.runtimetype_class : mono_defaults.systemtype_class, count, error);
2856 static gboolean
2857 set_type_object_in_array (MonoDomain *domain, MonoType *type, MonoArrayHandle dest, int i, MonoError *error)
2859 HANDLE_FUNCTION_ENTER();
2860 error_init (error);
2861 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, type, error);
2862 goto_if_nok (error, leave);
2864 MONO_HANDLE_ARRAY_SETREF (dest, i, rt);
2866 leave:
2867 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2870 MonoArrayHandle
2871 ves_icall_RuntimeType_GetGenericArguments (MonoReflectionTypeHandle ref_type, MonoBoolean runtimeTypeArray, MonoError *error)
2873 error_init (error);
2874 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2876 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2877 MonoClass *klass = mono_class_from_mono_type_internal (type);
2879 MonoArrayHandle res = MONO_HANDLE_NEW (MonoArray, NULL);
2880 if (mono_class_is_gtd (klass)) {
2881 MonoGenericContainer *container = mono_class_get_generic_container (klass);
2882 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, container->type_argc, error));
2883 goto_if_nok (error, leave);
2884 for (int i = 0; i < container->type_argc; ++i) {
2885 MonoClass *pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
2887 if (!set_type_object_in_array (domain, m_class_get_byval_arg (pklass), res, i, error))
2888 goto leave;
2891 } else if (mono_class_is_ginst (klass)) {
2892 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2893 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, inst->type_argc, error));
2894 goto_if_nok (error, leave);
2895 for (int i = 0; i < inst->type_argc; ++i) {
2896 if (!set_type_object_in_array (domain, inst->type_argv [i], res, i, error))
2897 goto leave;
2901 leave:
2902 return res;
2905 MonoBoolean
2906 ves_icall_RuntimeTypeHandle_IsGenericTypeDefinition (MonoReflectionTypeHandle ref_type, MonoError *error)
2908 error_init (error);
2910 if (!IS_MONOTYPE (MONO_HANDLE_RAW(ref_type)))
2911 return FALSE;
2913 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2914 if (type->byref)
2915 return FALSE;
2917 MonoClass *klass = mono_class_from_mono_type_internal (type);
2918 return mono_class_is_gtd (klass);
2921 MonoReflectionTypeHandle
2922 ves_icall_RuntimeTypeHandle_GetGenericTypeDefinition_impl (MonoReflectionTypeHandle ref_type, MonoError *error)
2924 error_init (error);
2925 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2927 MonoReflectionTypeHandle ret = MONO_HANDLE_NEW (MonoReflectionType, NULL);
2929 if (type->byref)
2930 goto leave;
2932 MonoClass *klass;
2933 klass = mono_class_from_mono_type_internal (type);
2935 if (mono_class_is_gtd (klass)) {
2936 /* check this one */
2937 MONO_HANDLE_ASSIGN (ret, ref_type);
2938 goto leave;
2940 if (mono_class_is_ginst (klass)) {
2941 MonoClass *generic_class = mono_class_get_generic_class (klass)->container_class;
2943 guint32 ref_info_handle = mono_class_get_ref_info_handle (generic_class);
2945 if (m_class_was_typebuilder (generic_class) && ref_info_handle) {
2946 MonoObjectHandle tb = mono_gchandle_get_target_handle (ref_info_handle);
2947 g_assert (!MONO_HANDLE_IS_NULL (tb));
2948 MONO_HANDLE_ASSIGN (ret, tb);
2949 } else {
2950 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2951 MONO_HANDLE_ASSIGN (ret, mono_type_get_object_handle (domain, m_class_get_byval_arg (generic_class), error));
2954 leave:
2955 return ret;
2958 MonoReflectionTypeHandle
2959 ves_icall_RuntimeType_MakeGenericType (MonoReflectionTypeHandle reftype, MonoArrayHandle type_array, MonoError *error)
2961 error_init (error);
2962 MonoDomain *domain = MONO_HANDLE_DOMAIN (reftype);
2964 g_assert (IS_MONOTYPE_HANDLE (reftype));
2965 MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
2966 mono_class_init_checked (mono_class_from_mono_type_internal (type), error);
2967 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
2969 int count = mono_array_handle_length (type_array);
2970 MonoType **types = g_new0 (MonoType *, count);
2972 MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
2973 for (int i = 0; i < count; i++) {
2974 MONO_HANDLE_ARRAY_GETREF (t, type_array, i);
2975 types [i] = MONO_HANDLE_GETVAL (t, type);
2978 MonoType *geninst = mono_reflection_bind_generic_parameters (reftype, count, types, error);
2979 g_free (types);
2980 if (!geninst) {
2981 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2984 MonoClass *klass = mono_class_from_mono_type_internal (geninst);
2986 /*we might inflate to the GTD*/
2987 if (mono_class_is_ginst (klass) && !mono_verifier_class_is_valid_generic_instantiation (klass)) {
2988 mono_error_set_argument (error, "typeArguments", "Invalid generic arguments");
2989 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2992 return mono_type_get_object_handle (domain, geninst, error);
2995 MonoBoolean
2996 ves_icall_RuntimeTypeHandle_HasInstantiation (MonoReflectionTypeHandle ref_type, MonoError *error)
2998 error_init (error);
2999 MonoClass *klass;
3001 if (!IS_MONOTYPE (MONO_HANDLE_RAW (ref_type)))
3002 return FALSE;
3004 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3005 if (type->byref)
3006 return FALSE;
3008 klass = mono_class_from_mono_type_internal (type);
3009 return mono_class_is_ginst (klass) || mono_class_is_gtd (klass);
3012 gint32
3013 ves_icall_RuntimeType_GetGenericParameterPosition (MonoReflectionTypeHandle ref_type, MonoError *error)
3015 error_init (error);
3016 if (!IS_MONOTYPE_HANDLE (ref_type))
3017 return -1;
3018 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3020 if (is_generic_parameter (type))
3021 return mono_type_get_generic_param_num (type);
3022 return -1;
3025 MonoGenericParamInfo *
3026 ves_icall_RuntimeTypeHandle_GetGenericParameterInfo (MonoReflectionTypeHandle ref_type, MonoError *error)
3028 error_init (error);
3029 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3030 return mono_generic_param_info (type->data.generic_param);
3033 MonoBoolean
3034 ves_icall_RuntimeTypeHandle_IsGenericVariable (MonoReflectionTypeHandle ref_type, MonoError *error)
3036 MonoType *type = MONO_HANDLE_GETVAL(ref_type, type);
3037 return is_generic_parameter (type);
3040 MonoReflectionMethodHandle
3041 ves_icall_RuntimeType_GetCorrespondingInflatedMethod (MonoReflectionTypeHandle ref_type,
3042 MonoReflectionMethodHandle generic,
3043 MonoError *error)
3045 error_init (error);
3046 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
3047 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3048 MonoClass *klass = mono_class_from_mono_type_internal (type);
3050 mono_class_init_checked (klass, error);
3051 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3053 MonoMethod *generic_method = MONO_HANDLE_GETVAL (generic, method);
3055 MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3056 MonoMethod *method;
3057 gpointer iter = NULL;
3058 while ((method = mono_class_get_methods (klass, &iter))) {
3059 if (method->token == generic_method->token) {
3060 ret = mono_method_get_object_handle (domain, method, klass, error);
3061 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3065 return ret;
3068 MonoReflectionMethodHandle
3069 ves_icall_RuntimeType_get_DeclaringMethod (MonoReflectionTypeHandle ref_type, MonoError *error)
3071 error_init (error);
3072 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3073 MonoReflectionMethodHandle ret = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
3075 if (type->byref || (type->type != MONO_TYPE_MVAR && type->type != MONO_TYPE_VAR)) {
3076 mono_error_set_invalid_operation (error, "DeclaringMethod can only be used on generic arguments");
3077 goto leave;
3079 if (type->type == MONO_TYPE_VAR)
3080 goto leave;
3082 MonoMethod *method;
3083 method = mono_type_get_generic_param_owner (type)->owner.method;
3084 g_assert (method);
3086 MonoDomain *domain;
3087 domain = MONO_HANDLE_DOMAIN (ref_type);
3089 MONO_HANDLE_ASSIGN (ret, mono_method_get_object_handle (domain, method, method->klass, error));
3090 leave:
3091 return ret;
3094 MonoBoolean
3095 ves_icall_System_RuntimeType_IsTypeExportedToWindowsRuntime (MonoError *error)
3097 error_init (error);
3098 mono_error_set_not_implemented (error, "%s", "System.RuntimeType.IsTypeExportedToWindowsRuntime");
3099 return FALSE;
3102 MonoBoolean
3103 ves_icall_System_RuntimeType_IsWindowsRuntimeObjectType (MonoError *error)
3105 error_init (error);
3106 mono_error_set_not_implemented (error, "%s", "System.RuntimeType.IsWindowsRuntimeObjectType");
3107 return FALSE;
3110 void
3111 ves_icall_RuntimeMethodInfo_GetPInvoke (MonoReflectionMethodHandle ref_method, int* flags, MonoStringHandleOut entry_point, MonoStringHandleOut dll_name, MonoError *error)
3113 MonoDomain *domain = mono_domain_get ();
3114 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3115 MonoImage *image = m_class_get_image (method->klass);
3116 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
3117 MonoTableInfo *tables = image->tables;
3118 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3119 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3120 guint32 im_cols [MONO_IMPLMAP_SIZE];
3121 guint32 scope_token;
3122 const char *import = NULL;
3123 const char *scope = NULL;
3125 error_init (error);
3127 if (image_is_dynamic (image)) {
3128 MonoReflectionMethodAux *method_aux =
3129 (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)image)->method_aux_hash, method);
3130 if (method_aux) {
3131 import = method_aux->dllentry;
3132 scope = method_aux->dll;
3135 if (!import || !scope) {
3136 mono_error_set_argument (error, "method", "System.Refleciton.Emit method with invalid pinvoke information");
3137 return;
3140 else {
3141 if (piinfo->implmap_idx) {
3142 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3144 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
3145 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
3146 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
3147 scope = mono_metadata_string_heap (image, scope_token);
3151 *flags = piinfo->piflags;
3152 MONO_HANDLE_ASSIGN (entry_point, mono_string_new_handle (domain, import, error));
3153 return_if_nok (error);
3154 MONO_HANDLE_ASSIGN (dll_name, mono_string_new_handle (domain, scope, error));
3157 MonoReflectionMethodHandle
3158 ves_icall_RuntimeMethodInfo_GetGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *error)
3160 error_init (error);
3161 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3163 if (method->is_generic)
3164 return ref_method;
3166 if (!method->is_inflated)
3167 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3169 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
3171 MonoMethod *result = imethod->declaring;
3172 /* Not a generic method. */
3173 if (!result->is_generic)
3174 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3176 if (image_is_dynamic (m_class_get_image (method->klass))) {
3177 MonoDynamicImage *image = (MonoDynamicImage*)m_class_get_image (method->klass);
3180 * FIXME: Why is this stuff needed at all ? Why can't the code below work for
3181 * the dynamic case as well ?
3183 mono_image_lock ((MonoImage*)image);
3184 MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, (MonoReflectionMethod*)mono_g_hash_table_lookup (image->generic_def_objects, imethod));
3185 mono_image_unlock ((MonoImage*)image);
3187 if (!MONO_HANDLE_IS_NULL (res))
3188 return res;
3191 if (imethod->context.class_inst) {
3192 MonoClass *klass = ((MonoMethod *) imethod)->klass;
3193 /*Generic methods gets the context of the GTD.*/
3194 if (mono_class_get_context (klass)) {
3195 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
3196 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3200 return mono_method_get_object_handle (MONO_HANDLE_DOMAIN (ref_method), result, NULL, error);
3203 MonoBoolean
3204 ves_icall_RuntimeMethodInfo_get_IsGenericMethod (MonoReflectionMethodHandle ref_method, MonoError *erro)
3206 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3207 return mono_method_signature_internal (method)->generic_param_count != 0;
3210 MonoBoolean
3211 ves_icall_RuntimeMethodInfo_get_IsGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *Error)
3213 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3214 return method->is_generic;
3217 static gboolean
3218 set_array_generic_argument_handle_inflated (MonoDomain *domain, MonoGenericInst *inst, int i, MonoArrayHandle arr, MonoError *error)
3220 HANDLE_FUNCTION_ENTER ();
3221 error_init (error);
3222 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, inst->type_argv [i], error);
3223 goto_if_nok (error, leave);
3224 MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3225 leave:
3226 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3229 static gboolean
3230 set_array_generic_argument_handle_gparam (MonoDomain *domain, MonoGenericContainer *container, int i, MonoArrayHandle arr, MonoError *error)
3232 HANDLE_FUNCTION_ENTER ();
3233 error_init (error);
3234 MonoGenericParam *param = mono_generic_container_get_param (container, i);
3235 MonoClass *pklass = mono_class_create_generic_parameter (param);
3236 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (pklass), error);
3237 goto_if_nok (error, leave);
3238 MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3239 leave:
3240 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3243 MonoArrayHandle
3244 ves_icall_RuntimeMethodInfo_GetGenericArguments (MonoReflectionMethodHandle ref_method, MonoError *error)
3246 error_init (error);
3247 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_method);
3248 MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3250 if (method->is_inflated) {
3251 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
3253 if (inst) {
3254 int count = inst->type_argc;
3255 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3256 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3258 for (int i = 0; i < count; i++) {
3259 if (!set_array_generic_argument_handle_inflated (domain, inst, i, res, error))
3260 break;
3262 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3263 return res;
3267 int count = mono_method_signature_internal (method)->generic_param_count;
3268 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3269 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3271 MonoGenericContainer *container = mono_method_get_generic_container (method);
3272 for (int i = 0; i < count; i++) {
3273 if (!set_array_generic_argument_handle_gparam (domain, container, i, res, error))
3274 break;
3276 return_val_if_nok (error, NULL_HANDLE_ARRAY);
3277 return res;
3280 MonoObject *
3281 ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this_arg, MonoArray *params, MonoException **exc)
3283 ERROR_DECL (error);
3285 * Invoke from reflection is supposed to always be a virtual call (the API
3286 * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
3287 * greater flexibility.
3289 MonoMethod *m = method->method;
3290 MonoMethodSignature *sig = mono_method_signature_internal (m);
3291 MonoImage *image;
3292 int pcount;
3293 void *obj = this_arg;
3295 *exc = NULL;
3297 if (mono_security_core_clr_enabled () &&
3298 !mono_security_core_clr_ensure_reflection_access_method (m, error)) {
3299 mono_error_set_pending_exception (error);
3300 return NULL;
3303 if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
3304 if (!mono_class_vtable_checked (mono_object_domain (method), m->klass, error)) {
3305 mono_error_cleanup (error); /* FIXME does this make sense? */
3306 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_class_get_exception_for_failure (m->klass));
3307 return NULL;
3310 if (this_arg) {
3311 if (!mono_object_isinst_checked (this_arg, m->klass, error)) {
3312 if (!is_ok (error)) {
3313 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_error_convert_to_exception (error));
3314 return NULL;
3316 char *this_name = mono_type_get_full_name (mono_object_class (this_arg));
3317 char *target_name = mono_type_get_full_name (m->klass);
3318 char *msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
3319 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", msg));
3320 g_free (msg);
3321 g_free (target_name);
3322 g_free (this_name);
3323 return NULL;
3325 m = mono_object_get_virtual_method_internal (this_arg, m);
3326 /* must pass the pointer to the value for valuetype methods */
3327 if (m_class_is_valuetype (m->klass))
3328 obj = mono_object_unbox_internal (this_arg);
3329 } else if (strcmp (m->name, ".ctor") && !m->wrapper_type) {
3330 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."));
3331 return NULL;
3335 if (sig->ret->byref) {
3336 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"));
3337 return NULL;
3340 pcount = params? mono_array_length_internal (params): 0;
3341 if (pcount != sig->param_count) {
3342 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetParameterCountException"));
3343 return NULL;
3346 if (mono_class_is_abstract (m->klass) && !strcmp (m->name, ".ctor") && !this_arg) {
3347 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."));
3348 return NULL;
3351 image = m_class_get_image (m->klass);
3352 if (mono_asmctx_get_kind (&image->assembly->context) == MONO_ASMCTX_REFONLY) {
3353 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."));
3354 return NULL;
3357 if (image_is_dynamic (image) && !((MonoDynamicImage*)image)->run) {
3358 mono_gc_wbarrier_generic_store_internal (exc, (MonoObject*) mono_get_exception_not_supported ("Cannot invoke a method in a dynamic assembly without run access."));
3359 return NULL;
3362 if (m_class_get_rank (m->klass) && !strcmp (m->name, ".ctor")) {
3363 MonoArray *arr;
3364 int i;
3365 uintptr_t *lengths;
3366 intptr_t *lower_bounds;
3367 pcount = mono_array_length_internal (params);
3368 lengths = g_newa (uintptr_t, pcount);
3369 /* Note: the synthetized array .ctors have int32 as argument type */
3370 for (i = 0; i < pcount; ++i)
3371 lengths [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, i) + sizeof (MonoObject));
3373 if (m_class_get_rank (m->klass) == 1 && sig->param_count == 2 && m_class_get_rank (m_class_get_element_class (m->klass))) {
3374 /* This is a ctor for jagged arrays. MS creates an array of arrays. */
3375 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, error);
3376 if (!is_ok (error)) {
3377 mono_error_set_pending_exception (error);
3378 return NULL;
3381 for (i = 0; i < mono_array_length_internal (arr); ++i) {
3382 MonoArray *subarray = mono_array_new_full_checked (mono_object_domain (params), m_class_get_element_class (m->klass), &lengths [1], NULL, error);
3383 if (!is_ok (error)) {
3384 mono_error_set_pending_exception (error);
3385 return NULL;
3387 mono_array_setref_fast (arr, i, subarray);
3389 return (MonoObject*)arr;
3392 if (m_class_get_rank (m->klass) == pcount) {
3393 /* Only lengths provided. */
3394 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, error);
3395 if (!is_ok (error)) {
3396 mono_error_set_pending_exception (error);
3397 return NULL;
3400 return (MonoObject*)arr;
3401 } else {
3402 g_assert (pcount == (m_class_get_rank (m->klass) * 2));
3403 /* The arguments are lower-bound-length pairs */
3404 lower_bounds = (intptr_t *)g_alloca (sizeof (intptr_t) * pcount);
3406 for (i = 0; i < pcount / 2; ++i) {
3407 lower_bounds [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, (i * 2)) + sizeof (MonoObject));
3408 lengths [i] = *(int32_t*) ((char*)mono_array_get_internal (params, gpointer, (i * 2) + 1) + sizeof (MonoObject));
3411 arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, lower_bounds, error);
3412 if (!is_ok (error)) {
3413 mono_error_set_pending_exception (error);
3414 return NULL;
3417 return (MonoObject*)arr;
3420 MonoObject *result = mono_runtime_invoke_array_checked (m, obj, params, error);
3421 mono_error_set_pending_exception (error);
3422 return result;
3425 #ifndef DISABLE_REMOTING
3426 static void
3427 internal_execute_field_getter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs, MonoError *error)
3429 error_init (error);
3430 MonoArray *out_args;
3431 MonoClass *k = mono_object_class (this_arg);
3432 MonoString *name;
3433 char *str;
3435 /* If this is a proxy, then it must be a CBO */
3436 if (mono_class_is_transparent_proxy (k)) {
3437 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
3438 this_arg = tp->rp->unwrapped_server;
3439 g_assert (this_arg);
3440 k = mono_object_class (this_arg);
3443 name = mono_array_get_internal (params, MonoString *, 1);
3444 str = mono_string_to_utf8_checked_internal (name, error);
3445 return_if_nok (error);
3447 do {
3448 MonoClassField* field = mono_class_get_field_from_name_full (k, str, NULL);
3449 if (field) {
3450 g_free (str);
3451 MonoClass *field_klass = mono_class_from_mono_type_internal (field->type);
3452 MonoObject *result;
3453 if (m_class_is_valuetype (field_klass)) {
3454 result = mono_value_box_checked (domain, field_klass, (char *)this_arg + field->offset, error);
3455 return_if_nok (error);
3456 } else
3457 result = (MonoObject *)*((gpointer *)((char *)this_arg + field->offset));
3459 out_args = mono_array_new_checked (domain, mono_defaults.object_class, 1, error);
3460 return_if_nok (error);
3461 mono_gc_wbarrier_generic_store_internal (outArgs, (MonoObject*) out_args);
3462 mono_array_setref_internal (out_args, 0, result);
3463 return;
3465 k = m_class_get_parent (k);
3466 } while (k);
3468 g_free (str);
3469 g_assert_not_reached ();
3472 static void
3473 internal_execute_field_setter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs, MonoError *error)
3475 error_init (error);
3476 MonoArray *out_args;
3477 MonoClass *k = mono_object_class (this_arg);
3478 MonoString *name;
3479 guint32 size;
3480 gint32 align;
3481 char *str;
3483 /* If this is a proxy, then it must be a CBO */
3484 if (mono_class_is_transparent_proxy (k)) {
3485 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
3486 this_arg = tp->rp->unwrapped_server;
3487 g_assert (this_arg);
3488 k = mono_object_class (this_arg);
3491 name = mono_array_get_internal (params, MonoString *, 1);
3492 str = mono_string_to_utf8_checked_internal (name, error);
3493 return_if_nok (error);
3495 do {
3496 MonoClassField* field = mono_class_get_field_from_name_full (k, str, NULL);
3497 if (field) {
3498 g_free (str);
3499 MonoClass *field_klass = mono_class_from_mono_type_internal (field->type);
3500 MonoObject *val = (MonoObject *)mono_array_get_internal (params, gpointer, 2);
3502 if (m_class_is_valuetype (field_klass)) {
3503 size = mono_type_size (field->type, &align);
3504 g_assert (size == mono_class_value_size (field_klass, NULL));
3505 mono_gc_wbarrier_value_copy_internal ((char *)this_arg + field->offset, (char*)val + sizeof (MonoObject), 1, field_klass);
3506 } else {
3507 mono_gc_wbarrier_set_field_internal (this_arg, (char*)this_arg + field->offset, val);
3510 out_args = mono_array_new_checked (domain, mono_defaults.object_class, 0, error);
3511 return_if_nok (error);
3512 mono_gc_wbarrier_generic_store_internal (outArgs, (MonoObject*) out_args);
3513 return;
3516 k = m_class_get_parent (k);
3517 } while (k);
3519 g_free (str);
3520 g_assert_not_reached ();
3523 MonoObject *
3524 ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs)
3526 ERROR_DECL (error);
3527 MonoDomain *domain = mono_object_domain (method);
3528 MonoMethod *m = method->method;
3529 MonoMethodSignature *sig = mono_method_signature_internal (m);
3530 MonoArray *out_args;
3531 MonoObject *result;
3532 int i, j, outarg_count = 0;
3534 if (m->klass == mono_defaults.object_class) {
3535 if (!strcmp (m->name, "FieldGetter")) {
3536 internal_execute_field_getter (domain, this_arg, params, outArgs, error);
3537 mono_error_set_pending_exception (error);
3538 return NULL;
3539 } else if (!strcmp (m->name, "FieldSetter")) {
3540 internal_execute_field_setter (domain, this_arg, params, outArgs, error);
3541 mono_error_set_pending_exception (error);
3542 return NULL;
3546 for (i = 0; i < mono_array_length_internal (params); i++) {
3547 if (sig->params [i]->byref)
3548 outarg_count++;
3551 out_args = mono_array_new_checked (domain, mono_defaults.object_class, outarg_count, error);
3552 if (mono_error_set_pending_exception (error))
3553 return NULL;
3555 /* handle constructors only for objects already allocated */
3556 if (!strcmp (method->method->name, ".ctor"))
3557 g_assert (this_arg);
3559 /* This can be called only on MBR objects, so no need to unbox for valuetypes. */
3560 g_assert (!m_class_is_valuetype (method->method->klass));
3561 result = mono_runtime_invoke_array_checked (method->method, this_arg, params, error);
3562 if (mono_error_set_pending_exception (error))
3563 return NULL;
3565 for (i = 0, j = 0; i < mono_array_length_internal (params); i++) {
3566 if (sig->params [i]->byref) {
3567 gpointer arg;
3568 arg = mono_array_get_internal (params, gpointer, i);
3569 mono_array_setref_internal (out_args, j, arg);
3570 j++;
3574 mono_gc_wbarrier_generic_store_internal (outArgs, (MonoObject*) out_args);
3576 return result;
3578 #endif
3580 static guint64
3581 read_enum_value (const char *mem, int type)
3583 switch (type) {
3584 case MONO_TYPE_BOOLEAN:
3585 case MONO_TYPE_U1:
3586 return *(guint8*)mem;
3587 case MONO_TYPE_I1:
3588 return *(gint8*)mem;
3589 case MONO_TYPE_CHAR:
3590 case MONO_TYPE_U2:
3591 return read16 (mem);
3592 case MONO_TYPE_I2:
3593 return (gint16) read16 (mem);
3594 case MONO_TYPE_U4:
3595 return read32 (mem);
3596 case MONO_TYPE_I4:
3597 return (gint32) read32 (mem);
3598 case MONO_TYPE_U8:
3599 case MONO_TYPE_I8:
3600 return read64 (mem);
3601 default:
3602 g_assert_not_reached ();
3604 return 0;
3607 static void
3608 write_enum_value (void *mem, int type, guint64 value)
3610 switch (type) {
3611 case MONO_TYPE_U1:
3612 case MONO_TYPE_I1: {
3613 guint8 *p = (guint8*)mem;
3614 *p = value;
3615 break;
3617 case MONO_TYPE_U2:
3618 case MONO_TYPE_I2:
3619 case MONO_TYPE_CHAR: {
3620 guint16 *p = (guint16 *)mem;
3621 *p = value;
3622 break;
3624 case MONO_TYPE_U4:
3625 case MONO_TYPE_I4: {
3626 guint32 *p = (guint32 *)mem;
3627 *p = value;
3628 break;
3630 case MONO_TYPE_U8:
3631 case MONO_TYPE_I8: {
3632 guint64 *p = (guint64 *)mem;
3633 *p = value;
3634 break;
3636 default:
3637 g_assert_not_reached ();
3639 return;
3642 MonoObjectHandle
3643 ves_icall_System_Enum_ToObject (MonoReflectionTypeHandle enumType, guint64 value, MonoError *error)
3645 MonoDomain *domain;
3646 MonoClass *enumc;
3647 MonoObjectHandle resultHandle;
3648 MonoType *etype;
3650 domain = MONO_HANDLE_DOMAIN (enumType);
3651 enumc = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (enumType, type));
3653 mono_class_init_checked (enumc, error);
3654 goto_if_nok (error, return_null);
3656 etype = mono_class_enum_basetype_internal (enumc);
3658 resultHandle = mono_object_new_handle (domain, enumc, error);
3659 goto_if_nok (error, return_null);
3661 write_enum_value (mono_handle_unbox_unsafe (resultHandle), etype->type, value);
3663 return resultHandle;
3665 return_null:
3666 return MONO_HANDLE_NEW (MonoObject, NULL);
3669 MonoBoolean
3670 ves_icall_System_Enum_InternalHasFlag (MonoObjectHandle a, MonoObjectHandle b, MonoError *error)
3672 int size = mono_class_value_size (mono_handle_class (a), NULL);
3673 guint64 a_val = 0, b_val = 0;
3675 memcpy (&a_val, mono_handle_unbox_unsafe (a), size);
3676 memcpy (&b_val, mono_handle_unbox_unsafe (b), size);
3678 return (a_val & b_val) == b_val;
3681 MonoObjectHandle
3682 ves_icall_System_Enum_get_value (MonoObjectHandle ehandle, MonoError *error)
3684 MonoObjectHandle resultHandle;
3685 MonoClass *enumc;
3686 int size;
3688 goto_if (MONO_HANDLE_IS_NULL (ehandle), return_null);
3690 g_assert (m_class_is_enumtype (mono_handle_class (ehandle)));
3692 enumc = mono_class_from_mono_type_internal (mono_class_enum_basetype_internal (mono_handle_class (ehandle)));
3694 resultHandle = mono_object_new_handle (MONO_HANDLE_DOMAIN (ehandle), enumc, error);
3695 goto_if_nok (error, return_null);
3696 size = mono_class_value_size (enumc, NULL);
3698 memcpy (mono_handle_unbox_unsafe (resultHandle), mono_handle_unbox_unsafe (ehandle), size);
3700 return resultHandle;
3701 return_null:
3702 return MONO_HANDLE_NEW (MonoObject, NULL);
3705 MonoReflectionTypeHandle
3706 ves_icall_System_Enum_get_underlying_type (MonoReflectionTypeHandle type, MonoError *error)
3708 MonoType *etype;
3709 MonoClass *klass;
3711 klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
3712 mono_class_init_checked (klass, error);
3713 goto_if_nok (error, return_null);
3715 etype = mono_class_enum_basetype_internal (klass);
3716 if (!etype) {
3717 mono_error_set_argument (error, "enumType", "Type provided must be an Enum.");
3718 goto return_null;
3721 return mono_type_get_object_handle (MONO_HANDLE_DOMAIN (type), etype, error);
3723 return_null:
3724 return MONO_HANDLE_NEW (MonoReflectionType, NULL);
3728 ves_icall_System_Enum_compare_value_to (MonoObjectHandle enumHandle, MonoObjectHandle otherHandle, MonoError *error)
3730 if (MONO_HANDLE_IS_NULL (otherHandle))
3731 return 1;
3733 if (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass != MONO_HANDLE_GETVAL (otherHandle, vtable)->klass)
3734 return 2;
3736 gpointer tdata = mono_handle_unbox_unsafe (enumHandle);
3737 gpointer odata = mono_handle_unbox_unsafe (otherHandle);
3738 MonoType *basetype = mono_class_enum_basetype_internal (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass);
3739 g_assert (basetype);
3741 #define COMPARE_ENUM_VALUES(ENUM_TYPE) do { \
3742 ENUM_TYPE me = *((ENUM_TYPE*)tdata); \
3743 ENUM_TYPE other = *((ENUM_TYPE*)odata); \
3744 if (me == other) \
3745 return 0; \
3746 return me > other ? 1 : -1; \
3747 } while (0)
3749 switch (basetype->type) {
3750 case MONO_TYPE_U1:
3751 COMPARE_ENUM_VALUES (guint8);
3752 case MONO_TYPE_I1:
3753 COMPARE_ENUM_VALUES (gint8);
3754 case MONO_TYPE_CHAR:
3755 case MONO_TYPE_U2:
3756 COMPARE_ENUM_VALUES (guint16);
3757 case MONO_TYPE_I2:
3758 COMPARE_ENUM_VALUES (gint16);
3759 case MONO_TYPE_U4:
3760 COMPARE_ENUM_VALUES (guint32);
3761 case MONO_TYPE_I4:
3762 COMPARE_ENUM_VALUES (gint32);
3763 case MONO_TYPE_U8:
3764 COMPARE_ENUM_VALUES (guint64);
3765 case MONO_TYPE_I8:
3766 COMPARE_ENUM_VALUES (gint64);
3768 #undef COMPARE_ENUM_VALUES
3769 /* indicates that the enum was of an unsupported underlying type */
3770 return 3;
3774 ves_icall_System_Enum_get_hashcode (MonoObjectHandle enumHandle, MonoError *error)
3776 gpointer data = mono_handle_unbox_unsafe (enumHandle);
3777 MonoType *basetype = mono_class_enum_basetype_internal (MONO_HANDLE_GETVAL (enumHandle, vtable)->klass);
3778 g_assert (basetype);
3780 switch (basetype->type) {
3781 case MONO_TYPE_I1: {
3782 gint8 value = *((gint8*)data);
3783 return ((int)value ^ (int)value << 8);
3785 case MONO_TYPE_U1:
3786 return *((guint8*)data);
3787 case MONO_TYPE_CHAR:
3788 case MONO_TYPE_U2:
3789 return *((guint16*)data);
3791 case MONO_TYPE_I2: {
3792 gint16 value = *((gint16*)data);
3793 return ((int)(guint16)value | (((int)value) << 16));
3795 case MONO_TYPE_U4:
3796 return *((guint32*)data);
3797 case MONO_TYPE_I4:
3798 return *((gint32*)data);
3799 case MONO_TYPE_U8:
3800 case MONO_TYPE_I8: {
3801 gint64 value = *((gint64*)data);
3802 return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
3804 default:
3805 g_error ("Implement type 0x%02x in get_hashcode", basetype->type);
3807 return 0;
3810 static void
3811 get_enum_field (MonoDomain *domain, MonoArrayHandle names, MonoArrayHandle values, int base_type, MonoClassField *field, guint* j, guint64 *previous_value, gboolean *sorted, MonoError *error)
3813 error_init (error);
3814 HANDLE_FUNCTION_ENTER();
3815 guint64 field_value;
3816 const char *p;
3817 MonoTypeEnum def_type;
3819 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3820 goto leave;
3821 if (strcmp ("value__", mono_field_get_name (field)) == 0)
3822 goto leave;
3823 if (mono_field_is_deleted (field))
3824 goto leave;
3825 MonoStringHandle name;
3826 name = mono_string_new_handle (domain, mono_field_get_name (field), error);
3827 goto_if_nok (error, leave);
3828 MONO_HANDLE_ARRAY_SETREF (names, *j, name);
3830 p = mono_class_get_field_default_value (field, &def_type);
3831 /* len = */ mono_metadata_decode_blob_size (p, &p);
3833 field_value = read_enum_value (p, base_type);
3834 MONO_HANDLE_ARRAY_SETVAL (values, guint64, *j, field_value);
3836 if (*previous_value > field_value)
3837 *sorted = FALSE;
3839 *previous_value = field_value;
3840 (*j)++;
3841 leave:
3842 HANDLE_FUNCTION_RETURN();
3845 MonoBoolean
3846 ves_icall_System_Enum_GetEnumValuesAndNames (MonoReflectionTypeHandle type, MonoArrayHandleOut values, MonoArrayHandleOut names, MonoError *error)
3848 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
3849 MonoClass *enumc = mono_class_from_mono_type_internal (MONO_HANDLE_RAW(type)->type);
3850 guint j = 0, nvalues;
3851 gpointer iter;
3852 MonoClassField *field;
3853 int base_type;
3854 guint64 previous_value = 0;
3855 gboolean sorted = TRUE;
3857 error_init (error);
3858 mono_class_init_checked (enumc, error);
3859 return_val_if_nok (error, FALSE);
3861 if (!m_class_is_enumtype (enumc)) {
3862 mono_error_set_argument (error, "enumType", "Type provided must be an Enum.");
3863 return TRUE;
3866 base_type = mono_class_enum_basetype_internal (enumc)->type;
3868 nvalues = mono_class_num_fields (enumc) > 0 ? mono_class_num_fields (enumc) - 1 : 0;
3869 MONO_HANDLE_ASSIGN(names, mono_array_new_handle (domain, mono_defaults.string_class, nvalues, error));
3870 return_val_if_nok (error, FALSE);
3871 MONO_HANDLE_ASSIGN(values, mono_array_new_handle (domain, mono_defaults.uint64_class, nvalues, error));
3872 return_val_if_nok (error, FALSE);
3874 iter = NULL;
3875 while ((field = mono_class_get_fields_internal (enumc, &iter))) {
3876 get_enum_field(domain, names, values, base_type, field, &j, &previous_value, &sorted, error);
3877 if (!is_ok (error))
3878 break;
3880 return_val_if_nok (error, FALSE);
3882 return sorted;
3885 enum {
3886 BFLAGS_IgnoreCase = 1,
3887 BFLAGS_DeclaredOnly = 2,
3888 BFLAGS_Instance = 4,
3889 BFLAGS_Static = 8,
3890 BFLAGS_Public = 0x10,
3891 BFLAGS_NonPublic = 0x20,
3892 BFLAGS_FlattenHierarchy = 0x40,
3893 BFLAGS_InvokeMethod = 0x100,
3894 BFLAGS_CreateInstance = 0x200,
3895 BFLAGS_GetField = 0x400,
3896 BFLAGS_SetField = 0x800,
3897 BFLAGS_GetProperty = 0x1000,
3898 BFLAGS_SetProperty = 0x2000,
3899 BFLAGS_ExactBinding = 0x10000,
3900 BFLAGS_SuppressChangeType = 0x20000,
3901 BFLAGS_OptionalParamBinding = 0x40000
3904 enum {
3905 MLISTTYPE_All = 0,
3906 MLISTTYPE_CaseSensitive = 1,
3907 MLISTTYPE_CaseInsensitive = 2,
3908 MLISTTYPE_HandleToInfo = 3
3911 GPtrArray*
3912 ves_icall_RuntimeType_GetFields_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 bflags, guint32 mlisttype, MonoError *error)
3914 error_init (error);
3915 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3917 if (type->byref) {
3918 return g_ptr_array_new ();
3921 int (*compare_func) (const char *s1, const char *s2) = NULL;
3922 compare_func = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
3924 MonoClass *startklass, *klass;
3925 klass = startklass = mono_class_from_mono_type_internal (type);
3927 GPtrArray *ptr_array = g_ptr_array_sized_new (16);
3929 handle_parent:
3930 if (mono_class_has_failure (klass)) {
3931 mono_error_set_for_class_failure (error, klass);
3932 goto fail;
3935 MonoClassField *field;
3936 gpointer iter;
3937 iter = NULL;
3938 while ((field = mono_class_get_fields_lazy (klass, &iter))) {
3939 guint32 flags = mono_field_get_flags (field);
3940 int match = 0;
3941 if (mono_field_is_deleted_with_flags (field, flags))
3942 continue;
3943 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
3944 if (bflags & BFLAGS_Public)
3945 match++;
3946 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
3947 if (bflags & BFLAGS_NonPublic) {
3948 match++;
3951 if (!match)
3952 continue;
3953 match = 0;
3954 if (flags & FIELD_ATTRIBUTE_STATIC) {
3955 if (bflags & BFLAGS_Static)
3956 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3957 match++;
3958 } else {
3959 if (bflags & BFLAGS_Instance)
3960 match++;
3963 if (!match)
3964 continue;
3966 if (((mlisttype != MLISTTYPE_All) && (utf8_name != NULL)) && compare_func (mono_field_get_name (field), utf8_name))
3967 continue;
3969 g_ptr_array_add (ptr_array, field);
3971 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
3972 goto handle_parent;
3974 return ptr_array;
3976 fail:
3977 g_ptr_array_free (ptr_array, TRUE);
3978 return NULL;
3981 static gboolean
3982 method_nonpublic (MonoMethod* method, gboolean start_klass)
3984 switch (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) {
3985 case METHOD_ATTRIBUTE_ASSEM:
3986 return (start_klass || mono_defaults.generic_ilist_class);
3987 case METHOD_ATTRIBUTE_PRIVATE:
3988 return start_klass;
3989 case METHOD_ATTRIBUTE_PUBLIC:
3990 return FALSE;
3991 default:
3992 return TRUE;
3996 GPtrArray*
3997 mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, guint32 mlisttype, gboolean allow_ctors, MonoError *error)
3999 GPtrArray *array;
4000 MonoClass *startklass;
4001 MonoMethod *method;
4002 gpointer iter;
4003 int match, nslots;
4004 /*FIXME, use MonoBitSet*/
4005 guint32 method_slots_default [8];
4006 guint32 *method_slots = NULL;
4007 int (*compare_func) (const char *s1, const char *s2) = NULL;
4009 array = g_ptr_array_new ();
4010 startklass = klass;
4011 error_init (error);
4013 compare_func = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
4015 /* An optimization for calls made from Delegate:CreateDelegate () */
4016 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))) {
4017 method = mono_get_delegate_invoke_internal (klass);
4018 g_assert (method);
4020 g_ptr_array_add (array, method);
4021 return array;
4024 mono_class_setup_methods (klass);
4025 mono_class_setup_vtable (klass);
4026 if (mono_class_has_failure (klass))
4027 goto loader_error;
4029 if (is_generic_parameter (m_class_get_byval_arg (klass)))
4030 nslots = mono_class_get_vtable_size (m_class_get_parent (klass));
4031 else
4032 nslots = MONO_CLASS_IS_INTERFACE_INTERNAL (klass) ? mono_class_num_methods (klass) : mono_class_get_vtable_size (klass);
4033 if (nslots >= sizeof (method_slots_default) * 8) {
4034 method_slots = g_new0 (guint32, nslots / 32 + 1);
4035 } else {
4036 method_slots = method_slots_default;
4037 memset (method_slots, 0, sizeof (method_slots_default));
4039 handle_parent:
4040 mono_class_setup_methods (klass);
4041 mono_class_setup_vtable (klass);
4042 if (mono_class_has_failure (klass))
4043 goto loader_error;
4045 iter = NULL;
4046 while ((method = mono_class_get_methods (klass, &iter))) {
4047 match = 0;
4048 if (method->slot != -1) {
4049 g_assert (method->slot < nslots);
4050 if (method_slots [method->slot >> 5] & (1 << (method->slot & 0x1f)))
4051 continue;
4052 if (!(method->flags & METHOD_ATTRIBUTE_NEW_SLOT))
4053 method_slots [method->slot >> 5] |= 1 << (method->slot & 0x1f);
4056 if (!allow_ctors && method->name [0] == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0))
4057 continue;
4058 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4059 if (bflags & BFLAGS_Public)
4060 match++;
4061 } else if ((bflags & BFLAGS_NonPublic) && method_nonpublic (method, (klass == startklass))) {
4062 match++;
4064 if (!match)
4065 continue;
4066 match = 0;
4067 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4068 if (bflags & BFLAGS_Static)
4069 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4070 match++;
4071 } else {
4072 if (bflags & BFLAGS_Instance)
4073 match++;
4076 if (!match)
4077 continue;
4079 if ((mlisttype != MLISTTYPE_All) && (name != NULL)) {
4080 if (compare_func (name, method->name))
4081 continue;
4084 match = 0;
4085 g_ptr_array_add (array, method);
4087 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
4088 goto handle_parent;
4089 if (method_slots != method_slots_default)
4090 g_free (method_slots);
4092 return array;
4094 loader_error:
4095 if (method_slots != method_slots_default)
4096 g_free (method_slots);
4097 g_ptr_array_free (array, TRUE);
4099 g_assert (mono_class_has_failure (klass));
4100 mono_error_set_for_class_failure (error, klass);
4101 return NULL;
4104 GPtrArray*
4105 ves_icall_RuntimeType_GetMethodsByName_native (MonoReflectionTypeHandle ref_type, const char *mname, guint32 bflags, guint32 mlisttype, MonoError *error)
4107 error_init (error);
4108 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4110 MonoClass *klass = mono_class_from_mono_type_internal (type);
4111 if (type->byref) {
4112 return g_ptr_array_new ();
4115 return mono_class_get_methods_by_name (klass, mname, bflags, mlisttype, FALSE, error);
4118 GPtrArray*
4119 ves_icall_RuntimeType_GetConstructors_native (MonoReflectionTypeHandle ref_type, guint32 bflags, MonoError *error)
4121 error_init (error);
4122 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4123 if (type->byref) {
4124 return g_ptr_array_new ();
4127 MonoClass *startklass, *klass;
4128 klass = startklass = mono_class_from_mono_type_internal (type);
4130 mono_class_setup_methods (klass);
4131 if (mono_class_has_failure (klass)) {
4132 mono_error_set_for_class_failure (error, klass);
4133 return NULL;
4137 GPtrArray *res_array = g_ptr_array_sized_new (4); /* FIXME, guestimating */
4139 MonoMethod *method;
4140 gpointer iter = NULL;
4141 while ((method = mono_class_get_methods (klass, &iter))) {
4142 int match = 0;
4143 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
4144 continue;
4145 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4146 if (bflags & BFLAGS_Public)
4147 match++;
4148 } else {
4149 if (bflags & BFLAGS_NonPublic)
4150 match++;
4152 if (!match)
4153 continue;
4154 match = 0;
4155 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4156 if (bflags & BFLAGS_Static)
4157 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4158 match++;
4159 } else {
4160 if (bflags & BFLAGS_Instance)
4161 match++;
4164 if (!match)
4165 continue;
4166 g_ptr_array_add (res_array, method);
4169 return res_array;
4172 static guint
4173 property_hash (gconstpointer data)
4175 MonoProperty *prop = (MonoProperty*)data;
4177 return g_str_hash (prop->name);
4180 static gboolean
4181 property_accessor_override (MonoMethod *method1, MonoMethod *method2)
4183 if (method1->slot != -1 && method1->slot == method2->slot)
4184 return TRUE;
4186 if (mono_class_get_generic_type_definition (method1->klass) == mono_class_get_generic_type_definition (method2->klass)) {
4187 if (method1->is_inflated)
4188 method1 = ((MonoMethodInflated*) method1)->declaring;
4189 if (method2->is_inflated)
4190 method2 = ((MonoMethodInflated*) method2)->declaring;
4193 return mono_metadata_signature_equal (mono_method_signature_internal (method1), mono_method_signature_internal (method2));
4196 static gboolean
4197 property_equal (MonoProperty *prop1, MonoProperty *prop2)
4199 // Properties are hide-by-name-and-signature
4200 if (!g_str_equal (prop1->name, prop2->name))
4201 return FALSE;
4203 /* If we see a property in a generic method, we want to
4204 compare the generic signatures, not the inflated signatures
4205 because we might conflate two properties that were
4206 distinct:
4208 class Foo<T,U> {
4209 public T this[T t] { getter { return t; } } // method 1
4210 public U this[U u] { getter { return u; } } // method 2
4213 If we see int Foo<int,int>::Item[int] we need to know if
4214 the indexer came from method 1 or from method 2, and we
4215 shouldn't conflate them. (Bugzilla 36283)
4217 if (prop1->get && prop2->get && !property_accessor_override (prop1->get, prop2->get))
4218 return FALSE;
4220 if (prop1->set && prop2->set && !property_accessor_override (prop1->set, prop2->set))
4221 return FALSE;
4223 return TRUE;
4226 static gboolean
4227 property_accessor_nonpublic (MonoMethod* accessor, gboolean start_klass)
4229 if (!accessor)
4230 return FALSE;
4232 return method_nonpublic (accessor, start_klass);
4235 GPtrArray*
4236 ves_icall_RuntimeType_GetPropertiesByName_native (MonoReflectionTypeHandle ref_type, gchar *propname, guint32 bflags, guint32 mlisttype, MonoError *error)
4238 error_init (error);
4239 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4242 if (type->byref) {
4243 return g_ptr_array_new ();
4247 MonoClass *startklass, *klass;
4248 klass = startklass = mono_class_from_mono_type_internal (type);
4250 int (*compare_func) (const char *s1, const char *s2) = (mlisttype == MLISTTYPE_CaseInsensitive) ? mono_utf8_strcasecmp : strcmp;
4252 GPtrArray *res_array = g_ptr_array_sized_new (8); /*This the average for ASP.NET types*/
4254 GHashTable *properties = g_hash_table_new (property_hash, (GEqualFunc)property_equal);
4256 handle_parent:
4257 mono_class_setup_methods (klass);
4258 mono_class_setup_vtable (klass);
4259 if (mono_class_has_failure (klass)) {
4260 mono_error_set_for_class_failure (error, klass);
4261 goto loader_error;
4264 MonoProperty *prop;
4265 gpointer iter;
4266 iter = NULL;
4267 while ((prop = mono_class_get_properties (klass, &iter))) {
4268 int match = 0;
4269 MonoMethod *method = prop->get;
4270 if (!method)
4271 method = prop->set;
4272 guint32 flags = 0;
4273 if (method)
4274 flags = method->flags;
4275 if ((prop->get && ((prop->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)) ||
4276 (prop->set && ((prop->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC))) {
4277 if (bflags & BFLAGS_Public)
4278 match++;
4279 } else if (bflags & BFLAGS_NonPublic) {
4280 if (property_accessor_nonpublic(prop->get, startklass == klass) ||
4281 property_accessor_nonpublic(prop->set, startklass == klass)) {
4282 match++;
4285 if (!match)
4286 continue;
4287 match = 0;
4288 if (flags & METHOD_ATTRIBUTE_STATIC) {
4289 if (bflags & BFLAGS_Static)
4290 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4291 match++;
4292 } else {
4293 if (bflags & BFLAGS_Instance)
4294 match++;
4297 if (!match)
4298 continue;
4299 match = 0;
4301 if ((mlisttype != MLISTTYPE_All) && (propname != NULL) && compare_func (propname, prop->name))
4302 continue;
4304 if (g_hash_table_lookup (properties, prop))
4305 continue;
4307 g_ptr_array_add (res_array, prop);
4309 g_hash_table_insert (properties, prop, prop);
4311 if (!(bflags & BFLAGS_DeclaredOnly) && (klass = m_class_get_parent (klass)))
4312 goto handle_parent;
4314 g_hash_table_destroy (properties);
4316 return res_array;
4319 loader_error:
4320 if (properties)
4321 g_hash_table_destroy (properties);
4322 g_ptr_array_free (res_array, TRUE);
4324 return NULL;
4327 static guint
4328 event_hash (gconstpointer data)
4330 MonoEvent *event = (MonoEvent*)data;
4332 return g_str_hash (event->name);
4335 static gboolean
4336 event_equal (MonoEvent *event1, MonoEvent *event2)
4338 // Events are hide-by-name
4339 return g_str_equal (event1->name, event2->name);
4342 GPtrArray*
4343 ves_icall_RuntimeType_GetEvents_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 mlisttype, MonoError *error)
4345 error_init (error);
4346 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4348 if (type->byref) {
4349 return g_ptr_array_new ();
4352 int (*compare_func) (const char *s1, const char *s2) = (mlisttype == MLISTTYPE_CaseInsensitive) ? mono_utf8_strcasecmp : strcmp;
4354 GPtrArray *res_array = g_ptr_array_sized_new (4);
4356 MonoClass *startklass, *klass;
4357 klass = startklass = mono_class_from_mono_type_internal (type);
4359 GHashTable *events = g_hash_table_new (event_hash, (GEqualFunc)event_equal);
4360 handle_parent:
4361 mono_class_setup_methods (klass);
4362 mono_class_setup_vtable (klass);
4363 if (mono_class_has_failure (klass)) {
4364 mono_error_set_for_class_failure (error, klass);
4365 goto failure;
4368 MonoEvent *event;
4369 gpointer iter;
4370 iter = NULL;
4371 while ((event = mono_class_get_events (klass, &iter))) {
4373 // Remove inherited privates and inherited
4374 // without add/remove/raise methods
4375 if (klass != startklass)
4377 MonoMethod *method = event->add;
4378 if (!method)
4379 method = event->remove;
4380 if (!method)
4381 method = event->raise;
4382 if (!method)
4383 continue;
4384 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PRIVATE)
4385 continue;
4388 if ((mlisttype != MLISTTYPE_All) && (utf8_name != NULL) && compare_func (event->name, utf8_name))
4389 continue;
4391 if (g_hash_table_lookup (events, event))
4392 continue;
4394 g_ptr_array_add (res_array, event);
4396 g_hash_table_insert (events, event, event);
4398 if ((klass = m_class_get_parent (klass)))
4399 goto handle_parent;
4401 g_hash_table_destroy (events);
4403 return res_array;
4405 failure:
4406 if (events != NULL)
4407 g_hash_table_destroy (events);
4409 g_ptr_array_free (res_array, TRUE);
4411 return NULL;
4414 GPtrArray *
4415 ves_icall_RuntimeType_GetNestedTypes_native (MonoReflectionTypeHandle ref_type, char *str, guint32 bflags, guint32 mlisttype, MonoError *error)
4417 error_init (error);
4418 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4420 if (type->byref) {
4421 return g_ptr_array_new ();
4424 int (*compare_func) (const char *s1, const char *s2) = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp;
4426 MonoClass *klass = mono_class_from_mono_type_internal (type);
4429 * If a nested type is generic, return its generic type definition.
4430 * Note that this means that the return value is essentially the set
4431 * of nested types of the generic type definition of @klass.
4433 * A note in MSDN claims that a generic type definition can have
4434 * nested types that aren't generic. In any case, the container of that
4435 * nested type would be the generic type definition.
4437 if (mono_class_is_ginst (klass))
4438 klass = mono_class_get_generic_class (klass)->container_class;
4440 GPtrArray *res_array = g_ptr_array_new ();
4442 MonoClass *nested;
4443 gpointer iter = NULL;
4444 while ((nested = mono_class_get_nested_types (klass, &iter))) {
4445 int match = 0;
4446 if ((mono_class_get_flags (nested) & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
4447 if (bflags & BFLAGS_Public)
4448 match++;
4449 } else {
4450 if (bflags & BFLAGS_NonPublic)
4451 match++;
4453 if (!match)
4454 continue;
4456 if ((mlisttype != MLISTTYPE_All) && (str != NULL) && compare_func (m_class_get_name (nested), str))
4457 continue;
4459 g_ptr_array_add (res_array, m_class_get_byval_arg (nested));
4462 return res_array;
4465 static MonoType*
4466 get_type_from_module_builder_module (MonoArrayHandle modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
4468 HANDLE_FUNCTION_ENTER ();
4469 error_init (error);
4470 MonoType *type = NULL;
4471 MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW (MonoReflectionModuleBuilder, NULL);
4472 MONO_HANDLE_ARRAY_GETREF (mb, modules, i);
4473 MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
4474 type = mono_reflection_get_type_checked (&dynamic_image->image, &dynamic_image->image, info, ignoreCase, type_resolve, error);
4475 HANDLE_FUNCTION_RETURN_VAL (type);
4478 static MonoType*
4479 get_type_from_module_builder_loaded_modules (MonoArrayHandle loaded_modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
4481 HANDLE_FUNCTION_ENTER ();
4482 error_init (error);
4483 MonoType *type = NULL;
4484 MonoReflectionModuleHandle mod = MONO_HANDLE_NEW (MonoReflectionModule, NULL);
4485 MONO_HANDLE_ARRAY_GETREF (mod, loaded_modules, i);
4486 MonoImage *image = MONO_HANDLE_GETVAL (mod, image);
4487 type = mono_reflection_get_type_checked (image, image, info, ignoreCase, type_resolve, error);
4488 HANDLE_FUNCTION_RETURN_VAL (type);
4491 MonoReflectionTypeHandle
4492 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssemblyHandle assembly_h, MonoReflectionModuleHandle module, MonoStringHandle name, MonoBoolean throwOnError, MonoBoolean ignoreCase, MonoError *error)
4494 error_init (error);
4495 ERROR_DECL (parse_error);
4497 MonoTypeNameParse info;
4498 gboolean type_resolve;
4500 /* On MS.NET, this does not fire a TypeResolve event */
4501 type_resolve = TRUE;
4502 char *str = mono_string_handle_to_utf8 (name, error);
4503 goto_if_nok (error, fail);
4505 /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
4506 if (!mono_reflection_parse_type_checked (str, &info, parse_error)) {
4507 g_free (str);
4508 mono_reflection_free_type_info (&info);
4509 mono_error_cleanup (parse_error);
4510 if (throwOnError) {
4511 mono_error_set_argument (error, "typeName", "failed to parse the type");
4512 goto fail;
4514 /*g_print ("failed parse\n");*/
4515 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4518 if (info.assembly.name) {
4519 g_free (str);
4520 mono_reflection_free_type_info (&info);
4521 if (throwOnError) {
4522 /* 1.0 and 2.0 throw different exceptions */
4523 if (mono_defaults.generic_ilist_class)
4524 mono_error_set_argument (error, NULL, "Type names passed to Assembly.GetType() must not specify an assembly.");
4525 else
4526 mono_error_set_type_load_name (error, g_strdup (""), g_strdup (""), "Type names passed to Assembly.GetType() must not specify an assembly.");
4527 goto fail;
4529 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4532 MonoType *type;
4533 type = NULL;
4534 if (!MONO_HANDLE_IS_NULL (module)) {
4535 MonoImage *image = MONO_HANDLE_GETVAL (module, image);
4536 if (image) {
4537 type = mono_reflection_get_type_checked (image, image, &info, ignoreCase, &type_resolve, error);
4538 if (!is_ok (error)) {
4539 g_free (str);
4540 mono_reflection_free_type_info (&info);
4541 goto fail;
4545 else {
4546 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4547 if (assembly_is_dynamic (assembly)) {
4548 /* Enumerate all modules */
4549 MonoReflectionAssemblyBuilderHandle abuilder = MONO_HANDLE_NEW (MonoReflectionAssemblyBuilder, NULL);
4550 MONO_HANDLE_ASSIGN (abuilder, assembly_h);
4551 int i;
4553 MonoArrayHandle modules = MONO_HANDLE_NEW (MonoArray, NULL);
4554 MONO_HANDLE_GET (modules, abuilder, modules);
4555 if (!MONO_HANDLE_IS_NULL (modules)) {
4556 int n = mono_array_handle_length (modules);
4557 for (i = 0; i < n; ++i) {
4558 type = get_type_from_module_builder_module (modules, i, &info, ignoreCase, &type_resolve, error);
4559 if (!is_ok (error)) {
4560 g_free (str);
4561 mono_reflection_free_type_info (&info);
4562 goto fail;
4564 if (type)
4565 break;
4569 MonoArrayHandle loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL);
4570 MONO_HANDLE_GET (loaded_modules, abuilder, loaded_modules);
4571 if (!type && !MONO_HANDLE_IS_NULL (loaded_modules)) {
4572 int n = mono_array_handle_length (loaded_modules);
4573 for (i = 0; i < n; ++i) {
4574 type = get_type_from_module_builder_loaded_modules (loaded_modules, i, &info, ignoreCase, &type_resolve, error);
4576 if (!is_ok (error)) {
4577 g_free (str);
4578 mono_reflection_free_type_info (&info);
4579 goto fail;
4581 if (type)
4582 break;
4586 else {
4587 type = mono_reflection_get_type_checked (assembly->image, assembly->image, &info, ignoreCase, &type_resolve, error);
4588 if (!is_ok (error)) {
4589 g_free (str);
4590 mono_reflection_free_type_info (&info);
4591 goto fail;
4595 g_free (str);
4596 mono_reflection_free_type_info (&info);
4598 if (!type) {
4599 if (throwOnError) {
4600 ERROR_DECL (inner_error);
4601 char *type_name = mono_string_handle_to_utf8 (name, inner_error);
4602 mono_error_assert_ok (inner_error);
4603 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4604 char *assmname = mono_stringify_assembly_name (&assembly->aname);
4605 mono_error_set_type_load_name (error, type_name, assmname, "%s", "");
4606 goto fail;
4609 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4612 if (type->type == MONO_TYPE_CLASS) {
4613 MonoClass *klass = mono_type_get_class (type);
4615 /* need to report exceptions ? */
4616 if (throwOnError && mono_class_has_failure (klass)) {
4617 /* report SecurityException (or others) that occured when loading the assembly */
4618 mono_error_set_for_class_failure (error, klass);
4619 goto fail;
4623 /* g_print ("got it\n"); */
4624 return mono_type_get_object_handle (MONO_HANDLE_DOMAIN (assembly_h), type, error);
4625 fail:
4626 g_assert (!is_ok (error));
4627 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4630 static gboolean
4631 replace_shadow_path (MonoDomain *domain, gchar *dirname, gchar **filename)
4633 gchar *content;
4634 gchar *shadow_ini_file;
4635 gsize len;
4637 /* Check for shadow-copied assembly */
4638 if (mono_is_shadow_copy_enabled (domain, dirname)) {
4639 shadow_ini_file = g_build_filename (dirname, "__AssemblyInfo__.ini", NULL);
4640 content = NULL;
4641 if (!g_file_get_contents (shadow_ini_file, &content, &len, NULL) ||
4642 !g_file_test (content, G_FILE_TEST_IS_REGULAR)) {
4643 g_free (content);
4644 content = NULL;
4646 g_free (shadow_ini_file);
4647 if (content != NULL) {
4648 g_free (*filename);
4649 *filename = content;
4650 return TRUE;
4653 return FALSE;
4656 MonoStringHandle
4657 ves_icall_System_Reflection_RuntimeAssembly_get_code_base (MonoReflectionAssemblyHandle assembly, MonoBoolean escaped, MonoError *error)
4659 error_init (error);
4660 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
4661 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
4662 gchar *absolute;
4663 gchar *dirname;
4665 if (g_path_is_absolute (mass->image->name)) {
4666 absolute = g_strdup (mass->image->name);
4667 dirname = g_path_get_dirname (absolute);
4668 } else {
4669 absolute = g_build_filename (mass->basedir, mass->image->name, NULL);
4670 dirname = g_strdup (mass->basedir);
4673 replace_shadow_path (domain, dirname, &absolute);
4674 g_free (dirname);
4676 mono_icall_make_platform_path (absolute);
4678 gchar *uri;
4679 if (escaped) {
4680 uri = g_filename_to_uri (absolute, NULL, NULL);
4681 } else {
4682 const gchar *prepend = mono_icall_get_file_path_prefix (absolute);
4683 uri = g_strconcat (prepend, absolute, NULL);
4686 g_free (absolute);
4688 MonoStringHandle res;
4689 if (uri) {
4690 res = mono_string_new_handle (domain, uri, error);
4691 g_free (uri);
4692 } else {
4693 res = MONO_HANDLE_NEW (MonoString, NULL);
4695 return res;
4698 MonoBoolean
4699 ves_icall_System_Reflection_RuntimeAssembly_get_global_assembly_cache (MonoReflectionAssemblyHandle assembly, MonoError *error)
4701 error_init (error);
4702 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly,assembly);
4704 return mass->in_gac;
4707 MonoReflectionAssemblyHandle
4708 ves_icall_System_Reflection_Assembly_load_with_partial_name (MonoStringHandle mname, MonoObjectHandle evidence, MonoError *error)
4710 gchar *name;
4711 MonoImageOpenStatus status;
4712 MonoReflectionAssemblyHandle result = MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
4714 name = mono_string_handle_to_utf8 (mname, error);
4715 goto_if_nok (error, leave);
4716 MonoAssembly *res;
4717 res = mono_assembly_load_with_partial_name_internal (name, &status);
4719 g_free (name);
4721 if (res == NULL)
4722 goto leave;
4723 result = mono_assembly_get_object_handle (mono_domain_get (), res, error);
4724 leave:
4725 return result;
4728 MonoStringHandle
4729 ves_icall_System_Reflection_RuntimeAssembly_get_location (MonoReflectionAssemblyHandle refassembly, MonoError *error)
4731 MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
4732 MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
4733 return mono_string_new_handle (domain, mono_image_get_filename (assembly->image), error);
4736 MonoBoolean
4737 ves_icall_System_Reflection_RuntimeAssembly_get_ReflectionOnly (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
4739 error_init (error);
4740 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4741 return mono_asmctx_get_kind (&assembly->context) == MONO_ASMCTX_REFONLY;
4744 MonoStringHandle
4745 ves_icall_System_Reflection_RuntimeAssembly_InternalImageRuntimeVersion (MonoReflectionAssemblyHandle refassembly, MonoError *error)
4747 MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
4748 MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
4750 return mono_string_new_handle (domain, assembly->image->version, error);
4753 MonoReflectionMethodHandle
4754 ves_icall_System_Reflection_RuntimeAssembly_get_EntryPoint (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
4756 error_init (error);
4757 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4758 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4759 MonoMethod *method;
4761 MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
4762 guint32 token = mono_image_get_entry_point (assembly->image);
4764 if (!token)
4765 goto leave;
4766 method = mono_get_method_checked (assembly->image, token, NULL, NULL, error);
4767 goto_if_nok (error, leave);
4769 MONO_HANDLE_ASSIGN (res, mono_method_get_object_handle (domain, method, NULL, error));
4770 leave:
4771 return res;
4774 MonoReflectionModuleHandle
4775 ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAssemblyHandle assembly, MonoError *error)
4777 error_init (error);
4778 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
4779 MonoAssembly *a = MONO_HANDLE_GETVAL (assembly, assembly);
4780 return mono_module_get_object_handle (domain, a->image, error);
4783 static gboolean
4784 add_manifest_resource_name_to_array (MonoDomain *domain, MonoImage *image, MonoTableInfo *table, int i, MonoArrayHandle dest, MonoError *error)
4786 HANDLE_FUNCTION_ENTER ();
4787 error_init (error);
4788 const char *val = mono_metadata_string_heap (image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
4789 MonoStringHandle str = mono_string_new_handle (domain, val, error);
4790 goto_if_nok (error, leave);
4791 MONO_HANDLE_ARRAY_SETREF (dest, i, str);
4792 leave:
4793 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
4796 MonoArrayHandle
4797 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceNames (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
4799 error_init (error);
4800 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4801 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4802 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4803 MonoArrayHandle result = mono_array_new_handle (domain, mono_defaults.string_class, table->rows, error);
4804 goto_if_nok (error, fail);
4805 int i;
4807 for (i = 0; i < table->rows; ++i) {
4808 if (!add_manifest_resource_name_to_array (domain, assembly->image, table, i, result, error))
4809 goto fail;
4811 return result;
4812 fail:
4813 return NULL_HANDLE_ARRAY;
4816 MonoStringHandle
4817 ves_icall_System_Reflection_RuntimeAssembly_GetAotId (MonoError *error)
4819 char *guid = mono_runtime_get_aotid ();
4820 if (guid == NULL)
4821 return MONO_HANDLE_CAST (MonoString, mono_new_null ());
4822 MonoStringHandle res = mono_string_new_handle (mono_domain_get (), guid, error);
4823 g_free (guid);
4824 return res;
4827 static MonoAssemblyName*
4828 create_referenced_assembly_name (MonoDomain *domain, MonoImage *image, MonoTableInfo *t, int i, MonoError *error)
4830 error_init (error);
4831 MonoAssemblyName *aname = g_new0 (MonoAssemblyName, 1);
4833 mono_assembly_get_assemblyref_checked (image, i, aname, error);
4834 return_val_if_nok (error, NULL);
4835 aname->hash_alg = ASSEMBLY_HASH_SHA1 /* SHA1 (default) */;
4836 /* name and culture are pointers into the image tables, but we need
4837 * real malloc'd strings (so that we can g_free() them later from
4838 * Mono.RuntimeMarshal.FreeAssemblyName) */
4839 aname->name = g_strdup (aname->name);
4840 aname->culture = g_strdup (aname->culture);
4841 /* Don't need the hash value in managed */
4842 aname->hash_value = NULL;
4843 aname->hash_len = 0;
4844 g_assert (aname->public_key == NULL);
4846 /* note: this function doesn't return the codebase on purpose (i.e. it can
4847 be used under partial trust as path information isn't present). */
4848 return aname;
4851 GPtrArray*
4852 ves_icall_System_Reflection_Assembly_InternalGetReferencedAssemblies (MonoReflectionAssemblyHandle assembly, MonoError *error)
4854 error_init (error);
4855 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
4856 MonoAssembly *ass = MONO_HANDLE_GETVAL(assembly, assembly);
4857 MonoImage *image = ass->image;
4859 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
4860 int count = t->rows;
4862 GPtrArray *result = g_ptr_array_sized_new (count);
4864 for (int i = 0; i < count; i++) {
4865 MonoAssemblyName *aname = create_referenced_assembly_name (domain, image, t, i, error);
4866 if (!is_ok (error))
4867 break;
4868 g_ptr_array_add (result, aname);
4870 return result;
4873 /* move this in some file in mono/util/ */
4874 static char *
4875 g_concat_dir_and_file (const char *dir, const char *file)
4877 g_return_val_if_fail (dir != NULL, NULL);
4878 g_return_val_if_fail (file != NULL, NULL);
4881 * If the directory name doesn't have a / on the end, we need
4882 * to add one so we get a proper path to the file
4884 if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
4885 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
4886 else
4887 return g_strconcat (dir, file, NULL);
4890 void *
4891 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, gint32 *size, MonoReflectionModuleHandleOut ref_module, MonoError *error)
4893 error_init (error);
4894 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4895 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4896 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4897 guint32 i;
4898 guint32 cols [MONO_MANIFEST_SIZE];
4899 guint32 impl, file_idx;
4900 const char *val;
4901 MonoImage *module;
4903 char *n = mono_string_handle_to_utf8 (name, error);
4904 return_val_if_nok (error, NULL);
4906 for (i = 0; i < table->rows; ++i) {
4907 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4908 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
4909 if (strcmp (val, n) == 0)
4910 break;
4912 g_free (n);
4913 if (i == table->rows)
4914 return NULL;
4915 /* FIXME */
4916 impl = cols [MONO_MANIFEST_IMPLEMENTATION];
4917 if (impl) {
4919 * this code should only be called after obtaining the
4920 * ResourceInfo and handling the other cases.
4922 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
4923 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
4925 module = mono_image_load_file_for_image_checked (assembly->image, file_idx, error);
4926 if (!is_ok (error) || !module)
4927 return NULL;
4929 else
4930 module = assembly->image;
4933 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
4934 return_val_if_nok (error, NULL);
4935 MONO_HANDLE_ASSIGN (ref_module, rm);
4937 return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
4940 static gboolean
4941 get_manifest_resource_info_internal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info, MonoError *error)
4943 HANDLE_FUNCTION_ENTER ();
4944 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4945 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4946 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4947 int i;
4948 guint32 cols [MONO_MANIFEST_SIZE];
4949 guint32 file_cols [MONO_FILE_SIZE];
4950 const char *val;
4951 char *n;
4953 gboolean result = FALSE;
4955 n = mono_string_handle_to_utf8 (name, error);
4956 goto_if_nok (error, leave);
4958 for (i = 0; i < table->rows; ++i) {
4959 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4960 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
4961 if (strcmp (val, n) == 0)
4962 break;
4964 g_free (n);
4965 if (i == table->rows)
4966 goto leave;
4968 if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
4969 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST);
4971 else {
4972 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
4973 case MONO_IMPLEMENTATION_FILE:
4974 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4975 table = &assembly->image->tables [MONO_TABLE_FILE];
4976 mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
4977 val = mono_metadata_string_heap (assembly->image, file_cols [MONO_FILE_NAME]);
4978 MONO_HANDLE_SET (info, filename, mono_string_new_handle (domain, val, error));
4979 if (file_cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA)
4980 MONO_HANDLE_SETVAL (info, location, guint32, 0);
4981 else
4982 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED);
4983 break;
4985 case MONO_IMPLEMENTATION_ASSEMBLYREF:
4986 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4987 mono_assembly_load_reference (assembly->image, i - 1);
4988 if (assembly->image->references [i - 1] == REFERENCE_MISSING) {
4989 mono_error_set_file_not_found (error, NULL, "Assembly %d referenced from assembly %s not found ", i - 1, assembly->image->name);
4990 goto leave;
4992 MonoReflectionAssemblyHandle assm_obj;
4993 assm_obj = mono_assembly_get_object_handle (mono_domain_get (), assembly->image->references [i - 1], error);
4994 goto_if_nok (error, leave);
4995 MONO_HANDLE_SET (info, assembly, assm_obj);
4997 /* Obtain info recursively */
4998 get_manifest_resource_info_internal (assm_obj, name, info, error);
4999 goto_if_nok (error, leave);
5000 guint32 location;
5001 location = MONO_HANDLE_GETVAL (info, location);
5002 location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
5003 MONO_HANDLE_SETVAL (info, location, guint32, location);
5004 break;
5006 case MONO_IMPLEMENTATION_EXP_TYPE:
5007 g_assert_not_reached ();
5008 break;
5012 result = TRUE;
5013 leave:
5014 HANDLE_FUNCTION_RETURN_VAL (result);
5017 MonoBoolean
5018 ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInfoInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info_h, MonoError *error)
5020 error_init (error);
5021 return get_manifest_resource_info_internal (assembly_h, name, info_h, error);
5024 static gboolean
5025 add_filename_to_files_array (MonoDomain *domain, MonoAssembly * assembly, MonoTableInfo *table, int i, MonoArrayHandle dest, int dest_idx, MonoError *error)
5027 HANDLE_FUNCTION_ENTER();
5028 error_init (error);
5029 const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
5030 char *n = g_concat_dir_and_file (assembly->basedir, val);
5031 MonoStringHandle str = mono_string_new_handle (domain, n, error);
5032 g_free (n);
5033 goto_if_nok (error, leave);
5034 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, str);
5035 leave:
5036 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5039 MonoObjectHandle
5040 ves_icall_System_Reflection_RuntimeAssembly_GetFilesInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoBoolean resource_modules, MonoError *error)
5042 error_init (error);
5043 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
5044 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5045 MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_FILE];
5046 int i, count;
5048 /* check hash if needed */
5049 if (!MONO_HANDLE_IS_NULL(name)) {
5050 char *n = mono_string_handle_to_utf8 (name, error);
5051 goto_if_nok (error, fail);
5053 for (i = 0; i < table->rows; ++i) {
5054 const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
5055 if (strcmp (val, n) == 0) {
5056 g_free (n);
5057 n = g_concat_dir_and_file (assembly->basedir, val);
5058 MonoStringHandle fn = mono_string_new_handle (domain, n, error);
5059 g_free (n);
5060 goto_if_nok (error, fail);
5061 return MONO_HANDLE_CAST (MonoObject, fn);
5064 g_free (n);
5065 return NULL_HANDLE;
5068 count = 0;
5069 for (i = 0; i < table->rows; ++i) {
5070 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA))
5071 count ++;
5074 MonoArrayHandle result;
5075 result = mono_array_new_handle (domain, mono_defaults.string_class, count, error);
5076 goto_if_nok (error, fail);
5078 count = 0;
5079 for (i = 0; i < table->rows; ++i) {
5080 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
5081 if (!add_filename_to_files_array (domain, assembly, table, i, result, count, error))
5082 goto fail;
5083 count++;
5086 return MONO_HANDLE_CAST (MonoObject, result);
5087 fail:
5088 return NULL_HANDLE;
5091 static gboolean
5092 add_module_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int *dest_idx, MonoImage* module, MonoError *error)
5094 HANDLE_FUNCTION_ENTER ();
5095 error_init (error);
5096 if (module) {
5097 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
5098 goto_if_nok (error, leave);
5100 MONO_HANDLE_ARRAY_SETREF (dest, *dest_idx, rm);
5101 ++(*dest_idx);
5104 leave:
5105 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5108 static gboolean
5109 add_file_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int dest_idx, MonoImage *image, MonoTableInfo *table, int table_idx, MonoError *error)
5111 HANDLE_FUNCTION_ENTER ();
5112 error_init (error);
5114 guint32 cols [MONO_FILE_SIZE];
5115 mono_metadata_decode_row (table, table_idx, cols, MONO_FILE_SIZE);
5116 if (cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA) {
5117 MonoReflectionModuleHandle rm = mono_module_file_get_object_handle (domain, image, table_idx, error);
5118 goto_if_nok (error, leave);
5119 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5120 } else {
5121 MonoImage *m = mono_image_load_file_for_image_checked (image, table_idx + 1, error);
5122 goto_if_nok (error, leave);
5123 if (!m) {
5124 const char *filename = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
5125 mono_error_set_file_not_found (error, filename, "%s", "");
5126 goto leave;
5128 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, m, error);
5129 goto_if_nok (error, leave);
5130 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5133 leave:
5134 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5137 MonoArrayHandle
5138 ves_icall_System_Reflection_RuntimeAssembly_GetModulesInternal (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5140 error_init (error);
5141 MonoDomain *domain = mono_domain_get();
5142 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5143 MonoClass *klass;
5144 int i, j, file_count = 0;
5145 MonoImage **modules;
5146 guint32 module_count, real_module_count;
5147 MonoTableInfo *table;
5148 MonoImage *image = assembly->image;
5150 g_assert (image != NULL);
5151 g_assert (!assembly_is_dynamic (assembly));
5153 table = &image->tables [MONO_TABLE_FILE];
5154 file_count = table->rows;
5156 modules = image->modules;
5157 module_count = image->module_count;
5159 real_module_count = 0;
5160 for (i = 0; i < module_count; ++i)
5161 if (modules [i])
5162 real_module_count ++;
5164 klass = mono_class_get_module_class ();
5165 MonoArrayHandle res = mono_array_new_handle (domain, klass, 1 + real_module_count + file_count, error);
5166 goto_if_nok (error, fail);
5168 MonoReflectionModuleHandle image_obj;
5169 image_obj = mono_module_get_object_handle (domain, image, error);
5170 goto_if_nok (error, fail);
5172 MONO_HANDLE_ARRAY_SETREF (res, 0, image_obj);
5174 j = 1;
5175 for (i = 0; i < module_count; ++i)
5176 if (!add_module_to_modules_array (domain, res, &j, modules[i], error))
5177 goto fail;
5179 for (i = 0; i < file_count; ++i, ++j) {
5180 if (!add_file_to_modules_array (domain, res, j, image, table, i, error))
5181 goto fail;
5184 return res;
5185 fail:
5186 return NULL_HANDLE_ARRAY;
5189 MonoReflectionMethodHandle
5190 ves_icall_GetCurrentMethod (MonoError *error)
5192 error_init (error);
5194 MonoMethod *m = mono_method_get_last_managed ();
5196 if (!m) {
5197 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5198 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5201 while (m->is_inflated)
5202 m = ((MonoMethodInflated*)m)->declaring;
5204 return mono_method_get_object_handle (mono_domain_get (), m, NULL, error);
5208 static MonoMethod*
5209 mono_method_get_equivalent_method (MonoMethod *method, MonoClass *klass)
5211 int offset = -1, i;
5212 if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) {
5213 ERROR_DECL (error);
5214 MonoMethod *result;
5215 MonoMethodInflated *inflated = (MonoMethodInflated*)method;
5216 //method is inflated, we should inflate it on the other class
5217 MonoGenericContext ctx;
5218 ctx.method_inst = inflated->context.method_inst;
5219 ctx.class_inst = inflated->context.class_inst;
5220 if (mono_class_is_ginst (klass))
5221 ctx.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
5222 else if (mono_class_is_gtd (klass))
5223 ctx.class_inst = mono_class_get_generic_container (klass)->context.class_inst;
5224 result = mono_class_inflate_generic_method_full_checked (inflated->declaring, klass, &ctx, error);
5225 g_assert (is_ok (error)); /* FIXME don't swallow the error */
5226 return result;
5229 mono_class_setup_methods (method->klass);
5230 if (mono_class_has_failure (method->klass))
5231 return NULL;
5232 int mcount = mono_class_get_method_count (method->klass);
5233 MonoMethod **method_klass_methods = m_class_get_methods (method->klass);
5234 for (i = 0; i < mcount; ++i) {
5235 if (method_klass_methods [i] == method) {
5236 offset = i;
5237 break;
5240 mono_class_setup_methods (klass);
5241 if (mono_class_has_failure (klass))
5242 return NULL;
5243 g_assert (offset >= 0 && offset < mono_class_get_method_count (klass));
5244 return m_class_get_methods (klass) [offset];
5247 MonoReflectionMethodHandle
5248 ves_icall_System_Reflection_RuntimeMethodInfo_GetMethodFromHandleInternalType_native (MonoMethod *method, MonoType *type, MonoBoolean generic_check, MonoError *error)
5250 error_init (error);
5251 MonoClass *klass;
5252 if (type && generic_check) {
5253 klass = mono_class_from_mono_type_internal (type);
5254 if (mono_class_get_generic_type_definition (method->klass) != mono_class_get_generic_type_definition (klass))
5255 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5257 if (method->klass != klass) {
5258 method = mono_method_get_equivalent_method (method, klass);
5259 if (!method)
5260 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5262 } else if (type)
5263 klass = mono_class_from_mono_type_internal (type);
5264 else
5265 klass = method->klass;
5266 return mono_method_get_object_handle (mono_domain_get (), method, klass, error);
5269 MonoReflectionMethodBodyHandle
5270 ves_icall_System_Reflection_RuntimeMethodInfo_GetMethodBodyInternal (MonoMethod *method, MonoError *error)
5272 error_init (error);
5273 return mono_method_body_get_object_handle (mono_domain_get (), method, error);
5276 MonoReflectionAssemblyHandle
5277 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (MonoError *error)
5279 error_init (error);
5281 MonoMethod *dest = NULL;
5282 mono_stack_walk_no_il (get_executing, &dest);
5283 g_assert (dest);
5284 return mono_assembly_get_object_handle (mono_domain_get (), m_class_get_image (dest->klass)->assembly, error);
5288 MonoReflectionAssemblyHandle
5289 ves_icall_System_Reflection_Assembly_GetEntryAssembly (MonoError *error)
5291 error_init (error);
5293 MonoDomain* domain = mono_domain_get ();
5295 if (!domain->entry_assembly)
5296 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5298 return mono_assembly_get_object_handle (domain, domain->entry_assembly, error);
5301 MonoReflectionAssemblyHandle
5302 ves_icall_System_Reflection_Assembly_GetCallingAssembly (MonoError *error)
5304 error_init (error);
5305 MonoMethod *m;
5306 MonoMethod *dest;
5308 dest = NULL;
5309 mono_stack_walk_no_il (get_executing, &dest);
5310 m = dest;
5311 mono_stack_walk_no_il (get_caller_no_reflection, &dest);
5312 if (!dest)
5313 dest = m;
5314 if (!m) {
5315 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5316 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5318 return mono_assembly_get_object_handle (mono_domain_get (), m_class_get_image (dest->klass)->assembly, error);
5321 MonoStringHandle
5322 ves_icall_System_RuntimeType_getFullName (MonoReflectionTypeHandle object, MonoBoolean full_name,
5323 MonoBoolean assembly_qualified, MonoError *error)
5325 MonoDomain *domain = mono_object_domain (MONO_HANDLE_RAW (object));
5326 MonoType *type = MONO_HANDLE_RAW (object)->type;
5327 MonoTypeNameFormat format;
5328 MonoStringHandle res;
5329 gchar *name;
5331 if (full_name)
5332 format = assembly_qualified ?
5333 MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED :
5334 MONO_TYPE_NAME_FORMAT_FULL_NAME;
5335 else
5336 format = MONO_TYPE_NAME_FORMAT_REFLECTION;
5338 name = mono_type_get_name_full (type, format);
5339 if (!name)
5340 return NULL_HANDLE_STRING;
5342 if (full_name && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
5343 g_free (name);
5344 return NULL_HANDLE_STRING;
5347 res = mono_string_new_handle (domain, name, error);
5348 g_free (name);
5350 return res;
5354 ves_icall_RuntimeType_get_core_clr_security_level (MonoReflectionTypeHandle rfield, MonoError *error)
5356 error_init (error);
5357 MonoType *type = MONO_HANDLE_GETVAL (rfield, type);
5358 MonoClass *klass = mono_class_from_mono_type_internal (type);
5360 mono_class_init_checked (klass, error);
5361 return_val_if_nok (error, -1);
5362 return mono_security_core_clr_class_level (klass);
5366 ves_icall_RuntimeFieldInfo_get_core_clr_security_level (MonoReflectionFieldHandle rfield, MonoError *error)
5368 MonoClassField *field = MONO_HANDLE_GETVAL (rfield, field);
5369 return mono_security_core_clr_field_level (field, TRUE);
5373 ves_icall_RuntimeMethodInfo_get_core_clr_security_level (MonoReflectionMethodHandle rfield, MonoError *error)
5375 MonoMethod *method = MONO_HANDLE_GETVAL (rfield, method);
5376 return mono_security_core_clr_method_level (method, TRUE);
5379 MonoStringHandle
5380 ves_icall_System_Reflection_RuntimeAssembly_get_fullname (MonoReflectionAssemblyHandle assembly, MonoError *error)
5382 error_init (error);
5383 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5384 MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
5385 gchar *name;
5387 name = mono_stringify_assembly_name (&mass->aname);
5388 MonoStringHandle res = mono_string_new_handle (domain, name, error);
5389 g_free (name);
5390 return res;
5393 MonoAssemblyName *
5394 ves_icall_System_Reflection_AssemblyName_GetNativeName (MonoAssembly *mass)
5396 return &mass->aname;
5399 void
5400 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoStringHandle fname, MonoAssemblyName *name, MonoStringHandleOut normalized_codebase, MonoError *error)
5402 char *filename;
5403 MonoImageOpenStatus status = MONO_IMAGE_OK;
5404 char *codebase = NULL;
5405 gboolean res;
5406 MonoImage *image;
5407 char *dirname;
5409 error_init (error);
5411 filename = mono_string_handle_to_utf8 (fname, error);
5412 return_if_nok (error);
5414 dirname = g_path_get_dirname (filename);
5415 replace_shadow_path (mono_domain_get (), dirname, &filename);
5416 g_free (dirname);
5418 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "InternalGetAssemblyName (\"%s\")", filename);
5420 image = mono_image_open_full (filename, &status, TRUE);
5422 if (!image){
5423 if (status == MONO_IMAGE_IMAGE_INVALID)
5424 mono_error_set_bad_image_by_name (error, filename, "Invalid Image");
5425 else
5426 mono_error_set_file_not_found (error, filename, "%s", "");
5427 g_free (filename);
5428 return;
5431 res = mono_assembly_fill_assembly_name_full (image, name, TRUE);
5432 if (!res) {
5433 mono_image_close (image);
5434 g_free (filename);
5435 mono_error_set_argument (error, "assemblyFile", "The file does not contain a manifest");
5436 return;
5439 if (filename != NULL && *filename != '\0') {
5440 gchar *result;
5442 codebase = g_strdup (filename);
5444 mono_icall_make_platform_path (codebase);
5446 const gchar *prepend = mono_icall_get_file_path_prefix (codebase);
5448 result = g_strconcat (prepend, codebase, NULL);
5449 g_free (codebase);
5450 codebase = result;
5452 MONO_HANDLE_ASSIGN (normalized_codebase, mono_string_new_handle (mono_domain_get (), codebase, error));
5453 g_free (codebase);
5455 mono_image_close (image);
5456 g_free (filename);
5459 MonoBoolean
5460 ves_icall_System_Reflection_RuntimeAssembly_LoadPermissions (MonoReflectionAssemblyHandle assembly_h,
5461 char **minimum, guint32 *minLength, char **optional, guint32 *optLength, char **refused, guint32 *refLength, MonoError *error)
5463 error_init (error);
5464 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5465 MonoBoolean result = FALSE;
5466 MonoDeclSecurityEntry entry;
5468 /* SecurityAction.RequestMinimum */
5469 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQMIN, &entry)) {
5470 *minimum = entry.blob;
5471 *minLength = entry.size;
5472 result = TRUE;
5474 /* SecurityAction.RequestOptional */
5475 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQOPT, &entry)) {
5476 *optional = entry.blob;
5477 *optLength = entry.size;
5478 result = TRUE;
5480 /* SecurityAction.RequestRefuse */
5481 if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQREFUSE, &entry)) {
5482 *refused = entry.blob;
5483 *refLength = entry.size;
5484 result = TRUE;
5487 return result;
5490 static gboolean
5491 mono_module_type_is_visible (MonoTableInfo *tdef, MonoImage *image, int type)
5493 guint32 attrs, visibility;
5494 do {
5495 attrs = mono_metadata_decode_row_col (tdef, type - 1, MONO_TYPEDEF_FLAGS);
5496 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5497 if (visibility != TYPE_ATTRIBUTE_PUBLIC && visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC)
5498 return FALSE;
5500 } while ((type = mono_metadata_token_index (mono_metadata_nested_in_typedef (image, type))));
5502 return TRUE;
5505 static void
5506 image_get_type (MonoDomain *domain, MonoImage *image, MonoTableInfo *tdef, int table_idx, int count, MonoArrayHandle res, MonoArrayHandle exceptions, MonoBoolean exportedOnly, MonoError *error)
5508 error_init (error);
5509 HANDLE_FUNCTION_ENTER ();
5510 ERROR_DECL (klass_error);
5511 MonoClass *klass = mono_class_get_checked (image, table_idx | MONO_TOKEN_TYPE_DEF, klass_error);
5513 if (klass) {
5514 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
5515 return_if_nok (error);
5517 MONO_HANDLE_ARRAY_SETREF (res, count, rt);
5518 } else {
5519 MonoExceptionHandle ex = mono_error_convert_to_exception_handle (klass_error);
5520 MONO_HANDLE_ARRAY_SETREF (exceptions, count, ex);
5522 HANDLE_FUNCTION_RETURN ();
5525 static MonoArrayHandle
5526 mono_module_get_types (MonoDomain *domain, MonoImage *image, MonoArrayHandleOut exceptions, MonoBoolean exportedOnly, MonoError *error)
5528 MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
5529 int i, count;
5531 error_init (error);
5533 /* we start the count from 1 because we skip the special type <Module> */
5534 if (exportedOnly) {
5535 count = 0;
5536 for (i = 1; i < tdef->rows; ++i) {
5537 if (mono_module_type_is_visible (tdef, image, i + 1))
5538 count++;
5540 } else {
5541 count = tdef->rows - 1;
5543 MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.runtimetype_class, count, error);
5544 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5545 MONO_HANDLE_ASSIGN (exceptions, mono_array_new_handle (domain, mono_defaults.exception_class, count, error));
5546 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5547 count = 0;
5548 for (i = 1; i < tdef->rows; ++i) {
5549 if (!exportedOnly || mono_module_type_is_visible (tdef, image, i+1)) {
5550 image_get_type (domain, image, tdef, i + 1, count, res, exceptions, exportedOnly, error);
5551 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5552 count++;
5556 return res;
5559 static void
5560 append_module_types (MonoDomain *domain, MonoArrayHandleOut res, MonoArrayHandleOut exceptions, MonoImage *image, MonoBoolean exportedOnly, MonoError *error)
5562 HANDLE_FUNCTION_ENTER ();
5563 error_init (error);
5564 MonoArrayHandle ex2 = MONO_HANDLE_NEW (MonoArray, NULL);
5565 MonoArrayHandle res2 = mono_module_get_types (domain, image, ex2, exportedOnly, error);
5566 goto_if_nok (error, leave);
5568 /* Append the new types to the end of the array */
5569 if (mono_array_handle_length (res2) > 0) {
5570 guint32 len1, len2;
5572 len1 = mono_array_handle_length (res);
5573 len2 = mono_array_handle_length (res2);
5575 MonoArrayHandle res3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
5576 goto_if_nok (error, leave);
5578 mono_array_handle_memcpy_refs (res3, 0, res, 0, len1);
5579 mono_array_handle_memcpy_refs (res3, len1, res2, 0, len2);
5580 MONO_HANDLE_ASSIGN (res, res3);
5582 MonoArrayHandle ex3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
5583 goto_if_nok (error, leave);
5585 mono_array_handle_memcpy_refs (ex3, 0, exceptions, 0, len1);
5586 mono_array_handle_memcpy_refs (ex3, len1, ex2, 0, len2);
5587 MONO_HANDLE_ASSIGN (exceptions, ex3);
5589 leave:
5590 HANDLE_FUNCTION_RETURN ();
5593 static void
5594 set_class_failure_in_array (MonoArrayHandle exl, int i, MonoClass *klass)
5596 HANDLE_FUNCTION_ENTER ();
5597 ERROR_DECL (unboxed_error);
5598 mono_error_set_for_class_failure (unboxed_error, klass);
5600 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, mono_error_convert_to_exception (unboxed_error));
5601 MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
5602 HANDLE_FUNCTION_RETURN ();
5605 MonoArrayHandle
5606 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssemblyHandle assembly_handle, MonoBoolean exportedOnly, MonoError *error)
5608 MonoArrayHandle exceptions = MONO_HANDLE_NEW(MonoArray, NULL);
5609 int i;
5611 MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_handle);
5612 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_handle, assembly);
5614 g_assert (!assembly_is_dynamic (assembly));
5615 MonoImage *image = assembly->image;
5616 MonoTableInfo *table = &image->tables [MONO_TABLE_FILE];
5617 MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, exportedOnly, error);
5618 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5620 /* Append data from all modules in the assembly */
5621 for (i = 0; i < table->rows; ++i) {
5622 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
5623 MonoImage *loaded_image = mono_assembly_load_module_checked (image->assembly, i + 1, error);
5624 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5626 if (loaded_image) {
5627 append_module_types (domain, res, exceptions, loaded_image, exportedOnly, error);
5628 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5633 /* the ReflectionTypeLoadException must have all the types (Types property),
5634 * NULL replacing types which throws an exception. The LoaderException must
5635 * contain all exceptions for NULL items.
5638 int len = mono_array_handle_length (res);
5640 int ex_count = 0;
5641 GList *list = NULL;
5642 MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
5643 for (i = 0; i < len; i++) {
5644 MONO_HANDLE_ARRAY_GETREF (t, res, i);
5646 if (!MONO_HANDLE_IS_NULL (t)) {
5647 MonoClass *klass = mono_type_get_class (MONO_HANDLE_GETVAL (t, type));
5648 if ((klass != NULL) && mono_class_has_failure (klass)) {
5649 /* keep the class in the list */
5650 list = g_list_append (list, klass);
5651 /* and replace Type with NULL */
5652 MONO_HANDLE_ARRAY_SETREF (res, i, NULL_HANDLE);
5654 } else {
5655 ex_count ++;
5659 if (list || ex_count) {
5660 GList *tmp = NULL;
5661 int j, length = g_list_length (list) + ex_count;
5663 MonoArrayHandle exl = mono_array_new_handle (domain, mono_defaults.exception_class, length, error);
5664 if (!is_ok (error)) {
5665 g_list_free (list);
5666 return NULL_HANDLE_ARRAY;
5668 /* Types for which mono_class_get_checked () succeeded */
5669 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5670 for (i = 0, tmp = list; tmp; i++, tmp = tmp->next) {
5671 set_class_failure_in_array (exl, i, (MonoClass*)tmp->data);
5673 /* Types for which it don't */
5674 for (j = 0; j < mono_array_handle_length (exceptions); ++j) {
5675 MONO_HANDLE_ARRAY_GETREF (exc, exceptions, j);
5676 if (!MONO_HANDLE_IS_NULL (exc)) {
5677 g_assert (i < length);
5678 MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
5679 i ++;
5682 g_list_free (list);
5683 list = NULL;
5685 MONO_HANDLE_ASSIGN (exc, mono_get_exception_reflection_type_load_checked (res, exl, error));
5686 return_val_if_nok (error, NULL_HANDLE_ARRAY);
5687 mono_error_set_exception_handle (error, exc);
5688 return NULL_HANDLE_ARRAY;
5691 return res;
5694 void
5695 ves_icall_Mono_RuntimeMarshal_FreeAssemblyName (MonoAssemblyName *aname, MonoBoolean free_struct, MonoError *error)
5697 mono_assembly_name_free (aname);
5698 if (free_struct)
5699 g_free (aname);
5702 void
5703 ves_icall_Mono_Runtime_DisableMicrosoftTelemetry (MonoError *error)
5705 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
5706 mono_merp_disable ();
5707 #else
5708 // Icall has platform check in managed too.
5709 g_assert_not_reached ();
5710 #endif
5713 void
5714 ves_icall_Mono_Runtime_AnnotateMicrosoftTelemetry (const char *key, const char *value, MonoError *error)
5716 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
5717 if (!mono_merp_enabled ())
5718 g_error ("Cannot add attributes to telemetry without enabling subsystem");
5719 mono_merp_add_annotation (key, value);
5720 #else
5721 // Icall has platform check in managed too.
5722 g_assert_not_reached ();
5723 #endif
5726 void
5727 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)
5729 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
5730 mono_merp_enable (appBundleID, appSignature, appVersion, merpGUIPath, eventType, appPath, configDir);
5732 mono_get_runtime_callbacks ()->install_state_summarizer ();
5733 #else
5734 // Icall has platform check in managed too.
5735 g_assert_not_reached ();
5736 #endif
5739 // Number derived from trials on relevant hardware.
5740 // If it seems large, please confirm it's safe to shrink
5741 // before doing so.
5742 #define MONO_MAX_SUMMARY_LEN_ICALL 500000
5744 MonoStringHandle
5745 ves_icall_Mono_Runtime_ExceptionToState (MonoExceptionHandle exc_handle, guint64 *portable_hash_out, guint64 *unportable_hash_out, MonoError *error)
5747 MonoStringHandle result;
5749 #ifndef DISABLE_CRASH_REPORTING
5750 if (mono_get_eh_callbacks ()->mono_summarize_exception) {
5751 // FIXME: Push handles down into mini/mini-exceptions.c
5752 MonoException *exc = MONO_HANDLE_RAW (exc_handle);
5753 MonoThreadSummary out;
5754 mono_get_eh_callbacks ()->mono_summarize_exception (exc, &out);
5756 *portable_hash_out = (guint64) out.hashes.offset_free_hash;
5757 *unportable_hash_out = (guint64) out.hashes.offset_rich_hash;
5759 MonoStateWriter writer;
5760 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
5761 mono_state_writer_init (&writer, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
5762 mono_native_state_init (&writer);
5763 gboolean first_thread_added = TRUE;
5764 mono_native_state_add_thread (&writer, &out, NULL, first_thread_added, TRUE);
5765 char *output = mono_native_state_free (&writer, FALSE);
5766 result = mono_string_new_handle (mono_domain_get (), output, error);
5767 g_free (output);
5768 g_free (scratch);
5769 return result;
5771 #endif
5773 *portable_hash_out = 0;
5774 *unportable_hash_out = 0;
5775 result = mono_string_new_handle (mono_domain_get (), "", error);
5776 return result;
5779 void
5780 ves_icall_Mono_Runtime_SendMicrosoftTelemetry (const char *payload, guint64 portable_hash, guint64 unportable_hash, MonoError *error)
5782 #if defined(TARGET_OSX) && !defined(DISABLE_CRASH_REPORTING)
5783 if (!mono_merp_enabled ())
5784 g_error ("Cannot send telemetry without registering parameters first");
5786 pid_t crashed_pid = getpid ();
5788 MonoStackHash hashes;
5789 memset (&hashes, 0, sizeof (MonoStackHash));
5790 hashes.offset_free_hash = portable_hash;
5791 hashes.offset_rich_hash = unportable_hash;
5793 // Tells mono that we want to send the HANG EXC_TYPE.
5794 const char *signal = "SIGTERM";
5796 gboolean success = mono_merp_invoke (crashed_pid, signal, payload, &hashes);
5797 if (!success) {
5798 //g_assert_not_reached ();
5799 mono_error_set_generic_error (error, "System", "Exception", "We were unable to start the Microsoft Error Reporting client.");
5801 #else
5802 // Icall has platform check in managed too.
5803 g_assert_not_reached ();
5804 #endif
5807 void
5808 ves_icall_Mono_Runtime_DumpTelemetry (const char *payload, guint64 portable_hash, guint64 unportable_hash, MonoError *error)
5810 #ifndef DISABLE_CRASH_REPORTING
5811 MonoStackHash hashes;
5812 memset (&hashes, 0, sizeof (MonoStackHash));
5813 hashes.offset_free_hash = portable_hash;
5814 hashes.offset_rich_hash = unportable_hash;
5815 mono_crash_dump (payload, &hashes);
5816 #else
5817 return;
5818 #endif
5821 MonoStringHandle
5822 ves_icall_Mono_Runtime_DumpStateSingle (guint64 *portable_hash, guint64 *unportable_hash, MonoError *error)
5824 MonoStringHandle result;
5826 #ifndef DISABLE_CRASH_REPORTING
5827 MonoStackHash hashes;
5828 memset (&hashes, 0, sizeof (MonoStackHash));
5829 MonoContext *ctx = NULL;
5831 MonoThreadSummary this_thread;
5832 if (!mono_threads_summarize_one (&this_thread, ctx))
5833 return mono_string_new_handle (mono_domain_get (), "", error);
5835 *portable_hash = (guint64) this_thread.hashes.offset_free_hash;
5836 *unportable_hash = (guint64) this_thread.hashes.offset_rich_hash;
5838 MonoStateWriter writer;
5839 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
5840 mono_state_writer_init (&writer, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
5841 mono_native_state_init (&writer);
5842 gboolean first_thread_added = TRUE;
5843 mono_native_state_add_thread (&writer, &this_thread, NULL, first_thread_added, TRUE);
5844 char *output = mono_native_state_free (&writer, FALSE);
5845 result = mono_string_new_handle (mono_domain_get (), output, error);
5846 g_free (output);
5847 g_free (scratch);
5848 #else
5849 *portable_hash = 0;
5850 *unportable_hash = 0;
5851 result = mono_string_new_handle (mono_domain_get (), "", error);
5852 #endif
5854 return result;
5858 void
5859 ves_icall_Mono_Runtime_RegisterReportingForNativeLib (const char *path_suffix, const char *module_name)
5861 #ifndef DISABLE_CRASH_REPORTING
5862 if (mono_get_eh_callbacks ()->mono_register_native_library)
5863 mono_get_eh_callbacks ()->mono_register_native_library (path_suffix, module_name);
5864 #endif
5867 void
5868 ves_icall_Mono_Runtime_EnableCrashReportingLog (const char *directory, MonoError *error)
5870 #ifndef DISABLE_CRASH_REPORTING
5871 mono_summarize_set_timeline_dir (directory);
5872 #endif
5876 ves_icall_Mono_Runtime_CheckCrashReportingLog (const char *directory, MonoBoolean clear, MonoError *error)
5878 int ret;
5879 #ifndef DISABLE_CRASH_REPORTING
5880 ret = (int) mono_summarize_timeline_read_level (directory, clear != 0);
5881 #else
5882 ret = 0;
5883 #endif
5884 return ret;
5887 MonoStringHandle
5888 ves_icall_Mono_Runtime_DumpStateTotal (guint64 *portable_hash, guint64 *unportable_hash, MonoError *error)
5890 MonoStringHandle result;
5892 #ifndef DISABLE_CRASH_REPORTING
5893 char *scratch = g_new0 (gchar, MONO_MAX_SUMMARY_LEN_ICALL);
5895 char *out;
5896 MonoStackHash hashes;
5897 memset (&hashes, 0, sizeof (MonoStackHash));
5898 MonoContext *ctx = NULL;
5900 mono_get_runtime_callbacks ()->install_state_summarizer ();
5902 mono_summarize_timeline_start ();
5904 gboolean success = mono_threads_summarize (ctx, &out, &hashes, TRUE, FALSE, scratch, MONO_MAX_SUMMARY_LEN_ICALL);
5905 mono_summarize_timeline_phase_log (MonoSummaryCleanup);
5907 if (!success)
5908 return mono_string_new_handle (mono_domain_get (), "", error);
5910 *portable_hash = (guint64) hashes.offset_free_hash;
5911 *unportable_hash = (guint64) hashes.offset_rich_hash;
5912 result = mono_string_new_handle (mono_domain_get (), out, error);
5914 // out is now a pointer into garbage memory
5915 g_free (scratch);
5917 mono_summarize_timeline_phase_log (MonoSummaryDone);
5918 #else
5919 *portable_hash = 0;
5920 *unportable_hash = 0;
5921 result = mono_string_new_handle (mono_domain_get (), "", error);
5922 #endif
5924 return result;
5927 MonoBoolean
5928 ves_icall_System_Reflection_AssemblyName_ParseAssemblyName (const char *name, MonoAssemblyName *aname, MonoBoolean *is_version_defined_arg, MonoBoolean *is_token_defined_arg)
5930 gboolean is_version_defined = FALSE;
5931 gboolean is_token_defined = FALSE;
5932 gboolean result = FALSE;
5934 result = mono_assembly_name_parse_full (name, aname, TRUE, &is_version_defined, &is_token_defined);
5936 *is_version_defined_arg = (MonoBoolean)is_version_defined;
5937 *is_token_defined_arg = (MonoBoolean)is_token_defined;
5939 return result;
5942 MonoReflectionTypeHandle
5943 ves_icall_System_Reflection_Module_GetGlobalType (MonoReflectionModuleHandle module, MonoError *error)
5945 MonoDomain *domain = MONO_HANDLE_DOMAIN (module);
5946 MonoImage *image = MONO_HANDLE_GETVAL (module, image);
5947 MonoClass *klass;
5949 g_assert (image);
5951 MonoReflectionTypeHandle ret = MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
5953 if (image_is_dynamic (image) && ((MonoDynamicImage*)image)->initial_image)
5954 /* These images do not have a global type */
5955 goto leave;
5957 klass = mono_class_get_checked (image, 1 | MONO_TOKEN_TYPE_DEF, error);
5958 goto_if_nok (error, leave);
5960 ret = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
5961 leave:
5962 return ret;
5965 void
5966 ves_icall_System_Reflection_Module_Close (MonoReflectionModuleHandle module, MonoError *error)
5968 /*if (module->image)
5969 mono_image_close (module->image);*/
5972 MonoStringHandle
5973 ves_icall_System_Reflection_Module_GetGuidInternal (MonoReflectionModuleHandle refmodule, MonoError *error)
5975 MonoDomain *domain = MONO_HANDLE_DOMAIN (refmodule);
5976 MonoImage *image = MONO_HANDLE_GETVAL (refmodule, image);
5978 g_assert (image);
5979 return mono_string_new_handle (domain, image->guid, error);
5982 #ifndef HOST_WIN32
5983 static inline gpointer
5984 mono_icall_module_get_hinstance (MonoReflectionModuleHandle module)
5986 return (gpointer) (-1);
5988 #endif /* HOST_WIN32 */
5990 gpointer
5991 ves_icall_System_Reflection_Module_GetHINSTANCE (MonoReflectionModuleHandle module, MonoError *error)
5993 return mono_icall_module_get_hinstance (module);
5996 void
5997 ves_icall_System_Reflection_Module_GetPEKind (MonoImage *image, gint32 *pe_kind, gint32 *machine, MonoError *error)
5999 if (image_is_dynamic (image)) {
6000 MonoDynamicImage *dyn = (MonoDynamicImage*)image;
6001 *pe_kind = dyn->pe_kind;
6002 *machine = dyn->machine;
6004 else {
6005 *pe_kind = (image->image_info->cli_cli_header.ch_flags & 0x3);
6006 *machine = image->image_info->cli_header.coff.coff_machine;
6010 gint32
6011 ves_icall_System_Reflection_Module_GetMDStreamVersion (MonoImage *image, MonoError *error)
6013 return (image->md_version_major << 16) | (image->md_version_minor);
6016 MonoArrayHandle
6017 ves_icall_System_Reflection_Module_InternalGetTypes (MonoReflectionModuleHandle module, MonoError *error)
6019 error_init (error);
6021 MonoImage *image = MONO_HANDLE_GETVAL (module, image);
6022 MonoDomain *domain = MONO_HANDLE_DOMAIN (module);
6024 if (!image) {
6025 MonoArrayHandle arr = mono_array_new_handle (domain, mono_defaults.runtimetype_class, 0, error);
6026 return arr;
6027 } else {
6028 MonoArrayHandle exceptions = MONO_HANDLE_NEW (MonoArray, NULL);
6029 MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, FALSE, error);
6030 return_val_if_nok (error, MONO_HANDLE_CAST(MonoArray, NULL_HANDLE));
6032 int n = mono_array_handle_length (exceptions);
6033 MonoExceptionHandle ex = MONO_HANDLE_NEW (MonoException, NULL);
6034 for (int i = 0; i < n; ++i) {
6035 MONO_HANDLE_ARRAY_GETREF(ex, exceptions, i);
6036 if (!MONO_HANDLE_IS_NULL (ex)) {
6037 mono_error_set_exception_handle (error, ex);
6038 return MONO_HANDLE_CAST(MonoArray, NULL_HANDLE);
6041 return res;
6045 static gboolean
6046 mono_memberref_is_method (MonoImage *image, guint32 token)
6048 if (!image_is_dynamic (image)) {
6049 guint32 cols [MONO_MEMBERREF_SIZE];
6050 const char *sig;
6051 const MonoTableInfo *table = &image->tables [MONO_TABLE_MEMBERREF];
6052 int idx = mono_metadata_token_index (token) - 1;
6053 if (idx < 0 || table->rows <= idx) {
6054 return FALSE;
6056 mono_metadata_decode_row (table, idx, cols, MONO_MEMBERREF_SIZE);
6057 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
6058 mono_metadata_decode_blob_size (sig, &sig);
6059 return (*sig != 0x6);
6060 } else {
6061 ERROR_DECL (error);
6062 MonoClass *handle_class;
6064 if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL, error)) {
6065 mono_error_cleanup (error); /* just probing, ignore error */
6066 return FALSE;
6069 return mono_defaults.methodhandle_class == handle_class;
6073 static MonoGenericInst *
6074 get_generic_inst_from_array_handle (MonoArrayHandle type_args)
6076 int type_argc = mono_array_handle_length (type_args);
6077 int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *);
6079 MonoGenericInst *ginst = (MonoGenericInst *)g_alloca (size);
6080 memset (ginst, 0, sizeof (MonoGenericInst));
6081 ginst->type_argc = type_argc;
6082 for (int i = 0; i < type_argc; i++) {
6083 MONO_HANDLE_ARRAY_GETVAL (ginst->type_argv[i], type_args, MonoType*, i);
6085 ginst->is_open = FALSE;
6086 for (int i = 0; i < type_argc; i++) {
6087 if (mono_class_is_open_constructed_type (ginst->type_argv[i])) {
6088 ginst->is_open = TRUE;
6089 break;
6093 return mono_metadata_get_canonical_generic_inst (ginst);
6096 static void
6097 init_generic_context_from_args_handles (MonoGenericContext *context, MonoArrayHandle type_args, MonoArrayHandle method_args)
6099 if (!MONO_HANDLE_IS_NULL (type_args)) {
6100 context->class_inst = get_generic_inst_from_array_handle (type_args);
6101 } else {
6102 context->class_inst = NULL;
6104 if (!MONO_HANDLE_IS_NULL (method_args)) {
6105 context->method_inst = get_generic_inst_from_array_handle (method_args);
6106 } else {
6107 context->method_inst = NULL;
6112 static MonoType*
6113 module_resolve_type_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6115 HANDLE_FUNCTION_ENTER ();
6116 error_init (error);
6117 MonoType *result = NULL;
6118 MonoClass *klass;
6119 int table = mono_metadata_token_table (token);
6120 int index = mono_metadata_token_index (token);
6121 MonoGenericContext context;
6123 *resolve_error = ResolveTokenError_Other;
6125 /* Validate token */
6126 if ((table != MONO_TABLE_TYPEDEF) && (table != MONO_TABLE_TYPEREF) &&
6127 (table != MONO_TABLE_TYPESPEC)) {
6128 *resolve_error = ResolveTokenError_BadTable;
6129 goto leave;
6132 if (image_is_dynamic (image)) {
6133 if ((table == MONO_TABLE_TYPEDEF) || (table == MONO_TABLE_TYPEREF)) {
6134 ERROR_DECL (inner_error);
6135 klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6136 mono_error_cleanup (inner_error);
6137 result = klass ? m_class_get_byval_arg (klass) : NULL;
6138 goto leave;
6141 init_generic_context_from_args_handles (&context, type_args, method_args);
6142 ERROR_DECL (inner_error);
6143 klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6144 mono_error_cleanup (inner_error);
6145 result = klass ? m_class_get_byval_arg (klass) : NULL;
6146 goto leave;
6149 if ((index <= 0) || (index > image->tables [table].rows)) {
6150 *resolve_error = ResolveTokenError_OutOfRange;
6151 goto leave;
6154 init_generic_context_from_args_handles (&context, type_args, method_args);
6155 klass = mono_class_get_checked (image, token, error);
6156 if (klass)
6157 klass = mono_class_inflate_generic_class_checked (klass, &context, error);
6158 goto_if_nok (error, leave);
6160 if (klass)
6161 result = m_class_get_byval_arg (klass);
6162 leave:
6163 HANDLE_FUNCTION_RETURN_VAL (result);
6166 MonoType*
6167 ves_icall_System_Reflection_Module_ResolveTypeToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6169 return module_resolve_type_token (image, token, type_args, method_args, resolve_error, error);
6172 static MonoMethod*
6173 module_resolve_method_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6175 HANDLE_FUNCTION_ENTER ();
6176 error_init (error);
6177 MonoMethod *method = NULL;
6178 int table = mono_metadata_token_table (token);
6179 int index = mono_metadata_token_index (token);
6180 MonoGenericContext context;
6182 *resolve_error = ResolveTokenError_Other;
6184 /* Validate token */
6185 if ((table != MONO_TABLE_METHOD) && (table != MONO_TABLE_METHODSPEC) &&
6186 (table != MONO_TABLE_MEMBERREF)) {
6187 *resolve_error = ResolveTokenError_BadTable;
6188 goto leave;
6191 if (image_is_dynamic (image)) {
6192 if (table == MONO_TABLE_METHOD) {
6193 ERROR_DECL (inner_error);
6194 method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6195 mono_error_cleanup (inner_error);
6196 goto leave;
6199 if ((table == MONO_TABLE_MEMBERREF) && !(mono_memberref_is_method (image, token))) {
6200 *resolve_error = ResolveTokenError_BadTable;
6201 goto leave;
6204 init_generic_context_from_args_handles (&context, type_args, method_args);
6205 ERROR_DECL (inner_error);
6206 method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6207 mono_error_cleanup (inner_error);
6208 goto leave;
6211 if ((index <= 0) || (index > image->tables [table].rows)) {
6212 *resolve_error = ResolveTokenError_OutOfRange;
6213 goto leave;
6215 if ((table == MONO_TABLE_MEMBERREF) && (!mono_memberref_is_method (image, token))) {
6216 *resolve_error = ResolveTokenError_BadTable;
6217 goto leave;
6220 init_generic_context_from_args_handles (&context, type_args, method_args);
6221 method = mono_get_method_checked (image, token, NULL, &context, error);
6223 leave:
6224 HANDLE_FUNCTION_RETURN_VAL (method);
6227 MonoMethod*
6228 ves_icall_System_Reflection_Module_ResolveMethodToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6230 return module_resolve_method_token (image, token, type_args, method_args, resolve_error, error);
6233 MonoStringHandle
6234 ves_icall_System_Reflection_Module_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error, MonoError *error)
6236 int index = mono_metadata_token_index (token);
6238 *resolve_error = ResolveTokenError_Other;
6240 /* Validate token */
6241 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
6242 *resolve_error = ResolveTokenError_BadTable;
6243 return NULL_HANDLE_STRING;
6246 if (image_is_dynamic (image)) {
6247 ERROR_DECL (ignore_inner_error);
6248 // FIXME ignoring error
6249 // FIXME Push MONO_HANDLE_NEW to lower layers.
6250 MonoStringHandle result = MONO_HANDLE_NEW (MonoString, (MonoString*)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, ignore_inner_error));
6251 mono_error_cleanup (ignore_inner_error);
6252 return result;
6255 if ((index <= 0) || (index >= image->heap_us.size)) {
6256 *resolve_error = ResolveTokenError_OutOfRange;
6257 return NULL_HANDLE_STRING;
6260 /* FIXME: What to do if the index points into the middle of a string ? */
6261 return mono_ldstr_handle (mono_domain_get (), image, index, error);
6264 static MonoClassField*
6265 module_resolve_field_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6267 HANDLE_FUNCTION_ENTER ();
6268 MonoClass *klass;
6269 int table = mono_metadata_token_table (token);
6270 int index = mono_metadata_token_index (token);
6271 MonoGenericContext context;
6272 MonoClassField *field = NULL;
6274 error_init (error);
6275 *resolve_error = ResolveTokenError_Other;
6277 /* Validate token */
6278 if ((table != MONO_TABLE_FIELD) && (table != MONO_TABLE_MEMBERREF)) {
6279 *resolve_error = ResolveTokenError_BadTable;
6280 goto leave;
6283 if (image_is_dynamic (image)) {
6284 if (table == MONO_TABLE_FIELD) {
6285 ERROR_DECL (inner_error);
6286 field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, inner_error);
6287 mono_error_cleanup (inner_error);
6288 goto leave;
6291 if (mono_memberref_is_method (image, token)) {
6292 *resolve_error = ResolveTokenError_BadTable;
6293 goto leave;
6296 init_generic_context_from_args_handles (&context, type_args, method_args);
6297 ERROR_DECL (inner_error);
6298 field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, inner_error);
6299 mono_error_cleanup (inner_error);
6300 goto leave;
6303 if ((index <= 0) || (index > image->tables [table].rows)) {
6304 *resolve_error = ResolveTokenError_OutOfRange;
6305 goto leave;
6307 if ((table == MONO_TABLE_MEMBERREF) && (mono_memberref_is_method (image, token))) {
6308 *resolve_error = ResolveTokenError_BadTable;
6309 goto leave;
6312 init_generic_context_from_args_handles (&context, type_args, method_args);
6313 field = mono_field_from_token_checked (image, token, &klass, &context, error);
6315 leave:
6316 HANDLE_FUNCTION_RETURN_VAL (field);
6319 MonoClassField*
6320 ves_icall_System_Reflection_Module_ResolveFieldToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
6322 return module_resolve_field_token (image, token, type_args, method_args, resolve_error, error);
6325 MonoObjectHandle
6326 ves_icall_System_Reflection_Module_ResolveMemberToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *error, MonoError *merror)
6328 int table = mono_metadata_token_table (token);
6330 error_init (merror);
6331 *error = ResolveTokenError_Other;
6333 switch (table) {
6334 case MONO_TABLE_TYPEDEF:
6335 case MONO_TABLE_TYPEREF:
6336 case MONO_TABLE_TYPESPEC: {
6337 MonoType *t = module_resolve_type_token (image, token, type_args, method_args, error, merror);
6338 if (t) {
6339 return MONO_HANDLE_CAST (MonoObject, mono_type_get_object_handle (mono_domain_get (), t, merror));
6341 else
6342 return NULL_HANDLE;
6344 case MONO_TABLE_METHOD:
6345 case MONO_TABLE_METHODSPEC: {
6346 MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
6347 if (m) {
6348 return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
6349 } else
6350 return NULL_HANDLE;
6352 case MONO_TABLE_FIELD: {
6353 MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
6354 if (f) {
6355 return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
6357 else
6358 return NULL_HANDLE;
6360 case MONO_TABLE_MEMBERREF:
6361 if (mono_memberref_is_method (image, token)) {
6362 MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
6363 if (m) {
6364 return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
6365 } else
6366 return NULL_HANDLE;
6368 else {
6369 MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
6370 if (f) {
6371 return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
6373 else
6374 return NULL_HANDLE;
6376 break;
6378 default:
6379 *error = ResolveTokenError_BadTable;
6382 return NULL_HANDLE;
6385 MonoArrayHandle
6386 ves_icall_System_Reflection_Module_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error, MonoError *error)
6388 error_init (error);
6389 int table = mono_metadata_token_table (token);
6390 int idx = mono_metadata_token_index (token);
6391 MonoTableInfo *tables = image->tables;
6392 guint32 sig, len;
6393 const char *ptr;
6395 *resolve_error = ResolveTokenError_OutOfRange;
6397 /* FIXME: Support other tables ? */
6398 if (table != MONO_TABLE_STANDALONESIG)
6399 return NULL_HANDLE_ARRAY;
6401 if (image_is_dynamic (image))
6402 return NULL_HANDLE_ARRAY;
6404 if ((idx == 0) || (idx > tables [MONO_TABLE_STANDALONESIG].rows))
6405 return NULL_HANDLE_ARRAY;
6407 sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
6409 ptr = mono_metadata_blob_heap (image, sig);
6410 len = mono_metadata_decode_blob_size (ptr, &ptr);
6412 MonoArrayHandle res = mono_array_new_handle (mono_domain_get (), mono_defaults.byte_class, len, error);
6413 return_val_if_nok (error, NULL_HANDLE_ARRAY);
6414 uint32_t h;
6415 gpointer array_base = MONO_ARRAY_HANDLE_PIN (res, guint8, 0, &h);
6416 memcpy (array_base, ptr, len);
6417 mono_gchandle_free_internal (h);
6418 return res;
6421 MonoBoolean
6422 ves_icall_RuntimeTypeHandle_IsArray (MonoReflectionTypeHandle ref_type, MonoError *error)
6424 error_init (error);
6425 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6427 MonoBoolean res = !type->byref && (type->type == MONO_TYPE_ARRAY || type->type == MONO_TYPE_SZARRAY);
6429 return res;
6432 static void
6433 check_for_invalid_type (MonoClass *klass, MonoError *error)
6435 char *name;
6437 error_init (error);
6439 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_TYPEDBYREF)
6440 return;
6442 name = mono_type_get_full_name (klass);
6443 mono_error_set_type_load_name (error, name, g_strdup (""), "");
6446 MonoReflectionTypeHandle
6447 ves_icall_RuntimeType_make_array_type (MonoReflectionTypeHandle ref_type, int rank, MonoError *error)
6449 error_init (error);
6450 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6452 MonoClass *klass = mono_class_from_mono_type_internal (type);
6453 check_for_invalid_type (klass, error);
6454 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6456 MonoClass *aklass;
6457 if (rank == 0) //single dimension array
6458 aklass = mono_class_create_array (klass, 1);
6459 else
6460 aklass = mono_class_create_bounded_array (klass, rank, TRUE);
6462 if (mono_class_has_failure (aklass)) {
6463 mono_error_set_for_class_failure (error, aklass);
6464 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6467 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6468 return mono_type_get_object_handle (domain, m_class_get_byval_arg (aklass), error);
6471 MonoReflectionTypeHandle
6472 ves_icall_RuntimeType_make_byref_type (MonoReflectionTypeHandle ref_type, MonoError *error)
6474 error_init (error);
6475 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6477 MonoClass *klass = mono_class_from_mono_type_internal (type);
6478 mono_class_init_checked (klass, error);
6479 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6481 check_for_invalid_type (klass, error);
6482 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6484 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6485 return mono_type_get_object_handle (domain, m_class_get_this_arg (klass), error);
6488 MonoReflectionTypeHandle
6489 ves_icall_RuntimeType_MakePointerType (MonoReflectionTypeHandle ref_type, MonoError *error)
6491 error_init (error);
6492 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6493 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6494 MonoClass *klass = mono_class_from_mono_type_internal (type);
6495 mono_class_init_checked (klass, error);
6496 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6498 check_for_invalid_type (klass, error);
6499 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE));
6501 MonoClass *pklass = mono_class_create_ptr (type);
6503 return mono_type_get_object_handle (domain, m_class_get_byval_arg (pklass), error);
6506 MonoObjectHandle
6507 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionTypeHandle ref_type, MonoObjectHandle target,
6508 MonoReflectionMethodHandle info, MonoBoolean throwOnBindFailure, MonoError *error)
6510 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6511 MonoClass *delegate_class = mono_class_from_mono_type_internal (type);
6512 MonoMethod *method = MONO_HANDLE_GETVAL (info, method);
6513 MonoMethodSignature *sig = mono_method_signature_internal (method);
6515 mono_class_init_checked (delegate_class, error);
6516 return_val_if_nok (error, NULL_HANDLE);
6518 if (!(m_class_get_parent (delegate_class) == mono_defaults.multicastdelegate_class)) {
6519 /* FIXME improve this exception message */
6520 mono_error_set_execution_engine (error, "file %s: line %d (%s): assertion failed: (%s)", __FILE__, __LINE__,
6521 __func__,
6522 "delegate_class->parent == mono_defaults.multicastdelegate_class");
6523 return NULL_HANDLE;
6526 if (mono_security_core_clr_enabled ()) {
6527 ERROR_DECL (security_error);
6528 if (!mono_security_core_clr_ensure_delegate_creation (method, security_error)) {
6529 if (throwOnBindFailure)
6530 mono_error_move (error, security_error);
6531 else
6532 mono_error_cleanup (security_error);
6533 return NULL_HANDLE;
6537 if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
6538 if (!method->is_inflated) {
6539 mono_error_set_argument (error, "method", " Cannot bind to the target method because its signature differs from that of the delegate type");
6540 return NULL_HANDLE;
6544 MonoObjectHandle delegate = mono_object_new_handle (MONO_HANDLE_DOMAIN (ref_type), delegate_class, error);
6545 return_val_if_nok (error, NULL_HANDLE);
6547 if (!method_is_dynamic (method) && (!MONO_HANDLE_IS_NULL (target) && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass != mono_handle_class (target))) {
6548 method = mono_object_handle_get_virtual_method (target, method, error);
6549 return_val_if_nok (error, NULL_HANDLE);
6552 mono_delegate_ctor_with_method (delegate, target, NULL, method, error);
6553 return_val_if_nok (error, NULL_HANDLE);
6554 return delegate;
6557 MonoMulticastDelegateHandle
6558 ves_icall_System_Delegate_AllocDelegateLike_internal (MonoDelegateHandle delegate, MonoError *error)
6560 error_init (error);
6562 MonoClass *klass = mono_handle_class (delegate);
6563 g_assert (mono_class_has_parent (klass, mono_defaults.multicastdelegate_class));
6565 MonoMulticastDelegateHandle ret = MONO_HANDLE_CAST (MonoMulticastDelegate, mono_object_new_handle (MONO_HANDLE_DOMAIN (delegate), klass, error));
6566 return_val_if_nok (error, MONO_HANDLE_CAST (MonoMulticastDelegate, NULL_HANDLE));
6568 MONO_HANDLE_SETVAL (MONO_HANDLE_CAST (MonoDelegate, ret), invoke_impl, gpointer, mono_runtime_create_delegate_trampoline (klass));
6570 return ret;
6573 MonoReflectionMethodHandle
6574 ves_icall_System_Delegate_GetVirtualMethod_internal (MonoDelegateHandle delegate, MonoError *error)
6576 error_init (error);
6578 MonoObjectHandle delegate_target = MONO_HANDLE_NEW_GET (MonoObject, delegate, target);
6579 MonoMethod *m = mono_object_handle_get_virtual_method (delegate_target, MONO_HANDLE_GETVAL (delegate, method), error);
6580 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
6581 return mono_method_get_object_handle (mono_domain_get (), m, m->klass, error);
6584 /* System.Buffer */
6586 static inline gint32
6587 mono_array_get_byte_length (MonoArray *array)
6589 MonoClass *klass;
6590 int length;
6591 int i;
6593 klass = array->obj.vtable->klass;
6595 if (array->bounds == NULL)
6596 length = array->max_length;
6597 else {
6598 length = 1;
6599 int klass_rank = m_class_get_rank (klass);
6600 for (i = 0; i < klass_rank; ++ i)
6601 length *= array->bounds [i].length;
6604 switch (m_class_get_byval_arg (m_class_get_element_class (klass))->type) {
6605 case MONO_TYPE_I1:
6606 case MONO_TYPE_U1:
6607 case MONO_TYPE_BOOLEAN:
6608 return length;
6609 case MONO_TYPE_I2:
6610 case MONO_TYPE_U2:
6611 case MONO_TYPE_CHAR:
6612 return length << 1;
6613 case MONO_TYPE_I4:
6614 case MONO_TYPE_U4:
6615 case MONO_TYPE_R4:
6616 return length << 2;
6617 case MONO_TYPE_I:
6618 case MONO_TYPE_U:
6619 return length * sizeof (gpointer);
6620 case MONO_TYPE_I8:
6621 case MONO_TYPE_U8:
6622 case MONO_TYPE_R8:
6623 return length << 3;
6624 default:
6625 return -1;
6629 gint32
6630 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array)
6632 return mono_array_get_byte_length (array);
6635 gint8
6636 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx)
6638 return mono_array_get_internal (array, gint8, idx);
6641 void
6642 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value)
6644 mono_array_set_internal (array, gint8, idx, value);
6647 void
6648 ves_icall_System_Buffer_MemcpyInternal (gpointer dest, gconstpointer src, gint32 count)
6650 memcpy (dest, src, count);
6653 MonoBoolean
6654 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count)
6656 guint8 *src_buf, *dest_buf;
6658 if (count < 0) {
6659 ERROR_DECL (error);
6660 mono_error_set_argument (error, "count", "is negative");
6661 mono_error_set_pending_exception (error);
6662 return FALSE;
6665 g_assert (count >= 0);
6667 /* This is called directly from the class libraries without going through the managed wrapper */
6668 MONO_CHECK_ARG_NULL (src, FALSE);
6669 MONO_CHECK_ARG_NULL (dest, FALSE);
6671 /* watch out for integer overflow */
6672 if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
6673 return FALSE;
6675 src_buf = (guint8 *)src->vector + src_offset;
6676 dest_buf = (guint8 *)dest->vector + dest_offset;
6678 if (src != dest)
6679 memcpy (dest_buf, src_buf, count);
6680 else
6681 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
6683 return TRUE;
6686 #ifndef DISABLE_REMOTING
6687 MonoObjectHandle
6688 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObjectHandle this_obj, MonoStringHandle class_name, MonoError *error)
6690 error_init (error);
6691 MonoDomain *domain = MONO_HANDLE_DOMAIN (this_obj);
6692 MonoRealProxyHandle rp = MONO_HANDLE_CAST (MonoRealProxy, this_obj);
6694 MonoObjectHandle res = mono_object_new_handle (domain, mono_defaults.transparent_proxy_class, error);
6695 return_val_if_nok (error, NULL_HANDLE);
6697 MonoTransparentProxyHandle tp = MONO_HANDLE_CAST (MonoTransparentProxy, res);
6699 MONO_HANDLE_SET (tp, rp, rp);
6701 MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
6702 MONO_HANDLE_GET (reftype, rp, class_to_proxy);
6703 MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
6704 MonoClass *klass = mono_class_from_mono_type_internal (type);
6706 // mono_remote_class_vtable cannot handle errors well, so force any loading error to occur early
6707 mono_class_setup_vtable (klass);
6708 if (mono_class_has_failure (klass)) {
6709 mono_error_set_for_class_failure (error, klass);
6710 return NULL_HANDLE;
6713 MonoObjectHandle remoting_obj = mono_object_handle_isinst (this_obj, mono_defaults.iremotingtypeinfo_class, error);
6714 return_val_if_nok (error, NULL_HANDLE);
6715 MONO_HANDLE_SETVAL (tp, custom_type_info, MonoBoolean, !MONO_HANDLE_IS_NULL (remoting_obj));
6717 MonoRemoteClass *remote_class = (MonoRemoteClass*)mono_remote_class (domain, class_name, klass, error);
6718 return_val_if_nok (error, NULL_HANDLE);
6719 MONO_HANDLE_SETVAL (tp, remote_class, MonoRemoteClass*, remote_class);
6721 MONO_HANDLE_SETVAL (res, vtable, MonoVTable*, (MonoVTable*)mono_remote_class_vtable (domain, remote_class, rp, error));
6722 return_val_if_nok (error, NULL_HANDLE);
6723 return res;
6726 MonoReflectionType *
6727 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
6729 ERROR_DECL (error);
6730 g_assert (tp != NULL && mono_object_class (tp) == mono_defaults.transparent_proxy_class);
6731 g_assert (tp->remote_class != NULL && tp->remote_class->proxy_class != NULL);
6732 MonoReflectionType *ret = mono_type_get_object_checked (mono_object_domain (tp), m_class_get_byval_arg (tp->remote_class->proxy_class), error);
6733 mono_error_set_pending_exception (error);
6735 return ret;
6737 #endif
6739 /* System.Environment */
6741 MonoStringHandle
6742 ves_icall_System_Environment_get_UserName (MonoError *error)
6744 error_init (error);
6745 /* using glib is more portable */
6746 const gchar *user_name = g_get_user_name ();
6747 if (user_name != NULL)
6748 return mono_string_new_handle (mono_domain_get (), user_name, error);
6749 else
6750 return NULL_HANDLE_STRING;
6753 #ifndef HOST_WIN32
6754 static MonoStringHandle
6755 mono_icall_get_machine_name (MonoError *error)
6757 error_init (error);
6758 #if !defined(DISABLE_SOCKETS)
6759 MonoStringHandle result;
6760 char *buf;
6761 int n, i;
6762 #if defined _SC_HOST_NAME_MAX
6763 n = sysconf (_SC_HOST_NAME_MAX);
6764 if (n == -1)
6765 #endif
6766 n = 512;
6767 buf = (char*)g_malloc (n + 1);
6769 #if defined(HAVE_GETHOSTNAME)
6770 if (gethostname (buf, n) == 0){
6771 buf [n] = 0;
6772 // try truncating the string at the first dot
6773 for (i = 0; i < n; i++) {
6774 if (buf [i] == '.') {
6775 buf [i] = 0;
6776 break;
6779 result = mono_string_new_handle (mono_domain_get (), buf, error);
6780 } else
6781 #endif
6782 result = MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
6784 g_free (buf);
6786 return result;
6787 #else
6788 return mono_string_new_handle (mono_domain_get (), "mono", error);
6789 #endif
6791 #endif /* !HOST_WIN32 */
6793 MonoStringHandle
6794 ves_icall_System_Environment_get_MachineName (MonoError *error)
6796 error_init (error);
6797 return mono_icall_get_machine_name (error);
6800 #ifndef HOST_WIN32
6801 static inline int
6802 mono_icall_get_platform (void)
6804 #if defined(__MACH__)
6805 /* OSX */
6807 // Notice that the value is hidden from user code, and only exposed
6808 // to mscorlib. This is due to Mono's Unix/MacOS code predating the
6809 // define and making assumptions based on Unix/128/4 values before there
6810 // was a MacOS define. Lots of code would assume that not-Unix meant
6811 // Windows, but in this case, it would be OSX.
6813 return 6;
6814 #else
6815 /* Unix */
6816 return 4;
6817 #endif
6819 #endif /* !HOST_WIN32 */
6822 ves_icall_System_Environment_get_Platform (void)
6824 return mono_icall_get_platform ();
6827 #ifndef HOST_WIN32
6828 static inline MonoStringHandle
6829 mono_icall_get_new_line (MonoError *error)
6831 error_init (error);
6832 return mono_string_new_handle (mono_domain_get (), "\n", error);
6834 #endif /* !HOST_WIN32 */
6836 MonoStringHandle
6837 ves_icall_System_Environment_get_NewLine (MonoError *error)
6839 return mono_icall_get_new_line (error);
6842 #ifndef HOST_WIN32
6843 static inline MonoBoolean
6844 mono_icall_is_64bit_os (void)
6846 #if SIZEOF_VOID_P == 8
6847 return TRUE;
6848 #else
6849 #if defined(HAVE_SYS_UTSNAME_H)
6850 struct utsname name;
6852 if (uname (&name) >= 0) {
6853 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;
6855 #endif
6856 return FALSE;
6857 #endif
6859 #endif /* !HOST_WIN32 */
6861 MonoBoolean
6862 ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
6864 return mono_icall_is_64bit_os ();
6867 MonoStringHandle
6868 ves_icall_System_Environment_GetEnvironmentVariable_native (const gchar *utf8_name, MonoError *error)
6870 gchar *value;
6872 if (utf8_name == NULL)
6873 return NULL_HANDLE_STRING;
6875 value = g_getenv (utf8_name);
6877 if (value == 0)
6878 return NULL_HANDLE_STRING;
6880 MonoStringHandle res = mono_string_new_handle (mono_domain_get (), value, error);
6881 g_free (value);
6882 return res;
6886 * There is no standard way to get at environ.
6888 #ifndef _MSC_VER
6889 #ifndef __MINGW32_VERSION
6890 #if defined(__APPLE__)
6891 #if defined (TARGET_OSX)
6892 /* Apple defines this in crt_externs.h but doesn't provide that header for
6893 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
6894 * in fact exist on all implementations (so far)
6896 G_BEGIN_DECLS
6897 gchar ***_NSGetEnviron(void);
6898 G_END_DECLS
6899 #define environ (*_NSGetEnviron())
6900 #else
6901 static char *mono_environ[1] = { NULL };
6902 #define environ mono_environ
6903 #endif /* defined (TARGET_OSX) */
6904 #else
6905 G_BEGIN_DECLS
6906 extern
6907 char **environ;
6908 G_END_DECLS
6909 #endif
6910 #endif
6911 #endif
6913 MonoArrayHandle
6914 ves_icall_System_Environment_GetCommandLineArgs (MonoError *error)
6916 error_init (error);
6917 MonoArrayHandle result = mono_runtime_get_main_args_handle (error);
6918 return result;
6921 #ifndef HOST_WIN32
6922 static MonoArray *
6923 mono_icall_get_environment_variable_names (MonoError *error)
6925 MonoArray *names;
6926 MonoDomain *domain;
6927 MonoString *str;
6928 gchar **e, **parts;
6929 int n;
6931 error_init (error);
6932 n = 0;
6933 for (e = environ; *e != 0; ++ e)
6934 ++ n;
6936 domain = mono_domain_get ();
6937 names = mono_array_new_checked (domain, mono_defaults.string_class, n, error);
6938 return_val_if_nok (error, NULL);
6940 n = 0;
6941 for (e = environ; *e != 0; ++ e) {
6942 parts = g_strsplit (*e, "=", 2);
6943 if (*parts != 0) {
6944 str = mono_string_new_checked (domain, *parts, error);
6945 if (!is_ok (error)) {
6946 g_strfreev (parts);
6947 return NULL;
6949 mono_array_setref_internal (names, n, str);
6952 g_strfreev (parts);
6954 ++ n;
6957 return names;
6959 #endif /* !HOST_WIN32 */
6961 MonoArray *
6962 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
6964 ERROR_DECL (error);
6965 MonoArray *result = mono_icall_get_environment_variable_names (error);
6966 mono_error_set_pending_exception (error);
6967 return result;
6970 void
6971 ves_icall_System_Environment_InternalSetEnvironmentVariable (const gunichar2 *name, gint32 name_length,
6972 const gunichar2 *value, gint32 value_length, MonoError *error)
6974 #ifdef HOST_WIN32
6975 if (!value || !value_length || !value [0])
6976 value = NULL;
6978 SetEnvironmentVariableW (name, value);
6979 #else
6980 char *utf8_name = NULL;
6981 char *utf8_value = NULL;
6983 utf8_name = mono_utf16_to_utf8 (name, name_length, error); // FIXME: this should be ascii
6984 goto_if_nok (error, exit);
6986 if (!value || !value_length || !value [0]) {
6987 g_unsetenv (utf8_name);
6988 goto exit;
6991 utf8_value = mono_utf16_to_utf8 (value, value_length, error);
6992 goto_if_nok (error, exit);
6994 g_setenv (utf8_name, utf8_value, TRUE);
6995 exit:
6996 g_free (utf8_name);
6997 g_free (utf8_value);
6998 #endif
7001 void
7002 ves_icall_System_Environment_Exit (int result)
7004 mono_environment_exitcode_set (result);
7006 if (!mono_runtime_try_shutdown ())
7007 mono_thread_exit ();
7009 /* Suspend all managed threads since the runtime is going away */
7010 mono_thread_suspend_all_other_threads ();
7012 mono_runtime_quit ();
7014 /* we may need to do some cleanup here... */
7015 exit (result);
7018 MonoStringHandle
7019 ves_icall_System_Environment_GetGacPath (MonoError *error)
7021 return mono_string_new_handle (mono_domain_get (), mono_assembly_getrootdir (), error);
7024 #ifndef HOST_WIN32
7025 static inline MonoStringHandle
7026 mono_icall_get_windows_folder_path (int folder, MonoError *error)
7028 error_init (error);
7029 g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
7030 return mono_string_new_handle (mono_domain_get (), "", error);
7032 #endif /* !HOST_WIN32 */
7034 MonoStringHandle
7035 ves_icall_System_Environment_GetWindowsFolderPath (int folder, MonoError *error)
7037 return mono_icall_get_windows_folder_path (folder, error);
7040 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
7041 static MonoArray *
7042 mono_icall_get_logical_drives (void)
7044 ERROR_DECL (error);
7045 gunichar2 buf [256], *ptr, *dname;
7046 gunichar2 *u16;
7047 guint initial_size = 127, size = 128;
7048 gint ndrives;
7049 MonoArray *result;
7050 MonoString *drivestr;
7051 MonoDomain *domain = mono_domain_get ();
7052 gint len;
7054 buf [0] = '\0';
7055 ptr = buf;
7057 while (size > initial_size) {
7058 size = (guint) mono_w32file_get_logical_drive (initial_size, ptr);
7059 if (size > initial_size) {
7060 if (ptr != buf)
7061 g_free (ptr);
7062 ptr = (gunichar2 *)g_malloc0 ((size + 1) * sizeof (gunichar2));
7063 initial_size = size;
7064 size++;
7068 /* Count strings */
7069 dname = ptr;
7070 ndrives = 0;
7071 do {
7072 while (*dname++);
7073 ndrives++;
7074 } while (*dname);
7076 dname = ptr;
7077 result = mono_array_new_checked (domain, mono_defaults.string_class, ndrives, error);
7078 if (mono_error_set_pending_exception (error))
7079 goto leave;
7081 ndrives = 0;
7082 do {
7083 len = 0;
7084 u16 = dname;
7085 while (*u16) { u16++; len ++; }
7086 drivestr = mono_string_new_utf16_checked (domain, dname, len, error);
7087 if (mono_error_set_pending_exception (error))
7088 goto leave;
7090 mono_array_setref_internal (result, ndrives++, drivestr);
7091 while (*dname++);
7092 } while (*dname);
7094 leave:
7095 if (ptr != buf)
7096 g_free (ptr);
7098 return result;
7100 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
7102 MonoArray *
7103 ves_icall_System_Environment_GetLogicalDrives (void)
7105 return mono_icall_get_logical_drives ();
7108 MonoStringHandle
7109 ves_icall_System_IO_DriveInfo_GetDriveFormat (const gunichar2 *path, gint32 path_length, MonoError *error)
7111 gunichar2 volume_name [MAX_PATH + 1];
7113 if (mono_w32file_get_file_system_type (path, volume_name, MAX_PATH + 1) == FALSE)
7114 return NULL_HANDLE_STRING;
7115 return mono_string_new_utf16_handle (mono_domain_get (), volume_name, g_utf16_len (volume_name), error);
7118 MonoStringHandle
7119 ves_icall_System_Environment_InternalGetHome (MonoError *error)
7121 const gchar *home_dir = g_get_home_dir ();
7122 if (home_dir != NULL)
7123 return mono_string_new_handle (mono_domain_get (), home_dir, error);
7124 else
7125 return NULL_HANDLE_STRING;
7128 static const char * const encodings [] = {
7129 (char *) 1,
7130 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
7131 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
7132 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
7133 (char *) 2,
7134 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
7135 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
7136 "x_unicode_2_0_utf_7",
7137 (char *) 3,
7138 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
7139 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
7140 (char *) 4,
7141 "utf_16", "UTF_16LE", "ucs_2", "unicode",
7142 "iso_10646_ucs2",
7143 (char *) 5,
7144 "unicodefffe", "utf_16be",
7145 (char *) 6,
7146 "iso_8859_1",
7147 (char *) 0
7151 * Returns the internal codepage, if the value of "int_code_page" is
7152 * 1 at entry, and we can not compute a suitable code page number,
7153 * returns the code page as a string
7155 MonoStringHandle
7156 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page, MonoError *error)
7158 error_init (error);
7159 const char *cset;
7160 const char *p;
7161 char *c;
7162 char *codepage = NULL;
7163 int code;
7164 int want_name = *int_code_page;
7165 int i;
7167 *int_code_page = -1;
7169 g_get_charset (&cset);
7170 c = codepage = g_strdup (cset);
7171 for (c = codepage; *c; c++){
7172 if (isascii (*c) && isalpha (*c))
7173 *c = tolower (*c);
7174 if (*c == '-')
7175 *c = '_';
7177 /* g_print ("charset: %s\n", cset); */
7179 /* handle some common aliases */
7180 p = encodings [0];
7181 code = 0;
7182 for (i = 0; p != 0; ){
7183 if ((gsize) p < 7){
7184 code = (gssize) p;
7185 p = encodings [++i];
7186 continue;
7188 if (strcmp (p, codepage) == 0){
7189 *int_code_page = code;
7190 break;
7192 p = encodings [++i];
7195 if (strstr (codepage, "utf_8") != NULL)
7196 *int_code_page |= 0x10000000;
7197 g_free (codepage);
7199 if (want_name && *int_code_page == -1)
7200 return mono_string_new_handle (mono_domain_get (), cset, error);
7201 return NULL_HANDLE_STRING;
7204 MonoBoolean
7205 ves_icall_System_Environment_get_HasShutdownStarted (void)
7207 return mono_runtime_is_shutting_down () || mono_domain_is_unloading (mono_domain_get ());
7210 #ifndef HOST_WIN32
7212 void
7213 ves_icall_System_Environment_BroadcastSettingChange (MonoError *error)
7217 #endif
7219 gint32
7220 ves_icall_System_Environment_get_TickCount (void)
7222 /* this will overflow after ~24 days */
7223 return (gint32) (mono_msec_boottime () & 0xffffffff);
7226 gint32
7227 ves_icall_System_Runtime_Versioning_VersioningHelper_GetRuntimeId (MonoError *error)
7229 return 9;
7232 #ifndef DISABLE_REMOTING
7233 MonoBoolean
7234 ves_icall_IsTransparentProxy (MonoObjectHandle proxy, MonoError *error)
7236 if (MONO_HANDLE_IS_NULL (proxy))
7237 return 0;
7239 if (mono_class_is_transparent_proxy (mono_handle_class (proxy)))
7240 return 1;
7242 return 0;
7245 MonoReflectionMethodHandle
7246 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
7247 MonoReflectionTypeHandle rtype, MonoReflectionMethodHandle rmethod, MonoError *error)
7249 MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
7251 if (MONO_HANDLE_IS_NULL (rtype)) {
7252 mono_error_set_argument_null (error, "type", "");
7253 return ret;
7255 if (MONO_HANDLE_IS_NULL (rmethod)) {
7256 mono_error_set_argument_null (error, "method", "");
7257 return ret;
7260 MonoMethod *method = MONO_HANDLE_GETVAL (rmethod, method);
7261 MonoType *type = MONO_HANDLE_GETVAL (rtype, type);
7262 MonoClass *klass = mono_class_from_mono_type_internal (type);
7263 mono_class_init_checked (klass, error);
7264 return_val_if_nok (error, ret);
7266 if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass))
7267 return ret;
7269 if (method->flags & METHOD_ATTRIBUTE_STATIC)
7270 return ret;
7272 if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
7273 if (klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE))
7274 ret = rmethod;
7275 return ret;
7278 mono_class_setup_vtable (klass);
7279 MonoMethod **vtable = m_class_get_vtable (klass);
7281 MonoMethod *res = NULL;
7282 if (mono_class_is_interface (method->klass)) {
7283 gboolean variance_used = FALSE;
7284 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
7285 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
7286 if (offs >= 0)
7287 res = vtable [offs + method->slot];
7288 } else {
7289 if (!(klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE)))
7290 return ret;
7292 if (method->slot != -1)
7293 res = vtable [method->slot];
7296 if (!res)
7297 return ret;
7299 ret = mono_method_get_object_handle (mono_domain_get (), res, NULL, error);
7300 return ret;
7303 void
7304 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
7306 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
7307 MonoVTable *vtable = mono_class_vtable_checked (mono_domain_get (), klass, error);
7308 return_if_nok (error);
7310 mono_vtable_set_is_remote (vtable, enable);
7313 #else /* DISABLE_REMOTING */
7315 void
7316 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
7318 g_assert_not_reached ();
7321 #endif
7323 MonoObjectHandle
7324 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionTypeHandle type, MonoError *error)
7326 MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
7327 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
7328 mono_class_init_checked (klass, error);
7329 return_val_if_nok (error, NULL_HANDLE);
7331 if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || mono_class_is_abstract (klass)) {
7332 mono_error_set_argument (error, "type", "Type cannot be instantiated");
7333 return NULL_HANDLE;
7336 if (m_class_get_rank (klass) >= 1) {
7337 g_assert (m_class_get_rank (klass) == 1);
7338 return MONO_HANDLE_CAST (MonoObject, mono_array_new_handle (domain, m_class_get_element_class (klass), 0, error));
7339 } else {
7340 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
7341 return_val_if_nok (error, NULL_HANDLE);
7343 /* Bypass remoting object creation check */
7344 return MONO_HANDLE_NEW (MonoObject, mono_object_new_alloc_specific_checked (vtable, error));
7348 MonoStringHandle
7349 ves_icall_System_IO_get_temp_path (MonoError *error)
7351 return mono_string_new_handle (mono_domain_get (), g_get_tmp_dir (), error);
7354 #if defined(ENABLE_MONODROID) || defined(ENABLE_MONOTOUCH)
7356 G_EXTERN_C gpointer CreateZStream (gint32 compress, MonoBoolean gzip, gpointer feeder, gpointer data);
7357 G_EXTERN_C gint32 CloseZStream (gpointer stream);
7358 G_EXTERN_C gint32 Flush (gpointer stream);
7359 G_EXTERN_C gint32 ReadZStream (gpointer stream, gpointer buffer, gint32 length);
7360 G_EXTERN_C gint32 WriteZStream (gpointer stream, gpointer buffer, gint32 length);
7362 gpointer
7363 ves_icall_System_IO_Compression_DeflateStreamNative_CreateZStream (gint32 compress, MonoBoolean gzip, gpointer feeder, gpointer data)
7365 #ifdef MONO_CROSS_COMPILE
7366 return NULL;
7367 #else
7368 return CreateZStream (compress, gzip, feeder, data);
7369 #endif
7372 gint32
7373 ves_icall_System_IO_Compression_DeflateStreamNative_CloseZStream (gpointer stream)
7375 #ifdef MONO_CROSS_COMPILE
7376 return 0;
7377 #else
7378 return CloseZStream (stream);
7379 #endif
7382 gint32
7383 ves_icall_System_IO_Compression_DeflateStreamNative_Flush (gpointer stream)
7385 #ifdef MONO_CROSS_COMPILE
7386 return 0;
7387 #else
7388 return Flush (stream);
7389 #endif
7392 gint32
7393 ves_icall_System_IO_Compression_DeflateStreamNative_ReadZStream (gpointer stream, gpointer buffer, gint32 length)
7395 #ifdef MONO_CROSS_COMPILE
7396 return 0;
7397 #else
7398 return ReadZStream (stream, buffer, length);
7399 #endif
7402 gint32
7403 ves_icall_System_IO_Compression_DeflateStreamNative_WriteZStream (gpointer stream, gpointer buffer, gint32 length)
7405 #ifdef MONO_CROSS_COMPILE
7406 return 0;
7407 #else
7408 return WriteZStream (stream, buffer, length);
7409 #endif
7412 #endif
7414 #ifndef PLATFORM_NO_DRIVEINFO
7415 MonoBoolean
7416 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (const gunichar2 *path_name, gint32 path_name_length, guint64 *free_bytes_avail,
7417 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
7418 gint32 *error)
7420 g_assert (error);
7421 g_assert (free_bytes_avail);
7422 g_assert (total_number_of_bytes);
7423 g_assert (total_number_of_free_bytes);
7425 // FIXME check for embedded nuls here or managed
7427 *error = ERROR_SUCCESS;
7428 *free_bytes_avail = (guint64)-1;
7429 *total_number_of_bytes = (guint64)-1;
7430 *total_number_of_free_bytes = (guint64)-1;
7432 gboolean result = mono_w32file_get_disk_free_space (path_name, free_bytes_avail, total_number_of_bytes, total_number_of_free_bytes);
7433 if (!result)
7434 *error = mono_w32error_get_last ();
7436 return result;
7438 #endif /* PLATFORM_NO_DRIVEINFO */
7440 gpointer
7441 ves_icall_RuntimeMethodHandle_GetFunctionPointer (MonoMethod *method, MonoError *error)
7443 return mono_compile_method_checked (method, error);
7446 MonoStringHandle
7447 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (MonoError *error)
7449 gchar *path;
7451 const char *mono_cfg_dir = mono_get_config_dir ();
7452 if (!mono_cfg_dir)
7453 return mono_string_new_handle (mono_domain_get (), "", error);
7455 path = g_build_path (G_DIR_SEPARATOR_S, mono_cfg_dir, "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
7457 mono_icall_make_platform_path (path);
7459 MonoStringHandle mcpath = mono_string_new_handle (mono_domain_get (), path, error);
7460 g_free (path);
7462 mono_error_assert_ok (error);
7464 return mcpath;
7467 MonoStringHandle
7468 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_app_config (MonoError *error)
7470 const gchar *app_config;
7471 MonoDomain *domain;
7472 gchar *config_file_name, *config_file_path;
7473 gsize len, config_file_path_length, config_ext_length;
7474 gchar *module;
7476 domain = mono_domain_get ();
7477 MonoStringHandle file = MONO_HANDLE_NEW (MonoString, domain->setup->configuration_file);
7478 if (MONO_HANDLE_IS_NULL (file) || MONO_HANDLE_GETVAL (file, length) == 0)
7479 return MONO_HANDLE_CAST (MonoString, mono_new_null ());
7481 // Retrieve config file and remove the extension
7482 config_file_name = mono_string_handle_to_utf8 (file, error);
7483 return_val_if_nok (error, MONO_HANDLE_CAST (MonoString, NULL_HANDLE));
7485 config_file_path = mono_portability_find_file (config_file_name, TRUE);
7486 if (!config_file_path)
7487 config_file_path = config_file_name;
7489 config_file_path_length = strlen (config_file_path);
7490 config_ext_length = strlen (".config");
7491 if (config_file_path_length <= config_ext_length) {
7492 if (config_file_name != config_file_path)
7493 g_free (config_file_name);
7494 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
7497 len = config_file_path_length - config_ext_length;
7498 module = (gchar *)g_malloc0 (len + 1);
7499 memcpy (module, config_file_path, len);
7500 // Get the config file from the module name
7501 app_config = mono_config_string_for_assembly_file (module);
7502 // Clean-up
7503 g_free (module);
7504 if (config_file_name != config_file_path)
7505 g_free (config_file_name);
7506 g_free (config_file_path);
7508 if (!app_config)
7509 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
7511 return mono_string_new_handle (mono_domain_get (), app_config, error);
7514 static MonoStringHandle
7515 get_bundled_machine_config (MonoError *error)
7517 const gchar *machine_config;
7519 machine_config = mono_get_machine_config ();
7521 if (!machine_config)
7522 return NULL_HANDLE_STRING;
7524 return mono_string_new_handle (mono_domain_get (), machine_config, error);
7527 MonoStringHandle
7528 ves_icall_System_Environment_get_bundled_machine_config (MonoError *error)
7530 return get_bundled_machine_config (error);
7534 MonoStringHandle
7535 ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
7537 return get_bundled_machine_config (error);
7540 MonoStringHandle
7541 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
7543 return get_bundled_machine_config (error);
7547 MonoStringHandle
7548 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (MonoError *error)
7550 const char *mono_cfg_dir = mono_get_config_dir ();
7551 if (!mono_cfg_dir)
7552 return mono_string_new_handle (mono_domain_get (), "", error);
7554 char *path = g_path_get_dirname (mono_cfg_dir);
7556 mono_icall_make_platform_path (path);
7558 MonoStringHandle ipath = mono_string_new_handle (mono_domain_get (), path, error);
7559 g_free (path);
7561 return ipath;
7564 MonoBoolean
7565 ves_icall_get_resources_ptr (MonoReflectionAssemblyHandle assembly, gpointer *result, gint32 *size, MonoError *error)
7567 MonoPEResourceDataEntry *entry;
7568 MonoImage *image;
7570 if (MONO_HANDLE_IS_NULL (assembly) || !result || !size)
7571 return FALSE;
7573 *result = NULL;
7574 *size = 0;
7575 MonoAssembly *assm = MONO_HANDLE_GETVAL (assembly, assembly);
7576 image = assm->image;
7577 entry = (MonoPEResourceDataEntry *)mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
7578 if (!entry)
7579 return FALSE;
7581 *result = mono_image_rva_map (image, entry->rde_data_offset);
7582 if (!(*result)) {
7583 g_free (entry);
7584 return FALSE;
7586 *size = entry->rde_size;
7587 g_free (entry);
7588 return TRUE;
7591 MonoBoolean
7592 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (MonoError *error)
7594 return mono_is_debugger_attached ();
7597 MonoBoolean
7598 ves_icall_System_Diagnostics_Debugger_IsLogging (MonoError *error)
7600 return mono_get_runtime_callbacks ()->debug_log_is_enabled
7601 && mono_get_runtime_callbacks ()->debug_log_is_enabled ();
7604 void
7605 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoStringHandle category, MonoStringHandle message, MonoError *error)
7607 if (mono_get_runtime_callbacks ()->debug_log)
7608 mono_get_runtime_callbacks ()->debug_log (level, category, message);
7611 #ifndef HOST_WIN32
7612 static inline void
7613 mono_icall_write_windows_debug_string (const gunichar2 *message)
7615 g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
7617 #endif /* !HOST_WIN32 */
7619 void
7620 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (const gunichar2 *message, MonoError *error)
7622 mono_icall_write_windows_debug_string (message);
7625 /* Only used for value types */
7626 MonoObjectHandle
7627 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
7629 MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
7630 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7631 MonoClass *klass = mono_class_from_mono_type_internal (type);
7633 mono_class_init_checked (klass, error);
7634 return_val_if_nok (error, NULL_HANDLE);
7636 if (mono_class_is_nullable (klass))
7637 /* No arguments -> null */
7638 return NULL_HANDLE;
7640 return mono_object_new_handle (domain, klass, error);
7643 MonoReflectionMethodHandle
7644 ves_icall_RuntimeMethodInfo_get_base_method (MonoReflectionMethodHandle m, MonoBoolean definition, MonoError *error)
7646 MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
7648 MonoMethod *base = mono_method_get_base_method (method, definition, error);
7649 return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
7650 if (base == method) {
7651 /* we want to short-circuit and return 'm' here. But we should
7652 return the same method object that
7653 mono_method_get_object_handle, below would return. Since
7654 that call takes NULL for the reftype argument, it will take
7655 base->klass as the reflected type for the MonoMethod. So we
7656 need to check that m also has base->klass as the reflected
7657 type. */
7658 MonoReflectionTypeHandle orig_reftype = MONO_HANDLE_NEW_GET (MonoReflectionType, m, reftype);
7659 MonoClass *orig_klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (orig_reftype, type));
7660 if (base->klass == orig_klass)
7661 return m;
7663 return mono_method_get_object_handle (mono_domain_get (), base, NULL, error);
7666 MonoStringHandle
7667 ves_icall_RuntimeMethodInfo_get_name (MonoReflectionMethodHandle m, MonoError *error)
7669 MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
7671 MonoStringHandle s = mono_string_new_handle (MONO_HANDLE_DOMAIN (m), method->name, error);
7672 return_val_if_nok (error, NULL_HANDLE_STRING);
7673 MONO_HANDLE_SET (m, name, s);
7674 return s;
7677 void
7678 ves_icall_System_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
7680 iter->sig = *(MonoMethodSignature**)argsp;
7682 g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
7683 g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
7685 iter->next_arg = 0;
7686 /* FIXME: it's not documented what start is exactly... */
7687 if (start) {
7688 iter->args = start;
7689 } else {
7690 iter->args = argsp + sizeof (gpointer);
7692 iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
7694 /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
7697 void
7698 ves_icall_System_ArgIterator_IntGetNextArg (MonoArgIterator *iter, MonoTypedRef *res)
7700 guint32 i, arg_size;
7701 gint32 align;
7703 i = iter->sig->sentinelpos + iter->next_arg;
7705 g_assert (i < iter->sig->param_count);
7707 res->type = iter->sig->params [i];
7708 res->klass = mono_class_from_mono_type_internal (res->type);
7709 arg_size = mono_type_stack_size (res->type, &align);
7710 #if defined(__arm__) || defined(__mips__)
7711 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7712 #endif
7713 res->value = iter->args;
7714 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
7715 if (arg_size <= sizeof (gpointer)) {
7716 int dummy;
7717 int padding = arg_size - mono_type_size (res->type, &dummy);
7718 res->value = (guint8*)res->value + padding;
7720 #endif
7721 iter->args = (char*)iter->args + arg_size;
7722 iter->next_arg++;
7724 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res->type->type, arg_size, res->value); */
7727 void
7728 ves_icall_System_ArgIterator_IntGetNextArgWithType (MonoArgIterator *iter, MonoTypedRef *res, MonoType *type)
7730 guint32 i, arg_size;
7731 gint32 align;
7733 i = iter->sig->sentinelpos + iter->next_arg;
7735 g_assert (i < iter->sig->param_count);
7737 while (i < iter->sig->param_count) {
7738 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
7739 continue;
7740 res->type = iter->sig->params [i];
7741 res->klass = mono_class_from_mono_type_internal (res->type);
7742 /* FIXME: endianess issue... */
7743 arg_size = mono_type_stack_size (res->type, &align);
7744 #if defined(__arm__) || defined(__mips__)
7745 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7746 #endif
7747 res->value = iter->args;
7748 iter->args = (char*)iter->args + arg_size;
7749 iter->next_arg++;
7750 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7751 return;
7753 /* g_print ("arg type 0x%02x not found\n", res.type->type); */
7755 memset (res, 0, sizeof (MonoTypedRef));
7758 MonoType*
7759 ves_icall_System_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
7761 gint i;
7763 i = iter->sig->sentinelpos + iter->next_arg;
7765 g_assert (i < iter->sig->param_count);
7767 return iter->sig->params [i];
7770 MonoObjectHandle
7771 ves_icall_System_TypedReference_ToObject (MonoTypedRef* tref, MonoError *error)
7773 return typed_reference_to_object (tref, error);
7776 void
7777 ves_icall_System_TypedReference_InternalMakeTypedReference (MonoTypedRef *res, MonoObjectHandle target, MonoArrayHandle fields, MonoReflectionTypeHandle last_field, MonoError *error)
7779 MonoClass *klass;
7780 MonoType *ftype = NULL;
7781 int i;
7783 memset (res, 0, sizeof (MonoTypedRef));
7785 g_assert (mono_array_handle_length (fields) > 0);
7787 klass = mono_handle_class (target);
7789 int offset = 0;
7790 for (i = 0; i < mono_array_handle_length (fields); ++i) {
7791 MonoClassField *f;
7792 MONO_HANDLE_ARRAY_GETVAL (f, fields, MonoClassField*, i);
7794 g_assert (f);
7796 if (i == 0)
7797 offset = f->offset;
7798 else
7799 offset += f->offset - sizeof (MonoObject);
7800 klass = mono_class_from_mono_type_internal (f->type);
7801 ftype = f->type;
7804 res->type = ftype;
7805 res->klass = mono_class_from_mono_type_internal (ftype);
7806 res->value = (guint8*)MONO_HANDLE_RAW (target) + offset;
7809 static void
7810 prelink_method (MonoMethod *method, MonoError *error)
7812 const char *exc_class, *exc_arg;
7814 error_init (error);
7815 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7816 return;
7817 mono_lookup_pinvoke_call_internal (method, &exc_class, &exc_arg);
7818 if (exc_class) {
7819 mono_error_set_generic_error (error, "System", exc_class, "%s", exc_arg);
7820 return;
7822 /* create the wrapper, too? */
7825 void
7826 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethodHandle method, MonoError *error)
7828 error_init (error);
7830 prelink_method (MONO_HANDLE_GETVAL (method, method), error);
7833 void
7834 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionTypeHandle type, MonoError *error)
7836 error_init (error);
7837 MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (type, type));
7838 MonoMethod* m;
7839 gpointer iter = NULL;
7841 mono_class_init_checked (klass, error);
7842 return_if_nok (error);
7844 while ((m = mono_class_get_methods (klass, &iter))) {
7845 prelink_method (m, error);
7846 return_if_nok (error);
7851 * used by System.Runtime.InteropServices.RuntimeInformation.(OS|Process)Architecture;
7852 * which use them in different ways for filling in an enum
7854 MonoStringHandle
7855 ves_icall_System_Runtime_InteropServices_RuntimeInformation_get_RuntimeArchitecture (MonoError *error)
7857 error_init (error);
7858 return mono_string_new_handle (mono_domain_get (), mono_config_get_cpu (), error);
7862 ves_icall_Interop_Sys_DoubleToString(double value, char *format, char *buffer, int bufferLength)
7864 #if defined(TARGET_ARM)
7865 /* workaround for faulty vcmp.f64 implementation on some 32bit ARM CPUs */
7866 guint64 bits = *(guint64 *) &value;
7867 if (bits == 0x1) { /* 4.9406564584124654E-324 */
7868 g_assert (!strcmp (format, "%.40e"));
7869 return snprintf (buffer, bufferLength, "%s", "4.9406564584124654417656879286822137236506e-324");
7870 } else if (bits == 0x4) { /* 2E-323 */
7871 g_assert (!strcmp (format, "%.40e"));
7872 return snprintf (buffer, bufferLength, "%s", "1.9762625833649861767062751714728854894602e-323");
7874 #endif
7876 return snprintf(buffer, bufferLength, format, value);
7879 void
7880 ves_icall_System_Runtime_RuntimeImports_ecvt_s(char *buffer, size_t sizeInBytes, double value, int count, int* dec, int* sign)
7882 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
7883 _ecvt_s(buffer, sizeInBytes, value, count, dec, sign);
7884 #endif
7888 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
7889 void
7890 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
7891 gint32 const **exponents,
7892 gunichar2 const **digitLowerTable,
7893 gunichar2 const **digitUpperTable,
7894 gint64 const **tenPowersList,
7895 gint32 const **decHexDigits)
7897 *mantissas = Formatter_MantissaBitsTable;
7898 *exponents = Formatter_TensExponentTable;
7899 *digitLowerTable = Formatter_DigitLowerTable;
7900 *digitUpperTable = Formatter_DigitUpperTable;
7901 *tenPowersList = Formatter_TenPowersList;
7902 *decHexDigits = Formatter_DecHexDigits;
7905 static gboolean
7906 add_modifier_to_array (MonoDomain *domain, MonoImage *image, MonoCustomMod *modifier, MonoArrayHandle dest, int dest_idx, MonoError *error)
7908 HANDLE_FUNCTION_ENTER ();
7909 error_init (error);
7910 MonoClass *klass = mono_class_get_checked (image, modifier->token, error);
7911 goto_if_nok (error, leave);
7913 MonoReflectionTypeHandle rt;
7914 rt = mono_type_get_object_handle (domain, m_class_get_byval_arg (klass), error);
7915 goto_if_nok (error, leave);
7917 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rt);
7918 leave:
7919 HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
7923 * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
7924 * and avoid useless allocations.
7926 static MonoArrayHandle
7927 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error)
7929 int i, count = 0;
7930 MonoDomain *domain = mono_domain_get ();
7932 MonoCustomModContainer *cmods = mono_type_get_cmods (type);
7933 if (!cmods)
7934 goto fail;
7936 error_init (error);
7937 for (i = 0; i < cmods->count; ++i) {
7938 if ((optional && !cmods->modifiers [i].required) || (!optional && cmods->modifiers [i].required))
7939 count++;
7941 if (!count)
7942 goto fail;
7944 MonoArrayHandle res;
7945 res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
7946 goto_if_nok (error, fail);
7947 count = 0;
7948 for (i = cmods->count - 1; i >= 0; --i) {
7949 if ((optional && !cmods->modifiers [i].required) || (!optional && cmods->modifiers [i].required)) {
7950 if (!add_modifier_to_array (domain, image, &cmods->modifiers [i], res, count , error))
7951 goto fail;
7952 count++;
7955 return res;
7956 fail:
7957 return MONO_HANDLE_NEW (MonoArray, NULL);
7960 MonoArrayHandle
7961 ves_icall_RuntimeParameterInfo_GetTypeModifiers (MonoReflectionParameterHandle param, MonoBoolean optional, MonoError *error)
7963 error_init (error);
7964 MonoReflectionTypeHandle rt = MONO_HANDLE_NEW (MonoReflectionType, NULL);
7965 MONO_HANDLE_GET (rt, param, ClassImpl);
7966 MonoType *type = MONO_HANDLE_GETVAL (rt, type);
7967 MonoObjectHandle member = MONO_HANDLE_NEW (MonoObject, NULL);
7968 MONO_HANDLE_GET (member, param, MemberImpl);
7969 MonoClass *member_class = mono_handle_class (member);
7970 MonoMethod *method = NULL;
7971 MonoImage *image;
7972 int pos;
7973 MonoMethodSignature *sig;
7975 if (mono_class_is_reflection_method_or_constructor (member_class)) {
7976 method = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionMethod, member), method);
7977 } else if (m_class_get_image (member_class) == mono_defaults.corlib && !strcmp ("RuntimePropertyInfo", m_class_get_name (member_class))) {
7978 MonoProperty *prop = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionProperty, member), property);
7979 if (!(method = prop->get))
7980 method = prop->set;
7981 g_assert (method);
7982 } else {
7983 char *type_name = mono_type_get_full_name (member_class);
7984 mono_error_set_not_supported (error, "Custom modifiers on a ParamInfo with member %s are not supported", type_name);
7985 g_free (type_name);
7986 return NULL_HANDLE_ARRAY;
7989 image = m_class_get_image (method->klass);
7990 pos = MONO_HANDLE_GETVAL (param, PositionImpl);
7991 sig = mono_method_signature_internal (method);
7992 if (pos == -1)
7993 type = sig->ret;
7994 else
7995 type = sig->params [pos];
7997 return type_array_from_modifiers (image, type, optional, error);
8000 static MonoType*
8001 get_property_type (MonoProperty *prop)
8003 MonoMethodSignature *sig;
8004 if (prop->get) {
8005 sig = mono_method_signature_internal (prop->get);
8006 return sig->ret;
8007 } else if (prop->set) {
8008 sig = mono_method_signature_internal (prop->set);
8009 return sig->params [sig->param_count - 1];
8011 return NULL;
8014 MonoArrayHandle
8015 ves_icall_RuntimePropertyInfo_GetTypeModifiers (MonoReflectionPropertyHandle property, MonoBoolean optional, MonoError *error)
8017 error_init (error);
8018 MonoProperty *prop = MONO_HANDLE_GETVAL (property, property);
8019 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
8020 MonoType *type = get_property_type (prop);
8021 MonoImage *image = m_class_get_image (klass);
8023 if (!type)
8024 return NULL_HANDLE_ARRAY;
8025 return type_array_from_modifiers (image, type, optional, error);
8029 *Construct a MonoType suited to be used to decode a constant blob object.
8031 * @type is the target type which will be constructed
8032 * @blob_type is the blob type, for example, that comes from the constant table
8033 * @real_type is the expected constructed type.
8035 static void
8036 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
8038 type->type = blob_type;
8039 type->data.klass = NULL;
8040 if (blob_type == MONO_TYPE_CLASS)
8041 type->data.klass = mono_defaults.object_class;
8042 else if (real_type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (real_type->data.klass)) {
8043 /* For enums, we need to use the base type */
8044 type->type = MONO_TYPE_VALUETYPE;
8045 type->data.klass = mono_class_from_mono_type_internal (real_type);
8046 } else
8047 type->data.klass = mono_class_from_mono_type_internal (real_type);
8050 MonoObject*
8051 ves_icall_property_info_get_default_value (MonoReflectionProperty *property)
8053 ERROR_DECL (error);
8054 MonoType blob_type;
8055 MonoProperty *prop = property->property;
8056 MonoType *type = get_property_type (prop);
8057 MonoDomain *domain = mono_object_domain (property);
8058 MonoTypeEnum def_type;
8059 const char *def_value;
8060 MonoObject *o;
8062 mono_class_init_internal (prop->parent);
8064 if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT)) {
8065 mono_error_set_invalid_operation (error, NULL);
8066 mono_error_set_pending_exception (error);
8067 return NULL;
8070 def_value = mono_class_get_property_default_value (prop, &def_type);
8072 mono_type_from_blob_type (&blob_type, def_type, type);
8073 o = mono_get_object_from_blob (domain, &blob_type, def_value, error);
8075 mono_error_set_pending_exception (error);
8076 return o;
8079 MonoBoolean
8080 ves_icall_MonoCustomAttrs_IsDefinedInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, MonoError *error)
8082 error_init (error);
8083 MonoClass *attr_class = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (attr_type, type));
8085 mono_class_init_checked (attr_class, error);
8086 return_val_if_nok (error, FALSE);
8088 MonoCustomAttrInfo *cinfo = mono_reflection_get_custom_attrs_info_checked (obj, error);
8089 return_val_if_nok (error, FALSE);
8091 if (!cinfo)
8092 return FALSE;
8093 gboolean found = mono_custom_attrs_has_attr (cinfo, attr_class);
8094 if (!cinfo->cached)
8095 mono_custom_attrs_free (cinfo);
8096 return found;
8099 MonoArrayHandle
8100 ves_icall_MonoCustomAttrs_GetCustomAttributesInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, MonoBoolean pseudoattrs, MonoError *error)
8102 MonoClass *attr_class;
8103 if (MONO_HANDLE_IS_NULL (attr_type))
8104 attr_class = NULL;
8105 else
8106 attr_class = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (attr_type, type));
8108 if (attr_class) {
8109 mono_class_init_checked (attr_class, error);
8110 return_val_if_nok (error, NULL_HANDLE_ARRAY);
8113 return mono_reflection_get_custom_attrs_by_type_handle (obj, attr_class, error);
8116 MonoArrayHandle
8117 ves_icall_MonoCustomAttrs_GetCustomAttributesDataInternal (MonoObjectHandle obj, MonoError *error)
8119 error_init (error);
8120 return mono_reflection_get_custom_attrs_data_checked (obj, error);
8124 MonoStringHandle
8125 ves_icall_Mono_Runtime_GetDisplayName (MonoError *error)
8127 char *info;
8128 MonoStringHandle display_name;
8130 error_init (error);
8131 info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
8132 display_name = mono_string_new_handle (mono_domain_get (), info, error);
8133 g_free (info);
8134 return display_name;
8137 #ifndef HOST_WIN32
8138 static inline gint32
8139 mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
8141 return WAIT_TIMEOUT;
8143 #endif /* !HOST_WIN32 */
8145 gint32
8146 ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle (gpointer handle, gint32 milliseconds, MonoError *error)
8148 return mono_icall_wait_for_input_idle (handle, milliseconds);
8151 gint32
8152 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcessId (MonoError *error)
8154 return mono_process_current_pid ();
8157 MonoBoolean
8158 ves_icall_Mono_TlsProviderFactory_IsBtlsSupported (MonoError *error)
8160 #if HAVE_BTLS
8161 return TRUE;
8162 #else
8163 return FALSE;
8164 #endif
8167 #ifndef DISABLE_COM
8170 ves_icall_System_Runtime_InteropServices_Marshal_GetHRForException_WinRT(MonoExceptionHandle ex, MonoError *error)
8172 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetHRForException_WinRT internal call is not implemented.");
8173 return 0;
8176 MonoObjectHandle
8177 ves_icall_System_Runtime_InteropServices_Marshal_GetNativeActivationFactory(MonoObjectHandle type, MonoError *error)
8179 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetNativeActivationFactory internal call is not implemented.");
8180 return NULL_HANDLE;
8183 void*
8184 ves_icall_System_Runtime_InteropServices_Marshal_GetRawIUnknownForComObjectNoAddRef(MonoObjectHandle obj, MonoError *error)
8186 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.Marshal.GetRawIUnknownForComObjectNoAddRef internal call is not implemented.");
8187 return NULL;
8190 MonoObjectHandle
8191 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_GetRestrictedErrorInfo(MonoError *error)
8193 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.GetRestrictedErrorInfo internal call is not implemented.");
8194 return NULL_HANDLE;
8197 MonoBoolean
8198 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoOriginateLanguageException (int ierr, MonoStringHandle message, void* languageException, MonoError *error)
8200 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoOriginateLanguageException internal call is not implemented.");
8201 return FALSE;
8204 void
8205 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoReportUnhandledError (MonoObjectHandle oerr, MonoError *error)
8207 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoReportUnhandledError internal call is not implemented.");
8211 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsCreateString(MonoStringHandle sourceString, int length, void** hstring, MonoError *error)
8213 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString internal call is not implemented.");
8214 return 0;
8218 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsDeleteString(void* hstring, MonoError *error)
8220 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString internal call is not implemented.");
8221 return 0;
8224 mono_unichar2*
8225 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsGetStringRawBuffer(void* hstring, unsigned* length, MonoError *error)
8227 mono_error_set_not_implemented (error, "System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsGetStringRawBuffer internal call is not implemented.");
8228 return NULL;
8231 #endif
8233 void
8234 ves_icall_System_IO_LogcatTextWriter_Log (const char *appname, gint32 level, const char *message)
8236 g_log (appname, (GLogLevelFlags)level, "%s", message);
8239 static MonoIcallTableCallbacks icall_table;
8240 static mono_mutex_t icall_mutex;
8241 static GHashTable *icall_hash = NULL;
8242 static GHashTable *icall_hash_foreign = NULL;
8243 static GHashTable *jit_icall_hash_name = NULL;
8244 static GHashTable *jit_icall_hash_addr = NULL;
8246 void
8247 mono_install_icall_table_callbacks (MonoIcallTableCallbacks *cb)
8249 g_assert (cb->version == MONO_ICALL_TABLE_CALLBACKS_VERSION);
8250 memcpy (&icall_table, cb, sizeof (MonoIcallTableCallbacks));
8253 void
8254 mono_icall_init (void)
8256 #ifndef DISABLE_ICALL_TABLES
8257 mono_icall_table_init ();
8258 #endif
8259 icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8260 icall_hash_foreign = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8261 mono_os_mutex_init (&icall_mutex);
8264 static void
8265 mono_icall_lock (void)
8267 mono_locks_os_acquire (&icall_mutex, IcallLock);
8270 static void
8271 mono_icall_unlock (void)
8273 mono_locks_os_release (&icall_mutex, IcallLock);
8276 void
8277 mono_icall_cleanup (void)
8279 g_hash_table_destroy (icall_hash);
8280 g_hash_table_destroy (icall_hash_foreign);
8281 g_hash_table_destroy (jit_icall_hash_name);
8282 g_hash_table_destroy (jit_icall_hash_addr);
8283 mono_os_mutex_destroy (&icall_mutex);
8287 * mono_add_internal_call:
8288 * \param name method specification to surface to the managed world
8289 * \param method pointer to a C method to invoke when the method is called
8291 * This method surfaces the C function pointed by \p method as a method
8292 * that has been surfaced in managed code with the method specified in
8293 * \p name as an internal call.
8295 * Internal calls are surfaced to all app domains loaded and they are
8296 * accessibly by a type with the specified name.
8298 * You must provide a fully qualified type name, that is namespaces
8299 * and type name, followed by a colon and the method name, with an
8300 * optional signature to bind.
8302 * For example, the following are all valid declarations:
8304 * \c MyApp.Services.ScriptService:Accelerate
8306 * \c MyApp.Services.ScriptService:Slowdown(int,bool)
8308 * You use method parameters in cases where there might be more than
8309 * one surface method to managed code. That way you can register different
8310 * internal calls for different method overloads.
8312 * The internal calls are invoked with no marshalling. This means that .NET
8313 * types like \c System.String are exposed as \c MonoString* parameters. This is
8314 * different than the way that strings are surfaced in P/Invoke.
8316 * For more information on how the parameters are marshalled, see the
8317 * <a href="http://www.mono-project.com/docs/advanced/embedding/">Mono Embedding</a>
8318 * page.
8320 * See the <a href="mono-api-methods.html#method-desc">Method Description</a>
8321 * reference for more information on the format of method descriptions.
8323 void
8324 mono_add_internal_call (const char *name, gconstpointer method)
8326 mono_add_internal_call_with_flags (name, method, FALSE);
8330 * mono_dangerous_add_raw_internal_call:
8331 * \param name method specification to surface to the managed world
8332 * \param method pointer to a C method to invoke when the method is called
8334 * Similar to \c mono_add_internal_call but with more requirements for correct
8335 * operation.
8337 * A thread running a dangerous raw internal call will avoid a thread state
8338 * transition on entry and exit, but it must take responsiblity for cooperating
8339 * with the Mono runtime.
8341 * The \p method must NOT:
8343 * Run for an unbounded amount of time without calling the mono runtime.
8344 * Additionally, the method must switch to GC Safe mode to perform all blocking
8345 * operations: performing blocking I/O, taking locks, etc.
8348 void
8349 mono_dangerous_add_raw_internal_call (const char *name, gconstpointer method)
8351 mono_add_internal_call_with_flags (name, method, TRUE);
8355 * mono_add_internal_call_with_flags:
8356 * \param name method specification to surface to the managed world
8357 * \param method pointer to a C method to invoke when the method is called
8358 * \param cooperative if \c TRUE, run icall in GC Unsafe (cooperatively suspended) mode,
8359 * otherwise GC Safe (blocking)
8361 * Like \c mono_add_internal_call, but if \p cooperative is \c TRUE the added
8362 * icall promises that it will use the coopertive API to inform the runtime
8363 * when it is running blocking operations, that it will not run for unbounded
8364 * amounts of time without safepointing, and that it will not hold managed
8365 * object references across suspend safepoints.
8367 * If \p cooperative is \c FALSE, run the icall in GC Safe mode - the icall may
8368 * block. The icall must obey the GC Safe rules, e.g. it must not touch
8369 * unpinned managed memory.
8372 void
8373 mono_add_internal_call_with_flags (const char *name, gconstpointer method, gboolean cooperative)
8375 mono_icall_lock ();
8377 g_hash_table_insert (cooperative ? icall_hash : icall_hash_foreign , g_strdup (name), (gpointer) method);
8379 mono_icall_unlock ();
8382 void
8383 mono_add_internal_call_internal (const char *name, gconstpointer method)
8385 mono_add_internal_call_with_flags (name, method, TRUE);
8389 * we should probably export this as an helper (handle nested types).
8390 * Returns the number of chars written in buf.
8392 static int
8393 concat_class_name (char *buf, int bufsize, MonoClass *klass)
8395 int nspacelen, cnamelen;
8396 nspacelen = strlen (m_class_get_name_space (klass));
8397 cnamelen = strlen (m_class_get_name (klass));
8398 if (nspacelen + cnamelen + 2 > bufsize)
8399 return 0;
8400 if (nspacelen) {
8401 memcpy (buf, m_class_get_name_space (klass), nspacelen);
8402 buf [nspacelen ++] = '.';
8404 memcpy (buf + nspacelen, m_class_get_name (klass), cnamelen);
8405 buf [nspacelen + cnamelen] = 0;
8406 return nspacelen + cnamelen;
8409 static void
8410 no_icall_table (void)
8412 g_assert_not_reached ();
8416 * mono_lookup_internal_call_full:
8417 * \param method the method to look up
8418 * \param uses_handles out argument if method needs handles around managed objects.
8419 * \returns a pointer to the icall code for the given method. If
8420 * \p uses_handles is not NULL, it will be set to TRUE if the method
8421 * needs managed objects wrapped using the infrastructure in handle.h
8423 * If the method is not found, warns and returns NULL.
8425 gpointer
8426 mono_lookup_internal_call_full (MonoMethod *method, gboolean warn_on_missing, mono_bool *uses_handles, mono_bool *foreign)
8428 char *sigstart;
8429 char *tmpsig;
8430 char mname [2048];
8431 char *classname;
8432 int typelen = 0, mlen, siglen;
8433 gpointer res;
8435 if (uses_handles)
8436 *uses_handles = FALSE;
8437 if (foreign)
8438 *foreign = FALSE;
8440 g_assert (method != NULL);
8442 if (method->is_inflated)
8443 method = ((MonoMethodInflated *) method)->declaring;
8445 if (m_class_get_nested_in (method->klass)) {
8446 int pos = concat_class_name (mname, sizeof (mname)-2, m_class_get_nested_in (method->klass));
8447 if (!pos)
8448 return NULL;
8450 mname [pos++] = '/';
8451 mname [pos] = 0;
8453 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
8454 if (!typelen)
8455 return NULL;
8457 typelen += pos;
8458 } else {
8459 typelen = concat_class_name (mname, sizeof (mname), method->klass);
8460 if (!typelen)
8461 return NULL;
8464 classname = g_strdup (mname);
8466 mname [typelen] = ':';
8467 mname [typelen + 1] = ':';
8469 mlen = strlen (method->name);
8470 memcpy (mname + typelen + 2, method->name, mlen);
8471 sigstart = mname + typelen + 2 + mlen;
8472 *sigstart = 0;
8474 tmpsig = mono_signature_get_desc (mono_method_signature_internal (method), TRUE);
8475 siglen = strlen (tmpsig);
8476 if (typelen + mlen + siglen + 6 > sizeof (mname)) {
8477 g_free (classname);
8478 return NULL;
8480 sigstart [0] = '(';
8481 memcpy (sigstart + 1, tmpsig, siglen);
8482 sigstart [siglen + 1] = ')';
8483 sigstart [siglen + 2] = 0;
8484 g_free (tmpsig);
8486 /* mono_marshal_get_native_wrapper () depends on this */
8487 if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor"))
8488 return (gpointer)ves_icall_System_String_ctor_RedirectToCreateString;
8490 mono_icall_lock ();
8492 res = g_hash_table_lookup (icall_hash, mname);
8493 if (res) {
8494 g_free (classname);
8495 mono_icall_unlock ();
8496 return res;
8498 res = g_hash_table_lookup (icall_hash_foreign, mname);
8499 if (res) {
8500 if (foreign)
8501 *foreign = TRUE;
8502 g_free (classname);
8503 mono_icall_unlock ();
8504 return res;
8507 /* try without signature */
8508 *sigstart = 0;
8509 res = g_hash_table_lookup (icall_hash, mname);
8510 if (res) {
8511 g_free (classname);
8512 mono_icall_unlock ();
8513 return res;
8515 res = g_hash_table_lookup (icall_hash_foreign, mname);
8516 if (res) {
8517 if (foreign)
8518 *foreign = TRUE;
8519 g_free (classname);
8520 mono_icall_unlock ();
8521 return res;
8524 if (!icall_table.lookup) {
8525 mono_icall_unlock ();
8526 g_free (classname);
8527 /* Fail only when the result is actually used */
8528 return (gpointer)no_icall_table;
8529 } else {
8530 res = icall_table.lookup (method, classname, sigstart - mlen, sigstart, uses_handles);
8531 g_free (classname);
8533 mono_icall_unlock ();
8535 if (res)
8536 return res;
8538 if (warn_on_missing) {
8539 g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
8540 g_print ("\nYour mono runtime and class libraries are out of sync.\n");
8541 g_print ("The out of sync library is: %s\n", m_class_get_image (method->klass)->name);
8542 g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
8543 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");
8544 g_print ("If you see other errors or faults after this message they are probably related\n");
8545 g_print ("and you need to fix your mono install first.\n");
8548 return NULL;
8553 * mono_lookup_internal_call:
8555 gpointer
8556 mono_lookup_internal_call (MonoMethod *method)
8558 return mono_lookup_internal_call_full (method, TRUE, NULL, NULL);
8562 * mono_lookup_icall_symbol:
8564 * Given the icall METHOD, returns its C symbol.
8566 const char*
8567 mono_lookup_icall_symbol (MonoMethod *m)
8569 if (!icall_table.lookup_icall_symbol)
8570 return NULL;
8572 gpointer func;
8573 func = mono_lookup_internal_call_full (m, FALSE, NULL, NULL);
8574 if (!func)
8575 return NULL;
8576 return icall_table.lookup_icall_symbol (func);
8579 static MonoType*
8580 type_from_typename (char *type_name)
8582 MonoClass *klass = NULL; /* assignment to shut GCC warning up */
8584 if (!strcmp (type_name, "int"))
8585 klass = mono_defaults.int_class;
8586 else if (!strcmp (type_name, "ptr&"))
8587 return mono_class_get_byref_type (mono_defaults.int_class);
8588 else if (!strcmp (type_name, "ptr"))
8589 klass = mono_defaults.int_class;
8590 else if (!strcmp (type_name, "void"))
8591 klass = mono_defaults.void_class;
8592 else if (!strcmp (type_name, "int32"))
8593 klass = mono_defaults.int32_class;
8594 else if (!strcmp (type_name, "uint32"))
8595 klass = mono_defaults.uint32_class;
8596 else if (!strcmp (type_name, "int8"))
8597 klass = mono_defaults.sbyte_class;
8598 else if (!strcmp (type_name, "uint8"))
8599 klass = mono_defaults.byte_class;
8600 else if (!strcmp (type_name, "int16"))
8601 klass = mono_defaults.int16_class;
8602 else if (!strcmp (type_name, "uint16"))
8603 klass = mono_defaults.uint16_class;
8604 else if (!strcmp (type_name, "long"))
8605 klass = mono_defaults.int64_class;
8606 else if (!strcmp (type_name, "ulong"))
8607 klass = mono_defaults.uint64_class;
8608 else if (!strcmp (type_name, "float"))
8609 klass = mono_defaults.single_class;
8610 else if (!strcmp (type_name, "double"))
8611 klass = mono_defaults.double_class;
8612 else if (!strcmp (type_name, "object"))
8613 klass = mono_defaults.object_class;
8614 else if (!strcmp (type_name, "obj"))
8615 klass = mono_defaults.object_class;
8616 else if (!strcmp (type_name, "string"))
8617 klass = mono_defaults.string_class;
8618 else if (!strcmp (type_name, "bool"))
8619 klass = mono_defaults.boolean_class;
8620 else if (!strcmp (type_name, "boolean"))
8621 klass = mono_defaults.boolean_class;
8622 else {
8623 g_error ("%s", type_name);
8624 g_assert_not_reached ();
8626 return m_class_get_byval_arg (klass);
8630 * LOCKING: Take the corlib image lock.
8632 MonoMethodSignature*
8633 mono_create_icall_signature (const char *sigstr)
8635 gchar **parts;
8636 int i, len;
8637 gchar **tmp;
8638 MonoMethodSignature *res, *res2;
8639 MonoImage *corlib = mono_defaults.corlib;
8641 mono_image_lock (corlib);
8642 res = (MonoMethodSignature *)g_hash_table_lookup (corlib->helper_signatures, sigstr);
8643 mono_image_unlock (corlib);
8645 if (res)
8646 return res;
8648 parts = g_strsplit (sigstr, " ", 256);
8650 tmp = parts;
8651 len = 0;
8652 while (*tmp) {
8653 len ++;
8654 tmp ++;
8657 res = mono_metadata_signature_alloc (corlib, len - 1);
8658 res->pinvoke = 1;
8660 #if defined(TARGET_WIN32) && defined(TARGET_X86)
8662 * Under windows, the default pinvoke calling convention is STDCALL but
8663 * we need CDECL.
8665 res->call_convention = MONO_CALL_C;
8666 #endif
8668 res->ret = type_from_typename (parts [0]);
8669 for (i = 1; i < len; ++i) {
8670 res->params [i - 1] = type_from_typename (parts [i]);
8673 g_strfreev (parts);
8675 mono_image_lock (corlib);
8676 res2 = (MonoMethodSignature *)g_hash_table_lookup (corlib->helper_signatures, sigstr);
8677 if (res2)
8678 res = res2; /*Value is allocated in the image pool*/
8679 else
8680 g_hash_table_insert (corlib->helper_signatures, (gpointer)sigstr, res);
8681 mono_image_unlock (corlib);
8683 return res;
8686 MonoJitICallInfo *
8687 mono_find_jit_icall_by_name (const char *name)
8689 MonoJitICallInfo *info;
8690 g_assert (jit_icall_hash_name);
8692 mono_icall_lock ();
8693 info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name);
8694 mono_icall_unlock ();
8695 return info;
8698 MonoJitICallInfo *
8699 mono_find_jit_icall_by_addr (gconstpointer addr)
8701 MonoJitICallInfo *info;
8702 g_assert (jit_icall_hash_addr);
8704 mono_icall_lock ();
8705 info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
8706 mono_icall_unlock ();
8708 return info;
8712 * mono_get_jit_icall_info:
8714 * Return the hashtable mapping JIT icall names to MonoJitICallInfo structures. The
8715 * caller should access it while holding the icall lock.
8717 GHashTable*
8718 mono_get_jit_icall_info (void)
8720 return jit_icall_hash_name;
8724 * mono_lookup_jit_icall_symbol:
8726 * Given the jit icall NAME, returns its C symbol if possible, or NULL.
8728 const char*
8729 mono_lookup_jit_icall_symbol (const char *name)
8731 MonoJitICallInfo *info;
8732 const char *res = NULL;
8734 mono_icall_lock ();
8735 info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name);
8736 if (info)
8737 res = info->c_symbol;
8738 mono_icall_unlock ();
8739 return res;
8742 void
8743 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
8745 mono_icall_lock ();
8746 g_hash_table_insert (jit_icall_hash_addr, (gpointer)wrapper, info);
8747 mono_icall_unlock ();
8750 MonoJitICallInfo *
8751 mono_register_jit_icall_full (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean avoid_wrapper, const char *c_symbol)
8753 MonoJitICallInfo *info;
8755 g_assert (func);
8756 g_assert (name);
8758 mono_icall_lock ();
8760 if (!jit_icall_hash_name) {
8761 jit_icall_hash_name = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
8762 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
8765 if ((info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name))) {
8766 g_warning ("jit icall already defined \"%s\" \"%s\" %p %p\n", name, info->name, func, info->func);
8767 g_assert_not_reached ();
8770 info = g_new0 (MonoJitICallInfo, 1);
8772 info->name = name;
8773 info->func = func;
8774 info->sig = sig;
8775 info->c_symbol = c_symbol;
8777 if (avoid_wrapper) {
8778 info->wrapper = func;
8779 } else {
8780 info->wrapper = NULL;
8783 g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
8784 g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
8786 mono_icall_unlock ();
8787 return info;
8790 MonoJitICallInfo *
8791 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean no_wrapper)
8793 return mono_register_jit_icall_full (func, name, sig, no_wrapper, NULL);
8797 ves_icall_System_GC_GetCollectionCount (int generation)
8799 return mono_gc_collection_count (generation);
8803 ves_icall_System_GC_GetGeneration (MonoObjectHandle object, MonoError *error)
8805 return mono_gc_get_generation (MONO_HANDLE_RAW (object));
8809 ves_icall_System_GC_GetMaxGeneration (void)
8811 return mono_gc_max_generation ();
8814 gint64
8815 ves_icall_System_GC_GetAllocatedBytesForCurrentThread (void)
8817 return 0; // TODO: implement https://github.com/mono/mono/issues/8397
8820 void
8821 ves_icall_System_GC_RecordPressure (gint64 value)
8823 mono_gc_add_memory_pressure (value);
8826 gint64
8827 ves_icall_System_Diagnostics_Stopwatch_GetTimestamp (void)
8829 return mono_100ns_ticks ();
8832 gint64
8833 ves_icall_System_Threading_Timer_GetTimeMonotonic (void)
8835 return mono_100ns_ticks ();
8838 gint64
8839 ves_icall_System_DateTime_GetSystemTimeAsFileTime (void)
8841 return mono_100ns_datetime ();
8845 ves_icall_System_Threading_Thread_SystemMaxStackSize (void)
8847 return mono_thread_info_get_system_max_stack_size ();
8850 MonoBoolean
8851 ves_icall_System_Threading_Thread_YieldInternal (void)
8853 mono_threads_platform_yield ();
8854 return TRUE;
8857 gint32
8858 ves_icall_System_Environment_get_ProcessorCount (void)
8860 return mono_cpu_count ();
8863 #if defined(ENABLE_MONODROID)
8865 G_EXTERN_C gint32 CreateNLSocket (void);
8866 G_EXTERN_C gint32 ReadEvents (gpointer sock, gpointer buffer, gint32 count, gint32 size);
8867 G_EXTERN_C gint32 CloseNLSocket (gpointer sock);
8869 gint32
8870 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CreateNLSocket (void)
8872 return CreateNLSocket ();
8875 gint32
8876 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_ReadEvents (gpointer sock, gpointer buffer, gint32 count, gint32 size)
8878 return ReadEvents (sock, buffer, count, size);
8881 gint32
8882 ves_icall_System_Net_NetworkInformation_LinuxNetworkChange_CloseNLSocket (gpointer sock)
8884 return CloseNLSocket (sock);
8887 #endif
8889 // Generate wrappers.
8891 #define ICALL_TYPE(id,name,first) /* nothing */
8892 #define ICALL(id,name,func) /* nothing */
8893 #define NOHANDLES(inner) /* nothing */
8895 #define MONO_HANDLE_REGISTER_ICALL(func, ret, nargs, argtypes) MONO_HANDLE_REGISTER_ICALL_IMPLEMENT (func, ret, nargs, argtypes)
8897 // Some native functions are exposed via multiple managed names.
8898 // Producing a wrapper for these results in duplicate wrappers with the same names,
8899 // which fails to compile. Do not produce such duplicate wrappers. Alternatively,
8900 // a one line native function with a different name that calls the main one could be used.
8901 // i.e. the wrapper would also have a different name.
8902 #define HANDLES_REUSE_WRAPPER(...) /* nothing */
8904 #define HANDLES(id, name, func, ret, nargs, argtypes) \
8905 MONO_HANDLE_DECLARE (id, name, func, ret, nargs, argtypes); \
8906 MONO_HANDLE_IMPLEMENT (id, name, func, ret, nargs, argtypes)
8908 #include "metadata/icall-def.h"
8910 #undef HANDLES
8911 #undef HANDLES_REUSE_WRAPPER
8912 #undef ICALL_TYPE
8913 #undef ICALL
8914 #undef NOHANDLES
8915 #undef MONO_HANDLE_REGISTER_ICALL