Remove the mono-profiler- prefix from all source files in the profiler subdir.
[mono.git] / mono / metadata / icall.c
1 /**
2  * \file
3  *
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)
10  *
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.
15  */
16
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/reflection-internals.h>
58 #include <mono/metadata/marshal.h>
59 #include <mono/metadata/gc-internals.h>
60 #include <mono/metadata/mono-gc.h>
61 #include <mono/metadata/rand.h>
62 #include <mono/metadata/sysmath.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/handle.h>
85 #include <mono/metadata/w32mutex.h>
86 #include <mono/metadata/w32semaphore.h>
87 #include <mono/metadata/w32event.h>
88 #include <mono/utils/monobitset.h>
89 #include <mono/utils/mono-time.h>
90 #include <mono/utils/mono-proclib.h>
91 #include <mono/utils/mono-string.h>
92 #include <mono/utils/mono-error-internals.h>
93 #include <mono/utils/mono-mmap.h>
94 #include <mono/utils/mono-io-portability.h>
95 #include <mono/utils/mono-digest.h>
96 #include <mono/utils/bsearch.h>
97 #include <mono/utils/mono-os-mutex.h>
98 #include <mono/utils/mono-threads.h>
99 #include <mono/metadata/w32error.h>
100 #include <mono/utils/w32api.h>
101
102 #include "decimal-ms.h"
103 #include "number-ms.h"
104
105 #if !defined(HOST_WIN32) && defined(HAVE_SYS_UTSNAME_H)
106 #include <sys/utsname.h>
107 #endif
108
109 extern MonoStringHandle ves_icall_System_Environment_GetOSVersionString (MonoError *error);
110
111 ICALL_EXPORT MonoReflectionAssemblyHandle ves_icall_System_Reflection_Assembly_GetCallingAssembly (MonoError *error);
112
113 /* Lazy class loading functions */
114 static GENERATE_GET_CLASS_WITH_CACHE (system_version, "System", "Version")
115 static GENERATE_GET_CLASS_WITH_CACHE (assembly_name, "System.Reflection", "AssemblyName")
116 static GENERATE_GET_CLASS_WITH_CACHE (constructor_info, "System.Reflection", "ConstructorInfo")
117 static GENERATE_GET_CLASS_WITH_CACHE (property_info, "System.Reflection", "PropertyInfo")
118 static GENERATE_GET_CLASS_WITH_CACHE (event_info, "System.Reflection", "EventInfo")
119 static GENERATE_GET_CLASS_WITH_CACHE (module, "System.Reflection", "Module")
120
121 static MonoArrayHandle
122 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error);
123
124 static inline MonoBoolean
125 is_generic_parameter (MonoType *type)
126 {
127         return !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR);
128 }
129
130 static void
131 mono_class_init_checked (MonoClass *klass, MonoError *error)
132 {
133         error_init (error);
134
135         if (!mono_class_init (klass))
136                 mono_error_set_for_class_failure (error, klass);
137 }
138
139 #ifndef HOST_WIN32
140 static inline void
141 mono_icall_make_platform_path (gchar *path)
142 {
143         return;
144 }
145
146 static inline const gchar *
147 mono_icall_get_file_path_prefix (const gchar *path)
148 {
149         return "file://";
150 }
151 #endif /* HOST_WIN32 */
152
153 ICALL_EXPORT MonoObject *
154 ves_icall_System_Array_GetValueImpl (MonoArray *arr, guint32 pos)
155 {
156         MonoError error;
157         MonoClass *ac;
158         gint32 esize;
159         gpointer *ea;
160         MonoObject *result = NULL;
161
162         ac = (MonoClass *)arr->obj.vtable->klass;
163
164         esize = mono_array_element_size (ac);
165         ea = (gpointer*)((char*)arr->vector + (pos * esize));
166
167         if (ac->element_class->valuetype) {
168                 result = mono_value_box_checked (arr->obj.vtable->domain, ac->element_class, ea, &error);
169                 mono_error_set_pending_exception (&error);
170         } else
171                 result = (MonoObject *)*ea;
172         return result;
173 }
174
175 ICALL_EXPORT MonoObject *
176 ves_icall_System_Array_GetValue (MonoArray *arr, MonoArray *idxs)
177 {
178         MonoClass *ac, *ic;
179         MonoArray *io;
180         gint32 i, pos, *ind;
181
182         MONO_CHECK_ARG_NULL (idxs, NULL);
183
184         io = idxs;
185         ic = (MonoClass *)io->obj.vtable->klass;
186         
187         ac = (MonoClass *)arr->obj.vtable->klass;
188
189         g_assert (ic->rank == 1);
190         if (io->bounds != NULL || io->max_length !=  ac->rank) {
191                 mono_set_pending_exception (mono_get_exception_argument (NULL, NULL));
192                 return NULL;
193         }
194
195         ind = (gint32 *)io->vector;
196
197         if (arr->bounds == NULL) {
198                 if (*ind < 0 || *ind >= arr->max_length) {
199                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
200                         return NULL;
201                 }
202
203                 return ves_icall_System_Array_GetValueImpl (arr, *ind);
204         }
205         
206         for (i = 0; i < ac->rank; i++) {
207                 if ((ind [i] < arr->bounds [i].lower_bound) ||
208                     (ind [i] >=  (mono_array_lower_bound_t)arr->bounds [i].length + arr->bounds [i].lower_bound)) {
209                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
210                         return NULL;
211                 }
212         }
213
214         pos = ind [0] - arr->bounds [0].lower_bound;
215         for (i = 1; i < ac->rank; i++)
216                 pos = pos * arr->bounds [i].length + ind [i] - 
217                         arr->bounds [i].lower_bound;
218
219         return ves_icall_System_Array_GetValueImpl (arr, pos);
220 }
221
222 ICALL_EXPORT void
223 ves_icall_System_Array_SetValueImpl (MonoArray *arr, MonoObject *value, guint32 pos)
224 {
225         MonoError error;
226         MonoClass *ac, *vc, *ec;
227         gint32 esize, vsize;
228         gpointer *ea, *va;
229         int et, vt;
230
231         guint64 u64 = 0;
232         gint64 i64 = 0;
233         gdouble r64 = 0;
234
235         error_init (&error);
236
237         if (value)
238                 vc = value->vtable->klass;
239         else
240                 vc = NULL;
241
242         ac = arr->obj.vtable->klass;
243         ec = ac->element_class;
244
245         esize = mono_array_element_size (ac);
246         ea = (gpointer*)((char*)arr->vector + (pos * esize));
247         va = (gpointer*)((char*)value + sizeof (MonoObject));
248
249         if (mono_class_is_nullable (ec)) {
250                 mono_nullable_init ((guint8*)ea, value, ec);
251                 return;
252         }
253
254         if (!value) {
255                 mono_gc_bzero_atomic (ea, esize);
256                 return;
257         }
258
259 #define NO_WIDENING_CONVERSION G_STMT_START{\
260         mono_set_pending_exception (mono_get_exception_argument ( \
261                 "value", "not a widening conversion")); \
262         return; \
263 }G_STMT_END
264
265 #define CHECK_WIDENING_CONVERSION(extra) G_STMT_START{\
266                 if (esize < vsize + (extra)) {                                                    \
267                         mono_set_pending_exception (mono_get_exception_argument (       \
268                         "value", "not a widening conversion")); \
269                         return;                                                                 \
270                 } \
271 }G_STMT_END
272
273 #define INVALID_CAST G_STMT_START{ \
274                 mono_get_runtime_callbacks ()->set_cast_details (vc, ec); \
275         mono_set_pending_exception (mono_get_exception_invalid_cast ()); \
276         return; \
277 }G_STMT_END
278
279         /* Check element (destination) type. */
280         switch (ec->byval_arg.type) {
281         case MONO_TYPE_STRING:
282                 switch (vc->byval_arg.type) {
283                 case MONO_TYPE_STRING:
284                         break;
285                 default:
286                         INVALID_CAST;
287                 }
288                 break;
289         case MONO_TYPE_BOOLEAN:
290                 switch (vc->byval_arg.type) {
291                 case MONO_TYPE_BOOLEAN:
292                         break;
293                 case MONO_TYPE_CHAR:
294                 case MONO_TYPE_U1:
295                 case MONO_TYPE_U2:
296                 case MONO_TYPE_U4:
297                 case MONO_TYPE_U8:
298                 case MONO_TYPE_I1:
299                 case MONO_TYPE_I2:
300                 case MONO_TYPE_I4:
301                 case MONO_TYPE_I8:
302                 case MONO_TYPE_R4:
303                 case MONO_TYPE_R8:
304                         NO_WIDENING_CONVERSION;
305                 default:
306                         INVALID_CAST;
307                 }
308                 break;
309         default:
310                 break;
311         }
312
313         if (!ec->valuetype) {
314                 gboolean castOk = (NULL != mono_object_isinst_checked (value, ec, &error));
315                 if (mono_error_set_pending_exception (&error))
316                         return;
317                 if (!castOk)
318                         INVALID_CAST;
319                 mono_gc_wbarrier_set_arrayref (arr, ea, (MonoObject*)value);
320                 return;
321         }
322
323         if (mono_object_isinst_checked (value, ec, &error)) {
324                 if (ec->has_references)
325                         mono_value_copy (ea, (char*)value + sizeof (MonoObject), ec);
326                 else
327                         mono_gc_memmove_atomic (ea, (char *)value + sizeof (MonoObject), esize);
328                 return;
329         }
330         if (mono_error_set_pending_exception (&error))
331                 return;
332
333         if (!vc->valuetype)
334                 INVALID_CAST;
335
336         vsize = mono_class_instance_size (vc) - sizeof (MonoObject);
337
338         et = ec->byval_arg.type;
339         if (et == MONO_TYPE_VALUETYPE && ec->byval_arg.data.klass->enumtype)
340                 et = mono_class_enum_basetype (ec->byval_arg.data.klass)->type;
341
342         vt = vc->byval_arg.type;
343         if (vt == MONO_TYPE_VALUETYPE && vc->byval_arg.data.klass->enumtype)
344                 vt = mono_class_enum_basetype (vc->byval_arg.data.klass)->type;
345
346 #define ASSIGN_UNSIGNED(etype) G_STMT_START{\
347         switch (vt) { \
348         case MONO_TYPE_U1: \
349         case MONO_TYPE_U2: \
350         case MONO_TYPE_U4: \
351         case MONO_TYPE_U8: \
352         case MONO_TYPE_CHAR: \
353                 CHECK_WIDENING_CONVERSION(0); \
354                 *(etype *) ea = (etype) u64; \
355                 return; \
356         /* You can't assign a signed value to an unsigned array. */ \
357         case MONO_TYPE_I1: \
358         case MONO_TYPE_I2: \
359         case MONO_TYPE_I4: \
360         case MONO_TYPE_I8: \
361         /* You can't assign a floating point number to an integer array. */ \
362         case MONO_TYPE_R4: \
363         case MONO_TYPE_R8: \
364                 NO_WIDENING_CONVERSION; \
365         } \
366 }G_STMT_END
367
368 #define ASSIGN_SIGNED(etype) G_STMT_START{\
369         switch (vt) { \
370         case MONO_TYPE_I1: \
371         case MONO_TYPE_I2: \
372         case MONO_TYPE_I4: \
373         case MONO_TYPE_I8: \
374                 CHECK_WIDENING_CONVERSION(0); \
375                 *(etype *) ea = (etype) i64; \
376                 return; \
377         /* You can assign an unsigned value to a signed array if the array's */ \
378         /* element size is larger than the value size. */ \
379         case MONO_TYPE_U1: \
380         case MONO_TYPE_U2: \
381         case MONO_TYPE_U4: \
382         case MONO_TYPE_U8: \
383         case MONO_TYPE_CHAR: \
384                 CHECK_WIDENING_CONVERSION(1); \
385                 *(etype *) ea = (etype) u64; \
386                 return; \
387         /* You can't assign a floating point number to an integer array. */ \
388         case MONO_TYPE_R4: \
389         case MONO_TYPE_R8: \
390                 NO_WIDENING_CONVERSION; \
391         } \
392 }G_STMT_END
393
394 #define ASSIGN_REAL(etype) G_STMT_START{\
395         switch (vt) { \
396         case MONO_TYPE_R4: \
397         case MONO_TYPE_R8: \
398                 CHECK_WIDENING_CONVERSION(0); \
399                 *(etype *) ea = (etype) r64; \
400                 return; \
401         /* All integer values fit into a floating point array, so we don't */ \
402         /* need to CHECK_WIDENING_CONVERSION here. */ \
403         case MONO_TYPE_I1: \
404         case MONO_TYPE_I2: \
405         case MONO_TYPE_I4: \
406         case MONO_TYPE_I8: \
407                 *(etype *) ea = (etype) i64; \
408                 return; \
409         case MONO_TYPE_U1: \
410         case MONO_TYPE_U2: \
411         case MONO_TYPE_U4: \
412         case MONO_TYPE_U8: \
413         case MONO_TYPE_CHAR: \
414                 *(etype *) ea = (etype) u64; \
415                 return; \
416         } \
417 }G_STMT_END
418
419         switch (vt) {
420         case MONO_TYPE_U1:
421                 u64 = *(guint8 *) va;
422                 break;
423         case MONO_TYPE_U2:
424                 u64 = *(guint16 *) va;
425                 break;
426         case MONO_TYPE_U4:
427                 u64 = *(guint32 *) va;
428                 break;
429         case MONO_TYPE_U8:
430                 u64 = *(guint64 *) va;
431                 break;
432         case MONO_TYPE_I1:
433                 i64 = *(gint8 *) va;
434                 break;
435         case MONO_TYPE_I2:
436                 i64 = *(gint16 *) va;
437                 break;
438         case MONO_TYPE_I4:
439                 i64 = *(gint32 *) va;
440                 break;
441         case MONO_TYPE_I8:
442                 i64 = *(gint64 *) va;
443                 break;
444         case MONO_TYPE_R4:
445                 r64 = *(gfloat *) va;
446                 break;
447         case MONO_TYPE_R8:
448                 r64 = *(gdouble *) va;
449                 break;
450         case MONO_TYPE_CHAR:
451                 u64 = *(guint16 *) va;
452                 break;
453         case MONO_TYPE_BOOLEAN:
454                 /* Boolean is only compatible with itself. */
455                 switch (et) {
456                 case MONO_TYPE_CHAR:
457                 case MONO_TYPE_U1:
458                 case MONO_TYPE_U2:
459                 case MONO_TYPE_U4:
460                 case MONO_TYPE_U8:
461                 case MONO_TYPE_I1:
462                 case MONO_TYPE_I2:
463                 case MONO_TYPE_I4:
464                 case MONO_TYPE_I8:
465                 case MONO_TYPE_R4:
466                 case MONO_TYPE_R8:
467                         NO_WIDENING_CONVERSION;
468                 default:
469                         INVALID_CAST;
470                 }
471                 break;
472         }
473
474         /* If we can't do a direct copy, let's try a widening conversion. */
475         switch (et) {
476         case MONO_TYPE_CHAR:
477                 ASSIGN_UNSIGNED (guint16);
478         case MONO_TYPE_U1:
479                 ASSIGN_UNSIGNED (guint8);
480         case MONO_TYPE_U2:
481                 ASSIGN_UNSIGNED (guint16);
482         case MONO_TYPE_U4:
483                 ASSIGN_UNSIGNED (guint32);
484         case MONO_TYPE_U8:
485                 ASSIGN_UNSIGNED (guint64);
486         case MONO_TYPE_I1:
487                 ASSIGN_SIGNED (gint8);
488         case MONO_TYPE_I2:
489                 ASSIGN_SIGNED (gint16);
490         case MONO_TYPE_I4:
491                 ASSIGN_SIGNED (gint32);
492         case MONO_TYPE_I8:
493                 ASSIGN_SIGNED (gint64);
494         case MONO_TYPE_R4:
495                 ASSIGN_REAL (gfloat);
496         case MONO_TYPE_R8:
497                 ASSIGN_REAL (gdouble);
498         }
499
500         INVALID_CAST;
501         /* Not reached, INVALID_CAST does not return. Just to avoid a compiler warning ... */
502         return;
503
504 #undef INVALID_CAST
505 #undef NO_WIDENING_CONVERSION
506 #undef CHECK_WIDENING_CONVERSION
507 #undef ASSIGN_UNSIGNED
508 #undef ASSIGN_SIGNED
509 #undef ASSIGN_REAL
510 }
511
512 ICALL_EXPORT void 
513 ves_icall_System_Array_SetValue (MonoArray *arr, MonoObject *value,
514                                  MonoArray *idxs)
515 {
516         MonoClass *ac, *ic;
517         gint32 i, pos, *ind;
518
519         MONO_CHECK_ARG_NULL (idxs,);
520
521         ic = idxs->obj.vtable->klass;
522         ac = arr->obj.vtable->klass;
523
524         g_assert (ic->rank == 1);
525         if (idxs->bounds != NULL || idxs->max_length != ac->rank) {
526                 mono_set_pending_exception (mono_get_exception_argument (NULL, NULL));
527                 return;
528         }
529
530         ind = (gint32 *)idxs->vector;
531
532         if (arr->bounds == NULL) {
533                 if (*ind < 0 || *ind >= arr->max_length) {
534                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
535                         return;
536                 }
537
538                 ves_icall_System_Array_SetValueImpl (arr, value, *ind);
539                 return;
540         }
541         
542         for (i = 0; i < ac->rank; i++)
543                 if ((ind [i] < arr->bounds [i].lower_bound) ||
544                     (ind [i] >= (mono_array_lower_bound_t)arr->bounds [i].length + arr->bounds [i].lower_bound)) {
545                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
546                         return;
547                 }
548
549         pos = ind [0] - arr->bounds [0].lower_bound;
550         for (i = 1; i < ac->rank; i++)
551                 pos = pos * arr->bounds [i].length + ind [i] - 
552                         arr->bounds [i].lower_bound;
553
554         ves_icall_System_Array_SetValueImpl (arr, value, pos);
555 }
556
557 ICALL_EXPORT MonoArray *
558 ves_icall_System_Array_CreateInstanceImpl (MonoReflectionType *type, MonoArray *lengths, MonoArray *bounds)
559 {
560         MonoError error;
561         MonoClass *aklass, *klass;
562         MonoArray *array;
563         uintptr_t *sizes, i;
564         gboolean bounded = FALSE;
565
566         MONO_CHECK_ARG_NULL (type, NULL);
567         MONO_CHECK_ARG_NULL (lengths, NULL);
568
569         MONO_CHECK_ARG (lengths, mono_array_length (lengths) > 0, NULL);
570         if (bounds)
571                 MONO_CHECK_ARG (bounds, mono_array_length (lengths) == mono_array_length (bounds), NULL);
572
573         for (i = 0; i < mono_array_length (lengths); i++) {
574                 if (mono_array_get (lengths, gint32, i) < 0) {
575                         mono_set_pending_exception (mono_get_exception_argument_out_of_range (NULL));
576                         return NULL;
577                 }
578         }
579
580         klass = mono_class_from_mono_type (type->type);
581         mono_class_init_checked (klass, &error);
582         if (mono_error_set_pending_exception (&error))
583                 return NULL;
584
585         if (klass->element_class->byval_arg.type == MONO_TYPE_VOID) {
586                 mono_set_pending_exception (mono_get_exception_not_supported ("Arrays of System.Void are not supported."));
587                 return NULL;
588         }
589
590         if (bounds && (mono_array_length (bounds) == 1) && (mono_array_get (bounds, gint32, 0) != 0))
591                 /* vectors are not the same as one dimensional arrays with no-zero bounds */
592                 bounded = TRUE;
593         else
594                 bounded = FALSE;
595
596         aklass = mono_bounded_array_class_get (klass, mono_array_length (lengths), bounded);
597
598         sizes = (uintptr_t *)alloca (aklass->rank * sizeof(intptr_t) * 2);
599         for (i = 0; i < aklass->rank; ++i) {
600                 sizes [i] = mono_array_get (lengths, guint32, i);
601                 if (bounds)
602                         sizes [i + aklass->rank] = mono_array_get (bounds, gint32, i);
603                 else
604                         sizes [i + aklass->rank] = 0;
605         }
606
607         array = mono_array_new_full_checked (mono_object_domain (type), aklass, sizes, (intptr_t*)sizes + aklass->rank, &error);
608         mono_error_set_pending_exception (&error);
609
610         return array;
611 }
612
613 ICALL_EXPORT MonoArray *
614 ves_icall_System_Array_CreateInstanceImpl64 (MonoReflectionType *type, MonoArray *lengths, MonoArray *bounds)
615 {
616         MonoError error;
617         MonoClass *aklass, *klass;
618         MonoArray *array;
619         uintptr_t *sizes, i;
620         gboolean bounded = FALSE;
621
622         MONO_CHECK_ARG_NULL (type, NULL);
623         MONO_CHECK_ARG_NULL (lengths, NULL);
624
625         MONO_CHECK_ARG (lengths, mono_array_length (lengths) > 0, NULL);
626         if (bounds)
627                 MONO_CHECK_ARG (bounds, mono_array_length (lengths) == mono_array_length (bounds), NULL);
628
629         for (i = 0; i < mono_array_length (lengths); i++) {
630                 if ((mono_array_get (lengths, gint64, i) < 0) ||
631                     (mono_array_get (lengths, gint64, i) > MONO_ARRAY_MAX_INDEX)) {
632                         mono_set_pending_exception (mono_get_exception_argument_out_of_range (NULL));
633                         return NULL;
634                 }
635         }
636
637         klass = mono_class_from_mono_type (type->type);
638         mono_class_init_checked (klass, &error);
639         if (mono_error_set_pending_exception (&error))
640                 return NULL;
641
642         if (bounds && (mono_array_length (bounds) == 1) && (mono_array_get (bounds, gint64, 0) != 0))
643                 /* vectors are not the same as one dimensional arrays with no-zero bounds */
644                 bounded = TRUE;
645         else
646                 bounded = FALSE;
647
648         aklass = mono_bounded_array_class_get (klass, mono_array_length (lengths), bounded);
649
650         sizes = (uintptr_t *)alloca (aklass->rank * sizeof(intptr_t) * 2);
651         for (i = 0; i < aklass->rank; ++i) {
652                 sizes [i] = mono_array_get (lengths, guint64, i);
653                 if (bounds)
654                         sizes [i + aklass->rank] = (mono_array_size_t) mono_array_get (bounds, guint64, i);
655                 else
656                         sizes [i + aklass->rank] = 0;
657         }
658
659         array = mono_array_new_full_checked (mono_object_domain (type), aklass, sizes, (intptr_t*)sizes + aklass->rank, &error);
660         mono_error_set_pending_exception (&error);
661
662         return array;
663 }
664
665 ICALL_EXPORT gint32 
666 ves_icall_System_Array_GetRank (MonoObject *arr)
667 {
668         return arr->vtable->klass->rank;
669 }
670
671 ICALL_EXPORT gint32
672 ves_icall_System_Array_GetLength (MonoArray *arr, gint32 dimension)
673 {
674         gint32 rank = arr->obj.vtable->klass->rank;
675         uintptr_t length;
676
677         if ((dimension < 0) || (dimension >= rank)) {
678                 mono_set_pending_exception (mono_get_exception_index_out_of_range ());
679                 return 0;
680         }
681         
682         if (arr->bounds == NULL)
683                 length = arr->max_length;
684         else
685                 length = arr->bounds [dimension].length;
686
687 #ifdef MONO_BIG_ARRAYS
688         if (length > G_MAXINT32) {
689                 mono_set_pending_exception (mono_get_exception_overflow ());
690                 return 0;
691         }
692 #endif
693         return length;
694 }
695
696 ICALL_EXPORT gint64
697 ves_icall_System_Array_GetLongLength (MonoArray *arr, gint32 dimension)
698 {
699         gint32 rank = arr->obj.vtable->klass->rank;
700
701         if ((dimension < 0) || (dimension >= rank)) {
702                 mono_set_pending_exception (mono_get_exception_index_out_of_range ());
703                 return 0;
704         }
705         
706         if (arr->bounds == NULL)
707                 return arr->max_length;
708         
709         return arr->bounds [dimension].length;
710 }
711
712 ICALL_EXPORT gint32
713 ves_icall_System_Array_GetLowerBound (MonoArray *arr, gint32 dimension)
714 {
715         gint32 rank = arr->obj.vtable->klass->rank;
716
717         if ((dimension < 0) || (dimension >= rank)) {
718                 mono_set_pending_exception (mono_get_exception_index_out_of_range ());
719                 return 0;
720         }
721         
722         if (arr->bounds == NULL)
723                 return 0;
724         
725         return arr->bounds [dimension].lower_bound;
726 }
727
728 ICALL_EXPORT void
729 ves_icall_System_Array_ClearInternal (MonoArray *arr, int idx, int length)
730 {
731         int sz = mono_array_element_size (mono_object_class (arr));
732         mono_gc_bzero_atomic (mono_array_addr_with_size_fast (arr, sz, idx), length * sz);
733 }
734
735
736 ICALL_EXPORT gboolean
737 ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* dest, int dest_idx, int length)
738 {
739         int element_size;
740         void * dest_addr;
741         void * source_addr;
742         MonoVTable *src_vtable;
743         MonoVTable *dest_vtable;
744         MonoClass *src_class;
745         MonoClass *dest_class;
746
747         src_vtable = source->obj.vtable;
748         dest_vtable = dest->obj.vtable;
749
750         if (src_vtable->rank != dest_vtable->rank)
751                 return FALSE;
752
753         if (source->bounds || dest->bounds)
754                 return FALSE;
755
756         /* there's no integer overflow since mono_array_length returns an unsigned integer */
757         if ((dest_idx + length > mono_array_length_fast (dest)) ||
758                 (source_idx + length > mono_array_length_fast (source)))
759                 return FALSE;
760
761         src_class = src_vtable->klass->element_class;
762         dest_class = dest_vtable->klass->element_class;
763
764         /*
765          * Handle common cases.
766          */
767
768         /* Case1: object[] -> valuetype[] (ArrayList::ToArray) 
769         We fallback to managed here since we need to typecheck each boxed valuetype before storing them in the dest array.
770         */
771         if (src_class == mono_defaults.object_class && dest_class->valuetype)
772                 return FALSE;
773
774         /* Check if we're copying a char[] <==> (u)short[] */
775         if (src_class != dest_class) {
776                 if (dest_class->valuetype || dest_class->enumtype || src_class->valuetype || src_class->enumtype)
777                         return FALSE;
778
779                 /* 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. */
780                 if (!mono_class_is_subclass_of (src_class, dest_class, FALSE))
781                         return FALSE;
782         }
783
784         if (dest_class->valuetype) {
785                 element_size = mono_array_element_size (source->obj.vtable->klass);
786                 source_addr = mono_array_addr_with_size_fast (source, element_size, source_idx);
787                 if (dest_class->has_references) {
788                         mono_value_copy_array (dest, dest_idx, source_addr, length);
789                 } else {
790                         dest_addr = mono_array_addr_with_size_fast (dest, element_size, dest_idx);
791                         mono_gc_memmove_atomic (dest_addr, source_addr, element_size * length);
792                 }
793         } else {
794                 mono_array_memcpy_refs_fast (dest, dest_idx, source, source_idx, length);
795         }
796
797         return TRUE;
798 }
799
800 ICALL_EXPORT void
801 ves_icall_System_Array_GetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
802 {
803         MonoClass *ac;
804         gint32 esize;
805         gpointer *ea;
806
807         ac = (MonoClass *)arr->obj.vtable->klass;
808
809         esize = mono_array_element_size (ac);
810         ea = (gpointer*)((char*)arr->vector + (pos * esize));
811
812         mono_gc_memmove_atomic (value, ea, esize);
813 }
814
815 ICALL_EXPORT void
816 ves_icall_System_Array_SetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
817 {
818         MonoClass *ac, *ec;
819         gint32 esize;
820         gpointer *ea;
821
822         ac = (MonoClass *)arr->obj.vtable->klass;
823         ec = ac->element_class;
824
825         esize = mono_array_element_size (ac);
826         ea = (gpointer*)((char*)arr->vector + (pos * esize));
827
828         if (MONO_TYPE_IS_REFERENCE (&ec->byval_arg)) {
829                 g_assert (esize == sizeof (gpointer));
830                 mono_gc_wbarrier_generic_store (ea, *(MonoObject **)value);
831         } else {
832                 g_assert (ec->inited);
833                 g_assert (esize == mono_class_value_size (ec, NULL));
834                 if (ec->has_references)
835                         mono_gc_wbarrier_value_copy (ea, value, 1, ec);
836                 else
837                         mono_gc_memmove_atomic (ea, value, esize);
838         }
839 }
840
841 ICALL_EXPORT void
842 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArrayHandle array, MonoClassField *field_handle, MonoError *error)
843 {
844         error_init (error);
845
846         MonoClass *klass = mono_handle_class (array);
847         guint32 size = mono_array_element_size (klass);
848         MonoType *type = mono_type_get_underlying_type (&klass->element_class->byval_arg);
849         int align;
850         const char *field_data;
851
852         if (MONO_TYPE_IS_REFERENCE (type) || type->type == MONO_TYPE_VALUETYPE) {
853                 mono_error_set_argument (error, "array", "Cannot initialize array of non-primitive type");
854                 return;
855         }
856
857         if (!(field_handle->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
858                 mono_error_set_argument (error, "field_handle", "Field '%s' doesn't have an RVA", mono_field_get_name (field_handle));
859                 return;
860         }
861
862         size *= MONO_HANDLE_GETVAL(array, max_length);
863         field_data = mono_field_get_data (field_handle);
864
865         if (size > mono_type_size (field_handle->type, &align)) {
866                 mono_error_set_argument (error, "field_handle", "Field not large enough to fill array");
867                 return;
868         }
869
870 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
871 #define SWAP(n) {                                                               \
872         guint ## n *data = (guint ## n *) mono_array_addr (MONO_HANDLE_RAW(array), char, 0); \
873         guint ## n *src = (guint ## n *) field_data;                            \
874         int i,                                                                  \
875             nEnt = (size / sizeof(guint ## n));                                 \
876                                                                                 \
877         for (i = 0; i < nEnt; i++) {                                            \
878                 data[i] = read ## n (&src[i]);                                  \
879         }                                                                       \
880 }
881
882         /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
883
884         switch (type->type) {
885         case MONO_TYPE_CHAR:
886         case MONO_TYPE_I2:
887         case MONO_TYPE_U2:
888                 SWAP (16);
889                 break;
890         case MONO_TYPE_I4:
891         case MONO_TYPE_U4:
892         case MONO_TYPE_R4:
893                 SWAP (32);
894                 break;
895         case MONO_TYPE_I8:
896         case MONO_TYPE_U8:
897         case MONO_TYPE_R8:
898                 SWAP (64);
899                 break;
900         default:
901                 memcpy (mono_array_addr (MONO_HANDLE_RAW(array), char, 0), field_data, size);
902                 break;
903         }
904 #else
905         memcpy (mono_array_addr (MONO_HANDLE_RAW(array), char, 0), field_data, size);
906 #endif
907 }
908
909 ICALL_EXPORT gint
910 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
911 {
912         return offsetof (MonoString, chars);
913 }
914
915 ICALL_EXPORT MonoObject *
916 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObject *obj)
917 {
918         if ((obj == NULL) || (! (obj->vtable->klass->valuetype)))
919                 return obj;
920         else {
921                 MonoError error;
922                 MonoObject *ret = mono_object_clone_checked (obj, &error);
923                 mono_error_set_pending_exception (&error);
924
925                 return ret;
926         }
927 }
928
929 ICALL_EXPORT void
930 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle)
931 {
932         MonoError error;
933         MonoClass *klass;
934         MonoVTable *vtable;
935
936         MONO_CHECK_ARG_NULL (handle,);
937
938         klass = mono_class_from_mono_type (handle);
939         MONO_CHECK_ARG (handle, klass,);
940
941         if (mono_class_is_gtd (klass))
942                 return;
943
944         vtable = mono_class_vtable_full (mono_domain_get (), klass, &error);
945         if (!is_ok (&error)) {
946                 mono_error_set_pending_exception (&error);
947                 return;
948         }
949
950         /* This will call the type constructor */
951         if (!mono_runtime_class_init_full (vtable, &error))
952                 mono_error_set_pending_exception (&error);
953 }
954
955 ICALL_EXPORT void
956 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (MonoImage *image)
957 {
958         MonoError error;
959
960         mono_image_check_for_module_cctor (image);
961         if (image->has_module_cctor) {
962                 MonoClass *module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, &error);
963                 if (!mono_error_ok (&error)) {
964                         mono_error_set_pending_exception (&error);
965                         return;
966                 }
967                 /*It's fine to raise the exception here*/
968                 MonoVTable * vtable = mono_class_vtable_full (mono_domain_get (), module_klass, &error);
969                 if (!is_ok (&error)) {
970                         mono_error_set_pending_exception (&error);
971                         return;
972                 }
973                 if (!mono_runtime_class_init_full (vtable, &error))
974                         mono_error_set_pending_exception (&error);
975         }
976 }
977
978 ICALL_EXPORT MonoBoolean
979 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
980 {
981 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
982         // It does not work on win32
983 #elif defined(TARGET_ANDROID)
984         // No need for now
985 #else
986         guint8 *stack_addr;
987         guint8 *current;
988         size_t stack_size;
989         int min_size;
990         MonoInternalThread *thread;
991
992         mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
993         /* if we have no info we are optimistic and assume there is enough room */
994         if (!stack_addr)
995                 return TRUE;
996
997         thread = mono_thread_internal_current ();
998         // .net seems to check that at least 50% of stack is available
999         min_size = thread->stack_size / 2;
1000
1001         // TODO: It's not always set
1002         if (!min_size)
1003                 return TRUE;
1004
1005         current = (guint8 *)&stack_addr;
1006         if (current > stack_addr) {
1007                 if ((current - stack_addr) < min_size)
1008                         return FALSE;
1009         } else {
1010                 if (current - (stack_addr - stack_size) < min_size)
1011                         return FALSE;
1012         }
1013 #endif
1014         return TRUE;
1015 }
1016
1017 ICALL_EXPORT MonoObject *
1018 ves_icall_System_Object_MemberwiseClone (MonoObject *this_obj)
1019 {
1020         MonoError error;
1021         MonoObject *ret = mono_object_clone_checked (this_obj, &error);
1022         mono_error_set_pending_exception (&error);
1023
1024         return ret;
1025 }
1026
1027 ICALL_EXPORT gint32
1028 ves_icall_System_ValueType_InternalGetHashCode (MonoObject *this_obj, MonoArray **fields)
1029 {
1030         MonoError error;
1031         MonoClass *klass;
1032         MonoObject **values = NULL;
1033         MonoObject *o;
1034         int count = 0;
1035         gint32 result = (int)(gsize)mono_defaults.int32_class;
1036         MonoClassField* field;
1037         gpointer iter;
1038
1039         klass = mono_object_class (this_obj);
1040
1041         if (mono_class_num_fields (klass) == 0)
1042                 return result;
1043
1044         /*
1045          * Compute the starting value of the hashcode for fields of primitive
1046          * types, and return the remaining fields in an array to the managed side.
1047          * This way, we can avoid costly reflection operations in managed code.
1048          */
1049         iter = NULL;
1050         while ((field = mono_class_get_fields (klass, &iter))) {
1051                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1052                         continue;
1053                 if (mono_field_is_deleted (field))
1054                         continue;
1055                 /* FIXME: Add more types */
1056                 switch (field->type->type) {
1057                 case MONO_TYPE_I4:
1058                         result ^= *(gint32*)((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 (s);
1065                         break;
1066                 }
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;
1074                         }
1075                         values [count++] = o;
1076                 }
1077         }
1078
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 (fields, (MonoObject*) fields_arr);
1085                 for (i = 0; i < count; ++i)
1086                         mono_array_setref (*fields, i, values [i]);
1087         } else {
1088                 *fields = NULL;
1089         }
1090         return result;
1091 }
1092
1093 ICALL_EXPORT MonoBoolean
1094 ves_icall_System_ValueType_Equals (MonoObject *this_obj, MonoObject *that, MonoArray **fields)
1095 {
1096         MonoError error;
1097         MonoClass *klass;
1098         MonoObject **values = NULL;
1099         MonoObject *o;
1100         MonoClassField* field;
1101         gpointer iter;
1102         int count = 0;
1103
1104         MONO_CHECK_ARG_NULL (that, FALSE);
1105
1106         if (this_obj->vtable != that->vtable)
1107                 return FALSE;
1108
1109         klass = mono_object_class (this_obj);
1110
1111         if (klass->enumtype && mono_class_enum_basetype (klass) && mono_class_enum_basetype (klass)->type == MONO_TYPE_I4)
1112                 return (*(gint32*)((guint8*)this_obj + sizeof (MonoObject)) == *(gint32*)((guint8*)that + sizeof (MonoObject)));
1113
1114         /*
1115          * Do the comparison for fields of primitive type and return a result if
1116          * possible. Otherwise, return the remaining fields in an array to the 
1117          * managed side. This way, we can avoid costly reflection operations in 
1118          * managed code.
1119          */
1120         *fields = NULL;
1121         iter = NULL;
1122         while ((field = mono_class_get_fields (klass, &iter))) {
1123                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1124                         continue;
1125                 if (mono_field_is_deleted (field))
1126                         continue;
1127                 /* FIXME: Add more types */
1128                 switch (field->type->type) {
1129                 case MONO_TYPE_U1:
1130                 case MONO_TYPE_I1:
1131                 case MONO_TYPE_BOOLEAN:
1132                         if (*((guint8*)this_obj + field->offset) != *((guint8*)that + field->offset))
1133                                 return FALSE;
1134                         break;
1135                 case MONO_TYPE_U2:
1136                 case MONO_TYPE_I2:
1137                 case MONO_TYPE_CHAR:
1138                         if (*(gint16*)((guint8*)this_obj + field->offset) != *(gint16*)((guint8*)that + field->offset))
1139                                 return FALSE;
1140                         break;
1141                 case MONO_TYPE_U4:
1142                 case MONO_TYPE_I4:
1143                         if (*(gint32*)((guint8*)this_obj + field->offset) != *(gint32*)((guint8*)that + field->offset))
1144                                 return FALSE;
1145                         break;
1146                 case MONO_TYPE_U8:
1147                 case MONO_TYPE_I8:
1148                         if (*(gint64*)((guint8*)this_obj + field->offset) != *(gint64*)((guint8*)that + field->offset))
1149                                 return FALSE;
1150                         break;
1151                 case MONO_TYPE_R4:
1152                         if (*(float*)((guint8*)this_obj + field->offset) != *(float*)((guint8*)that + field->offset))
1153                                 return FALSE;
1154                         break;
1155                 case MONO_TYPE_R8:
1156                         if (*(double*)((guint8*)this_obj + field->offset) != *(double*)((guint8*)that + field->offset))
1157                                 return FALSE;
1158                         break;
1159
1160
1161                 case MONO_TYPE_STRING: {
1162                         MonoString *s1, *s2;
1163                         guint32 s1len, s2len;
1164                         s1 = *(MonoString**)((guint8*)this_obj + field->offset);
1165                         s2 = *(MonoString**)((guint8*)that + field->offset);
1166                         if (s1 == s2)
1167                                 break;
1168                         if ((s1 == NULL) || (s2 == NULL))
1169                                 return FALSE;
1170                         s1len = mono_string_length (s1);
1171                         s2len = mono_string_length (s2);
1172                         if (s1len != s2len)
1173                                 return FALSE;
1174
1175                         if (memcmp (mono_string_chars (s1), mono_string_chars (s2), s1len * sizeof (gunichar2)) != 0)
1176                                 return FALSE;
1177                         break;
1178                 }
1179                 default:
1180                         if (!values)
1181                                 values = g_newa (MonoObject*, mono_class_num_fields (klass) * 2);
1182                         o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, this_obj, &error);
1183                         if (!is_ok (&error)) {
1184                                 mono_error_set_pending_exception (&error);
1185                                 return FALSE;
1186                         }
1187                         values [count++] = o;
1188                         o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, that, &error);
1189                         if (!is_ok (&error)) {
1190                                 mono_error_set_pending_exception (&error);
1191                                 return FALSE;
1192                         }
1193                         values [count++] = o;
1194                 }
1195
1196                 if (klass->enumtype)
1197                         /* enums only have one non-static field */
1198                         break;
1199         }
1200
1201         if (values) {
1202                 int i;
1203                 MonoArray *fields_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.object_class, count, &error);
1204                 if (mono_error_set_pending_exception (&error))
1205                         return FALSE;
1206                 mono_gc_wbarrier_generic_store (fields, (MonoObject*) fields_arr);
1207                 for (i = 0; i < count; ++i)
1208                         mono_array_setref_fast (*fields, i, values [i]);
1209                 return FALSE;
1210         } else {
1211                 return TRUE;
1212         }
1213 }
1214
1215 ICALL_EXPORT MonoReflectionTypeHandle
1216 ves_icall_System_Object_GetType (MonoObjectHandle obj, MonoError *error)
1217 {
1218         error_init (error);
1219         MonoDomain *domain = MONO_HANDLE_DOMAIN (obj);
1220         MonoClass *klass = mono_handle_class (obj);
1221 #ifndef DISABLE_REMOTING
1222         if (mono_class_is_transparent_proxy (klass)) {
1223                 MonoTransparentProxyHandle proxy_obj = MONO_HANDLE_CAST (MonoTransparentProxy, obj);
1224                 MonoRemoteClass *remote_class = MONO_HANDLE_GETVAL (proxy_obj, remote_class);
1225                 MonoType *proxy_type = &remote_class->proxy_class->byval_arg;
1226                 return mono_type_get_object_handle (domain, proxy_type, error);
1227         } else
1228 #endif
1229                 return mono_type_get_object_handle (domain, &klass->byval_arg, error);
1230 }
1231
1232 static gboolean
1233 get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1234 {
1235         MonoMethod **dest = (MonoMethod **)data;
1236
1237         /* skip unmanaged frames */
1238         if (!managed)
1239                 return FALSE;
1240
1241         if (!(*dest)) {
1242                 if (!strcmp (m->klass->name_space, "System.Reflection"))
1243                         return FALSE;
1244                 *dest = m;
1245                 return TRUE;
1246         }
1247         return FALSE;
1248 }
1249
1250 static gboolean
1251 get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1252 {
1253         MonoMethod **dest = (MonoMethod **)data;
1254
1255         /* skip unmanaged frames */
1256         if (!managed)
1257                 return FALSE;
1258
1259         if (m->wrapper_type != MONO_WRAPPER_NONE)
1260                 return FALSE;
1261
1262         if (m == *dest) {
1263                 *dest = NULL;
1264                 return FALSE;
1265         }
1266
1267         if (m->klass->image == mono_defaults.corlib && !strcmp (m->klass->name_space, "System.Reflection"))
1268                 return FALSE;
1269
1270         if (!(*dest)) {
1271                 *dest = m;
1272                 return TRUE;
1273         }
1274         return FALSE;
1275 }
1276
1277 static gboolean
1278 get_caller_no_system_or_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1279 {
1280         MonoMethod **dest = (MonoMethod **)data;
1281
1282         /* skip unmanaged frames */
1283         if (!managed)
1284                 return FALSE;
1285
1286         if (m->wrapper_type != MONO_WRAPPER_NONE)
1287                 return FALSE;
1288
1289         if (m == *dest) {
1290                 *dest = NULL;
1291                 return FALSE;
1292         }
1293
1294         if (m->klass->image == mono_defaults.corlib && ((!strcmp (m->klass->name_space, "System.Reflection"))
1295                                                                                                         || (!strcmp (m->klass->name_space, "System"))))
1296                 return FALSE;
1297
1298         if (!(*dest)) {
1299                 *dest = m;
1300                 return TRUE;
1301         }
1302         return FALSE;
1303 }
1304
1305 static MonoReflectionTypeHandle
1306 type_from_parsed_name (MonoTypeNameParse *info, MonoBoolean ignoreCase, MonoAssembly **caller_assembly, MonoError *error)
1307 {
1308         MonoMethod *m, *dest;
1309
1310         MonoType *type = NULL;
1311         MonoAssembly *assembly = NULL;
1312         gboolean type_resolve = FALSE;
1313         MonoImage *rootimage = NULL;
1314
1315         error_init (error);
1316
1317         /*
1318          * We must compute the calling assembly as type loading must happen under a metadata context.
1319          * For example. The main assembly is a.exe and Type.GetType is called from dir/b.dll. Without
1320          * the metadata context (basedir currently) set to dir/b.dll we won't be able to load a dir/c.dll.
1321          */
1322         m = mono_method_get_last_managed ();
1323         dest = m;
1324         if (m && m->klass->image != mono_defaults.corlib) {
1325                 /* Happens with inlining */
1326         } else {
1327                 /* Ugly hack: type_from_parsed_name is called from
1328                  * System.Type.internal_from_name, which is called most
1329                  * directly from System.Type.GetType(string,bool,bool) but
1330                  * also indirectly from places such as
1331                  * System.Type.GetType(string,func,func) (via
1332                  * System.TypeNameParser.GetType and System.TypeSpec.Resolve)
1333                  * so we need to skip over all of those to find the true caller.
1334                  *
1335                  * It would be nice if we had stack marks.
1336                  */
1337                 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1338                 if (!dest)
1339                         dest = m;
1340         }
1341
1342         /*
1343          * FIXME: mono_method_get_last_managed() sometimes returns NULL, thus
1344          *        causing ves_icall_System_Reflection_Assembly_GetCallingAssembly()
1345          *        to crash.  This only seems to happen in some strange remoting
1346          *        scenarios and I was unable to figure out what's happening there.
1347          *        Dec 10, 2005 - Martin.
1348          */
1349
1350         if (dest) {
1351                 assembly = dest->klass->image->assembly;
1352                 type_resolve = TRUE;
1353                 rootimage = assembly->image;
1354         } else {
1355                 g_warning (G_STRLOC);
1356         }
1357         *caller_assembly = assembly;
1358
1359         if (info->assembly.name)
1360                 assembly = mono_assembly_load (&info->assembly, assembly ? assembly->basedir : NULL, NULL);
1361
1362         if (assembly) {
1363                 /* When loading from the current assembly, AppDomain.TypeResolve will not be called yet */
1364                 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
1365                 if (!is_ok (error))
1366                         goto fail;
1367         }
1368
1369         // XXXX - aleksey -
1370         //  Say we're looking for System.Generic.Dict<int, Local>
1371         //  we FAIL the get type above, because S.G.Dict isn't in assembly->image.  So we drop down here.
1372         //  but then we FAIL AGAIN because now we pass null as the image and the rootimage and everything
1373         //  is messed up when we go to construct the Local as the type arg...
1374         //
1375         // By contrast, if we started with Mine<System.Generic.Dict<int, Local>> we'd go in with assembly->image
1376         // as the root and then even the detour into generics would still not screw us when we went to load Local.
1377         if (!info->assembly.name && !type) {
1378                 /* try mscorlib */
1379                 type = mono_reflection_get_type_checked (rootimage, NULL, info, ignoreCase, &type_resolve, error);
1380                 if (!is_ok (error))
1381                         goto fail;
1382         }
1383         if (assembly && !type && type_resolve) {
1384                 type_resolve = FALSE; /* This will invoke TypeResolve if not done in the first 'if' */
1385                 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
1386                 if (!is_ok (error))
1387                         goto fail;
1388         }
1389
1390         if (!type) 
1391                 goto fail;
1392
1393         return mono_type_get_object_handle (mono_domain_get (), type, error);
1394 fail:
1395         return MONO_HANDLE_NEW (MonoReflectionType, NULL);
1396 }
1397
1398 ICALL_EXPORT MonoReflectionTypeHandle
1399 ves_icall_System_Type_internal_from_name (MonoStringHandle name,
1400                                           MonoBoolean throwOnError,
1401                                           MonoBoolean ignoreCase,
1402                                           MonoError *error)
1403 {
1404         error_init (error);
1405         MonoTypeNameParse info;
1406         gboolean parsedOk;
1407         MonoAssembly *caller_assembly;
1408         MonoReflectionTypeHandle type = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1409
1410         char *str = mono_string_handle_to_utf8 (name, error);
1411         if (!is_ok (error))
1412                 goto leave;
1413
1414         parsedOk = mono_reflection_parse_type (str, &info);
1415
1416         /* mono_reflection_parse_type() mangles the string */
1417         if (!parsedOk) {
1418                 mono_reflection_free_type_info (&info);
1419                 if (throwOnError)
1420                         mono_error_set_argument (error, "typeName", "failed parse: %s", str);
1421                 goto leave;
1422         }
1423
1424         MONO_HANDLE_ASSIGN (type, type_from_parsed_name (&info, ignoreCase, &caller_assembly, error));
1425
1426         if (!is_ok (error)) {
1427                 mono_reflection_free_type_info (&info);
1428                 goto leave;
1429         }
1430
1431         if (MONO_HANDLE_IS_NULL (type)) {
1432                 if (throwOnError) {
1433                         char *tname = info.name_space ? g_strdup_printf ("%s.%s", info.name_space, info.name) : g_strdup (info.name);
1434                         char *aname;
1435                         if (info.assembly.name)
1436                                 aname = mono_stringify_assembly_name (&info.assembly);
1437                         else if (caller_assembly)
1438                                 aname = mono_stringify_assembly_name (mono_assembly_get_name (caller_assembly));
1439                         else
1440                                 aname = g_strdup ("");
1441                         mono_error_set_type_load_name (error, tname, aname, "");
1442                 }
1443                 mono_reflection_free_type_info (&info);
1444                 goto leave;
1445         }
1446         
1447 leave:
1448         g_free (str);
1449         if (!is_ok (error)) {
1450                 if (!throwOnError)
1451                         mono_error_cleanup (error);
1452                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
1453         }
1454
1455         return type;
1456 }
1457
1458
1459 ICALL_EXPORT MonoReflectionTypeHandle
1460 ves_icall_System_Type_internal_from_handle (MonoType *handle, MonoError *error)
1461 {
1462         error_init (error);
1463         MonoDomain *domain = mono_domain_get (); 
1464
1465         return mono_type_get_object_handle (domain, handle, error);
1466 }
1467
1468 ICALL_EXPORT MonoType*
1469 ves_icall_Mono_RuntimeClassHandle_GetTypeFromClass (MonoClass *klass)
1470 {
1471         return mono_class_get_type (klass);
1472 }
1473
1474 ICALL_EXPORT void
1475 ves_icall_Mono_RuntimeGPtrArrayHandle_GPtrArrayFree (GPtrArray *ptr_array)
1476 {
1477         g_ptr_array_free (ptr_array, TRUE);
1478 }
1479
1480 ICALL_EXPORT void
1481 ves_icall_Mono_SafeStringMarshal_GFree (void *c_str)
1482 {
1483         g_free (c_str);
1484 }
1485
1486 ICALL_EXPORT char*
1487 ves_icall_Mono_SafeStringMarshal_StringToUtf8 (MonoString *s)
1488 {
1489         MonoError error;
1490         char *res = mono_string_to_utf8_checked (s, &error);
1491         mono_error_set_pending_exception (&error);
1492         return res;
1493 }
1494
1495 /* System.TypeCode */
1496 typedef enum {
1497         TYPECODE_EMPTY,
1498         TYPECODE_OBJECT,
1499         TYPECODE_DBNULL,
1500         TYPECODE_BOOLEAN,
1501         TYPECODE_CHAR,
1502         TYPECODE_SBYTE,
1503         TYPECODE_BYTE,
1504         TYPECODE_INT16,
1505         TYPECODE_UINT16,
1506         TYPECODE_INT32,
1507         TYPECODE_UINT32,
1508         TYPECODE_INT64,
1509         TYPECODE_UINT64,
1510         TYPECODE_SINGLE,
1511         TYPECODE_DOUBLE,
1512         TYPECODE_DECIMAL,
1513         TYPECODE_DATETIME,
1514         TYPECODE_STRING = 18
1515 } TypeCode;
1516
1517 ICALL_EXPORT guint32
1518 ves_icall_type_GetTypeCodeInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
1519 {
1520         error_init (error);
1521         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1522         int t = type->type;
1523
1524         if (type->byref)
1525                 return TYPECODE_OBJECT;
1526
1527 handle_enum:
1528         switch (t) {
1529         case MONO_TYPE_VOID:
1530                 return TYPECODE_OBJECT;
1531         case MONO_TYPE_BOOLEAN:
1532                 return TYPECODE_BOOLEAN;
1533         case MONO_TYPE_U1:
1534                 return TYPECODE_BYTE;
1535         case MONO_TYPE_I1:
1536                 return TYPECODE_SBYTE;
1537         case MONO_TYPE_U2:
1538                 return TYPECODE_UINT16;
1539         case MONO_TYPE_I2:
1540                 return TYPECODE_INT16;
1541         case MONO_TYPE_CHAR:
1542                 return TYPECODE_CHAR;
1543         case MONO_TYPE_PTR:
1544         case MONO_TYPE_U:
1545         case MONO_TYPE_I:
1546                 return TYPECODE_OBJECT;
1547         case MONO_TYPE_U4:
1548                 return TYPECODE_UINT32;
1549         case MONO_TYPE_I4:
1550                 return TYPECODE_INT32;
1551         case MONO_TYPE_U8:
1552                 return TYPECODE_UINT64;
1553         case MONO_TYPE_I8:
1554                 return TYPECODE_INT64;
1555         case MONO_TYPE_R4:
1556                 return TYPECODE_SINGLE;
1557         case MONO_TYPE_R8:
1558                 return TYPECODE_DOUBLE;
1559         case MONO_TYPE_VALUETYPE: {
1560                 MonoClass *klass = type->data.klass;
1561                 
1562                 if (klass->enumtype) {
1563                         t = mono_class_enum_basetype (klass)->type;
1564                         goto handle_enum;
1565                 } else if (mono_is_corlib_image (klass->image)) {
1566                         if (strcmp (klass->name_space, "System") == 0) {
1567                                 if (strcmp (klass->name, "Decimal") == 0)
1568                                         return TYPECODE_DECIMAL;
1569                                 else if (strcmp (klass->name, "DateTime") == 0)
1570                                         return TYPECODE_DATETIME;
1571                         }
1572                 }
1573                 return TYPECODE_OBJECT;
1574         }
1575         case MONO_TYPE_STRING:
1576                 return TYPECODE_STRING;
1577         case MONO_TYPE_SZARRAY:
1578         case MONO_TYPE_ARRAY:
1579         case MONO_TYPE_OBJECT:
1580         case MONO_TYPE_VAR:
1581         case MONO_TYPE_MVAR:
1582         case MONO_TYPE_TYPEDBYREF:
1583                 return TYPECODE_OBJECT;
1584         case MONO_TYPE_CLASS:
1585                 {
1586                         MonoClass *klass =  type->data.klass;
1587                         if (klass->image == mono_defaults.corlib && strcmp (klass->name_space, "System") == 0) {
1588                                 if (strcmp (klass->name, "DBNull") == 0)
1589                                         return TYPECODE_DBNULL;
1590                         }
1591                 }
1592                 return TYPECODE_OBJECT;
1593         case MONO_TYPE_GENERICINST:
1594                 return TYPECODE_OBJECT;
1595         default:
1596                 g_error ("type 0x%02x not handled in GetTypeCode()", t);
1597         }
1598         return 0;
1599 }
1600
1601 static MonoType*
1602 mono_type_get_underlying_type_ignore_byref (MonoType *type)
1603 {
1604         if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
1605                 return mono_class_enum_basetype (type->data.klass);
1606         if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
1607                 return mono_class_enum_basetype (type->data.generic_class->container_class);
1608         return type;
1609 }
1610
1611 ICALL_EXPORT guint32
1612 ves_icall_RuntimeTypeHandle_type_is_assignable_from (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_c, MonoError *error)
1613 {
1614         error_init (error);
1615
1616         g_assert (!MONO_HANDLE_IS_NULL (ref_type));
1617         
1618         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1619         MonoClass *klass = mono_class_from_mono_type (type);
1620         MonoType *ctype = MONO_HANDLE_GETVAL (ref_c, type);
1621         MonoClass *klassc = mono_class_from_mono_type (ctype);
1622
1623         if (type->byref ^ ctype->byref)
1624                 return FALSE;
1625
1626         if (type->byref) {
1627                 MonoType *t = mono_type_get_underlying_type_ignore_byref (type);
1628                 MonoType *ot = mono_type_get_underlying_type_ignore_byref (ctype);
1629
1630                 klass = mono_class_from_mono_type (t);
1631                 klassc = mono_class_from_mono_type (ot);
1632
1633                 if (mono_type_is_primitive (t)) {
1634                         return mono_type_is_primitive (ot) && klass->instance_size == klassc->instance_size;
1635                 } else if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) {
1636                         return t->type == ot->type && t->data.generic_param->num == ot->data.generic_param->num;
1637                 } else if (t->type == MONO_TYPE_PTR || t->type == MONO_TYPE_FNPTR) {
1638                         return t->type == ot->type;
1639                 } else {
1640                          if (ot->type == MONO_TYPE_VAR || ot->type == MONO_TYPE_MVAR)
1641                                  return FALSE;
1642
1643                          if (klass->valuetype)
1644                                 return klass == klassc;
1645                         return klass->valuetype == klassc->valuetype;
1646                 }
1647         }
1648         return mono_class_is_assignable_from (klass, klassc);
1649 }
1650
1651 ICALL_EXPORT guint32
1652 ves_icall_RuntimeTypeHandle_IsInstanceOfType (MonoReflectionTypeHandle ref_type, MonoObjectHandle obj, MonoError *error)
1653 {
1654         error_init (error);
1655         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1656         MonoClass *klass = mono_class_from_mono_type (type);
1657         mono_class_init_checked (klass, error);
1658         return_val_if_nok (error, FALSE);
1659         MonoObjectHandle inst = mono_object_handle_isinst (obj, klass, error);
1660         return_val_if_nok (error, FALSE);
1661         return !MONO_HANDLE_IS_NULL (inst);
1662 }
1663
1664 ICALL_EXPORT guint32
1665 ves_icall_RuntimeTypeHandle_GetAttributes (MonoReflectionTypeHandle ref_type, MonoError *error)
1666 {
1667         error_init (error);
1668         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1669         MonoClass *klass = mono_class_from_mono_type (type);
1670         return mono_class_get_flags (klass);
1671 }
1672
1673 ICALL_EXPORT MonoReflectionMarshalAsAttributeHandle
1674 ves_icall_System_Reflection_FieldInfo_get_marshal_info (MonoReflectionFieldHandle field_h, MonoError *error)
1675 {
1676         error_init (error);
1677         MonoDomain *domain = MONO_HANDLE_DOMAIN (field_h);
1678         MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
1679         MonoClass *klass = field->parent;
1680
1681         MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
1682         if (mono_class_is_gtd (klass) ||
1683             (gklass && gklass->context.class_inst->is_open))
1684                 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1685
1686         MonoType *ftype = mono_field_get_type (field);
1687         if (ftype && !(ftype->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL))
1688                 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1689
1690         MonoMarshalType *info = mono_marshal_load_type_info (klass);
1691
1692         for (int i = 0; i < info->num_fields; ++i) {
1693                 if (info->fields [i].field == field) {
1694                         if (!info->fields [i].mspec)
1695                                 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1696                         else {
1697                                 return mono_reflection_marshal_as_attribute_from_marshal_spec (domain, klass, info->fields [i].mspec, error);
1698                         }
1699                 }
1700         }
1701
1702         return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1703 }
1704
1705 ICALL_EXPORT MonoReflectionFieldHandle
1706 ves_icall_System_Reflection_FieldInfo_internal_from_handle_type (MonoClassField *handle, MonoType *type, MonoError *error)
1707 {
1708         MonoClass *klass;
1709
1710         g_assert (handle);
1711
1712         error_init (error);
1713
1714         if (!type) {
1715                 klass = handle->parent;
1716         } else {
1717                 klass = mono_class_from_mono_type (type);
1718
1719                 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1720
1721                 if (!found)
1722                         /* The managed code will throw the exception */
1723                         return MONO_HANDLE_CAST (MonoReflectionField, NULL_HANDLE);
1724         }
1725
1726         return mono_field_get_object_handle (mono_domain_get (), klass, handle, error);
1727 }
1728
1729 ICALL_EXPORT MonoReflectionEventHandle
1730 ves_icall_System_Reflection_EventInfo_internal_from_handle_type (MonoEvent *handle, MonoType *type, MonoError *error)
1731 {
1732         MonoClass *klass;
1733
1734         g_assert (handle);
1735
1736         error_init (error);
1737
1738         if (!type) {
1739                 klass = handle->parent;
1740         } else {
1741                 klass = mono_class_from_mono_type (type);
1742
1743                 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1744                 if (!found)
1745                         /* Managed code will throw an exception */
1746                         return MONO_HANDLE_CAST (MonoReflectionEvent, NULL_HANDLE);
1747         }
1748
1749         return mono_event_get_object_handle (mono_domain_get (), klass, handle, error);
1750 }
1751
1752
1753 ICALL_EXPORT MonoReflectionPropertyHandle
1754 ves_icall_System_Reflection_PropertyInfo_internal_from_handle_type (MonoProperty *handle, MonoType *type, MonoError *error)
1755 {
1756         error_init (error);
1757         MonoClass *klass;
1758
1759         g_assert (handle);
1760
1761         if (!type) {
1762                 klass = handle->parent;
1763         } else {
1764                 klass = mono_class_from_mono_type (type);
1765
1766                 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1767                 if (!found)
1768                         /* Managed code will throw an exception */
1769                         return MONO_HANDLE_CAST (MonoReflectionProperty, NULL_HANDLE);
1770         }
1771
1772         return mono_property_get_object_handle (mono_domain_get (), klass, handle, error);
1773 }
1774
1775 ICALL_EXPORT MonoArrayHandle
1776 ves_icall_System_Reflection_FieldInfo_GetTypeModifiers (MonoReflectionFieldHandle field_h, MonoBoolean optional, MonoError *error)
1777 {
1778         error_init (error);
1779         MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
1780
1781         MonoType *type = mono_field_get_type_checked (field, error);
1782         if (!is_ok (error))
1783                 return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
1784
1785         return type_array_from_modifiers (field->parent->image, type, optional, error);
1786 }
1787
1788 ICALL_EXPORT int
1789 vell_icall_get_method_attributes (MonoMethod *method)
1790 {
1791         return method->flags;
1792 }
1793
1794 ICALL_EXPORT void
1795 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info, MonoError *error)
1796 {
1797         MonoDomain *domain = mono_domain_get ();
1798
1799         MonoMethodSignature* sig = mono_method_signature_checked (method, error);
1800         return_if_nok (error);
1801
1802         MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &method->klass->byval_arg, error);
1803         return_if_nok (error);
1804
1805         MONO_STRUCT_SETREF (info, parent, MONO_HANDLE_RAW (rt));
1806
1807         MONO_HANDLE_ASSIGN (rt, mono_type_get_object_handle (domain, sig->ret, error));
1808         return_if_nok (error);
1809
1810         MONO_STRUCT_SETREF (info, ret, MONO_HANDLE_RAW (rt));
1811
1812         info->attrs = method->flags;
1813         info->implattrs = method->iflags;
1814         guint32 callconv;
1815         if (sig->call_convention == MONO_CALL_DEFAULT)
1816                 callconv = sig->sentinelpos >= 0 ? 2 : 1;
1817         else {
1818                 if (sig->call_convention == MONO_CALL_VARARG || sig->sentinelpos >= 0)
1819                         callconv = 2;
1820                 else
1821                         callconv = 1;
1822         }
1823         callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6);
1824         info->callconv = callconv;
1825 }
1826
1827 ICALL_EXPORT MonoArrayHandle
1828 ves_icall_System_Reflection_MonoMethodInfo_get_parameter_info (MonoMethod *method, MonoReflectionMethodHandle member, MonoError *error)
1829 {
1830         error_init (error);
1831         MonoDomain *domain = mono_domain_get (); 
1832
1833         MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1834         MONO_HANDLE_GET (reftype, member, reftype);
1835         MonoClass *klass = NULL;
1836         if (!MONO_HANDLE_IS_NULL (reftype))
1837                 klass = mono_class_from_mono_type (MONO_HANDLE_GETVAL (reftype, type));
1838         return mono_param_get_objects_internal (domain, method, klass, error);
1839 }
1840
1841 ICALL_EXPORT MonoReflectionMarshalAsAttributeHandle
1842 ves_icall_System_MonoMethodInfo_get_retval_marshal (MonoMethod *method, MonoError *error)
1843 {
1844         error_init (error);
1845         MonoDomain *domain = mono_domain_get (); 
1846         MonoReflectionMarshalAsAttributeHandle res = MONO_HANDLE_NEW (MonoReflectionMarshalAsAttribute, NULL);
1847
1848         MonoMarshalSpec **mspecs = g_new (MonoMarshalSpec*, mono_method_signature (method)->param_count + 1);
1849         mono_method_get_marshal_info (method, mspecs);
1850
1851         if (mspecs [0]) {
1852                 MONO_HANDLE_ASSIGN (res, mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [0], error));
1853                 if (!is_ok (error))
1854                         goto leave;
1855         }
1856                 
1857 leave:
1858         for (int i = mono_method_signature (method)->param_count; i >= 0; i--)
1859                 if (mspecs [i])
1860                         mono_metadata_free_marshal_spec (mspecs [i]);
1861         g_free (mspecs);
1862
1863         return res;
1864 }
1865
1866 ICALL_EXPORT gint32
1867 ves_icall_MonoField_GetFieldOffset (MonoReflectionField *field)
1868 {
1869         MonoClass *parent = field->field->parent;
1870         mono_class_setup_fields (parent);
1871
1872         return field->field->offset - sizeof (MonoObject);
1873 }
1874
1875 ICALL_EXPORT MonoReflectionTypeHandle
1876 ves_icall_MonoField_GetParentType (MonoReflectionFieldHandle field, MonoBoolean declaring, MonoError *error)
1877 {
1878         error_init (error);
1879         MonoDomain *domain = MONO_HANDLE_DOMAIN (field);
1880         MonoClass *parent;
1881
1882         if (declaring) {
1883                 MonoClassField *f = MONO_HANDLE_GETVAL (field, field);
1884                 parent = f->parent;
1885         } else {
1886                 parent = MONO_HANDLE_GETVAL (field, klass);
1887         }
1888
1889         return mono_type_get_object_handle (domain, &parent->byval_arg, error);
1890 }
1891
1892 ICALL_EXPORT MonoObject *
1893 ves_icall_MonoField_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
1894 {       
1895         MonoError error;
1896         MonoClass *fklass = field->klass;
1897         MonoClassField *cf = field->field;
1898         MonoDomain *domain = mono_object_domain (field);
1899
1900         if (fklass->image->assembly->ref_only) {
1901                 mono_set_pending_exception (mono_get_exception_invalid_operation (
1902                                         "It is illegal to get the value on a field on a type loaded using the ReflectionOnly methods."));
1903                 return NULL;
1904         }
1905
1906         if (mono_security_core_clr_enabled () &&
1907             !mono_security_core_clr_ensure_reflection_access_field (cf, &error)) {
1908                 mono_error_set_pending_exception (&error);
1909                 return NULL;
1910         }
1911
1912         MonoObject * result = mono_field_get_value_object_checked (domain, cf, obj, &error);
1913         mono_error_set_pending_exception (&error);
1914         return result;
1915 }
1916
1917 ICALL_EXPORT void
1918 ves_icall_MonoField_SetValueInternal (MonoReflectionField *field, MonoObject *obj, MonoObject *value)
1919 {
1920         MonoError error;
1921         MonoClassField *cf = field->field;
1922         MonoType *type;
1923         gchar *v;
1924
1925         if (field->klass->image->assembly->ref_only) {
1926                 mono_set_pending_exception (mono_get_exception_invalid_operation (
1927                                         "It is illegal to set the value on a field on a type loaded using the ReflectionOnly methods."));
1928                 return;
1929         }
1930
1931         if (mono_security_core_clr_enabled () &&
1932             !mono_security_core_clr_ensure_reflection_access_field (cf, &error)) {
1933                 mono_error_set_pending_exception (&error);
1934                 return;
1935         }
1936
1937         type = mono_field_get_type_checked (cf, &error);
1938         if (!mono_error_ok (&error)) {
1939                 mono_error_set_pending_exception (&error);
1940                 return;
1941         }
1942
1943         v = (gchar *) value;
1944         if (!type->byref) {
1945                 switch (type->type) {
1946                 case MONO_TYPE_U1:
1947                 case MONO_TYPE_I1:
1948                 case MONO_TYPE_BOOLEAN:
1949                 case MONO_TYPE_U2:
1950                 case MONO_TYPE_I2:
1951                 case MONO_TYPE_CHAR:
1952                 case MONO_TYPE_U:
1953                 case MONO_TYPE_I:
1954                 case MONO_TYPE_U4:
1955                 case MONO_TYPE_I4:
1956                 case MONO_TYPE_R4:
1957                 case MONO_TYPE_U8:
1958                 case MONO_TYPE_I8:
1959                 case MONO_TYPE_R8:
1960                 case MONO_TYPE_VALUETYPE:
1961                 case MONO_TYPE_PTR:
1962                         if (v != NULL)
1963                                 v += sizeof (MonoObject);
1964                         break;
1965                 case MONO_TYPE_STRING:
1966                 case MONO_TYPE_OBJECT:
1967                 case MONO_TYPE_CLASS:
1968                 case MONO_TYPE_ARRAY:
1969                 case MONO_TYPE_SZARRAY:
1970                         /* Do nothing */
1971                         break;
1972                 case MONO_TYPE_GENERICINST: {
1973                         MonoGenericClass *gclass = type->data.generic_class;
1974                         g_assert (!gclass->context.class_inst->is_open);
1975
1976                         if (mono_class_is_nullable (mono_class_from_mono_type (type))) {
1977                                 MonoClass *nklass = mono_class_from_mono_type (type);
1978                                 MonoObject *nullable;
1979
1980                                 /* 
1981                                  * Convert the boxed vtype into a Nullable structure.
1982                                  * This is complicated by the fact that Nullables have
1983                                  * a variable structure.
1984                                  */
1985                                 nullable = mono_object_new_checked (mono_domain_get (), nklass, &error);
1986                                 if (!mono_error_ok (&error)) {
1987                                         mono_error_set_pending_exception (&error);
1988                                         return;
1989                                 }
1990
1991                                 mono_nullable_init ((guint8 *)mono_object_unbox (nullable), value, nklass);
1992
1993                                 v = (gchar *)mono_object_unbox (nullable);
1994                         }
1995                         else 
1996                                 if (gclass->container_class->valuetype && (v != NULL))
1997                                         v += sizeof (MonoObject);
1998                         break;
1999                 }
2000                 default:
2001                         g_error ("type 0x%x not handled in "
2002                                  "ves_icall_FieldInfo_SetValueInternal", type->type);
2003                         return;
2004                 }
2005         }
2006
2007         if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
2008                 MonoVTable *vtable = mono_class_vtable_full (mono_object_domain (field), cf->parent, &error);
2009                 if (!is_ok (&error)) {
2010                         mono_error_set_pending_exception (&error);
2011                         return;
2012                 }
2013                 if (!vtable->initialized) {
2014                         if (!mono_runtime_class_init_full (vtable, &error)) {
2015                                 mono_error_set_pending_exception (&error);
2016                                 return;
2017                         }
2018                 }
2019                 mono_field_static_set_value (vtable, cf, v);
2020         } else {
2021                 mono_field_set_value (obj, cf, v);
2022         }
2023 }
2024
2025 ICALL_EXPORT void
2026 ves_icall_System_RuntimeFieldHandle_SetValueDirect (MonoReflectionField *field, MonoReflectionType *field_type, MonoTypedRef *obj, MonoObject *value, MonoReflectionType *context_type)
2027 {
2028         MonoClassField *f;
2029
2030         g_assert (field);
2031         g_assert (obj);
2032         g_assert (value);
2033
2034         f = field->field;
2035         if (!MONO_TYPE_ISSTRUCT (&f->parent->byval_arg)) {
2036                 mono_set_pending_exception (mono_get_exception_not_implemented (NULL));
2037                 return;
2038         }
2039
2040         if (MONO_TYPE_IS_REFERENCE (f->type))
2041                 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), value, FALSE);
2042         else
2043                 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), mono_object_unbox (value), FALSE);
2044 }
2045
2046 ICALL_EXPORT MonoObject *
2047 ves_icall_MonoField_GetRawConstantValue (MonoReflectionField *rfield)
2048 {       
2049         MonoObject *o = NULL;
2050         MonoClassField *field = rfield->field;
2051         MonoClass *klass;
2052         MonoDomain *domain = mono_object_domain (rfield);
2053         gchar *v;
2054         MonoTypeEnum def_type;
2055         const char *def_value;
2056         MonoType *t;
2057         MonoError error;
2058
2059         mono_class_init (field->parent);
2060
2061         t = mono_field_get_type_checked (field, &error);
2062         if (!mono_error_ok (&error)) {
2063                 mono_error_set_pending_exception (&error);
2064                 return NULL;
2065         }
2066
2067         if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT)) {
2068                 mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
2069                 return NULL;
2070         }
2071
2072         if (image_is_dynamic (field->parent->image)) {
2073                 MonoClass *klass = field->parent;
2074                 int fidx = field - klass->fields;
2075                 MonoFieldDefaultValue *def_values = mono_class_get_field_def_values (klass);
2076
2077                 g_assert (def_values);
2078                 def_type = def_values [fidx].def_type;
2079                 def_value = def_values [fidx].data;
2080
2081                 if (def_type == MONO_TYPE_END) {
2082                         mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
2083                         return NULL;
2084                 }
2085         } else {
2086                 def_value = mono_class_get_field_default_value (field, &def_type);
2087                 /* FIXME, maybe we should try to raise TLE if field->parent is broken */
2088                 if (!def_value) {
2089                         mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
2090                         return NULL;
2091                 }
2092         }
2093
2094         /*FIXME unify this with reflection.c:mono_get_object_from_blob*/
2095         switch (def_type) {
2096         case MONO_TYPE_U1:
2097         case MONO_TYPE_I1:
2098         case MONO_TYPE_BOOLEAN:
2099         case MONO_TYPE_U2:
2100         case MONO_TYPE_I2:
2101         case MONO_TYPE_CHAR:
2102         case MONO_TYPE_U:
2103         case MONO_TYPE_I:
2104         case MONO_TYPE_U4:
2105         case MONO_TYPE_I4:
2106         case MONO_TYPE_R4:
2107         case MONO_TYPE_U8:
2108         case MONO_TYPE_I8:
2109         case MONO_TYPE_R8: {
2110                 MonoType *t;
2111
2112                 /* boxed value type */
2113                 t = g_new0 (MonoType, 1);
2114                 t->type = def_type;
2115                 klass = mono_class_from_mono_type (t);
2116                 g_free (t);
2117                 o = mono_object_new_checked (domain, klass, &error);
2118                 if (!mono_error_ok (&error)) {
2119                         mono_error_set_pending_exception (&error);
2120                         return NULL;
2121                 }
2122                 v = ((gchar *) o) + sizeof (MonoObject);
2123                 mono_get_constant_value_from_blob (domain, def_type, def_value, v, &error);
2124                 if (mono_error_set_pending_exception (&error))
2125                         return NULL;
2126                 break;
2127         }
2128         case MONO_TYPE_STRING:
2129         case MONO_TYPE_CLASS:
2130                 mono_get_constant_value_from_blob (domain, def_type, def_value, &o, &error);
2131                 if (mono_error_set_pending_exception (&error))
2132                         return NULL;
2133                 break;
2134         default:
2135                 g_assert_not_reached ();
2136         }
2137
2138         return o;
2139 }
2140
2141 ICALL_EXPORT MonoReflectionTypeHandle
2142 ves_icall_MonoField_ResolveType (MonoReflectionFieldHandle ref_field, MonoError *error)
2143 {
2144         error_init (error);
2145         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_field);
2146         MonoClassField *field = MONO_HANDLE_GETVAL (ref_field, field);
2147         MonoType *type = mono_field_get_type_checked (field, error);
2148         if (!is_ok (error)) {
2149                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2150         }
2151         return mono_type_get_object_handle (domain, type, error);
2152 }
2153
2154 /* From MonoProperty.cs */
2155 typedef enum {
2156         PInfo_Attributes = 1,
2157         PInfo_GetMethod  = 1 << 1,
2158         PInfo_SetMethod  = 1 << 2,
2159         PInfo_ReflectedType = 1 << 3,
2160         PInfo_DeclaringType = 1 << 4,
2161         PInfo_Name = 1 << 5
2162 } PInfo;
2163
2164 ICALL_EXPORT void
2165 ves_icall_MonoPropertyInfo_get_property_info (MonoReflectionPropertyHandle property, MonoPropertyInfo *info, PInfo req_info, MonoError *error)
2166 {
2167         error_init (error);
2168         MonoDomain *domain = MONO_HANDLE_DOMAIN (property); 
2169         const MonoProperty *pproperty = MONO_HANDLE_GETVAL (property, property);
2170
2171         if ((req_info & PInfo_ReflectedType) != 0) {
2172                 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
2173                 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &klass->byval_arg, error);
2174                 return_if_nok (error);
2175
2176                 MONO_STRUCT_SETREF (info, parent, MONO_HANDLE_RAW (rt));
2177         }
2178         if ((req_info & PInfo_DeclaringType) != 0) {
2179                 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &pproperty->parent->byval_arg, error);
2180                 return_if_nok (error);
2181
2182                 MONO_STRUCT_SETREF (info, declaring_type, MONO_HANDLE_RAW (rt));
2183         }
2184
2185         if ((req_info & PInfo_Name) != 0) {
2186                 MonoStringHandle name = mono_string_new_handle (domain, pproperty->name, error);
2187                 return_if_nok (error);
2188
2189                 MONO_STRUCT_SETREF (info, name, MONO_HANDLE_RAW (name));
2190         }
2191
2192         if ((req_info & PInfo_Attributes) != 0)
2193                 info->attrs = pproperty->attrs;
2194
2195         if ((req_info & PInfo_GetMethod) != 0) {
2196                 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2197                 MonoReflectionMethodHandle rm;
2198                 if (pproperty->get &&
2199                     (((pproperty->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2200                      pproperty->get->klass == property_klass)) {
2201                         rm = mono_method_get_object_handle (domain, pproperty->get, property_klass, error);
2202                         return_if_nok (error);
2203                 } else {
2204                         rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2205                 }
2206
2207                 MONO_STRUCT_SETREF (info, get, MONO_HANDLE_RAW (rm));
2208         }
2209         if ((req_info & PInfo_SetMethod) != 0) {
2210                 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2211                 MonoReflectionMethodHandle rm;
2212                 if (pproperty->set &&
2213                     (((pproperty->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2214                      pproperty->set->klass == property_klass)) {
2215                         rm =  mono_method_get_object_handle (domain, pproperty->set, property_klass, error);
2216                         return_if_nok (error);
2217                 } else {
2218                         rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2219                 }
2220
2221                 MONO_STRUCT_SETREF (info, set, MONO_HANDLE_RAW (rm));
2222         }
2223         /* 
2224          * There may be other methods defined for properties, though, it seems they are not exposed 
2225          * in the reflection API 
2226          */
2227 }
2228
2229 static gboolean
2230 add_event_other_methods_to_array (MonoDomain *domain, MonoMethod *m, MonoArrayHandle dest, int i, MonoError *error)
2231 {
2232         HANDLE_FUNCTION_ENTER ();
2233         error_init (error);
2234         MonoReflectionMethodHandle rm = mono_method_get_object_handle (domain, m, NULL, error);
2235         if (!is_ok (error))
2236                 goto leave;
2237         MONO_HANDLE_ARRAY_SETREF (dest, i, rm);
2238 leave:
2239         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2240 }
2241
2242 ICALL_EXPORT void
2243 ves_icall_MonoEventInfo_get_event_info (MonoReflectionMonoEventHandle ref_event, MonoEventInfo *info, MonoError *error)
2244 {
2245         error_init (error);
2246         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_event); 
2247
2248         MonoClass *klass = MONO_HANDLE_GETVAL (ref_event, klass);
2249         MonoEvent *event = MONO_HANDLE_GETVAL (ref_event, event);
2250
2251         MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &klass->byval_arg, error);
2252         return_if_nok (error);
2253         MONO_STRUCT_SETREF (info, reflected_type, MONO_HANDLE_RAW (rt));
2254
2255         rt = mono_type_get_object_handle (domain, &event->parent->byval_arg, error);
2256         return_if_nok (error);
2257         MONO_STRUCT_SETREF (info, declaring_type, MONO_HANDLE_RAW (rt));
2258
2259         MonoStringHandle ev_name = mono_string_new_handle (domain, event->name, error);
2260         return_if_nok (error);
2261         MONO_STRUCT_SETREF (info, name, MONO_HANDLE_RAW (ev_name));
2262
2263         info->attrs = event->attrs;
2264
2265         MonoReflectionMethodHandle rm;
2266         if (event->add) {
2267                 rm = mono_method_get_object_handle (domain, event->add, NULL, error);
2268                 return_if_nok (error);
2269         } else {
2270                 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2271         }
2272
2273         MONO_STRUCT_SETREF (info, add_method, MONO_HANDLE_RAW (rm));
2274
2275         if (event->remove) {
2276                 rm = mono_method_get_object_handle (domain, event->remove, NULL, error);
2277                 return_if_nok (error);
2278         } else {
2279                 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2280         }
2281
2282         MONO_STRUCT_SETREF (info, remove_method, MONO_HANDLE_RAW (rm));
2283
2284         if (event->raise) {
2285                 rm = mono_method_get_object_handle (domain, event->raise, NULL, error);
2286                 return_if_nok (error);
2287         } else {
2288                 rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2289         }
2290
2291         MONO_STRUCT_SETREF (info, raise_method, MONO_HANDLE_RAW (rm));
2292
2293 #ifndef MONO_SMALL_CONFIG
2294         if (event->other) {
2295                 int i, n = 0;
2296                 while (event->other [n])
2297                         n++;
2298                 MonoArrayHandle info_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, n, error);
2299                 return_if_nok (error);
2300
2301                 MONO_STRUCT_SETREF (info, other_methods, MONO_HANDLE_RAW  (info_arr));
2302
2303                 for (i = 0; i < n; i++)
2304                         if (!add_event_other_methods_to_array (domain, event->other [i], info_arr, i, error))
2305                                 return;
2306         }               
2307 #endif
2308 }
2309
2310 static void
2311 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
2312 {
2313         int i;
2314         MonoClass *ic;
2315
2316         mono_class_setup_interfaces (klass, error);
2317         if (!mono_error_ok (error))
2318                 return;
2319
2320         for (i = 0; i < klass->interface_count; i++) {
2321                 ic = klass->interfaces [i];
2322                 g_hash_table_insert (ifaces, ic, ic);
2323
2324                 collect_interfaces (ic, ifaces, error);
2325                 if (!mono_error_ok (error))
2326                         return;
2327         }
2328 }
2329
2330 typedef struct {
2331         MonoArrayHandle iface_array;
2332         MonoGenericContext *context;
2333         MonoError *error;
2334         MonoDomain *domain;
2335         int next_idx;
2336 } FillIfaceArrayData;
2337
2338 static void
2339 fill_iface_array (gpointer key, gpointer value, gpointer user_data)
2340 {
2341         HANDLE_FUNCTION_ENTER ();
2342         FillIfaceArrayData *data = (FillIfaceArrayData *)user_data;
2343         MonoClass *ic = (MonoClass *)key;
2344         MonoType *ret = &ic->byval_arg, *inflated = NULL;
2345         MonoError *error = data->error;
2346
2347         if (!is_ok (error))
2348                 goto leave;
2349
2350         if (data->context && mono_class_is_ginst (ic) && mono_class_get_generic_class (ic)->context.class_inst->is_open) {
2351                 inflated = ret = mono_class_inflate_generic_type_checked (ret, data->context, error);
2352                 if (!is_ok (error))
2353                         goto leave;
2354         }
2355
2356         MonoReflectionTypeHandle rt = mono_type_get_object_handle (data->domain, ret, error);
2357         if (!is_ok (error))
2358                 goto leave;
2359
2360         MONO_HANDLE_ARRAY_SETREF (data->iface_array, data->next_idx, rt);
2361         data->next_idx++;
2362
2363         if (inflated)
2364                 mono_metadata_free_type (inflated);
2365 leave:
2366         HANDLE_FUNCTION_RETURN ();
2367 }
2368
2369 static guint
2370 get_interfaces_hash (gconstpointer v1)
2371 {
2372         MonoClass *k = (MonoClass*)v1;
2373
2374         return k->type_token;
2375 }
2376
2377 ICALL_EXPORT MonoArrayHandle
2378 ves_icall_RuntimeType_GetInterfaces (MonoReflectionTypeHandle ref_type, MonoError *error)
2379 {
2380         error_init (error);
2381         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2382         MonoClass *klass = mono_class_from_mono_type (type);
2383
2384         GHashTable *iface_hash = g_hash_table_new (get_interfaces_hash, NULL);
2385
2386         MonoGenericContext *context = NULL;
2387         if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open) {
2388                 context = mono_class_get_context (klass);
2389                 klass = mono_class_get_generic_class (klass)->container_class;
2390         }
2391
2392         for (MonoClass *parent = klass; parent; parent = parent->parent) {
2393                 mono_class_setup_interfaces (parent, error);
2394                 if (!is_ok (error))
2395                         goto fail;
2396                 collect_interfaces (parent, iface_hash, error);
2397                 if (!is_ok (error))
2398                         goto fail;
2399         }
2400
2401         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2402
2403         int len = g_hash_table_size (iface_hash);
2404         if (len == 0) {
2405                 g_hash_table_destroy (iface_hash);
2406                 if (!domain->empty_types) {
2407                         domain->empty_types = mono_array_new_cached (domain, mono_defaults.runtimetype_class, 0, error);
2408                         if (!is_ok (error))
2409                                 goto fail;
2410                 }
2411                 return MONO_HANDLE_NEW (MonoArray, domain->empty_types);
2412         }
2413
2414         FillIfaceArrayData data;
2415         data.iface_array = MONO_HANDLE_NEW (MonoArray, mono_array_new_cached (domain, mono_defaults.runtimetype_class, len, error));
2416         if (!is_ok (error))
2417                 goto fail;
2418         data.context = context;
2419         data.error = error;
2420         data.domain = domain;
2421         data.next_idx = 0;
2422
2423         g_hash_table_foreach (iface_hash, fill_iface_array, &data);
2424
2425         if (!is_ok (error))
2426                 goto fail;
2427
2428         g_hash_table_destroy (iface_hash);
2429         return data.iface_array;
2430
2431 fail:
2432         g_hash_table_destroy (iface_hash);
2433         return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
2434 }
2435
2436 static gboolean
2437 set_interface_map_data_method_object (MonoDomain *domain, MonoMethod *method, MonoClass *iclass, int ioffset, MonoClass *klass, MonoArrayHandle targets, MonoArrayHandle methods, int i, MonoError *error)
2438 {
2439         HANDLE_FUNCTION_ENTER ();
2440         error_init (error);
2441         MonoReflectionMethodHandle member = mono_method_get_object_handle (domain, method, iclass, error);
2442         if (!is_ok (error))
2443                 goto leave;
2444
2445         MONO_HANDLE_ARRAY_SETREF (methods, i, member);
2446
2447         MONO_HANDLE_ASSIGN (member, mono_method_get_object_handle (domain, klass->vtable [i + ioffset], klass, error));
2448         if (!is_ok (error))
2449                 goto leave;
2450
2451         MONO_HANDLE_ARRAY_SETREF (targets, i, member);
2452                 
2453 leave:
2454         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2455 }
2456
2457 ICALL_EXPORT void
2458 ves_icall_RuntimeType_GetInterfaceMapData (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_iface, MonoArrayHandleOut targets, MonoArrayHandleOut methods, MonoError *error)
2459 {
2460         error_init (error);
2461         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2462         MonoClass *klass = mono_class_from_mono_type (type);
2463         MonoType *iface = MONO_HANDLE_GETVAL (ref_iface, type);
2464         MonoClass *iclass = mono_class_from_mono_type (iface);
2465
2466         mono_class_init_checked (klass, error);
2467         return_if_nok (error);
2468         mono_class_init_checked (iclass, error);
2469         return_if_nok (error);
2470
2471         mono_class_setup_vtable (klass);
2472
2473         gboolean variance_used;
2474         int ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
2475         if (ioffset == -1)
2476                 return;
2477
2478         int len = mono_class_num_methods (iclass);
2479         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2480         MonoArrayHandle targets_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
2481         return_if_nok (error);
2482         MONO_HANDLE_ASSIGN (targets, targets_arr);
2483
2484         MonoArrayHandle methods_arr = mono_array_new_handle (domain, mono_defaults.method_info_class, len, error);
2485         return_if_nok (error);
2486         MONO_HANDLE_ASSIGN (methods, methods_arr);
2487
2488         MonoMethod* method;
2489         int i = 0;
2490         gpointer iter = NULL;
2491         while ((method = mono_class_get_methods (iclass, &iter))) {
2492                 if (!set_interface_map_data_method_object (domain, method, iclass, ioffset, klass, targets, methods, i, error))
2493                         return;
2494                 i ++;
2495         }
2496 }
2497
2498 ICALL_EXPORT void
2499 ves_icall_RuntimeType_GetPacking (MonoReflectionTypeHandle ref_type, guint32 *packing, guint32 *size, MonoError *error)
2500 {
2501         error_init (error);
2502         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2503         MonoClass *klass = mono_class_from_mono_type (type);
2504
2505         mono_class_init_checked (klass, error);
2506         if (!is_ok (error))
2507                 return;
2508
2509         if (image_is_dynamic (klass->image)) {
2510                 MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, ref_type);
2511                 *packing = MONO_HANDLE_GETVAL (tb, packing_size);
2512                 *size = MONO_HANDLE_GETVAL (tb, class_size);
2513         } else {
2514                 mono_metadata_packing_from_typedef (klass->image, klass->type_token, packing, size);
2515         }
2516 }
2517
2518 ICALL_EXPORT MonoReflectionTypeHandle
2519 ves_icall_RuntimeTypeHandle_GetElementType (MonoReflectionTypeHandle ref_type, MonoError *error)
2520 {
2521         error_init (error);
2522
2523         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2524         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2525
2526         if (!type->byref && type->type == MONO_TYPE_SZARRAY) {
2527                 return mono_type_get_object_handle (domain, &type->data.klass->byval_arg, error);
2528         }
2529
2530         MonoClass *klass = mono_class_from_mono_type (type);
2531         mono_class_init_checked (klass, error);
2532         if (!is_ok (error))
2533                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2534
2535         // GetElementType should only return a type for:
2536         // Array Pointer PassedByRef
2537         if (type->byref)
2538                 return mono_type_get_object_handle (domain, &klass->byval_arg, error);
2539         else if (klass->element_class && MONO_CLASS_IS_ARRAY (klass))
2540                 return mono_type_get_object_handle (domain, &klass->element_class->byval_arg, error);
2541         else if (klass->element_class && type->type == MONO_TYPE_PTR)
2542                 return mono_type_get_object_handle (domain, &klass->element_class->byval_arg, error);
2543         else
2544                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2545 }
2546
2547 ICALL_EXPORT MonoReflectionTypeHandle
2548 ves_icall_RuntimeTypeHandle_GetBaseType (MonoReflectionTypeHandle ref_type, MonoError *error)
2549 {
2550         error_init (error);
2551
2552         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2553         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2554
2555         if (type->byref)
2556                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2557
2558         MonoClass *klass = mono_class_from_mono_type (type);
2559         if (!klass->parent)
2560                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2561
2562         return mono_type_get_object_handle (domain, &klass->parent->byval_arg, error);
2563 }
2564
2565 ICALL_EXPORT MonoBoolean
2566 ves_icall_RuntimeTypeHandle_IsPointer (MonoReflectionTypeHandle ref_type, MonoError *error)
2567 {
2568         error_init (error);
2569         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2570         return type->type == MONO_TYPE_PTR;
2571 }
2572
2573 ICALL_EXPORT MonoBoolean
2574 ves_icall_RuntimeTypeHandle_IsPrimitive (MonoReflectionTypeHandle ref_type, MonoError *error)
2575 {
2576         error_init (error);
2577         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2578         return (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)));
2579 }
2580
2581 ICALL_EXPORT MonoBoolean
2582 ves_icall_RuntimeTypeHandle_HasReferences (MonoReflectionTypeHandle ref_type, MonoError *error)
2583 {
2584         error_init (error);
2585         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2586         MonoClass *klass;
2587
2588         klass = mono_class_from_mono_type (type);
2589         mono_class_init (klass);
2590         return klass->has_references;
2591 }
2592
2593 ICALL_EXPORT MonoBoolean
2594 ves_icall_RuntimeTypeHandle_IsByRef (MonoReflectionTypeHandle ref_type, MonoError *error)
2595 {
2596         error_init (error);
2597         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2598         return type->byref;
2599 }
2600
2601 ICALL_EXPORT MonoBoolean
2602 ves_icall_RuntimeTypeHandle_IsComObject (MonoReflectionTypeHandle ref_type, MonoError *error)
2603 {
2604         error_init (error);
2605         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2606         MonoClass *klass = mono_class_from_mono_type (type);
2607         mono_class_init_checked (klass, error);
2608         if (!is_ok (error))
2609                 return FALSE;
2610
2611         return mono_class_is_com_object (klass);
2612 }
2613
2614 ICALL_EXPORT guint32
2615 ves_icall_reflection_get_token (MonoObjectHandle obj, MonoError *error)
2616 {
2617         error_init (error);
2618         return mono_reflection_get_token_checked (obj, error);
2619 }
2620
2621 ICALL_EXPORT MonoReflectionModuleHandle
2622 ves_icall_RuntimeTypeHandle_GetModule (MonoReflectionTypeHandle type, MonoError *error)
2623 {
2624         error_init (error);
2625         MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
2626         MonoType *t = MONO_HANDLE_GETVAL (type, type);
2627         MonoClass *klass = mono_class_from_mono_type (t);
2628         return mono_module_get_object_handle (domain, klass->image, error);
2629 }
2630
2631 ICALL_EXPORT MonoReflectionAssemblyHandle
2632 ves_icall_RuntimeTypeHandle_GetAssembly (MonoReflectionTypeHandle type, MonoError *error)
2633 {
2634         error_init (error);
2635         MonoDomain *domain = mono_domain_get (); 
2636         MonoType *t = MONO_HANDLE_GETVAL (type, type);
2637         MonoClass *klass = mono_class_from_mono_type (t);
2638         return mono_assembly_get_object_handle (domain, klass->image->assembly, error);
2639 }
2640
2641 ICALL_EXPORT MonoReflectionTypeHandle
2642 ves_icall_RuntimeType_get_DeclaringType (MonoReflectionTypeHandle ref_type, MonoError *error)
2643 {
2644         error_init (error);
2645         MonoDomain *domain = mono_domain_get ();
2646         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2647         MonoClass *klass;
2648
2649         if (type->byref)
2650                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2651         if (type->type == MONO_TYPE_VAR) {
2652                 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
2653                 klass = param ? param->owner.klass : NULL;
2654         } else if (type->type == MONO_TYPE_MVAR) {
2655                 MonoGenericContainer *param = mono_type_get_generic_param_owner (type);
2656                 klass = param ? param->owner.method->klass : NULL;
2657         } else {
2658                 klass = mono_class_from_mono_type (type)->nested_in;
2659         }
2660
2661         if (!klass)
2662                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2663
2664         return mono_type_get_object_handle (domain, &klass->byval_arg, error);
2665 }
2666
2667 ICALL_EXPORT MonoStringHandle
2668 ves_icall_RuntimeType_get_Name (MonoReflectionTypeHandle reftype, MonoError *error)
2669 {
2670         MonoDomain *domain = mono_domain_get ();
2671         MonoType *type = MONO_HANDLE_RAW(reftype)->type; 
2672         MonoClass *klass = mono_class_from_mono_type (type);
2673
2674         if (type->byref) {
2675                 char *n = g_strdup_printf ("%s&", klass->name);
2676                 MonoStringHandle res = mono_string_new_handle (domain, n, error);
2677
2678                 g_free (n);
2679
2680                 return res;
2681         } else {
2682                 return mono_string_new_handle (domain, klass->name, error);
2683         }
2684 }
2685
2686 ICALL_EXPORT MonoStringHandle
2687 ves_icall_RuntimeType_get_Namespace (MonoReflectionTypeHandle type, MonoError *error)
2688 {
2689         MonoDomain *domain = mono_domain_get (); 
2690         MonoClass *klass = mono_class_from_mono_type_handle (type);
2691
2692         while (klass->nested_in)
2693                 klass = klass->nested_in;
2694
2695         if (klass->name_space [0] == '\0')
2696                 return NULL_HANDLE_STRING;
2697         else
2698                 return mono_string_new_handle (domain, klass->name_space, error);
2699 }
2700
2701 ICALL_EXPORT gint32
2702 ves_icall_RuntimeTypeHandle_GetArrayRank (MonoReflectionTypeHandle ref_type, MonoError *error)
2703 {
2704         error_init (error);
2705         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2706
2707         if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
2708                 mono_error_set_argument (error, "type", "Type must be an array type");
2709                 return 0;
2710         }
2711
2712         MonoClass *klass = mono_class_from_mono_type (type);
2713
2714         return klass->rank;
2715 }
2716
2717 static MonoArrayHandle
2718 create_type_array (MonoDomain *domain, MonoBoolean runtimeTypeArray, int count, MonoError *error)
2719 {
2720         return mono_array_new_handle (domain, runtimeTypeArray ? mono_defaults.runtimetype_class : mono_defaults.systemtype_class, count, error);
2721 }
2722
2723 static gboolean
2724 set_type_object_in_array (MonoDomain *domain, MonoType *type, MonoArrayHandle dest, int i, MonoError *error)
2725 {
2726         HANDLE_FUNCTION_ENTER();
2727         error_init (error);
2728         MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, type, error);
2729         if (!is_ok (error))
2730                 goto leave;
2731
2732         MONO_HANDLE_ARRAY_SETREF (dest, i, rt);
2733
2734 leave:
2735         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
2736 }
2737
2738 ICALL_EXPORT MonoArrayHandle
2739 ves_icall_RuntimeType_GetGenericArguments (MonoReflectionTypeHandle ref_type, MonoBoolean runtimeTypeArray, MonoError *error)
2740 {
2741         error_init (error);
2742         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2743
2744         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2745         MonoClass *klass = mono_class_from_mono_type (type);
2746
2747         MonoArrayHandle res = MONO_HANDLE_NEW (MonoArray, NULL);
2748         if (mono_class_is_gtd (klass)) {
2749                 MonoGenericContainer *container = mono_class_get_generic_container (klass);
2750                 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, container->type_argc, error));
2751                 if (!is_ok (error))
2752                         goto leave;
2753                 for (int i = 0; i < container->type_argc; ++i) {
2754                         MonoClass *pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
2755
2756                         if (!set_type_object_in_array (domain, &pklass->byval_arg, res, i, error))
2757                                 goto leave;
2758                 }
2759                 
2760         } else if (mono_class_is_ginst (klass)) {
2761                 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2762                 MONO_HANDLE_ASSIGN (res, create_type_array (domain, runtimeTypeArray, inst->type_argc, error));
2763                 if (!is_ok (error))
2764                         goto leave;
2765                 for (int i = 0; i < inst->type_argc; ++i) {
2766                         if (!set_type_object_in_array (domain, inst->type_argv [i], res, i, error))
2767                                 goto leave;
2768                 }
2769         }
2770
2771 leave:
2772         return res;
2773 }
2774
2775 ICALL_EXPORT gboolean
2776 ves_icall_RuntimeTypeHandle_IsGenericTypeDefinition (MonoReflectionTypeHandle ref_type, MonoError *error)
2777 {
2778         error_init (error);
2779
2780         if (!IS_MONOTYPE (MONO_HANDLE_RAW(ref_type)))
2781                 return FALSE;
2782
2783         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2784         if (type->byref)
2785                 return FALSE;
2786
2787         MonoClass *klass = mono_class_from_mono_type (type);
2788         return mono_class_is_gtd (klass);
2789 }
2790
2791 ICALL_EXPORT MonoReflectionTypeHandle
2792 ves_icall_RuntimeTypeHandle_GetGenericTypeDefinition_impl (MonoReflectionTypeHandle ref_type, MonoError *error)
2793 {
2794         error_init (error);
2795         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2796
2797         MonoReflectionTypeHandle ret = MONO_HANDLE_NEW (MonoReflectionType, NULL);
2798
2799         if (type->byref)
2800                 goto leave;
2801
2802         MonoClass *klass = mono_class_from_mono_type (type);
2803
2804         if (mono_class_is_gtd (klass)) {
2805                 /* check this one */
2806                 MONO_HANDLE_ASSIGN (ret, ref_type);
2807                 goto leave;
2808         }
2809         if (mono_class_is_ginst (klass)) {
2810                 MonoClass *generic_class = mono_class_get_generic_class (klass)->container_class;
2811
2812                 guint32 ref_info_handle = mono_class_get_ref_info_handle (generic_class);
2813                 
2814                 if (generic_class->wastypebuilder && ref_info_handle) {
2815                         MonoObjectHandle tb = mono_gchandle_get_target_handle (ref_info_handle);
2816                         g_assert (!MONO_HANDLE_IS_NULL (tb));
2817                         MONO_HANDLE_ASSIGN (ret, tb);
2818                 } else {
2819                         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2820                         MONO_HANDLE_ASSIGN (ret, mono_type_get_object_handle (domain, &generic_class->byval_arg, error));
2821                 }
2822         }
2823 leave:
2824         return ret;
2825 }
2826
2827 ICALL_EXPORT MonoReflectionTypeHandle
2828 ves_icall_RuntimeType_MakeGenericType (MonoReflectionTypeHandle reftype, MonoArrayHandle type_array, MonoError *error)
2829 {
2830         error_init (error);
2831         MonoDomain *domain = MONO_HANDLE_DOMAIN (reftype);
2832
2833         g_assert (IS_MONOTYPE_HANDLE (reftype));
2834         MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
2835         mono_class_init_checked (mono_class_from_mono_type (type), error);
2836         if (!is_ok (error))
2837                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2838
2839         int count = mono_array_handle_length (type_array);
2840         MonoType **types = g_new0 (MonoType *, count);
2841
2842         MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
2843         for (int i = 0; i < count; i++) {
2844                 MONO_HANDLE_ARRAY_GETREF (t, type_array, i);
2845                 types [i] = MONO_HANDLE_GETVAL (t, type);
2846         }
2847
2848         MonoType *geninst = mono_reflection_bind_generic_parameters (reftype, count, types, error);
2849         g_free (types);
2850         if (!geninst) {
2851                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2852         }
2853
2854         MonoClass *klass = mono_class_from_mono_type (geninst);
2855
2856         /*we might inflate to the GTD*/
2857         if (mono_class_is_ginst (klass) && !mono_verifier_class_is_valid_generic_instantiation (klass)) {
2858                 mono_error_set_argument (error, "typeArguments", "Invalid generic arguments");
2859                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2860         }
2861
2862         return mono_type_get_object_handle (domain, geninst, error);
2863 }
2864
2865 ICALL_EXPORT gboolean
2866 ves_icall_RuntimeTypeHandle_HasInstantiation (MonoReflectionTypeHandle ref_type, MonoError *error)
2867 {
2868         error_init (error);
2869         MonoClass *klass;
2870
2871         if (!IS_MONOTYPE (MONO_HANDLE_RAW (ref_type)))
2872                 return FALSE;
2873
2874         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2875         if (type->byref)
2876                 return FALSE;
2877
2878         klass = mono_class_from_mono_type (type);
2879         return mono_class_is_ginst (klass) || mono_class_is_gtd (klass);
2880 }
2881
2882 ICALL_EXPORT gint32
2883 ves_icall_RuntimeType_GetGenericParameterPosition (MonoReflectionTypeHandle ref_type, MonoError *error)
2884 {
2885         error_init (error);
2886         if (!IS_MONOTYPE_HANDLE (ref_type))
2887                 return -1;
2888         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2889
2890         if (is_generic_parameter (type))
2891                 return mono_type_get_generic_param_num (type);
2892         return -1;
2893 }
2894
2895 ICALL_EXPORT MonoGenericParamInfo *
2896 ves_icall_RuntimeTypeHandle_GetGenericParameterInfo (MonoReflectionTypeHandle ref_type, MonoError *error)
2897 {
2898         error_init (error);
2899         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2900         return mono_generic_param_info (type->data.generic_param);
2901 }
2902
2903 ICALL_EXPORT MonoBoolean
2904 ves_icall_RuntimeTypeHandle_IsGenericVariable (MonoReflectionTypeHandle ref_type, MonoError *error)
2905 {
2906         MonoType *type = MONO_HANDLE_GETVAL(ref_type, type);
2907         return is_generic_parameter (type);
2908 }
2909
2910 ICALL_EXPORT MonoReflectionMethodHandle
2911 ves_icall_RuntimeType_GetCorrespondingInflatedMethod (MonoReflectionTypeHandle ref_type, 
2912                                                       MonoReflectionMethodHandle generic,
2913                                                       MonoError *error)
2914 {
2915         error_init (error);
2916         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2917         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2918         MonoClass *klass = mono_class_from_mono_type (type);
2919                 
2920         mono_class_init_checked (klass, error);
2921         if (!is_ok (error))
2922                 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
2923
2924         MonoMethod *generic_method = MONO_HANDLE_GETVAL (generic, method);
2925         
2926         MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
2927         MonoMethod *method;
2928         gpointer iter = NULL;
2929         while ((method = mono_class_get_methods (klass, &iter))) {
2930                 if (method->token == generic_method->token) {
2931                         ret = mono_method_get_object_handle (domain, method, klass, error);
2932                         if (!is_ok (error))
2933                                 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
2934                 }
2935         }
2936
2937         return ret;
2938 }
2939
2940 ICALL_EXPORT MonoReflectionMethodHandle
2941 ves_icall_RuntimeType_get_DeclaringMethod (MonoReflectionTypeHandle ref_type, MonoError *error)
2942 {
2943         error_init (error);
2944         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
2945         MonoReflectionMethodHandle ret = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2946
2947         if (type->byref || (type->type != MONO_TYPE_MVAR && type->type != MONO_TYPE_VAR)) {
2948                 mono_error_set_invalid_operation (error, "DeclaringMethod can only be used on generic arguments");
2949                 goto leave;
2950         }
2951         if (type->type == MONO_TYPE_VAR)
2952                 goto leave;
2953
2954         MonoMethod *method = mono_type_get_generic_param_owner (type)->owner.method;
2955         g_assert (method);
2956
2957         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
2958
2959         MONO_HANDLE_ASSIGN (ret, mono_method_get_object_handle (domain, method, method->klass, error));
2960 leave:
2961         return ret;
2962 }
2963
2964 ICALL_EXPORT MonoBoolean
2965 ves_icall_System_RuntimeType_IsTypeExportedToWindowsRuntime (MonoError *error)
2966 {
2967         error_init (error);
2968         mono_error_set_not_implemented (error, "%s", "");
2969         return FALSE;
2970 }
2971
2972 ICALL_EXPORT MonoBoolean
2973 ves_icall_System_RuntimeType_IsWindowsRuntimeObjectType (MonoError *error)
2974 {
2975         error_init (error);
2976         mono_error_set_not_implemented (error, "%s", "");
2977         return FALSE;
2978 }
2979
2980 ICALL_EXPORT void
2981 ves_icall_MonoMethod_GetPInvoke (MonoReflectionMethodHandle ref_method, int* flags, MonoStringHandleOut entry_point, MonoStringHandleOut dll_name, MonoError *error)
2982 {
2983         MonoDomain *domain = mono_domain_get ();
2984         MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
2985         MonoImage *image = method->klass->image;
2986         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
2987         MonoTableInfo *tables = image->tables;
2988         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
2989         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
2990         guint32 im_cols [MONO_IMPLMAP_SIZE];
2991         guint32 scope_token;
2992         const char *import = NULL;
2993         const char *scope = NULL;
2994
2995         error_init (error);
2996
2997         if (image_is_dynamic (image)) {
2998                 MonoReflectionMethodAux *method_aux = 
2999                         (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)image)->method_aux_hash, method);
3000                 if (method_aux) {
3001                         import = method_aux->dllentry;
3002                         scope = method_aux->dll;
3003                 }
3004
3005                 if (!import || !scope) {
3006                         mono_error_set_argument (error, "method", "System.Refleciton.Emit method with invalid pinvoke information");
3007                         return;
3008                 }
3009         }
3010         else {
3011                 if (piinfo->implmap_idx) {
3012                         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3013                         
3014                         piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
3015                         import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
3016                         scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
3017                         scope = mono_metadata_string_heap (image, scope_token);
3018                 }
3019         }
3020         
3021         *flags = piinfo->piflags;
3022         MONO_HANDLE_ASSIGN (entry_point,  mono_string_new_handle (domain, import, error));
3023         return_if_nok (error);
3024         MONO_HANDLE_ASSIGN (dll_name, mono_string_new_handle (domain, scope, error));
3025 }
3026
3027 ICALL_EXPORT MonoReflectionMethodHandle
3028 ves_icall_MonoMethod_GetGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *error)
3029 {
3030         error_init (error);
3031         MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3032
3033         if (method->is_generic)
3034                 return ref_method;
3035
3036         if (!method->is_inflated)
3037                 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3038
3039         MonoMethodInflated *imethod = (MonoMethodInflated *) method;
3040
3041         MonoMethod *result = imethod->declaring;
3042         /* Not a generic method.  */
3043         if (!result->is_generic)
3044                 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
3045
3046         if (image_is_dynamic (method->klass->image)) {
3047                 MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
3048
3049                 /*
3050                  * FIXME: Why is this stuff needed at all ? Why can't the code below work for
3051                  * the dynamic case as well ?
3052                  */
3053                 mono_image_lock ((MonoImage*)image);
3054                 MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, mono_g_hash_table_lookup (image->generic_def_objects, imethod));
3055                 mono_image_unlock ((MonoImage*)image);
3056
3057                 if (!MONO_HANDLE_IS_NULL (res))
3058                         return res;
3059         }
3060
3061         if (imethod->context.class_inst) {
3062                 MonoClass *klass = ((MonoMethod *) imethod)->klass;
3063                 /*Generic methods gets the context of the GTD.*/
3064                 if (mono_class_get_context (klass)) {
3065                         result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
3066                         return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
3067                 }
3068         }
3069
3070         return mono_method_get_object_handle (MONO_HANDLE_DOMAIN (ref_method), result, NULL, error);
3071 }
3072
3073 ICALL_EXPORT gboolean
3074 ves_icall_MonoMethod_get_IsGenericMethod (MonoReflectionMethodHandle ref_method, MonoError *erro)
3075 {
3076         MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3077         return mono_method_signature (method)->generic_param_count != 0;
3078 }
3079
3080 ICALL_EXPORT gboolean
3081 ves_icall_MonoMethod_get_IsGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *Error)
3082 {
3083         MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3084         return method->is_generic;
3085 }
3086
3087 static gboolean
3088 set_array_generic_argument_handle_inflated (MonoDomain *domain, MonoGenericInst *inst, int i, MonoArrayHandle arr, MonoError *error)
3089 {
3090         HANDLE_FUNCTION_ENTER ();
3091         error_init (error);
3092         MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, inst->type_argv [i], error);
3093         if (!is_ok (error))
3094                 goto leave;
3095         MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3096 leave:
3097         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3098 }
3099
3100 static gboolean
3101 set_array_generic_argument_handle_gparam (MonoDomain *domain, MonoGenericContainer *container, int i, MonoArrayHandle arr, MonoError *error)
3102 {
3103         HANDLE_FUNCTION_ENTER ();
3104         error_init (error);
3105         MonoGenericParam *param = mono_generic_container_get_param (container, i);
3106         MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
3107         MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &pklass->byval_arg, error);
3108         if (!is_ok (error))
3109                 goto leave;
3110         MONO_HANDLE_ARRAY_SETREF (arr, i, rt);
3111 leave:
3112         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
3113 }
3114
3115 ICALL_EXPORT MonoArrayHandle
3116 ves_icall_MonoMethod_GetGenericArguments (MonoReflectionMethodHandle ref_method, MonoError *error)
3117 {
3118         error_init (error);
3119         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_method);
3120         MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method);
3121
3122         if (method->is_inflated) {
3123                 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
3124
3125                 if (inst) {
3126                         int count = inst->type_argc;
3127                         MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3128                         return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
3129
3130                         for (int i = 0; i < count; i++) {
3131                                 if (!set_array_generic_argument_handle_inflated (domain, inst, i, res, error))
3132                                         break;
3133                         }
3134                         return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
3135                         return res;
3136                 }
3137         }
3138
3139         int count = mono_method_signature (method)->generic_param_count;
3140         MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
3141         return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
3142
3143         MonoGenericContainer *container = mono_method_get_generic_container (method);
3144         for (int i = 0; i < count; i++) {
3145                 if (!set_array_generic_argument_handle_gparam (domain, container, i, res, error))
3146                         break;
3147         }
3148         return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
3149         return res;
3150 }
3151
3152 ICALL_EXPORT MonoObject *
3153 ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this_arg, MonoArray *params, MonoException **exc) 
3154 {
3155         MonoError error;
3156         /* 
3157          * Invoke from reflection is supposed to always be a virtual call (the API
3158          * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
3159          * greater flexibility.
3160          */
3161         MonoMethod *m = method->method;
3162         MonoMethodSignature *sig = mono_method_signature (m);
3163         MonoImage *image;
3164         int pcount;
3165         void *obj = this_arg;
3166
3167         *exc = NULL;
3168
3169         if (mono_security_core_clr_enabled () &&
3170             !mono_security_core_clr_ensure_reflection_access_method (m, &error)) {
3171                 mono_error_set_pending_exception (&error);
3172                 return NULL;
3173         }
3174
3175         if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
3176                 if (!mono_class_vtable_full (mono_object_domain (method), m->klass, &error)) {
3177                         mono_error_cleanup (&error); /* FIXME does this make sense? */
3178                         mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_class_get_exception_for_failure (m->klass));
3179                         return NULL;
3180                 }
3181
3182                 if (this_arg) {
3183                         if (!mono_object_isinst_checked (this_arg, m->klass, &error)) {
3184                                 if (!is_ok (&error)) {
3185                                         mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_error_convert_to_exception (&error));
3186                                         return NULL;
3187                                 }
3188                                 char *this_name = mono_type_get_full_name (mono_object_get_class (this_arg));
3189                                 char *target_name = mono_type_get_full_name (m->klass);
3190                                 char *msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
3191                                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", msg));
3192                                 g_free (msg);
3193                                 g_free (target_name);
3194                                 g_free (this_name);
3195                                 return NULL;
3196                         }
3197                         m = mono_object_get_virtual_method (this_arg, m);
3198                         /* must pass the pointer to the value for valuetype methods */
3199                         if (m->klass->valuetype)
3200                                 obj = mono_object_unbox (this_arg);
3201                 } else if (strcmp (m->name, ".ctor") && !m->wrapper_type) {
3202                         mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Non-static method requires a target."));
3203                         return NULL;
3204                 }
3205         }
3206
3207         if (sig->ret->byref) {
3208                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method returning ByRef type via reflection"));
3209                 return NULL;
3210         }
3211
3212         pcount = params? mono_array_length (params): 0;
3213         if (pcount != sig->param_count) {
3214                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetParameterCountException"));
3215                 return NULL;
3216         }
3217
3218         if (mono_class_is_abstract (m->klass) && !strcmp (m->name, ".ctor") && !this_arg) {
3219                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Cannot invoke constructor of an abstract class."));
3220                 return NULL;
3221         }
3222
3223         image = m->klass->image;
3224         if (image->assembly->ref_only) {
3225                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_get_exception_invalid_operation ("It is illegal to invoke a method on a type loaded using the ReflectionOnly api."));
3226                 return NULL;
3227         }
3228
3229         if (image_is_dynamic (image) && !((MonoDynamicImage*)image)->run) {
3230                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_get_exception_not_supported ("Cannot invoke a method in a dynamic assembly without run access."));
3231                 return NULL;
3232         }
3233         
3234         if (m->klass->rank && !strcmp (m->name, ".ctor")) {
3235                 MonoArray *arr;
3236                 int i;
3237                 uintptr_t *lengths;
3238                 intptr_t *lower_bounds;
3239                 pcount = mono_array_length (params);
3240                 lengths = (uintptr_t *)alloca (sizeof (uintptr_t) * pcount);
3241                 /* Note: the synthetized array .ctors have int32 as argument type */
3242                 for (i = 0; i < pcount; ++i)
3243                         lengths [i] = *(int32_t*) ((char*)mono_array_get (params, gpointer, i) + sizeof (MonoObject));
3244
3245                 if (m->klass->rank == 1 && sig->param_count == 2 && m->klass->element_class->rank) {
3246                         /* This is a ctor for jagged arrays. MS creates an array of arrays. */
3247                         arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, &error);
3248                         if (!mono_error_ok (&error)) {
3249                                 mono_error_set_pending_exception (&error);
3250                                 return NULL;
3251                         }
3252
3253                         for (i = 0; i < mono_array_length (arr); ++i) {
3254                                 MonoArray *subarray = mono_array_new_full_checked (mono_object_domain (params), m->klass->element_class, &lengths [1], NULL, &error);
3255                                 if (!mono_error_ok (&error)) {
3256                                         mono_error_set_pending_exception (&error);
3257                                         return NULL;
3258                                 }
3259                                 mono_array_setref_fast (arr, i, subarray);
3260                         }
3261                         return (MonoObject*)arr;
3262                 }
3263
3264                 if (m->klass->rank == pcount) {
3265                         /* Only lengths provided. */
3266                         arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, NULL, &error);
3267                         if (!mono_error_ok (&error)) {
3268                                 mono_error_set_pending_exception (&error);
3269                                 return NULL;
3270                         }
3271
3272                         return (MonoObject*)arr;
3273                 } else {
3274                         g_assert (pcount == (m->klass->rank * 2));
3275                         /* The arguments are lower-bound-length pairs */
3276                         lower_bounds = (intptr_t *)g_alloca (sizeof (intptr_t) * pcount);
3277
3278                         for (i = 0; i < pcount / 2; ++i) {
3279                                 lower_bounds [i] = *(int32_t*) ((char*)mono_array_get (params, gpointer, (i * 2)) + sizeof (MonoObject));
3280                                 lengths [i] = *(int32_t*) ((char*)mono_array_get (params, gpointer, (i * 2) + 1) + sizeof (MonoObject));
3281                         }
3282
3283                         arr = mono_array_new_full_checked (mono_object_domain (params), m->klass, lengths, lower_bounds, &error);
3284                         if (!mono_error_ok (&error)) {
3285                                 mono_error_set_pending_exception (&error);
3286                                 return NULL;
3287                         }
3288
3289                         return (MonoObject*)arr;
3290                 }
3291         }
3292         MonoObject *result = mono_runtime_invoke_array_checked (m, obj, params, &error);
3293         mono_error_set_pending_exception (&error);
3294         return result;
3295 }
3296
3297 #ifndef DISABLE_REMOTING
3298 static void
3299 internal_execute_field_getter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs, MonoError *error)
3300 {
3301         error_init (error);
3302         MonoArray *out_args;
3303         MonoClass *k = mono_object_class (this_arg);
3304         MonoString *name;
3305         char *str;
3306                         
3307         /* If this is a proxy, then it must be a CBO */
3308         if (mono_class_is_transparent_proxy (k)) {
3309                 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
3310                 this_arg = tp->rp->unwrapped_server;
3311                 g_assert (this_arg);
3312                 k = mono_object_class (this_arg);
3313         }
3314                         
3315         name = mono_array_get (params, MonoString *, 1);
3316         str = mono_string_to_utf8_checked (name, error);
3317         return_if_nok (error);
3318                 
3319         do {
3320                 MonoClassField* field = mono_class_get_field_from_name (k, str);
3321                 if (field) {
3322                         g_free (str);
3323                         MonoClass *field_klass =  mono_class_from_mono_type (field->type);
3324                         MonoObject *result;
3325                         if (field_klass->valuetype) {
3326                                 result = mono_value_box_checked (domain, field_klass, (char *)this_arg + field->offset, error);
3327                                 return_if_nok (error);
3328                         } else 
3329                                 result = (MonoObject *)*((gpointer *)((char *)this_arg + field->offset));
3330
3331                         out_args = mono_array_new_checked (domain, mono_defaults.object_class, 1, error);
3332                         return_if_nok (error);
3333                         mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
3334                         mono_array_setref (out_args, 0, result);
3335                         return;
3336                 }
3337                 k = k->parent;
3338         } while (k);
3339
3340         g_free (str);
3341         g_assert_not_reached ();
3342 }
3343
3344 static void
3345 internal_execute_field_setter (MonoDomain *domain, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs, MonoError *error)
3346 {
3347         error_init (error);
3348         MonoArray *out_args;
3349         MonoClass *k = mono_object_class (this_arg);
3350         MonoString *name;
3351         guint32 size;
3352         gint32 align;
3353         char *str;
3354                         
3355         /* If this is a proxy, then it must be a CBO */
3356         if (mono_class_is_transparent_proxy (k)) {
3357                 MonoTransparentProxy *tp = (MonoTransparentProxy*) this_arg;
3358                 this_arg = tp->rp->unwrapped_server;
3359                 g_assert (this_arg);
3360                 k = mono_object_class (this_arg);
3361         }
3362                         
3363         name = mono_array_get (params, MonoString *, 1);
3364         str = mono_string_to_utf8_checked (name, error);
3365         return_if_nok (error);
3366                 
3367         do {
3368                 MonoClassField* field = mono_class_get_field_from_name (k, str);
3369                 if (field) {
3370                         g_free (str);
3371                         MonoClass *field_klass =  mono_class_from_mono_type (field->type);
3372                         MonoObject *val = (MonoObject *)mono_array_get (params, gpointer, 2);
3373
3374                         if (field_klass->valuetype) {
3375                                 size = mono_type_size (field->type, &align);
3376                                 g_assert (size == mono_class_value_size (field_klass, NULL));
3377                                 mono_gc_wbarrier_value_copy ((char *)this_arg + field->offset, (char*)val + sizeof (MonoObject), 1, field_klass);
3378                         } else {
3379                                 mono_gc_wbarrier_set_field (this_arg, (char*)this_arg + field->offset, val);
3380                         }
3381
3382                         out_args = mono_array_new_checked (domain, mono_defaults.object_class, 0, error);
3383                         return_if_nok (error);
3384                         mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
3385                         return;
3386                 }
3387                                 
3388                 k = k->parent;
3389         } while (k);
3390
3391         g_free (str);
3392         g_assert_not_reached ();
3393 }
3394
3395 ICALL_EXPORT MonoObject *
3396 ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs) 
3397 {
3398         MonoError error;
3399         MonoDomain *domain = mono_object_domain (method); 
3400         MonoMethod *m = method->method;
3401         MonoMethodSignature *sig = mono_method_signature (m);
3402         MonoArray *out_args;
3403         MonoObject *result;
3404         int i, j, outarg_count = 0;
3405
3406         if (m->klass == mono_defaults.object_class) {
3407                 if (!strcmp (m->name, "FieldGetter")) {
3408                         internal_execute_field_getter (domain, this_arg, params, outArgs, &error);
3409                         mono_error_set_pending_exception (&error);
3410                         return NULL;
3411                 } else if (!strcmp (m->name, "FieldSetter")) {
3412                         internal_execute_field_setter (domain, this_arg, params, outArgs, &error);
3413                         mono_error_set_pending_exception (&error);
3414                         return NULL;
3415                 }
3416         }
3417
3418         for (i = 0; i < mono_array_length (params); i++) {
3419                 if (sig->params [i]->byref) 
3420                         outarg_count++;
3421         }
3422
3423         out_args = mono_array_new_checked (domain, mono_defaults.object_class, outarg_count, &error);
3424         if (mono_error_set_pending_exception (&error))
3425                 return NULL;
3426
3427         /* handle constructors only for objects already allocated */
3428         if (!strcmp (method->method->name, ".ctor"))
3429                 g_assert (this_arg);
3430
3431         /* This can be called only on MBR objects, so no need to unbox for valuetypes. */
3432         g_assert (!method->method->klass->valuetype);
3433         result = mono_runtime_invoke_array_checked (method->method, this_arg, params, &error);
3434         if (mono_error_set_pending_exception (&error))
3435                 return NULL;
3436
3437         for (i = 0, j = 0; i < mono_array_length (params); i++) {
3438                 if (sig->params [i]->byref) {
3439                         gpointer arg;
3440                         arg = mono_array_get (params, gpointer, i);
3441                         mono_array_setref (out_args, j, arg);
3442                         j++;
3443                 }
3444         }
3445
3446         mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
3447
3448         return result;
3449 }
3450 #endif
3451
3452 static guint64
3453 read_enum_value (const char *mem, int type)
3454 {
3455         switch (type) {
3456         case MONO_TYPE_BOOLEAN:
3457         case MONO_TYPE_U1:
3458                 return *(guint8*)mem;
3459         case MONO_TYPE_I1:
3460                 return *(gint8*)mem;
3461         case MONO_TYPE_CHAR:
3462         case MONO_TYPE_U2:
3463                 return read16 (mem);
3464         case MONO_TYPE_I2:
3465                 return (gint16) read16 (mem);
3466         case MONO_TYPE_U4:
3467                 return read32 (mem);
3468         case MONO_TYPE_I4:
3469                 return (gint32) read32 (mem);
3470         case MONO_TYPE_U8:
3471         case MONO_TYPE_I8:
3472                 return read64 (mem);
3473         default:
3474                 g_assert_not_reached ();
3475         }
3476         return 0;
3477 }
3478
3479 static void
3480 write_enum_value (char *mem, int type, guint64 value)
3481 {
3482         switch (type) {
3483         case MONO_TYPE_U1:
3484         case MONO_TYPE_I1: {
3485                 guint8 *p = (guint8*)mem;
3486                 *p = value;
3487                 break;
3488         }
3489         case MONO_TYPE_U2:
3490         case MONO_TYPE_I2:
3491         case MONO_TYPE_CHAR: {
3492                 guint16 *p = (guint16 *)mem;
3493                 *p = value;
3494                 break;
3495         }
3496         case MONO_TYPE_U4:
3497         case MONO_TYPE_I4: {
3498                 guint32 *p = (guint32 *)mem;
3499                 *p = value;
3500                 break;
3501         }
3502         case MONO_TYPE_U8:
3503         case MONO_TYPE_I8: {
3504                 guint64 *p = (guint64 *)mem;
3505                 *p = value;
3506                 break;
3507         }
3508         default:
3509                 g_assert_not_reached ();
3510         }
3511         return;
3512 }
3513
3514 ICALL_EXPORT MonoObject *
3515 ves_icall_System_Enum_ToObject (MonoReflectionType *enumType, guint64 value)
3516 {
3517         MonoError error;
3518         MonoDomain *domain; 
3519         MonoClass *enumc;
3520         MonoObject *res;
3521         MonoType *etype;
3522
3523         domain = mono_object_domain (enumType); 
3524         enumc = mono_class_from_mono_type (enumType->type);
3525
3526         mono_class_init_checked (enumc, &error);
3527         if (mono_error_set_pending_exception (&error))
3528                 return NULL;
3529
3530         etype = mono_class_enum_basetype (enumc);
3531
3532         res = mono_object_new_checked (domain, enumc, &error);
3533         if (mono_error_set_pending_exception (&error))
3534                 return NULL;
3535         write_enum_value ((char *)res + sizeof (MonoObject), etype->type, value);
3536
3537         return res;
3538 }
3539
3540 ICALL_EXPORT MonoBoolean
3541 ves_icall_System_Enum_InternalHasFlag (MonoObject *a, MonoObject *b)
3542 {
3543         int size = mono_class_value_size (a->vtable->klass, NULL);
3544         guint64 a_val = 0, b_val = 0;
3545
3546         memcpy (&a_val, mono_object_unbox (a), size);
3547         memcpy (&b_val, mono_object_unbox (b), size);
3548
3549         return (a_val & b_val) == b_val;
3550 }
3551
3552 ICALL_EXPORT MonoObject *
3553 ves_icall_System_Enum_get_value (MonoObject *eobj)
3554 {
3555         MonoError error;
3556         MonoObject *res;
3557         MonoClass *enumc;
3558         gpointer dst;
3559         gpointer src;
3560         int size;
3561
3562         if (!eobj)
3563                 return NULL;
3564
3565         g_assert (eobj->vtable->klass->enumtype);
3566         
3567         enumc = mono_class_from_mono_type (mono_class_enum_basetype (eobj->vtable->klass));
3568         res = mono_object_new_checked (mono_object_domain (eobj), enumc, &error);
3569         if (mono_error_set_pending_exception (&error))
3570                 return NULL;
3571         dst = (char *)res + sizeof (MonoObject);
3572         src = (char *)eobj + sizeof (MonoObject);
3573         size = mono_class_value_size (enumc, NULL);
3574
3575         memcpy (dst, src, size);
3576
3577         return res;
3578 }
3579
3580 ICALL_EXPORT MonoReflectionType *
3581 ves_icall_System_Enum_get_underlying_type (MonoReflectionType *type)
3582 {
3583         MonoError error;
3584         MonoReflectionType *ret;
3585         MonoType *etype;
3586         MonoClass *klass;
3587
3588         klass = mono_class_from_mono_type (type->type);
3589         mono_class_init_checked (klass, &error);
3590         if (mono_error_set_pending_exception (&error))
3591                 return NULL;
3592
3593         etype = mono_class_enum_basetype (klass);
3594         if (!etype) {
3595                 mono_set_pending_exception (mono_get_exception_argument ("enumType", "Type provided must be an Enum."));
3596                 return NULL;
3597         }
3598
3599         ret = mono_type_get_object_checked (mono_object_domain (type), etype, &error);
3600         mono_error_set_pending_exception (&error);
3601
3602         return ret;
3603 }
3604
3605 ICALL_EXPORT int
3606 ves_icall_System_Enum_compare_value_to (MonoObject *eobj, MonoObject *other)
3607 {
3608         gpointer tdata = (char *)eobj + sizeof (MonoObject);
3609         gpointer odata = (char *)other + sizeof (MonoObject);
3610         MonoType *basetype = mono_class_enum_basetype (eobj->vtable->klass);
3611         g_assert (basetype);
3612
3613         if (other == NULL)
3614                 return 1;
3615
3616         if (eobj->vtable->klass != other->vtable->klass)
3617                 return 2;
3618
3619 #define COMPARE_ENUM_VALUES(ENUM_TYPE) do { \
3620                 ENUM_TYPE me = *((ENUM_TYPE*)tdata); \
3621                 ENUM_TYPE other = *((ENUM_TYPE*)odata); \
3622                 if (me == other) \
3623                         return 0; \
3624                 return me > other ? 1 : -1; \
3625         } while (0)
3626
3627         switch (basetype->type) {
3628                 case MONO_TYPE_U1:
3629                         COMPARE_ENUM_VALUES (guint8);
3630                 case MONO_TYPE_I1:
3631                         COMPARE_ENUM_VALUES (gint8);
3632                 case MONO_TYPE_CHAR:
3633                 case MONO_TYPE_U2:
3634                         COMPARE_ENUM_VALUES (guint16);
3635                 case MONO_TYPE_I2:
3636                         COMPARE_ENUM_VALUES (gint16);
3637                 case MONO_TYPE_U4:
3638                         COMPARE_ENUM_VALUES (guint32);
3639                 case MONO_TYPE_I4:
3640                         COMPARE_ENUM_VALUES (gint32);
3641                 case MONO_TYPE_U8:
3642                         COMPARE_ENUM_VALUES (guint64);
3643                 case MONO_TYPE_I8:
3644                         COMPARE_ENUM_VALUES (gint64);
3645                 default:
3646                         break;
3647         }
3648 #undef COMPARE_ENUM_VALUES
3649         /* indicates that the enum was of an unsupported unerlying type */
3650         return 3;
3651 }
3652
3653 ICALL_EXPORT int
3654 ves_icall_System_Enum_get_hashcode (MonoObject *eobj)
3655 {
3656         gpointer data = (char *)eobj + sizeof (MonoObject);
3657         MonoType *basetype = mono_class_enum_basetype (eobj->vtable->klass);
3658         g_assert (basetype);
3659
3660         switch (basetype->type) {
3661                 case MONO_TYPE_I1:       {
3662                         gint8 value = *((gint8*)data);
3663                         return ((int)value ^ (int)value << 8);
3664                 }
3665                 case MONO_TYPE_U1:
3666                         return *((guint8*)data);
3667                 case MONO_TYPE_CHAR:
3668                 case MONO_TYPE_U2:
3669                         return *((guint16*)data);
3670                 
3671                 case MONO_TYPE_I2: {
3672                         gint16 value = *((gint16*)data);
3673                         return ((int)(guint16)value | (((int)value) << 16));
3674                 }
3675                 case MONO_TYPE_U4:
3676                         return *((guint32*)data);
3677                 case MONO_TYPE_I4:
3678                         return *((gint32*)data);
3679                 case MONO_TYPE_U8:
3680                 case MONO_TYPE_I8: {
3681                         gint64 value = *((gint64*)data);
3682                         return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
3683                 }
3684                 default:
3685                         g_error ("Implement type 0x%02x in get_hashcode", basetype->type);
3686         }
3687         return 0;
3688 }
3689
3690 static void
3691 get_enum_field (MonoDomain *domain, MonoArrayHandle names, MonoArrayHandle values, int base_type, MonoClassField *field, guint* j, guint64 *previous_value, gboolean *sorted, MonoError *error)
3692 {
3693         error_init (error);
3694         HANDLE_FUNCTION_ENTER();
3695         guint64 field_value;
3696         const char *p;
3697         MonoTypeEnum def_type;
3698
3699         if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3700                 goto leave;
3701         if (strcmp ("value__", mono_field_get_name (field)) == 0)
3702                 goto leave;
3703         if (mono_field_is_deleted (field))
3704                 goto leave;
3705         MonoStringHandle name = mono_string_new_handle (domain, mono_field_get_name (field), error);
3706         if (!is_ok (error))
3707                 goto leave;
3708         MONO_HANDLE_ARRAY_SETREF (names, *j, name);
3709
3710         p = mono_class_get_field_default_value (field, &def_type);
3711         /* len = */ mono_metadata_decode_blob_size (p, &p);
3712
3713         field_value = read_enum_value (p, base_type);
3714         MONO_HANDLE_ARRAY_SETVAL (values, guint64, *j, field_value);
3715
3716         if (*previous_value > field_value)
3717                 *sorted = FALSE;
3718
3719         *previous_value = field_value;
3720         (*j)++;
3721 leave:
3722         HANDLE_FUNCTION_RETURN();
3723 }
3724
3725 ICALL_EXPORT MonoBoolean
3726 ves_icall_System_Enum_GetEnumValuesAndNames (MonoReflectionTypeHandle type, MonoArrayHandleOut values, MonoArrayHandleOut names, MonoError *error)
3727 {
3728         MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
3729         MonoClass *enumc = mono_class_from_mono_type (MONO_HANDLE_RAW(type)->type);
3730         guint j = 0, nvalues;
3731         gpointer iter;
3732         MonoClassField *field;
3733         int base_type;
3734         guint64 previous_value = 0;
3735         gboolean sorted = TRUE;
3736
3737         error_init (error);
3738         mono_class_init_checked (enumc, error);
3739         return_val_if_nok (error, FALSE);
3740
3741         if (!enumc->enumtype) {
3742                 mono_error_set_argument (error, "enumType", "Type provided must be an Enum.");
3743                 return TRUE;
3744         }
3745
3746         base_type = mono_class_enum_basetype (enumc)->type;
3747
3748         nvalues = mono_class_num_fields (enumc) > 0 ? mono_class_num_fields (enumc) - 1 : 0;
3749         MONO_HANDLE_ASSIGN(names, mono_array_new_handle (domain, mono_defaults.string_class, nvalues, error));
3750         return_val_if_nok (error, FALSE);
3751         MONO_HANDLE_ASSIGN(values, mono_array_new_handle (domain, mono_defaults.uint64_class, nvalues, error));
3752         return_val_if_nok (error, FALSE);
3753
3754         iter = NULL;
3755         while ((field = mono_class_get_fields (enumc, &iter))) {
3756                 get_enum_field(domain, names, values, base_type, field, &j, &previous_value, &sorted, error);
3757                 if (!is_ok (error))
3758                         break;
3759         }
3760         return_val_if_nok (error, FALSE);
3761
3762         return sorted;
3763 }
3764
3765 enum {
3766         BFLAGS_IgnoreCase = 1,
3767         BFLAGS_DeclaredOnly = 2,
3768         BFLAGS_Instance = 4,
3769         BFLAGS_Static = 8,
3770         BFLAGS_Public = 0x10,
3771         BFLAGS_NonPublic = 0x20,
3772         BFLAGS_FlattenHierarchy = 0x40,
3773         BFLAGS_InvokeMethod = 0x100,
3774         BFLAGS_CreateInstance = 0x200,
3775         BFLAGS_GetField = 0x400,
3776         BFLAGS_SetField = 0x800,
3777         BFLAGS_GetProperty = 0x1000,
3778         BFLAGS_SetProperty = 0x2000,
3779         BFLAGS_ExactBinding = 0x10000,
3780         BFLAGS_SuppressChangeType = 0x20000,
3781         BFLAGS_OptionalParamBinding = 0x40000
3782 };
3783
3784 ICALL_EXPORT GPtrArray*
3785 ves_icall_RuntimeType_GetFields_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 bflags, MonoError *error)
3786 {
3787         error_init (error);
3788         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3789
3790         if (type->byref) {
3791                 return g_ptr_array_new ();
3792         }
3793
3794         int (*compare_func) (const char *s1, const char *s2) = NULL;    
3795         compare_func = (bflags & BFLAGS_IgnoreCase) ? mono_utf8_strcasecmp : strcmp;
3796
3797         MonoClass *startklass, *klass;
3798         klass = startklass = mono_class_from_mono_type (type);
3799
3800         GPtrArray *ptr_array = g_ptr_array_sized_new (16);
3801         
3802 handle_parent:  
3803         if (mono_class_has_failure (klass)) {
3804                 mono_error_set_for_class_failure (error, klass);
3805                 goto fail;
3806         }
3807
3808         MonoClassField *field;
3809         gpointer iter = NULL;
3810         while ((field = mono_class_get_fields_lazy (klass, &iter))) {
3811                 guint32 flags = mono_field_get_flags (field);
3812                 int match = 0;
3813                 if (mono_field_is_deleted_with_flags (field, flags))
3814                         continue;
3815                 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
3816                         if (bflags & BFLAGS_Public)
3817                                 match++;
3818                 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
3819                         if (bflags & BFLAGS_NonPublic) {
3820                                 match++;
3821                         }
3822                 }
3823                 if (!match)
3824                         continue;
3825                 match = 0;
3826                 if (flags & FIELD_ATTRIBUTE_STATIC) {
3827                         if (bflags & BFLAGS_Static)
3828                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3829                                         match++;
3830                 } else {
3831                         if (bflags & BFLAGS_Instance)
3832                                 match++;
3833                 }
3834
3835                 if (!match)
3836                         continue;
3837
3838                 if (utf8_name != NULL && compare_func (mono_field_get_name (field), utf8_name))
3839                                 continue;
3840
3841                 g_ptr_array_add (ptr_array, field);
3842         }
3843         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3844                 goto handle_parent;
3845
3846         return ptr_array;
3847
3848 fail:
3849         g_ptr_array_free (ptr_array, TRUE);
3850         return NULL;
3851 }
3852
3853 static gboolean
3854 method_nonpublic (MonoMethod* method, gboolean start_klass)
3855 {
3856         switch (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) {
3857                 case METHOD_ATTRIBUTE_ASSEM:
3858                         return (start_klass || mono_defaults.generic_ilist_class);
3859                 case METHOD_ATTRIBUTE_PRIVATE:
3860                         return start_klass;
3861                 case METHOD_ATTRIBUTE_PUBLIC:
3862                         return FALSE;
3863                 default:
3864                         return TRUE;
3865         }
3866 }
3867
3868 GPtrArray*
3869 mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, gboolean ignore_case, gboolean allow_ctors, MonoError *error)
3870 {
3871         GPtrArray *array;
3872         MonoClass *startklass;
3873         MonoMethod *method;
3874         gpointer iter;
3875         int match, nslots;
3876         /*FIXME, use MonoBitSet*/
3877         guint32 method_slots_default [8];
3878         guint32 *method_slots = NULL;
3879         int (*compare_func) (const char *s1, const char *s2) = NULL;
3880
3881         array = g_ptr_array_new ();
3882         startklass = klass;
3883         error_init (error);
3884
3885         if (name != NULL)
3886                 compare_func = (ignore_case) ? mono_utf8_strcasecmp : strcmp;
3887
3888         /* An optimization for calls made from Delegate:CreateDelegate () */
3889         if (klass->delegate && name && !strcmp (name, "Invoke") && (bflags == (BFLAGS_Public | BFLAGS_Static | BFLAGS_Instance))) {
3890                 method = mono_get_delegate_invoke (klass);
3891                 g_assert (method);
3892
3893                 g_ptr_array_add (array, method);
3894                 return array;
3895         }
3896
3897         mono_class_setup_methods (klass);
3898         mono_class_setup_vtable (klass);
3899         if (mono_class_has_failure (klass))
3900                 goto loader_error;
3901
3902         if (is_generic_parameter (&klass->byval_arg))
3903                 nslots = mono_class_get_vtable_size (klass->parent);
3904         else
3905                 nslots = MONO_CLASS_IS_INTERFACE (klass) ? mono_class_num_methods (klass) : mono_class_get_vtable_size (klass);
3906         if (nslots >= sizeof (method_slots_default) * 8) {
3907                 method_slots = g_new0 (guint32, nslots / 32 + 1);
3908         } else {
3909                 method_slots = method_slots_default;
3910                 memset (method_slots, 0, sizeof (method_slots_default));
3911         }
3912 handle_parent:
3913         mono_class_setup_methods (klass);
3914         mono_class_setup_vtable (klass);
3915         if (mono_class_has_failure (klass))
3916                 goto loader_error;              
3917
3918         iter = NULL;
3919         while ((method = mono_class_get_methods (klass, &iter))) {
3920                 match = 0;
3921                 if (method->slot != -1) {
3922                         g_assert (method->slot < nslots);
3923                         if (method_slots [method->slot >> 5] & (1 << (method->slot & 0x1f)))
3924                                 continue;
3925                         if (!(method->flags & METHOD_ATTRIBUTE_NEW_SLOT))
3926                                 method_slots [method->slot >> 5] |= 1 << (method->slot & 0x1f);
3927                 }
3928
3929                 if (!allow_ctors && method->name [0] == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0))
3930                         continue;
3931                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3932                         if (bflags & BFLAGS_Public)
3933                                 match++;
3934                 } else if ((bflags & BFLAGS_NonPublic) && method_nonpublic (method, (klass == startklass))) {
3935                                 match++;
3936                 }
3937                 if (!match)
3938                         continue;
3939                 match = 0;
3940                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3941                         if (bflags & BFLAGS_Static)
3942                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3943                                         match++;
3944                 } else {
3945                         if (bflags & BFLAGS_Instance)
3946                                 match++;
3947                 }
3948
3949                 if (!match)
3950                         continue;
3951
3952                 if (name != NULL) {
3953                         if (compare_func (name, method->name))
3954                                 continue;
3955                 }
3956                 
3957                 match = 0;
3958                 g_ptr_array_add (array, method);
3959         }
3960         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3961                 goto handle_parent;
3962         if (method_slots != method_slots_default)
3963                 g_free (method_slots);
3964
3965         return array;
3966
3967 loader_error:
3968         if (method_slots != method_slots_default)
3969                 g_free (method_slots);
3970         g_ptr_array_free (array, TRUE);
3971
3972         g_assert (mono_class_has_failure (klass));
3973         mono_error_set_for_class_failure (error, klass);
3974         return NULL;
3975 }
3976
3977 ICALL_EXPORT GPtrArray*
3978 ves_icall_RuntimeType_GetMethodsByName_native (MonoReflectionTypeHandle ref_type, const char *mname, guint32 bflags, MonoBoolean ignore_case, MonoError *error)
3979 {
3980         error_init (error);
3981         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3982
3983         MonoClass *klass = mono_class_from_mono_type (type);
3984         if (type->byref) {
3985                 return g_ptr_array_new ();
3986         }
3987
3988         return mono_class_get_methods_by_name (klass, mname, bflags, ignore_case, FALSE, error);
3989 }
3990
3991 ICALL_EXPORT GPtrArray*
3992 ves_icall_RuntimeType_GetConstructors_native (MonoReflectionTypeHandle ref_type, guint32 bflags, MonoError *error)
3993 {
3994         error_init (error);
3995         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
3996         if (type->byref) {
3997                 return g_ptr_array_new ();
3998         }
3999
4000         MonoClass *startklass, *klass;
4001         klass = startklass = mono_class_from_mono_type (type);
4002
4003         mono_class_setup_methods (klass);
4004         if (mono_class_has_failure (klass)) {
4005                 mono_error_set_for_class_failure (error, klass);
4006                 return NULL;
4007         }
4008         
4009
4010         GPtrArray *res_array = g_ptr_array_sized_new (4); /* FIXME, guestimating */
4011
4012         MonoMethod *method;
4013         gpointer iter = NULL;
4014         while ((method = mono_class_get_methods (klass, &iter))) {
4015                 int match = 0;
4016                 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
4017                         continue;
4018                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4019                         if (bflags & BFLAGS_Public)
4020                                 match++;
4021                 } else {
4022                         if (bflags & BFLAGS_NonPublic)
4023                                 match++;
4024                 }
4025                 if (!match)
4026                         continue;
4027                 match = 0;
4028                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4029                         if (bflags & BFLAGS_Static)
4030                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4031                                         match++;
4032                 } else {
4033                         if (bflags & BFLAGS_Instance)
4034                                 match++;
4035                 }
4036
4037                 if (!match)
4038                         continue;
4039                 g_ptr_array_add (res_array, method);
4040         }
4041
4042         return res_array;
4043 }
4044
4045 static guint
4046 property_hash (gconstpointer data)
4047 {
4048         MonoProperty *prop = (MonoProperty*)data;
4049
4050         return g_str_hash (prop->name);
4051 }
4052
4053 static gboolean
4054 property_accessor_override (MonoMethod *method1, MonoMethod *method2)
4055 {
4056         if (method1->slot != -1 && method1->slot == method2->slot)
4057                 return TRUE;
4058
4059         if (mono_class_get_generic_type_definition (method1->klass) == mono_class_get_generic_type_definition (method2->klass)) {
4060                 if (method1->is_inflated)
4061                         method1 = ((MonoMethodInflated*) method1)->declaring;
4062                 if (method2->is_inflated)
4063                         method2 = ((MonoMethodInflated*) method2)->declaring;
4064         }
4065
4066         return mono_metadata_signature_equal (mono_method_signature (method1), mono_method_signature (method2));
4067 }
4068
4069 static gboolean
4070 property_equal (MonoProperty *prop1, MonoProperty *prop2)
4071 {
4072         // Properties are hide-by-name-and-signature
4073         if (!g_str_equal (prop1->name, prop2->name))
4074                 return FALSE;
4075
4076         /* If we see a property in a generic method, we want to
4077            compare the generic signatures, not the inflated signatures
4078            because we might conflate two properties that were
4079            distinct:
4080
4081            class Foo<T,U> {
4082              public T this[T t] { getter { return t; } } // method 1
4083              public U this[U u] { getter { return u; } } // method 2
4084            }
4085
4086            If we see int Foo<int,int>::Item[int] we need to know if
4087            the indexer came from method 1 or from method 2, and we
4088            shouldn't conflate them.   (Bugzilla 36283)
4089         */
4090         if (prop1->get && prop2->get && !property_accessor_override (prop1->get, prop2->get))
4091                 return FALSE;
4092
4093         if (prop1->set && prop2->set && !property_accessor_override (prop1->set, prop2->set))
4094                 return FALSE;
4095
4096         return TRUE;
4097 }
4098
4099 static gboolean
4100 property_accessor_nonpublic (MonoMethod* accessor, gboolean start_klass)
4101 {
4102         if (!accessor)
4103                 return FALSE;
4104
4105         return method_nonpublic (accessor, start_klass);
4106 }
4107
4108 ICALL_EXPORT GPtrArray*
4109 ves_icall_RuntimeType_GetPropertiesByName_native (MonoReflectionTypeHandle ref_type, gchar *propname, guint32 bflags, MonoBoolean ignore_case, MonoError *error)
4110 {
4111         error_init (error);
4112         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4113
4114
4115         if (type->byref) {
4116                 return g_ptr_array_new ();
4117         }
4118
4119         
4120         MonoClass *startklass, *klass;
4121         klass = startklass = mono_class_from_mono_type (type);
4122
4123         int (*compare_func) (const char *s1, const char *s2) = (ignore_case) ? mono_utf8_strcasecmp : strcmp;
4124
4125         GPtrArray *res_array = g_ptr_array_sized_new (8); /*This the average for ASP.NET types*/
4126
4127         GHashTable *properties = g_hash_table_new (property_hash, (GEqualFunc)property_equal);
4128
4129 handle_parent:
4130         mono_class_setup_methods (klass);
4131         mono_class_setup_vtable (klass);
4132         if (mono_class_has_failure (klass)) {
4133                 mono_error_set_for_class_failure (error, klass);
4134                 goto loader_error;
4135         }
4136
4137         MonoProperty *prop;
4138         gpointer iter = NULL;
4139         while ((prop = mono_class_get_properties (klass, &iter))) {
4140                 int match = 0;
4141                 MonoMethod *method = prop->get;
4142                 if (!method)
4143                         method = prop->set;
4144                 guint32 flags = 0;
4145                 if (method)
4146                         flags = method->flags;
4147                 if ((prop->get && ((prop->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)) ||
4148                         (prop->set && ((prop->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC))) {
4149                         if (bflags & BFLAGS_Public)
4150                                 match++;
4151                 } else if (bflags & BFLAGS_NonPublic) {
4152                         if (property_accessor_nonpublic(prop->get, startklass == klass) ||
4153                                 property_accessor_nonpublic(prop->set, startklass == klass)) {
4154                                 match++;
4155                         }
4156                 }
4157                 if (!match)
4158                         continue;
4159                 match = 0;
4160                 if (flags & METHOD_ATTRIBUTE_STATIC) {
4161                         if (bflags & BFLAGS_Static)
4162                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4163                                         match++;
4164                 } else {
4165                         if (bflags & BFLAGS_Instance)
4166                                 match++;
4167                 }
4168
4169                 if (!match)
4170                         continue;
4171                 match = 0;
4172
4173                 if (propname != NULL && compare_func (propname, prop->name))
4174                         continue;
4175                 
4176                 if (g_hash_table_lookup (properties, prop))
4177                         continue;
4178
4179                 g_ptr_array_add (res_array, prop);
4180                 
4181                 g_hash_table_insert (properties, prop, prop);
4182         }
4183         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
4184                 goto handle_parent;
4185
4186         g_hash_table_destroy (properties);
4187
4188         return res_array;
4189
4190
4191 loader_error:
4192         if (properties)
4193                 g_hash_table_destroy (properties);
4194         g_ptr_array_free (res_array, TRUE);
4195
4196         return NULL;
4197 }
4198
4199 static guint
4200 event_hash (gconstpointer data)
4201 {
4202         MonoEvent *event = (MonoEvent*)data;
4203
4204         return g_str_hash (event->name);
4205 }
4206
4207 static gboolean
4208 event_equal (MonoEvent *event1, MonoEvent *event2)
4209 {
4210         // Events are hide-by-name
4211         return g_str_equal (event1->name, event2->name);
4212 }
4213
4214 ICALL_EXPORT GPtrArray*
4215 ves_icall_RuntimeType_GetEvents_native (MonoReflectionTypeHandle ref_type, char *utf8_name, guint32 bflags, MonoError *error)
4216 {
4217         error_init (error);
4218         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4219
4220         if (type->byref) {
4221                 return g_ptr_array_new ();
4222         }
4223
4224         int (*compare_func) (const char *s1, const char *s2) = (bflags & BFLAGS_IgnoreCase) ? mono_utf8_strcasecmp : strcmp;
4225
4226         GPtrArray *res_array = g_ptr_array_sized_new (4);
4227
4228         MonoClass *startklass, *klass;
4229         klass = startklass = mono_class_from_mono_type (type);
4230
4231         GHashTable *events = g_hash_table_new (event_hash, (GEqualFunc)event_equal);
4232 handle_parent:
4233         mono_class_setup_methods (klass);
4234         mono_class_setup_vtable (klass);
4235         if (mono_class_has_failure (klass)) {
4236                 mono_error_set_for_class_failure (error, klass);
4237                 goto failure;
4238         }
4239
4240         MonoEvent *event;
4241         gpointer iter = NULL;
4242         while ((event = mono_class_get_events (klass, &iter))) {
4243                 int match = 0;
4244                 MonoMethod *method = event->add;
4245                 if (!method)
4246                         method = event->remove;
4247                 if (!method)
4248                         method = event->raise;
4249                 if (method) {
4250                         if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
4251                                 if (bflags & BFLAGS_Public)
4252                                         match++;
4253                         } else if ((klass == startklass) || (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) {
4254                                 if (bflags & BFLAGS_NonPublic)
4255                                         match++;
4256                         }
4257                 }
4258                 else
4259                         if (bflags & BFLAGS_NonPublic)
4260                                 match ++;
4261                 if (!match)
4262                         continue;
4263                 match = 0;
4264                 if (method) {
4265                         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4266                                 if (bflags & BFLAGS_Static)
4267                                         if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
4268                                                 match++;
4269                         } else {
4270                                 if (bflags & BFLAGS_Instance)
4271                                         match++;
4272                         }
4273                 }
4274                 else
4275                         if (bflags & BFLAGS_Instance)
4276                                 match ++;
4277                 if (!match)
4278                         continue;
4279
4280                 if (utf8_name != NULL && compare_func (event->name, utf8_name))
4281                         continue;
4282
4283                 if (g_hash_table_lookup (events, event))
4284                         continue;
4285
4286                 g_ptr_array_add (res_array, event); 
4287
4288                 g_hash_table_insert (events, event, event);
4289         }
4290         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
4291                 goto handle_parent;
4292
4293         g_hash_table_destroy (events);
4294
4295         return res_array;
4296
4297 failure:
4298         if (events != NULL)
4299                 g_hash_table_destroy (events);
4300
4301         g_ptr_array_free (res_array, TRUE);
4302
4303         return NULL;
4304 }
4305
4306 ICALL_EXPORT GPtrArray *
4307 ves_icall_RuntimeType_GetNestedTypes_native (MonoReflectionTypeHandle ref_type, char *str, guint32 bflags, MonoError *error)
4308 {
4309         error_init (error);
4310         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
4311
4312         if (type->byref) {
4313                 return g_ptr_array_new ();
4314         }
4315
4316         MonoClass *klass = mono_class_from_mono_type (type);
4317
4318         /*
4319          * If a nested type is generic, return its generic type definition.
4320          * Note that this means that the return value is essentially the set
4321          * of nested types of the generic type definition of @klass.
4322          *
4323          * A note in MSDN claims that a generic type definition can have
4324          * nested types that aren't generic.  In any case, the container of that
4325          * nested type would be the generic type definition.
4326          */
4327         if (mono_class_is_ginst (klass))
4328                 klass = mono_class_get_generic_class (klass)->container_class;
4329
4330         GPtrArray *res_array = g_ptr_array_new ();
4331         
4332         MonoClass *nested;
4333         gpointer iter = NULL;
4334         while ((nested = mono_class_get_nested_types (klass, &iter))) {
4335                 int match = 0;
4336                 if ((mono_class_get_flags (nested) & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
4337                         if (bflags & BFLAGS_Public)
4338                                 match++;
4339                 } else {
4340                         if (bflags & BFLAGS_NonPublic)
4341                                 match++;
4342                 }
4343                 if (!match)
4344                         continue;
4345
4346                 if (str != NULL && strcmp (nested->name, str))
4347                                 continue;
4348
4349                 g_ptr_array_add (res_array, &nested->byval_arg);
4350         }
4351
4352         return res_array;
4353 }
4354
4355 static MonoType*
4356 get_type_from_module_builder_module (MonoArrayHandle modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
4357 {
4358         HANDLE_FUNCTION_ENTER ();
4359         error_init (error);
4360         MonoType *type = NULL;
4361         MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW (MonoReflectionModuleBuilder, NULL);
4362         MONO_HANDLE_ARRAY_GETREF (mb, modules, i);
4363         MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
4364         type = mono_reflection_get_type_checked (&dynamic_image->image, &dynamic_image->image, info, ignoreCase, type_resolve, error);
4365         HANDLE_FUNCTION_RETURN_VAL (type);
4366 }
4367
4368 static MonoType*
4369 get_type_from_module_builder_loaded_modules (MonoArrayHandle loaded_modules, int i, MonoTypeNameParse *info, MonoBoolean ignoreCase, gboolean *type_resolve, MonoError *error)
4370 {
4371         HANDLE_FUNCTION_ENTER ();
4372         error_init (error);
4373         MonoType *type = NULL;
4374         MonoReflectionModuleHandle mod = MONO_HANDLE_NEW (MonoReflectionModule, NULL);
4375         MONO_HANDLE_ARRAY_GETREF (mod, loaded_modules, i);
4376         MonoImage *image = MONO_HANDLE_GETVAL (mod, image);
4377         type = mono_reflection_get_type_checked (image, image, info, ignoreCase, type_resolve, error);
4378         HANDLE_FUNCTION_RETURN_VAL (type);
4379 }
4380
4381 ICALL_EXPORT MonoReflectionTypeHandle
4382 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssemblyHandle assembly_h, MonoReflectionModuleHandle module, MonoStringHandle name, MonoBoolean throwOnError, MonoBoolean ignoreCase, MonoError *error)
4383 {
4384         error_init (error);
4385
4386         MonoTypeNameParse info;
4387         gboolean type_resolve;
4388
4389         /* On MS.NET, this does not fire a TypeResolve event */
4390         type_resolve = TRUE;
4391         char *str = mono_string_handle_to_utf8 (name, error);
4392         if (!is_ok (error))
4393                 goto fail;
4394
4395         /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
4396         if (!mono_reflection_parse_type (str, &info)) {
4397                 g_free (str);
4398                 mono_reflection_free_type_info (&info);
4399                 if (throwOnError) {
4400                         mono_error_set_argument (error, "name", "failed to parse the type");
4401                         goto fail;
4402                 }
4403                 /*g_print ("failed parse\n");*/
4404                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4405         }
4406
4407         if (info.assembly.name) {
4408                 g_free (str);
4409                 mono_reflection_free_type_info (&info);
4410                 if (throwOnError) {
4411                         /* 1.0 and 2.0 throw different exceptions */
4412                         if (mono_defaults.generic_ilist_class)
4413                                 mono_error_set_argument (error, NULL, "Type names passed to Assembly.GetType() must not specify an assembly.");
4414                         else
4415                                 mono_error_set_type_load_name (error, g_strdup (""), g_strdup (""), "Type names passed to Assembly.GetType() must not specify an assembly.");
4416                         goto fail;
4417                 }
4418                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4419         }
4420
4421         MonoType *type = NULL;
4422         if (!MONO_HANDLE_IS_NULL (module)) {
4423                 MonoImage *image = MONO_HANDLE_GETVAL (module, image);
4424                 if (image) {
4425                         type = mono_reflection_get_type_checked (image, image, &info, ignoreCase, &type_resolve, error);
4426                         if (!is_ok (error)) {
4427                                 g_free (str);
4428                                 mono_reflection_free_type_info (&info);
4429                                 goto fail;
4430                         }
4431                 }
4432         }
4433         else {
4434                 MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4435                 if (assembly_is_dynamic (assembly)) {
4436                         /* Enumerate all modules */
4437                         MonoReflectionAssemblyBuilderHandle abuilder = MONO_HANDLE_NEW (MonoReflectionAssemblyBuilder, NULL);
4438                         MONO_HANDLE_ASSIGN (abuilder, assembly_h);
4439                         int i;
4440
4441                         MonoArrayHandle modules = MONO_HANDLE_NEW (MonoArray, NULL);
4442                         MONO_HANDLE_GET (modules, abuilder, modules);
4443                         if (!MONO_HANDLE_IS_NULL (modules)) {
4444                                 int n = mono_array_handle_length (modules);
4445                                 for (i = 0; i < n; ++i) {
4446                                         type = get_type_from_module_builder_module (modules, i, &info, ignoreCase, &type_resolve, error);
4447                                         if (!is_ok (error)) {
4448                                                 g_free (str);
4449                                                 mono_reflection_free_type_info (&info);
4450                                                 goto fail;
4451                                         }
4452                                         if (type)
4453                                                 break;
4454                                 }
4455                         }
4456
4457                         MonoArrayHandle loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL);
4458                         MONO_HANDLE_GET (loaded_modules, abuilder, loaded_modules);
4459                         if (!type && !MONO_HANDLE_IS_NULL (loaded_modules)) {
4460                                 int n = mono_array_handle_length (loaded_modules);
4461                                 for (i = 0; i < n; ++i) {
4462                                         type = get_type_from_module_builder_loaded_modules (loaded_modules, i, &info, ignoreCase, &type_resolve, error);
4463
4464                                         if (!is_ok (error)) {
4465                                                 g_free (str);
4466                                                 mono_reflection_free_type_info (&info);
4467                                                 goto fail;
4468                                         }
4469                                         if (type)
4470                                                 break;
4471                                 }
4472                         }
4473                 }
4474                 else {
4475                         type = mono_reflection_get_type_checked (assembly->image, assembly->image, &info, ignoreCase, &type_resolve, error);
4476                         if (!is_ok (error)) {
4477                                 g_free (str);
4478                                 mono_reflection_free_type_info (&info);
4479                                 goto fail;
4480                         }
4481                 }
4482         }
4483         g_free (str);
4484         mono_reflection_free_type_info (&info);
4485
4486         if (!type) {
4487                 if (throwOnError) {
4488                         MonoError inner_error;
4489                         char *typename = mono_string_handle_to_utf8 (name, &inner_error);
4490                         mono_error_assert_ok (&inner_error);
4491                         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4492                         char *assmname = mono_stringify_assembly_name (&assembly->aname);
4493                         mono_error_set_type_load_name (error, typename, assmname, "%s", "");
4494                         goto fail;
4495                 }
4496
4497                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4498         }
4499
4500         if (type->type == MONO_TYPE_CLASS) {
4501                 MonoClass *klass = mono_type_get_class (type);
4502
4503                 /* need to report exceptions ? */
4504                 if (throwOnError && mono_class_has_failure (klass)) {
4505                         /* report SecurityException (or others) that occured when loading the assembly */
4506                         mono_error_set_for_class_failure (error, klass);
4507                         goto fail;
4508                 }
4509         }
4510
4511         /* g_print ("got it\n"); */
4512         return mono_type_get_object_handle (MONO_HANDLE_DOMAIN (assembly_h), type, error);
4513 fail:
4514         g_assert (!is_ok (error));
4515         return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
4516 }
4517
4518 static gboolean
4519 replace_shadow_path (MonoDomain *domain, gchar *dirname, gchar **filename)
4520 {
4521         gchar *content;
4522         gchar *shadow_ini_file;
4523         gsize len;
4524
4525         /* Check for shadow-copied assembly */
4526         if (mono_is_shadow_copy_enabled (domain, dirname)) {
4527                 shadow_ini_file = g_build_filename (dirname, "__AssemblyInfo__.ini", NULL);
4528                 content = NULL;
4529                 if (!g_file_get_contents (shadow_ini_file, &content, &len, NULL) ||
4530                         !g_file_test (content, G_FILE_TEST_IS_REGULAR)) {
4531                         if (content) {
4532                                 g_free (content);
4533                                 content = NULL;
4534                         }
4535                 }
4536                 g_free (shadow_ini_file);
4537                 if (content != NULL) {
4538                         if (*filename)
4539                                 g_free (*filename);
4540                         *filename = content;
4541                         return TRUE;
4542                 }
4543         }
4544         return FALSE;
4545 }
4546
4547 ICALL_EXPORT MonoStringHandle
4548 ves_icall_System_Reflection_Assembly_get_code_base (MonoReflectionAssemblyHandle assembly, MonoBoolean escaped, MonoError *error)
4549 {
4550         error_init (error);
4551         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
4552         MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
4553         gchar *absolute;
4554         gchar *dirname;
4555         
4556         if (g_path_is_absolute (mass->image->name)) {
4557                 absolute = g_strdup (mass->image->name);
4558                 dirname = g_path_get_dirname (absolute);
4559         } else {
4560                 absolute = g_build_filename (mass->basedir, mass->image->name, NULL);
4561                 dirname = g_strdup (mass->basedir);
4562         }
4563
4564         replace_shadow_path (domain, dirname, &absolute);
4565         g_free (dirname);
4566
4567         mono_icall_make_platform_path (absolute);
4568
4569         gchar *uri;
4570         if (escaped) {
4571                 uri = g_filename_to_uri (absolute, NULL, NULL);
4572         } else {
4573                 const gchar *prepend = mono_icall_get_file_path_prefix (absolute);
4574                 uri = g_strconcat (prepend, absolute, NULL);
4575         }
4576
4577         g_free (absolute);
4578
4579         MonoStringHandle res;
4580         if (uri) {
4581                 res = mono_string_new_handle (domain, uri, error);
4582                 g_free (uri);
4583         } else {
4584                 res = MONO_HANDLE_NEW (MonoString, NULL);
4585         }
4586         return res;
4587 }
4588
4589 ICALL_EXPORT MonoBoolean
4590 ves_icall_System_Reflection_Assembly_get_global_assembly_cache (MonoReflectionAssemblyHandle assembly, MonoError *error)
4591 {
4592         error_init (error);
4593         MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly,assembly);
4594
4595         return mass->in_gac;
4596 }
4597
4598 ICALL_EXPORT MonoReflectionAssemblyHandle
4599 ves_icall_System_Reflection_Assembly_load_with_partial_name (MonoStringHandle mname, MonoObjectHandle evidence, MonoError *error)
4600 {
4601         gchar *name;
4602         MonoImageOpenStatus status;
4603         MonoReflectionAssemblyHandle result = MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
4604         
4605         name = mono_string_handle_to_utf8 (mname, error);
4606         if (!is_ok (error))
4607                 goto leave;
4608         MonoAssembly *res = mono_assembly_load_with_partial_name (name, &status);
4609
4610         g_free (name);
4611
4612         if (res == NULL)
4613                 goto leave;
4614         result = mono_assembly_get_object_handle (mono_domain_get (), res, error);
4615 leave:
4616         return result;
4617 }
4618
4619 ICALL_EXPORT MonoStringHandle
4620 ves_icall_System_Reflection_Assembly_get_location (MonoReflectionAssemblyHandle refassembly, MonoError *error)
4621 {
4622         MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
4623         MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
4624         return mono_string_new_handle (domain, mono_image_get_filename (assembly->image), error);
4625 }
4626
4627 ICALL_EXPORT MonoBoolean
4628 ves_icall_System_Reflection_Assembly_get_ReflectionOnly (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
4629 {
4630         error_init (error);
4631         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4632         return assembly->ref_only;
4633 }
4634
4635 ICALL_EXPORT MonoStringHandle
4636 ves_icall_System_Reflection_Assembly_InternalImageRuntimeVersion (MonoReflectionAssemblyHandle refassembly, MonoError *error)
4637 {
4638         MonoDomain *domain = MONO_HANDLE_DOMAIN (refassembly);
4639         MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly);
4640
4641         return mono_string_new_handle (domain, assembly->image->version, error);
4642 }
4643
4644 ICALL_EXPORT MonoReflectionMethodHandle
4645 ves_icall_System_Reflection_Assembly_get_EntryPoint (MonoReflectionAssemblyHandle assembly_h, MonoError *error) 
4646 {
4647         error_init (error);
4648         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4649         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4650         MonoMethod *method;
4651
4652         MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
4653         guint32 token = mono_image_get_entry_point (assembly->image);
4654
4655         if (!token)
4656                 goto leave;
4657         method = mono_get_method_checked (assembly->image, token, NULL, NULL, error);
4658         if (!is_ok (error))
4659                 goto leave;
4660
4661         MONO_HANDLE_ASSIGN (res, mono_method_get_object_handle (domain, method, NULL, error));
4662 leave:
4663         return res;
4664 }
4665
4666 ICALL_EXPORT MonoReflectionModuleHandle
4667 ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAssemblyHandle assembly, MonoError *error) 
4668 {
4669         error_init (error);
4670         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
4671         MonoAssembly *a = MONO_HANDLE_GETVAL (assembly, assembly);
4672         return mono_module_get_object_handle (domain, a->image, error);
4673 }
4674
4675 static gboolean
4676 add_manifest_resource_name_to_array (MonoDomain *domain, MonoImage *image, MonoTableInfo *table, int i, MonoArrayHandle dest, MonoError *error)
4677 {
4678         HANDLE_FUNCTION_ENTER ();
4679         error_init (error);
4680         const char *val = mono_metadata_string_heap (image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
4681         MonoStringHandle str = mono_string_new_handle (domain, val, error);
4682         if (!is_ok (error))
4683                 goto leave;
4684         MONO_HANDLE_ARRAY_SETREF (dest, i, str);
4685 leave:
4686         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
4687 }
4688
4689 ICALL_EXPORT MonoArrayHandle
4690 ves_icall_System_Reflection_Assembly_GetManifestResourceNames (MonoReflectionAssemblyHandle assembly_h, MonoError *error) 
4691 {
4692         error_init (error);
4693         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4694         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4695         MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4696         MonoArrayHandle result = mono_array_new_handle (domain, mono_defaults.string_class, table->rows, error);
4697         if (!is_ok (error))
4698                 goto fail;
4699         int i;
4700
4701         for (i = 0; i < table->rows; ++i) {
4702                 if (!add_manifest_resource_name_to_array (domain, assembly->image, table, i, result, error))
4703                         goto fail;
4704         }
4705         return result;
4706 fail:
4707         return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
4708 }
4709
4710 ICALL_EXPORT MonoStringHandle
4711 ves_icall_System_Reflection_Assembly_GetAotId (MonoError *error)
4712 {
4713         char *guid = mono_runtime_get_aotid ();
4714         if (guid == NULL)
4715                 return NULL;
4716         MonoStringHandle res = mono_string_new_handle (mono_domain_get (), guid, error);
4717         g_free (guid);
4718         return res;
4719 }
4720
4721 static MonoAssemblyName*
4722 create_referenced_assembly_name (MonoDomain *domain, MonoImage *image, MonoTableInfo *t, int i, MonoError *error)
4723 {
4724         error_init (error);
4725         MonoAssemblyName *aname = g_new0 (MonoAssemblyName, 1);
4726
4727         mono_assembly_get_assemblyref (image, i, aname);
4728         aname->hash_alg = ASSEMBLY_HASH_SHA1 /* SHA1 (default) */;
4729         /* name and culture are pointers into the image tables, but we need
4730          * real malloc'd strings (so that we can g_free() them later from
4731          * Mono.RuntimeMarshal.FreeAssemblyName) */
4732         aname->name = g_strdup (aname->name);
4733         aname->culture = g_strdup  (aname->culture);
4734         /* Don't need the hash value in managed */
4735         aname->hash_value = NULL;
4736         aname->hash_len = 0;
4737         g_assert (aname->public_key == NULL);
4738                 
4739         /* note: this function doesn't return the codebase on purpose (i.e. it can
4740            be used under partial trust as path information isn't present). */
4741         return aname;
4742 }
4743
4744 ICALL_EXPORT GPtrArray*
4745 ves_icall_System_Reflection_Assembly_InternalGetReferencedAssemblies (MonoReflectionAssemblyHandle assembly, MonoError *error) 
4746 {
4747         error_init (error);
4748         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
4749         MonoAssembly *ass = MONO_HANDLE_GETVAL(assembly, assembly);
4750         MonoImage *image = ass->image;
4751
4752         MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
4753         int count = t->rows;
4754
4755         GPtrArray *result = g_ptr_array_sized_new (count);
4756
4757         for (int i = 0; i < count; i++) {
4758                 MonoAssemblyName *aname = create_referenced_assembly_name (domain, image, t, i, error);
4759                 if (!is_ok (error))
4760                         break;
4761                 g_ptr_array_add (result, aname);
4762         }
4763         return result;
4764 }
4765
4766 /* move this in some file in mono/util/ */
4767 static char *
4768 g_concat_dir_and_file (const char *dir, const char *file)
4769 {
4770         g_return_val_if_fail (dir != NULL, NULL);
4771         g_return_val_if_fail (file != NULL, NULL);
4772
4773         /*
4774          * If the directory name doesn't have a / on the end, we need
4775          * to add one so we get a proper path to the file
4776          */
4777         if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
4778                 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
4779         else
4780                 return g_strconcat (dir, file, NULL);
4781 }
4782
4783 ICALL_EXPORT void *
4784 ves_icall_System_Reflection_Assembly_GetManifestResourceInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, gint32 *size, MonoReflectionModuleHandleOut ref_module, MonoError *error) 
4785 {
4786         error_init (error);
4787         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4788         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4789         MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4790         guint32 i;
4791         guint32 cols [MONO_MANIFEST_SIZE];
4792         guint32 impl, file_idx;
4793         const char *val;
4794         MonoImage *module;
4795
4796         char *n = mono_string_handle_to_utf8 (name, error);
4797         return_val_if_nok (error, NULL);
4798
4799         for (i = 0; i < table->rows; ++i) {
4800                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4801                 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
4802                 if (strcmp (val, n) == 0)
4803                         break;
4804         }
4805         g_free (n);
4806         if (i == table->rows)
4807                 return NULL;
4808         /* FIXME */
4809         impl = cols [MONO_MANIFEST_IMPLEMENTATION];
4810         if (impl) {
4811                 /*
4812                  * this code should only be called after obtaining the 
4813                  * ResourceInfo and handling the other cases.
4814                  */
4815                 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
4816                 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
4817
4818                 module = mono_image_load_file_for_image_checked (assembly->image, file_idx, error);
4819                 if (!is_ok (error) || !module)
4820                         return NULL;
4821         }
4822         else
4823                 module = assembly->image;
4824
4825         
4826         MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
4827         if (!is_ok (error))
4828                 return NULL;
4829         MONO_HANDLE_ASSIGN (ref_module, rm);
4830
4831         return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
4832 }
4833
4834 static gboolean
4835 get_manifest_resource_info_internal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info, MonoError *error)
4836 {
4837         HANDLE_FUNCTION_ENTER ();
4838         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4839         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4840         MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4841         int i;
4842         guint32 cols [MONO_MANIFEST_SIZE];
4843         guint32 file_cols [MONO_FILE_SIZE];
4844         const char *val;
4845         char *n;
4846
4847         gboolean result = FALSE;
4848         
4849         n = mono_string_handle_to_utf8 (name, error);
4850         if (!is_ok (error))
4851                 goto leave;
4852
4853         for (i = 0; i < table->rows; ++i) {
4854                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4855                 val = mono_metadata_string_heap (assembly->image, cols [MONO_MANIFEST_NAME]);
4856                 if (strcmp (val, n) == 0)
4857                         break;
4858         }
4859         g_free (n);
4860         if (i == table->rows)
4861                 goto leave;
4862
4863         if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
4864                 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST);
4865         }
4866         else {
4867                 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
4868                 case MONO_IMPLEMENTATION_FILE:
4869                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4870                         table = &assembly->image->tables [MONO_TABLE_FILE];
4871                         mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
4872                         val = mono_metadata_string_heap (assembly->image, file_cols [MONO_FILE_NAME]);
4873                         MONO_HANDLE_SET (info, filename, mono_string_new_handle (domain, val, error));
4874                         if (file_cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA)
4875                                 MONO_HANDLE_SETVAL (info, location, guint32, 0);
4876                         else
4877                                 MONO_HANDLE_SETVAL (info, location, guint32, RESOURCE_LOCATION_EMBEDDED);
4878                         break;
4879
4880                 case MONO_IMPLEMENTATION_ASSEMBLYREF:
4881                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4882                         mono_assembly_load_reference (assembly->image, i - 1);
4883                         if (assembly->image->references [i - 1] == REFERENCE_MISSING) {
4884                                 mono_error_set_assembly_load (error, NULL, "Assembly %d referenced from assembly %s not found ", i - 1, assembly->image->name);
4885                                 goto leave;
4886                         }
4887                         MonoReflectionAssemblyHandle assm_obj = mono_assembly_get_object_handle (mono_domain_get (), assembly->image->references [i - 1], error);
4888                         if (!is_ok (error))
4889                                 goto leave;
4890                         MONO_HANDLE_SET (info, assembly, assm_obj);
4891
4892                         /* Obtain info recursively */
4893                         get_manifest_resource_info_internal (assm_obj, name, info, error);
4894                         if (!is_ok (error))
4895                                 goto leave;
4896                         guint32 location = MONO_HANDLE_GETVAL (info, location);
4897                         location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
4898                         MONO_HANDLE_SETVAL (info, location, guint32, location);
4899                         break;
4900
4901                 case MONO_IMPLEMENTATION_EXP_TYPE:
4902                         g_assert_not_reached ();
4903                         break;
4904                 }
4905         }
4906
4907         result = TRUE;
4908 leave:
4909         HANDLE_FUNCTION_RETURN_VAL (result);
4910 }
4911
4912 ICALL_EXPORT gboolean
4913 ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info_h, MonoError *error)
4914 {
4915         error_init (error);
4916         return get_manifest_resource_info_internal (assembly_h, name, info_h, error);
4917 }
4918
4919 static gboolean
4920 add_filename_to_files_array (MonoDomain *domain, MonoAssembly * assembly, MonoTableInfo *table, int i, MonoArrayHandle dest, int dest_idx, MonoError *error)
4921 {
4922         HANDLE_FUNCTION_ENTER();
4923         error_init (error);
4924         const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
4925         char *n = g_concat_dir_and_file (assembly->basedir, val);
4926         MonoStringHandle str = mono_string_new_handle (domain, n, error);
4927         g_free (n);
4928         if (!is_ok (error))
4929                 goto leave;
4930         MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, str);
4931 leave:
4932         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
4933 }
4934
4935 ICALL_EXPORT MonoObjectHandle
4936 ves_icall_System_Reflection_Assembly_GetFilesInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoBoolean resource_modules, MonoError *error) 
4937 {
4938         error_init (error);
4939         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_h);
4940         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
4941         MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_FILE];
4942         int i, count;
4943
4944         /* check hash if needed */
4945         if (!MONO_HANDLE_IS_NULL(name)) {
4946                 char *n = mono_string_handle_to_utf8 (name, error);
4947                 if (!is_ok (error))
4948                         goto fail;
4949
4950                 for (i = 0; i < table->rows; ++i) {
4951                         const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
4952                         if (strcmp (val, n) == 0) {
4953                                 g_free (n);
4954                                 n = g_concat_dir_and_file (assembly->basedir, val);
4955                                 MonoStringHandle fn = mono_string_new_handle (domain, n, error);
4956                                 g_free (n);
4957                                 if (!is_ok (error))
4958                                         goto fail;
4959                                 return MONO_HANDLE_CAST (MonoObject, fn);
4960                         }
4961                 }
4962                 g_free (n);
4963                 return NULL_HANDLE;
4964         }
4965
4966         count = 0;
4967         for (i = 0; i < table->rows; ++i) {
4968                 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA))
4969                         count ++;
4970         }
4971
4972         MonoArrayHandle result = mono_array_new_handle (domain, mono_defaults.string_class, count, error);
4973         if (!is_ok (error))
4974                 goto fail;
4975
4976         count = 0;
4977         for (i = 0; i < table->rows; ++i) {
4978                 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
4979                         if (!add_filename_to_files_array (domain, assembly, table, i, result, count, error))
4980                                 goto fail;
4981                         count++;
4982                 }
4983         }
4984         return MONO_HANDLE_CAST (MonoObject, result);
4985 fail:
4986         return NULL_HANDLE;
4987 }
4988
4989 static gboolean
4990 add_module_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int *dest_idx, MonoImage* module, MonoError *error)
4991 {
4992         HANDLE_FUNCTION_ENTER ();
4993         error_init (error);
4994         if (module) {
4995                 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, module, error);
4996                 if (!is_ok (error))
4997                         goto leave;
4998                 
4999                 MONO_HANDLE_ARRAY_SETREF (dest, *dest_idx, rm);
5000                 ++(*dest_idx);
5001         }
5002
5003 leave:
5004         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5005 }
5006
5007 static gboolean
5008 add_file_to_modules_array (MonoDomain *domain, MonoArrayHandle dest, int dest_idx, MonoImage *image, MonoTableInfo *table, int table_idx,  MonoError *error)
5009 {
5010         HANDLE_FUNCTION_ENTER ();
5011         error_init (error);
5012
5013         guint32 cols [MONO_FILE_SIZE];
5014         mono_metadata_decode_row (table, table_idx, cols, MONO_FILE_SIZE);
5015         if (cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA) {
5016                 MonoReflectionModuleHandle rm = mono_module_file_get_object_handle (domain, image, table_idx, error);
5017                 if (!is_ok (error))
5018                         goto leave;
5019                 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5020         } else {
5021                 MonoImage *m = mono_image_load_file_for_image_checked (image, table_idx + 1, error);
5022                 if (!is_ok (error))
5023                         goto leave;
5024                 if (!m) {
5025                         const char *filename = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
5026                         mono_error_set_assembly_load (error, g_strdup (filename), "%s", "");
5027                         goto leave;
5028                 }
5029                 MonoReflectionModuleHandle rm = mono_module_get_object_handle (domain, m, error);
5030                 if (!is_ok (error))
5031                         goto leave;
5032                 MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rm);
5033         }
5034
5035 leave:
5036         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
5037 }
5038
5039 ICALL_EXPORT MonoArrayHandle
5040 ves_icall_System_Reflection_Assembly_GetModulesInternal (MonoReflectionAssemblyHandle assembly_h, MonoError *error)
5041 {
5042         error_init (error);
5043         MonoDomain *domain = mono_domain_get();
5044         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5045         MonoClass *klass;
5046         int i, j, file_count = 0;
5047         MonoImage **modules;
5048         guint32 module_count, real_module_count;
5049         MonoTableInfo *table;
5050         MonoImage *image = assembly->image;
5051
5052         g_assert (image != NULL);
5053         g_assert (!assembly_is_dynamic (assembly));
5054
5055         table = &image->tables [MONO_TABLE_FILE];
5056         file_count = table->rows;
5057
5058         modules = image->modules;
5059         module_count = image->module_count;
5060
5061         real_module_count = 0;
5062         for (i = 0; i < module_count; ++i)
5063                 if (modules [i])
5064                         real_module_count ++;
5065
5066         klass = mono_class_get_module_class ();
5067         MonoArrayHandle res = mono_array_new_handle (domain, klass, 1 + real_module_count + file_count, error);
5068         if (!is_ok (error))
5069                 goto fail;
5070
5071         MonoReflectionModuleHandle image_obj = mono_module_get_object_handle (domain, image, error);
5072         if (!is_ok (error))
5073                 goto fail;
5074
5075         MONO_HANDLE_ARRAY_SETREF (res, 0, image_obj);
5076
5077         j = 1;
5078         for (i = 0; i < module_count; ++i)
5079                 if (!add_module_to_modules_array (domain, res, &j, modules[i], error))
5080                         goto fail;
5081
5082         for (i = 0; i < file_count; ++i, ++j) {
5083                 if (!add_file_to_modules_array (domain, res, j, image, table, i, error))
5084                         goto fail;
5085         }
5086
5087         return res;
5088 fail:
5089         return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
5090 }
5091
5092 ICALL_EXPORT MonoReflectionMethodHandle
5093 ves_icall_GetCurrentMethod (MonoError *error) 
5094 {
5095         error_init (error);
5096
5097         MonoMethod *m = mono_method_get_last_managed ();
5098
5099         if (!m) {
5100                 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5101                 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5102         }
5103
5104         while (m->is_inflated)
5105                 m = ((MonoMethodInflated*)m)->declaring;
5106
5107         return mono_method_get_object_handle (mono_domain_get (), m, NULL, error);
5108 }
5109
5110
5111 static MonoMethod*
5112 mono_method_get_equivalent_method (MonoMethod *method, MonoClass *klass)
5113 {
5114         int offset = -1, i;
5115         if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) {
5116                 MonoError error;
5117                 MonoMethod *result;
5118                 MonoMethodInflated *inflated = (MonoMethodInflated*)method;
5119                 //method is inflated, we should inflate it on the other class
5120                 MonoGenericContext ctx;
5121                 ctx.method_inst = inflated->context.method_inst;
5122                 ctx.class_inst = inflated->context.class_inst;
5123                 if (mono_class_is_ginst (klass))
5124                         ctx.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
5125                 else if (mono_class_is_gtd (klass))
5126                         ctx.class_inst = mono_class_get_generic_container (klass)->context.class_inst;
5127                 result = mono_class_inflate_generic_method_full_checked (inflated->declaring, klass, &ctx, &error);
5128                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5129                 return result;
5130         }
5131
5132         mono_class_setup_methods (method->klass);
5133         if (mono_class_has_failure (method->klass))
5134                 return NULL;
5135         int mcount = mono_class_get_method_count (method->klass);
5136         for (i = 0; i < mcount; ++i) {
5137                 if (method->klass->methods [i] == method) {
5138                         offset = i;
5139                         break;
5140                 }       
5141         }
5142         mono_class_setup_methods (klass);
5143         if (mono_class_has_failure (klass))
5144                 return NULL;
5145         g_assert (offset >= 0 && offset < mono_class_get_method_count (klass));
5146         return klass->methods [offset];
5147 }
5148
5149 ICALL_EXPORT MonoReflectionMethodHandle
5150 ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternalType_native (MonoMethod *method, MonoType *type, MonoBoolean generic_check, MonoError *error)
5151 {
5152         error_init (error);
5153         MonoClass *klass;
5154         if (type && generic_check) {
5155                 klass = mono_class_from_mono_type (type);
5156                 if (mono_class_get_generic_type_definition (method->klass) != mono_class_get_generic_type_definition (klass))
5157                         return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5158
5159                 if (method->klass != klass) {
5160                         method = mono_method_get_equivalent_method (method, klass);
5161                         if (!method)
5162                                 return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
5163                 }
5164         } else if (type)
5165                 klass = mono_class_from_mono_type (type);
5166         else
5167                 klass = method->klass;
5168         return mono_method_get_object_handle (mono_domain_get (), method, klass, error);
5169 }
5170
5171 ICALL_EXPORT MonoReflectionMethodBodyHandle
5172 ves_icall_System_Reflection_MethodBase_GetMethodBodyInternal (MonoMethod *method, MonoError *error)
5173 {
5174         error_init (error);
5175         return mono_method_body_get_object_handle (mono_domain_get (), method, error);
5176 }
5177
5178 ICALL_EXPORT MonoReflectionAssemblyHandle
5179 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (MonoError *error)
5180 {
5181         error_init (error);
5182
5183         MonoMethod *dest = NULL;
5184         mono_stack_walk_no_il (get_executing, &dest);
5185         g_assert (dest);
5186         return mono_assembly_get_object_handle (mono_domain_get (), dest->klass->image->assembly, error);
5187 }
5188
5189
5190 ICALL_EXPORT MonoReflectionAssemblyHandle
5191 ves_icall_System_Reflection_Assembly_GetEntryAssembly (MonoError *error)
5192 {
5193         error_init (error);
5194
5195         MonoDomain* domain = mono_domain_get ();
5196
5197         if (!domain->entry_assembly)
5198                 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5199
5200         return mono_assembly_get_object_handle (domain, domain->entry_assembly, error);
5201 }
5202
5203 ICALL_EXPORT MonoReflectionAssemblyHandle
5204 ves_icall_System_Reflection_Assembly_GetCallingAssembly (MonoError *error)
5205 {
5206         error_init (error);
5207         MonoMethod *m;
5208         MonoMethod *dest;
5209
5210         dest = NULL;
5211         mono_stack_walk_no_il (get_executing, &dest);
5212         m = dest;
5213         mono_stack_walk_no_il (get_caller_no_reflection, &dest);
5214         if (!dest)
5215                 dest = m;
5216         if (!m) {
5217                 mono_error_set_not_supported (error, "Stack walks are not supported on this platform.");
5218                 return MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE);
5219         }
5220         return mono_assembly_get_object_handle (mono_domain_get (), dest->klass->image->assembly, error);
5221 }
5222
5223 ICALL_EXPORT MonoStringHandle
5224 ves_icall_System_RuntimeType_getFullName (MonoReflectionTypeHandle object, gboolean full_name,
5225                                                                                   gboolean assembly_qualified, MonoError *error)
5226 {
5227         MonoDomain *domain = mono_object_domain (MONO_HANDLE_RAW (object));
5228         MonoType *type = MONO_HANDLE_RAW (object)->type;
5229         MonoTypeNameFormat format;
5230         MonoStringHandle res;
5231         gchar *name;
5232
5233         if (full_name)
5234                 format = assembly_qualified ?
5235                         MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED :
5236                         MONO_TYPE_NAME_FORMAT_FULL_NAME;
5237         else
5238                 format = MONO_TYPE_NAME_FORMAT_REFLECTION;
5239  
5240         name = mono_type_get_name_full (type, format);
5241         if (!name)
5242                 return NULL_HANDLE_STRING;
5243
5244         if (full_name && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
5245                 g_free (name);
5246                 return NULL_HANDLE_STRING;
5247         }
5248
5249         res = mono_string_new_handle (domain, name, error);
5250         g_free (name);
5251
5252         return res;
5253 }
5254
5255 ICALL_EXPORT int
5256 vell_icall_RuntimeType_get_core_clr_security_level (MonoReflectionTypeHandle rfield, MonoError *error)
5257 {
5258         error_init (error);
5259         MonoType *type = MONO_HANDLE_GETVAL (rfield, type);
5260         MonoClass *klass = mono_class_from_mono_type (type);
5261
5262         mono_class_init_checked (klass, error);
5263         if (!is_ok (error))
5264                 return -1;
5265         return mono_security_core_clr_class_level (klass);
5266 }
5267
5268 ICALL_EXPORT int
5269 ves_icall_MonoField_get_core_clr_security_level (MonoReflectionField *rfield)
5270 {
5271         MonoClassField *field = rfield->field;
5272         return mono_security_core_clr_field_level (field, TRUE);
5273 }
5274
5275 ICALL_EXPORT int
5276 ves_icall_MonoMethod_get_core_clr_security_level (MonoReflectionMethodHandle rfield, MonoError *error)
5277 {
5278         error_init (error);
5279         MonoMethod *method = MONO_HANDLE_GETVAL (rfield, method);
5280         return mono_security_core_clr_method_level (method, TRUE);
5281 }
5282
5283 ICALL_EXPORT MonoStringHandle
5284 ves_icall_System_Reflection_Assembly_get_fullName (MonoReflectionAssemblyHandle assembly, MonoError *error)
5285 {
5286         error_init (error);
5287         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly);
5288         MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly);
5289         gchar *name;
5290
5291         name = mono_stringify_assembly_name (&mass->aname);
5292         MonoStringHandle res = mono_string_new_handle (domain, name, error);
5293         g_free (name);
5294         return res;
5295 }
5296
5297 ICALL_EXPORT MonoAssemblyName *
5298 ves_icall_System_Reflection_AssemblyName_GetNativeName (MonoAssembly *mass)
5299 {
5300         return &mass->aname;
5301 }
5302
5303 ICALL_EXPORT void
5304 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoStringHandle fname, MonoAssemblyName *name, MonoStringHandleOut normalized_codebase, MonoError *error)
5305 {
5306         char *filename;
5307         MonoImageOpenStatus status = MONO_IMAGE_OK;
5308         char *codebase = NULL;
5309         gboolean res;
5310         MonoImage *image;
5311         char *dirname;
5312
5313         error_init (error);
5314
5315         filename = mono_string_handle_to_utf8 (fname, error);
5316         return_if_nok (error);
5317
5318         dirname = g_path_get_dirname (filename);
5319         replace_shadow_path (mono_domain_get (), dirname, &filename);
5320         g_free (dirname);
5321
5322         image = mono_image_open_full (filename, &status, TRUE);
5323
5324         if (!image){
5325                 if (status == MONO_IMAGE_IMAGE_INVALID)
5326                         mono_error_set_bad_image_name (error, g_strdup (filename), "%s", "");
5327                 else
5328                         mono_error_set_assembly_load (error, g_strdup (filename), "%s", "");
5329                 g_free (filename);
5330                 return;
5331         }
5332
5333         res = mono_assembly_fill_assembly_name_full (image, name, TRUE);
5334         if (!res) {
5335                 mono_image_close (image);
5336                 g_free (filename);
5337                 mono_error_set_argument (error, "assemblyFile", "The file does not contain a manifest");
5338                 return;
5339         }
5340
5341         if (filename != NULL && *filename != '\0') {
5342                 gchar *result;
5343
5344                 codebase = g_strdup (filename);
5345
5346                 mono_icall_make_platform_path (codebase);
5347
5348                 const gchar *prepend = mono_icall_get_file_path_prefix (codebase);
5349
5350                 result = g_strconcat (prepend, codebase, NULL);
5351                 g_free (codebase);
5352                 codebase = result;
5353         }
5354         MONO_HANDLE_ASSIGN (normalized_codebase, mono_string_new_handle (mono_domain_get (), codebase, error));
5355         g_free (codebase);
5356
5357         mono_image_close (image);
5358         g_free (filename);
5359 }
5360
5361 ICALL_EXPORT MonoBoolean
5362 ves_icall_System_Reflection_Assembly_LoadPermissions (MonoReflectionAssemblyHandle assembly_h,
5363                                                       char **minimum, guint32 *minLength, char **optional, guint32 *optLength, char **refused, guint32 *refLength, MonoError *error)
5364 {
5365         error_init (error);
5366         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly);
5367         MonoBoolean result = FALSE;
5368         MonoDeclSecurityEntry entry;
5369
5370         /* SecurityAction.RequestMinimum */
5371         if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQMIN, &entry)) {
5372                 *minimum = entry.blob;
5373                 *minLength = entry.size;
5374                 result = TRUE;
5375         }
5376         /* SecurityAction.RequestOptional */
5377         if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQOPT, &entry)) {
5378                 *optional = entry.blob;
5379                 *optLength = entry.size;
5380                 result = TRUE;
5381         }
5382         /* SecurityAction.RequestRefuse */
5383         if (mono_declsec_get_assembly_action (assembly, SECURITY_ACTION_REQREFUSE, &entry)) {
5384                 *refused = entry.blob;
5385                 *refLength = entry.size;
5386                 result = TRUE;
5387         }
5388
5389         return result;  
5390 }
5391
5392 static gboolean
5393 mono_module_type_is_visible (MonoTableInfo *tdef, MonoImage *image, int type)
5394 {
5395         guint32 attrs, visibility;
5396         do {
5397                 attrs = mono_metadata_decode_row_col (tdef, type - 1, MONO_TYPEDEF_FLAGS);
5398                 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5399                 if (visibility != TYPE_ATTRIBUTE_PUBLIC && visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC)
5400                         return FALSE;
5401
5402         } while ((type = mono_metadata_token_index (mono_metadata_nested_in_typedef (image, type))));
5403
5404         return TRUE;
5405 }
5406
5407 static void
5408 image_get_type (MonoDomain *domain, MonoImage *image, MonoTableInfo *tdef, int table_idx, int count, MonoArrayHandle res, MonoArrayHandle exceptions, MonoBoolean exportedOnly, MonoError *error)
5409 {
5410         error_init (error);
5411         HANDLE_FUNCTION_ENTER ();
5412         MonoError klass_error;
5413         MonoClass *klass = mono_class_get_checked (image, table_idx | MONO_TOKEN_TYPE_DEF, &klass_error);
5414
5415         if (klass) {
5416                 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &klass->byval_arg, error);
5417                 return_if_nok (error);
5418
5419                 MONO_HANDLE_ARRAY_SETREF (res, count, rt);
5420         } else {
5421                 MonoException *ex = mono_error_convert_to_exception (error);
5422                 MONO_HANDLE_ARRAY_SETRAW (exceptions, count, ex);
5423         }
5424         HANDLE_FUNCTION_RETURN ();
5425 }
5426
5427 static MonoArrayHandle
5428 mono_module_get_types (MonoDomain *domain, MonoImage *image, MonoArrayHandleOut exceptions, MonoBoolean exportedOnly, MonoError *error)
5429 {
5430         MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
5431         int i, count;
5432
5433         error_init (error);
5434
5435         /* we start the count from 1 because we skip the special type <Module> */
5436         if (exportedOnly) {
5437                 count = 0;
5438                 for (i = 1; i < tdef->rows; ++i) {
5439                         if (mono_module_type_is_visible (tdef, image, i + 1))
5440                                 count++;
5441                 }
5442         } else {
5443                 count = tdef->rows - 1;
5444         }
5445         MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.runtimetype_class, count, error);
5446         return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
5447         MONO_HANDLE_ASSIGN (exceptions,  mono_array_new_handle (domain, mono_defaults.exception_class, count, error));
5448         return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
5449         count = 0;
5450         for (i = 1; i < tdef->rows; ++i) {
5451                 if (!exportedOnly || mono_module_type_is_visible (tdef, image, i+1)) {
5452                         image_get_type (domain, image, tdef, i + 1, count, res, exceptions, exportedOnly, error);
5453                         return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
5454                         count++;
5455                 }
5456         }
5457         
5458         return res;
5459 }
5460
5461 static void
5462 append_module_types (MonoDomain *domain, MonoArrayHandleOut res, MonoArrayHandleOut exceptions, MonoImage *image, MonoBoolean exportedOnly, MonoError *error)
5463 {
5464         HANDLE_FUNCTION_ENTER ();
5465         error_init (error);
5466         MonoArrayHandle ex2 = MONO_HANDLE_NEW (MonoArray, NULL);
5467         MonoArrayHandle res2 = mono_module_get_types (domain, image, ex2, exportedOnly, error);
5468         if (!is_ok (error))
5469                 goto leave;
5470
5471         /* Append the new types to the end of the array */
5472         if (mono_array_handle_length (res2) > 0) {
5473                 guint32 len1, len2;
5474
5475                 len1 = mono_array_handle_length (res);
5476                 len2 = mono_array_handle_length (res2);
5477
5478                 MonoArrayHandle res3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
5479                 if (!is_ok (error))
5480                         goto leave;
5481
5482                 mono_array_handle_memcpy_refs (res3, 0, res, 0, len1);
5483                 mono_array_handle_memcpy_refs (res3, len1, res2, 0, len2);
5484                 MONO_HANDLE_ASSIGN (res, res3);
5485
5486                 MonoArrayHandle ex3 = mono_array_new_handle (domain, mono_defaults.runtimetype_class, len1 + len2, error);
5487                 if (!is_ok (error))
5488                         goto leave;
5489
5490                 mono_array_handle_memcpy_refs (ex3, 0, exceptions, 0, len1);
5491                 mono_array_handle_memcpy_refs (ex3, len1, ex2, 0, len2);
5492                 MONO_HANDLE_ASSIGN (exceptions, ex3);
5493         }
5494 leave:
5495         HANDLE_FUNCTION_RETURN ();
5496 }
5497
5498 static void
5499 set_class_failure_in_array (MonoArrayHandle exl, int i, MonoClass *klass)
5500 {
5501         HANDLE_FUNCTION_ENTER ();
5502         MonoError unboxed_error;
5503         error_init (&unboxed_error);
5504         mono_error_set_for_class_failure (&unboxed_error, klass);
5505
5506         MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, mono_error_convert_to_exception (&unboxed_error));
5507         MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
5508         HANDLE_FUNCTION_RETURN ();
5509 }
5510
5511 ICALL_EXPORT MonoArrayHandle
5512 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssemblyHandle assembly_handle, MonoBoolean exportedOnly, MonoError *error)
5513 {
5514         MonoArrayHandle exceptions = MONO_HANDLE_NEW(MonoArray, NULL);
5515         int i;
5516
5517         MonoDomain *domain = MONO_HANDLE_DOMAIN (assembly_handle);
5518         MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_handle, assembly);
5519
5520         g_assert (!assembly_is_dynamic (assembly));
5521         MonoImage *image = assembly->image;
5522         MonoTableInfo *table = &image->tables [MONO_TABLE_FILE];
5523         MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, exportedOnly, error);
5524         return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
5525
5526         /* Append data from all modules in the assembly */
5527         for (i = 0; i < table->rows; ++i) {
5528                 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
5529                         MonoImage *loaded_image = mono_assembly_load_module_checked (image->assembly, i + 1, error);
5530                         return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
5531
5532                         if (loaded_image) {
5533                                 append_module_types (domain, res, exceptions, loaded_image, exportedOnly, error);
5534                                 return_val_if_nok (error, MONO_HANDLE_CAST (MonoArray, NULL_HANDLE));
5535                         }
5536                 }
5537         }
5538
5539         /* the ReflectionTypeLoadException must have all the types (Types property), 
5540          * NULL replacing types which throws an exception. The LoaderException must
5541          * contain all exceptions for NULL items.
5542          */
5543
5544         int len = mono_array_handle_length (res);
5545
5546         int ex_count = 0;
5547         GList *list = NULL;
5548         MonoReflectionTypeHandle t = MONO_HANDLE_NEW (MonoReflectionType, NULL);
5549         for (i = 0; i < len; i++) {
5550                 MONO_HANDLE_ARRAY_GETREF (t, res, i);
5551
5552                 if (!MONO_HANDLE_IS_NULL (t)) {
5553                         MonoClass *klass = mono_type_get_class (MONO_HANDLE_GETVAL (t, type));
5554                         if ((klass != NULL) && mono_class_has_failure (klass)) {
5555                                 /* keep the class in the list */
5556                                 list = g_list_append (list, klass);
5557                                 /* and replace Type with NULL */
5558                                 MONO_HANDLE_ARRAY_SETRAW (res, i, NULL);
5559                         }
5560                 } else {
5561                         ex_count ++;
5562                 }
5563         }
5564
5565         if (list || ex_count) {
5566                 GList *tmp = NULL;
5567                 int j, length = g_list_length (list) + ex_count;
5568
5569                 MonoArrayHandle exl = mono_array_new_handle (domain, mono_defaults.exception_class, length, error);
5570                 if (!is_ok (error)) {
5571                         g_list_free (list);
5572                         return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
5573                 }
5574                 /* Types for which mono_class_get_checked () succeeded */
5575                 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5576                 for (i = 0, tmp = list; tmp; i++, tmp = tmp->next) {
5577                         set_class_failure_in_array (exl, i, (MonoClass*)tmp->data);
5578                 }
5579                 /* Types for which it don't */
5580                 for (j = 0; j < mono_array_handle_length (exceptions); ++j) {
5581                         MONO_HANDLE_ARRAY_GETREF (exc, exceptions, j);
5582                         if (!MONO_HANDLE_IS_NULL (exc)) {
5583                                 g_assert (i < length);
5584                                 MONO_HANDLE_ARRAY_SETREF (exl, i, exc);
5585                                 i ++;
5586                         }
5587                 }
5588                 g_list_free (list);
5589                 list = NULL;
5590
5591                 MONO_HANDLE_ASSIGN (exc, mono_get_exception_reflection_type_load_checked (res, exl, error));
5592                 if (!is_ok (error)) {
5593                         return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
5594                 }
5595                 mono_error_set_exception_handle (error, exc);
5596                 return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
5597         }
5598                 
5599         return res;
5600 }
5601
5602 ICALL_EXPORT void
5603 ves_icall_Mono_RuntimeMarshal_FreeAssemblyName (MonoAssemblyName *aname, gboolean free_struct)
5604 {
5605         mono_assembly_name_free (aname);
5606         if (free_struct)
5607                 g_free (aname);
5608 }
5609
5610 ICALL_EXPORT gboolean
5611 ves_icall_System_Reflection_AssemblyName_ParseAssemblyName (const char *name, MonoAssemblyName *aname, gboolean *is_version_definited, gboolean *is_token_defined)
5612 {
5613         *is_version_definited = *is_token_defined = FALSE;
5614
5615         return mono_assembly_name_parse_full (name, aname, TRUE, is_version_definited, is_token_defined);
5616 }
5617
5618 ICALL_EXPORT MonoReflectionTypeHandle
5619 ves_icall_System_Reflection_Module_GetGlobalType (MonoReflectionModuleHandle module, MonoError *error)
5620 {
5621         MonoDomain *domain = MONO_HANDLE_DOMAIN (module);
5622         MonoImage *image = MONO_HANDLE_GETVAL (module, image);
5623         MonoClass *klass;
5624
5625         g_assert (image);
5626
5627         MonoReflectionTypeHandle ret = MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
5628
5629         if (image_is_dynamic (image) && ((MonoDynamicImage*)image)->initial_image)
5630                 /* These images do not have a global type */
5631                 goto leave;
5632
5633         klass = mono_class_get_checked (image, 1 | MONO_TOKEN_TYPE_DEF, error);
5634         if (!is_ok (error))
5635                 goto leave;
5636
5637         ret = mono_type_get_object_handle (domain, &klass->byval_arg, error);
5638 leave:
5639         return ret;
5640 }
5641
5642 ICALL_EXPORT void
5643 ves_icall_System_Reflection_Module_Close (MonoReflectionModuleHandle module, MonoError *error)
5644 {
5645         /*if (module->image)
5646                 mono_image_close (module->image);*/
5647 }
5648
5649 ICALL_EXPORT MonoStringHandle
5650 ves_icall_System_Reflection_Module_GetGuidInternal (MonoReflectionModuleHandle refmodule, MonoError *error)
5651 {
5652         MonoDomain *domain = MONO_HANDLE_DOMAIN (refmodule);
5653         MonoImage *image = MONO_HANDLE_GETVAL (refmodule, image);
5654
5655         g_assert (image);
5656         return mono_string_new_handle (domain, image->guid, error);
5657 }
5658
5659 #ifndef HOST_WIN32
5660 static inline gpointer
5661 mono_icall_module_get_hinstance (MonoReflectionModuleHandle module)
5662 {
5663         return (gpointer) (-1);
5664 }
5665 #endif /* HOST_WIN32 */
5666
5667 ICALL_EXPORT gpointer
5668 ves_icall_System_Reflection_Module_GetHINSTANCE (MonoReflectionModuleHandle module, MonoError *error)
5669 {
5670         return mono_icall_module_get_hinstance (module);
5671 }
5672
5673 ICALL_EXPORT void
5674 ves_icall_System_Reflection_Module_GetPEKind (MonoImage *image, gint32 *pe_kind, gint32 *machine, MonoError *error)
5675 {
5676         if (image_is_dynamic (image)) {
5677                 MonoDynamicImage *dyn = (MonoDynamicImage*)image;
5678                 *pe_kind = dyn->pe_kind;
5679                 *machine = dyn->machine;
5680         }
5681         else {
5682                 *pe_kind = ((MonoCLIImageInfo*)(image->image_info))->cli_cli_header.ch_flags & 0x3;
5683                 *machine = ((MonoCLIImageInfo*)(image->image_info))->cli_header.coff.coff_machine;
5684         }
5685 }
5686
5687 ICALL_EXPORT gint32
5688 ves_icall_System_Reflection_Module_GetMDStreamVersion (MonoImage *image, MonoError *error)
5689 {
5690         return (image->md_version_major << 16) | (image->md_version_minor);
5691 }
5692
5693 ICALL_EXPORT MonoArrayHandle
5694 ves_icall_System_Reflection_Module_InternalGetTypes (MonoReflectionModuleHandle module, MonoError *error)
5695 {
5696         error_init (error);
5697
5698         MonoImage *image = MONO_HANDLE_GETVAL (module, image);
5699         MonoDomain *domain = MONO_HANDLE_DOMAIN (module);
5700
5701         if (!image) {
5702                 MonoArrayHandle arr = mono_array_new_handle (domain, mono_defaults.runtimetype_class, 0, error);
5703                 return arr;
5704         } else {
5705                 MonoArrayHandle exceptions = MONO_HANDLE_NEW (MonoArray, NULL);
5706                 MonoArrayHandle res = mono_module_get_types (domain, image, exceptions, FALSE, error);
5707                 return_val_if_nok (error, MONO_HANDLE_CAST(MonoArray, NULL_HANDLE));
5708
5709                 int n = mono_array_handle_length (exceptions);
5710                 MonoExceptionHandle ex = MONO_HANDLE_NEW (MonoException, NULL);
5711                 for (int i = 0; i < n; ++i) {
5712                         MONO_HANDLE_ARRAY_GETREF(ex, exceptions, i);
5713                         if (!MONO_HANDLE_IS_NULL (ex)) {
5714                                 mono_error_set_exception_handle (error, ex);
5715                                 return MONO_HANDLE_CAST(MonoArray, NULL_HANDLE);
5716                         }
5717                 }
5718                 return res;
5719         }
5720 }
5721
5722 static gboolean
5723 mono_memberref_is_method (MonoImage *image, guint32 token)
5724 {
5725         if (!image_is_dynamic (image)) {
5726                 guint32 cols [MONO_MEMBERREF_SIZE];
5727                 const char *sig;
5728                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
5729                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
5730                 mono_metadata_decode_blob_size (sig, &sig);
5731                 return (*sig != 0x6);
5732         } else {
5733                 MonoError error;
5734                 MonoClass *handle_class;
5735
5736                 if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL, &error)) {
5737                         mono_error_cleanup (&error); /* just probing, ignore error */
5738                         return FALSE;
5739                 }
5740
5741                 return mono_defaults.methodhandle_class == handle_class;
5742         }
5743 }
5744
5745 static MonoGenericInst *
5746 get_generic_inst_from_array_handle (MonoArrayHandle type_args)
5747 {
5748         int type_argc = mono_array_handle_length (type_args);
5749         int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *);
5750
5751         MonoGenericInst *ginst = (MonoGenericInst *)g_alloca (size);
5752         memset (ginst, 0, sizeof (MonoGenericInst));
5753         ginst->type_argc = type_argc;
5754         for (int i = 0; i < type_argc; i++) {
5755                 MONO_HANDLE_ARRAY_GETVAL (ginst->type_argv[i], type_args, MonoType*, i);
5756         }
5757         ginst->is_open = FALSE;
5758         for (int i = 0; i < type_argc; i++) {
5759                 if (mono_class_is_open_constructed_type (ginst->type_argv[i])) {
5760                         ginst->is_open = TRUE;
5761                         break;
5762                 }
5763         }
5764
5765         return mono_metadata_get_canonical_generic_inst (ginst);
5766 }
5767
5768 static void
5769 init_generic_context_from_args_handles (MonoGenericContext *context, MonoArrayHandle type_args, MonoArrayHandle method_args)
5770 {
5771         if (!MONO_HANDLE_IS_NULL (type_args)) {
5772                 context->class_inst = get_generic_inst_from_array_handle (type_args);
5773         } else {
5774                 context->class_inst = NULL;
5775         }
5776         if (!MONO_HANDLE_IS_NULL  (method_args)) {
5777                 context->method_inst = get_generic_inst_from_array_handle (method_args);
5778         } else {
5779                 context->method_inst = NULL;
5780         }
5781 }
5782
5783
5784 static MonoType*
5785 module_resolve_type_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
5786 {
5787         HANDLE_FUNCTION_ENTER ();
5788         error_init (error);
5789         MonoType *result = NULL;
5790         MonoClass *klass;
5791         int table = mono_metadata_token_table (token);
5792         int index = mono_metadata_token_index (token);
5793         MonoGenericContext context;
5794
5795         *resolve_error = ResolveTokenError_Other;
5796
5797         /* Validate token */
5798         if ((table != MONO_TABLE_TYPEDEF) && (table != MONO_TABLE_TYPEREF) && 
5799                 (table != MONO_TABLE_TYPESPEC)) {
5800                 *resolve_error = ResolveTokenError_BadTable;
5801                 goto leave;
5802         }
5803
5804         if (image_is_dynamic (image)) {
5805                 if ((table == MONO_TABLE_TYPEDEF) || (table == MONO_TABLE_TYPEREF)) {
5806                         MonoError inner_error;
5807                         klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, &inner_error);
5808                         mono_error_cleanup (&inner_error);
5809                         result = klass ? &klass->byval_arg : NULL;
5810                         goto leave;
5811                 }
5812
5813                 init_generic_context_from_args_handles (&context, type_args, method_args);
5814                 MonoError inner_error;
5815                 klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, &inner_error);
5816                 mono_error_cleanup (&inner_error);
5817                 result = klass ? &klass->byval_arg : NULL;
5818                 goto leave;
5819         }
5820
5821         if ((index <= 0) || (index > image->tables [table].rows)) {
5822                 *resolve_error = ResolveTokenError_OutOfRange;
5823                 goto leave;
5824         }
5825
5826         init_generic_context_from_args_handles (&context, type_args, method_args);
5827         klass = mono_class_get_checked (image, token, error);
5828         if (klass)
5829                 klass = mono_class_inflate_generic_class_checked (klass, &context, error);
5830         if (!is_ok (error))
5831                 goto leave;
5832
5833         if (klass)
5834                 result = &klass->byval_arg;
5835 leave:
5836         HANDLE_FUNCTION_RETURN_VAL (result);
5837
5838 }
5839 ICALL_EXPORT MonoType*
5840 ves_icall_System_Reflection_Module_ResolveTypeToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
5841 {
5842         return module_resolve_type_token (image, token, type_args, method_args, resolve_error, error);
5843 }
5844
5845 static MonoMethod*
5846 module_resolve_method_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
5847 {
5848         HANDLE_FUNCTION_ENTER ();
5849         error_init (error);
5850         MonoMethod *method = NULL;
5851         int table = mono_metadata_token_table (token);
5852         int index = mono_metadata_token_index (token);
5853         MonoGenericContext context;
5854
5855         *resolve_error = ResolveTokenError_Other;
5856
5857         /* Validate token */
5858         if ((table != MONO_TABLE_METHOD) && (table != MONO_TABLE_METHODSPEC) && 
5859                 (table != MONO_TABLE_MEMBERREF)) {
5860                 *resolve_error = ResolveTokenError_BadTable;
5861                 goto leave;
5862         }
5863
5864         if (image_is_dynamic (image)) {
5865                 if (table == MONO_TABLE_METHOD) {
5866                         MonoError inner_error;
5867                         method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, &inner_error);
5868                         mono_error_cleanup (&inner_error);
5869                         goto leave;
5870                 }
5871
5872                 if ((table == MONO_TABLE_MEMBERREF) && !(mono_memberref_is_method (image, token))) {
5873                         *resolve_error = ResolveTokenError_BadTable;
5874                         goto leave;
5875                 }
5876
5877                 init_generic_context_from_args_handles (&context, type_args, method_args);
5878                 MonoError inner_error;
5879                 method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, &inner_error);
5880                 mono_error_cleanup (&inner_error);
5881                 goto leave;
5882         }
5883
5884         if ((index <= 0) || (index > image->tables [table].rows)) {
5885                 *resolve_error = ResolveTokenError_OutOfRange;
5886                 goto leave;
5887         }
5888         if ((table == MONO_TABLE_MEMBERREF) && (!mono_memberref_is_method (image, token))) {
5889                 *resolve_error = ResolveTokenError_BadTable;
5890                 goto leave;
5891         }
5892
5893         init_generic_context_from_args_handles (&context, type_args, method_args);
5894         method = mono_get_method_checked (image, token, NULL, &context, error);
5895
5896 leave:
5897         HANDLE_FUNCTION_RETURN_VAL (method);
5898 }
5899
5900 ICALL_EXPORT MonoMethod*
5901 ves_icall_System_Reflection_Module_ResolveMethodToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
5902 {
5903         return module_resolve_method_token (image, token, type_args, method_args, resolve_error, error);
5904 }
5905
5906 ICALL_EXPORT MonoString*
5907 ves_icall_System_Reflection_Module_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error)
5908 {
5909         MonoError error;
5910         int index = mono_metadata_token_index (token);
5911
5912         *resolve_error = ResolveTokenError_Other;
5913
5914         /* Validate token */
5915         if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
5916                 *resolve_error = ResolveTokenError_BadTable;
5917                 return NULL;
5918         }
5919
5920         if (image_is_dynamic (image)) {
5921                 MonoString * result = (MonoString *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, &error);
5922                 mono_error_cleanup (&error);
5923                 return result;
5924         }
5925
5926         if ((index <= 0) || (index >= image->heap_us.size)) {
5927                 *resolve_error = ResolveTokenError_OutOfRange;
5928                 return NULL;
5929         }
5930
5931         /* FIXME: What to do if the index points into the middle of a string ? */
5932
5933         MonoString *result = mono_ldstr_checked (mono_domain_get (), image, index, &error);
5934         mono_error_set_pending_exception (&error);
5935         return result;
5936 }
5937
5938 static MonoClassField*
5939 module_resolve_field_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
5940 {
5941         HANDLE_FUNCTION_ENTER ();
5942         MonoClass *klass;
5943         int table = mono_metadata_token_table (token);
5944         int index = mono_metadata_token_index (token);
5945         MonoGenericContext context;
5946         MonoClassField *field = NULL;
5947
5948         error_init (error);
5949         *resolve_error = ResolveTokenError_Other;
5950
5951         /* Validate token */
5952         if ((table != MONO_TABLE_FIELD) && (table != MONO_TABLE_MEMBERREF)) {
5953                 *resolve_error = ResolveTokenError_BadTable;
5954                 goto leave;
5955         }
5956
5957         if (image_is_dynamic (image)) {
5958                 if (table == MONO_TABLE_FIELD) {
5959                         MonoError inner_error;
5960                         field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, &inner_error);
5961                         mono_error_cleanup (&inner_error);
5962                         goto leave;
5963                 }
5964
5965                 if (mono_memberref_is_method (image, token)) {
5966                         *resolve_error = ResolveTokenError_BadTable;
5967                         goto leave;
5968                 }
5969
5970                 init_generic_context_from_args_handles (&context, type_args, method_args);
5971                 MonoError inner_error;
5972                 field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, &inner_error);
5973                 mono_error_cleanup (&inner_error);
5974                 goto leave;
5975         }
5976
5977         if ((index <= 0) || (index > image->tables [table].rows)) {
5978                 *resolve_error = ResolveTokenError_OutOfRange;
5979                 goto leave;
5980         }
5981         if ((table == MONO_TABLE_MEMBERREF) && (mono_memberref_is_method (image, token))) {
5982                 *resolve_error = ResolveTokenError_BadTable;
5983                 goto leave;
5984         }
5985
5986         init_generic_context_from_args_handles (&context, type_args, method_args);
5987         field = mono_field_from_token_checked (image, token, &klass, &context, error);
5988         
5989 leave:
5990         HANDLE_FUNCTION_RETURN_VAL (field);
5991 }
5992
5993 ICALL_EXPORT MonoClassField*
5994 ves_icall_System_Reflection_Module_ResolveFieldToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error)
5995 {
5996         return module_resolve_field_token (image, token, type_args, method_args, resolve_error, error);
5997 }
5998
5999 ICALL_EXPORT MonoObjectHandle
6000 ves_icall_System_Reflection_Module_ResolveMemberToken (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *error, MonoError *merror)
6001 {
6002         int table = mono_metadata_token_table (token);
6003
6004         error_init (merror);
6005         *error = ResolveTokenError_Other;
6006
6007         switch (table) {
6008         case MONO_TABLE_TYPEDEF:
6009         case MONO_TABLE_TYPEREF:
6010         case MONO_TABLE_TYPESPEC: {
6011                 MonoType *t = module_resolve_type_token (image, token, type_args, method_args, error, merror);
6012                 if (t) {
6013                         return MONO_HANDLE_CAST (MonoObject, mono_type_get_object_handle (mono_domain_get (), t, merror));
6014                 }
6015                 else
6016                         return NULL_HANDLE;
6017         }
6018         case MONO_TABLE_METHOD:
6019         case MONO_TABLE_METHODSPEC: {
6020                 MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
6021                 if (m) {
6022                         return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
6023                 } else
6024                         return NULL_HANDLE;
6025         }               
6026         case MONO_TABLE_FIELD: {
6027                 MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
6028                 if (f) {
6029                         return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
6030                 }
6031                 else
6032                         return NULL_HANDLE;
6033         }
6034         case MONO_TABLE_MEMBERREF:
6035                 if (mono_memberref_is_method (image, token)) {
6036                         MonoMethod *m = module_resolve_method_token (image, token, type_args, method_args, error, merror);
6037                         if (m) {
6038                                 return MONO_HANDLE_CAST (MonoObject, mono_method_get_object_handle (mono_domain_get (), m, m->klass, merror));
6039                         } else
6040                                 return NULL_HANDLE;
6041                 }
6042                 else {
6043                         MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror);
6044                         if (f) {
6045                                 return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (mono_domain_get (), f->parent, f, merror));
6046                         }
6047                         else
6048                                 return NULL_HANDLE;
6049                 }
6050                 break;
6051
6052         default:
6053                 *error = ResolveTokenError_BadTable;
6054         }
6055
6056         return NULL_HANDLE;
6057 }
6058
6059 ICALL_EXPORT MonoArrayHandle
6060 ves_icall_System_Reflection_Module_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error, MonoError *error)
6061 {
6062         error_init (error);
6063         int table = mono_metadata_token_table (token);
6064         int idx = mono_metadata_token_index (token);
6065         MonoTableInfo *tables = image->tables;
6066         guint32 sig, len;
6067         const char *ptr;
6068
6069         *resolve_error = ResolveTokenError_OutOfRange;
6070
6071         /* FIXME: Support other tables ? */
6072         if (table != MONO_TABLE_STANDALONESIG)
6073                 return MONO_HANDLE_CAST (MonoArray, NULL);
6074
6075         if (image_is_dynamic (image))
6076                 return MONO_HANDLE_CAST (MonoArray, NULL);
6077
6078         if ((idx == 0) || (idx > tables [MONO_TABLE_STANDALONESIG].rows))
6079                 return MONO_HANDLE_CAST (MonoArray, NULL);
6080
6081         sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
6082
6083         ptr = mono_metadata_blob_heap (image, sig);
6084         len = mono_metadata_decode_blob_size (ptr, &ptr);
6085
6086         MonoArrayHandle res = mono_array_new_handle (mono_domain_get (), mono_defaults.byte_class, len, error);
6087         if (!is_ok (error))
6088                 return MONO_HANDLE_CAST (MonoArray, NULL);
6089         uint32_t h;
6090         gpointer array_base = MONO_ARRAY_HANDLE_PIN (res, guint8, 0, &h);
6091         memcpy (array_base, ptr, len);
6092         mono_gchandle_free (h);
6093         return res;
6094 }
6095
6096 ICALL_EXPORT MonoBoolean
6097 ves_icall_RuntimeTypeHandle_IsArray (MonoReflectionTypeHandle ref_type, MonoError *error)
6098 {
6099         error_init (error);
6100         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6101
6102         MonoBoolean res = !type->byref && (type->type == MONO_TYPE_ARRAY || type->type == MONO_TYPE_SZARRAY);
6103
6104         return res;
6105 }
6106
6107 static void
6108 check_for_invalid_type (MonoClass *klass, MonoError *error)
6109 {
6110         char *name;
6111
6112         error_init (error);
6113
6114         if (klass->byval_arg.type != MONO_TYPE_TYPEDBYREF)
6115                 return;
6116
6117         name = mono_type_get_full_name (klass);
6118         mono_error_set_type_load_name (error, name, g_strdup (""), "");
6119 }
6120
6121 ICALL_EXPORT MonoReflectionTypeHandle
6122 ves_icall_RuntimeType_make_array_type (MonoReflectionTypeHandle ref_type, int rank, MonoError *error)
6123 {
6124         error_init (error);
6125         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6126
6127         MonoClass *klass = mono_class_from_mono_type (type);
6128         check_for_invalid_type (klass, error);
6129         if (!is_ok (error))
6130                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6131
6132         MonoClass *aklass;
6133         if (rank == 0) //single dimentional array
6134                 aklass = mono_array_class_get (klass, 1);
6135         else
6136                 aklass = mono_bounded_array_class_get (klass, rank, TRUE);
6137
6138         if (mono_class_has_failure (aklass)) {
6139                 mono_error_set_for_class_failure (error, aklass);
6140                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6141         }
6142
6143         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6144         return mono_type_get_object_handle (domain, &aklass->byval_arg, error);
6145 }
6146
6147 ICALL_EXPORT MonoReflectionTypeHandle
6148 ves_icall_RuntimeType_make_byref_type (MonoReflectionTypeHandle ref_type, MonoError *error)
6149 {
6150         error_init (error);
6151         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6152
6153         MonoClass *klass = mono_class_from_mono_type (type);
6154         mono_class_init_checked (klass, error);
6155         if (!is_ok (error))
6156                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6157
6158         check_for_invalid_type (klass, error);
6159         if (!is_ok (error))
6160                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6161
6162         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6163         return mono_type_get_object_handle (domain, &klass->this_arg, error);
6164 }
6165
6166 ICALL_EXPORT MonoReflectionTypeHandle
6167 ves_icall_RuntimeType_MakePointerType (MonoReflectionTypeHandle ref_type, MonoError *error)
6168 {
6169         error_init (error);
6170         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
6171         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6172         MonoClass *klass = mono_class_from_mono_type (type);
6173         mono_class_init_checked (klass, error);
6174         if (!is_ok (error))
6175                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6176
6177         check_for_invalid_type (klass, error);
6178         if (!is_ok (error))
6179                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
6180
6181         MonoClass *pklass = mono_ptr_class_get (type);
6182
6183         return mono_type_get_object_handle (domain, &pklass->byval_arg, error);
6184 }
6185
6186 ICALL_EXPORT MonoObjectHandle
6187 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionTypeHandle ref_type, MonoObjectHandle target,
6188                                                    MonoReflectionMethodHandle info, MonoBoolean throwOnBindFailure, MonoError *error)
6189 {
6190         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
6191         MonoClass *delegate_class = mono_class_from_mono_type (type);
6192         gpointer func;
6193         MonoMethod *method = MONO_HANDLE_GETVAL (info, method);
6194         MonoMethodSignature *sig = mono_method_signature(method);
6195
6196         mono_class_init_checked (delegate_class, error);
6197         return_val_if_nok (error, NULL_HANDLE);
6198
6199         if (!(delegate_class->parent == mono_defaults.multicastdelegate_class)) {
6200                 /* FIXME improve this exception message */
6201                 mono_error_set_execution_engine (error, "file %s: line %d (%s): assertion failed: (%s)", __FILE__, __LINE__,
6202                                                  __func__,
6203                                                  "delegate_class->parent == mono_defaults.multicastdelegate_class");
6204                 return NULL_HANDLE;
6205         }
6206
6207         if (mono_security_core_clr_enabled ()) {
6208                 MonoError security_error;
6209                 if (!mono_security_core_clr_ensure_delegate_creation (method, &security_error)) {
6210                         if (throwOnBindFailure)
6211                                 mono_error_move (error, &security_error);
6212                         else
6213                                 mono_error_cleanup (&security_error);
6214                         return NULL_HANDLE;
6215                 }
6216         }
6217
6218         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
6219                 if (!method->is_inflated) {
6220                         mono_error_set_argument (error, "method", " Cannot bind to the target method because its signature differs from that of the delegate type");
6221                         return NULL_HANDLE;
6222                 }
6223         }
6224
6225         MonoObjectHandle delegate = MONO_HANDLE_NEW (MonoObject, mono_object_new_checked (MONO_HANDLE_DOMAIN (ref_type), delegate_class, error));
6226         return_val_if_nok (error, NULL_HANDLE);
6227
6228         if (method_is_dynamic (method)) {
6229                 /* Creating a trampoline would leak memory */
6230                 func = mono_compile_method_checked (method, error);
6231                 return_val_if_nok (error, NULL_HANDLE);
6232         } else {
6233                 if (!MONO_HANDLE_IS_NULL (target) && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass != mono_handle_class (target)) {
6234                         method = mono_object_handle_get_virtual_method (target, method, error);
6235                         return_val_if_nok (error, NULL_HANDLE);
6236                 }
6237                 gpointer trampoline = mono_runtime_create_jump_trampoline (mono_domain_get (), method, TRUE, error);
6238                 return_val_if_nok (error, NULL_HANDLE);
6239                 func = mono_create_ftnptr (mono_domain_get (), trampoline);
6240         }
6241
6242         mono_delegate_ctor_with_method (delegate, target, func, method, error);
6243         return_val_if_nok (error, NULL_HANDLE);
6244         return delegate;
6245 }
6246
6247 ICALL_EXPORT MonoMulticastDelegateHandle
6248 ves_icall_System_Delegate_AllocDelegateLike_internal (MonoDelegateHandle delegate, MonoError *error)
6249 {
6250         error_init (error);
6251
6252         MonoClass *klass = mono_handle_class (delegate);
6253         g_assert (mono_class_has_parent (klass, mono_defaults.multicastdelegate_class));
6254
6255         MonoMulticastDelegateHandle ret = MONO_HANDLE_NEW (MonoMulticastDelegate,  mono_object_new_checked (MONO_HANDLE_DOMAIN (delegate), klass, error));
6256         return_val_if_nok (error, MONO_HANDLE_CAST (MonoMulticastDelegate, NULL_HANDLE));
6257
6258         MONO_HANDLE_SETVAL (MONO_HANDLE_CAST (MonoDelegate, ret), invoke_impl, gpointer, mono_runtime_create_delegate_trampoline (klass));
6259
6260         return ret;
6261 }
6262
6263 ICALL_EXPORT MonoReflectionMethodHandle
6264 ves_icall_System_Delegate_GetVirtualMethod_internal (MonoDelegateHandle delegate, MonoError *error)
6265 {
6266         error_init (error);
6267
6268         MonoObjectHandle delegate_target = MONO_HANDLE_NEW_GET (MonoObject, delegate, target);
6269         MonoMethod *m = mono_object_handle_get_virtual_method (delegate_target, MONO_HANDLE_GETVAL (delegate, method), error);
6270         return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
6271         return mono_method_get_object_handle (mono_domain_get (), m, m->klass, error);
6272 }
6273
6274 /* System.Buffer */
6275
6276 static inline gint32 
6277 mono_array_get_byte_length (MonoArray *array)
6278 {
6279         MonoClass *klass;
6280         int length;
6281         int i;
6282
6283         klass = array->obj.vtable->klass;
6284
6285         if (array->bounds == NULL)
6286                 length = array->max_length;
6287         else {
6288                 length = 1;
6289                 for (i = 0; i < klass->rank; ++ i)
6290                         length *= array->bounds [i].length;
6291         }
6292
6293         switch (klass->element_class->byval_arg.type) {
6294         case MONO_TYPE_I1:
6295         case MONO_TYPE_U1:
6296         case MONO_TYPE_BOOLEAN:
6297                 return length;
6298         case MONO_TYPE_I2:
6299         case MONO_TYPE_U2:
6300         case MONO_TYPE_CHAR:
6301                 return length << 1;
6302         case MONO_TYPE_I4:
6303         case MONO_TYPE_U4:
6304         case MONO_TYPE_R4:
6305                 return length << 2;
6306         case MONO_TYPE_I:
6307         case MONO_TYPE_U:
6308                 return length * sizeof (gpointer);
6309         case MONO_TYPE_I8:
6310         case MONO_TYPE_U8:
6311         case MONO_TYPE_R8:
6312                 return length << 3;
6313         default:
6314                 return -1;
6315         }
6316 }
6317
6318 ICALL_EXPORT gint32 
6319 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array) 
6320 {
6321         return mono_array_get_byte_length (array);
6322 }
6323
6324 ICALL_EXPORT gint8 
6325 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx) 
6326 {
6327         return mono_array_get (array, gint8, idx);
6328 }
6329
6330 ICALL_EXPORT void 
6331 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value) 
6332 {
6333         mono_array_set (array, gint8, idx, value);
6334 }
6335
6336 ICALL_EXPORT MonoBoolean
6337 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count) 
6338 {
6339         guint8 *src_buf, *dest_buf;
6340
6341         if (count < 0) {
6342                 mono_set_pending_exception (mono_get_exception_argument ("count", "is negative"));
6343                 return FALSE;
6344         }
6345
6346         g_assert (count >= 0);
6347
6348         /* This is called directly from the class libraries without going through the managed wrapper */
6349         MONO_CHECK_ARG_NULL (src, FALSE);
6350         MONO_CHECK_ARG_NULL (dest, FALSE);
6351
6352         /* watch out for integer overflow */
6353         if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
6354                 return FALSE;
6355
6356         src_buf = (guint8 *)src->vector + src_offset;
6357         dest_buf = (guint8 *)dest->vector + dest_offset;
6358
6359         if (src != dest)
6360                 memcpy (dest_buf, src_buf, count);
6361         else
6362                 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
6363
6364         return TRUE;
6365 }
6366
6367 #ifndef DISABLE_REMOTING
6368 ICALL_EXPORT MonoObjectHandle
6369 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObjectHandle this_obj, MonoStringHandle class_name, MonoError *error)
6370 {
6371         error_init (error);
6372         MonoDomain *domain = MONO_HANDLE_DOMAIN (this_obj);
6373         MonoRealProxyHandle rp = MONO_HANDLE_CAST (MonoRealProxy, this_obj);
6374
6375         MonoObjectHandle res = MONO_HANDLE_NEW (MonoObject, mono_object_new_checked (domain, mono_defaults.transparent_proxy_class, error));
6376         if (!is_ok (error))
6377                 return NULL_HANDLE;
6378
6379         MonoTransparentProxyHandle tp = MONO_HANDLE_CAST (MonoTransparentProxy, res);
6380         
6381         MONO_HANDLE_SET (tp, rp, rp);
6382
6383         MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
6384         MONO_HANDLE_GET (reftype, rp, class_to_proxy);
6385         MonoType *type = MONO_HANDLE_GETVAL (reftype, type);
6386         MonoClass *klass = mono_class_from_mono_type (type);
6387
6388         // mono_remote_class_vtable cannot handle errors well, so force any loading error to occur early
6389         mono_class_setup_vtable (klass);
6390         if (mono_class_has_failure (klass)) {
6391                 mono_error_set_for_class_failure (error, klass);
6392                 return NULL_HANDLE;
6393         }
6394
6395         MonoObjectHandle remoting_obj = mono_object_handle_isinst (this_obj, mono_defaults.iremotingtypeinfo_class, error);
6396         if (!is_ok (error))
6397                 return NULL_HANDLE;
6398         MONO_HANDLE_SETVAL (tp, custom_type_info, MonoBoolean, !MONO_HANDLE_IS_NULL (remoting_obj));
6399
6400         MonoRemoteClass *remote_class = mono_remote_class (domain, class_name, klass, error);
6401         if (!is_ok (error))
6402                 return NULL_HANDLE;
6403         MONO_HANDLE_SETVAL (tp, remote_class, MonoRemoteClass*, remote_class);
6404
6405         MONO_HANDLE_SETVAL (res, vtable, MonoVTable*, mono_remote_class_vtable (domain, remote_class, rp, error));
6406         if (!is_ok (error))
6407                 return NULL_HANDLE;
6408         return res;
6409 }
6410
6411 ICALL_EXPORT MonoReflectionType *
6412 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
6413 {
6414         MonoError error;
6415         g_assert (tp != NULL && mono_object_class (tp) == mono_defaults.transparent_proxy_class);
6416         g_assert (tp->remote_class != NULL && tp->remote_class->proxy_class != NULL);
6417         MonoReflectionType *ret = mono_type_get_object_checked (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg, &error);
6418         mono_error_set_pending_exception (&error);
6419
6420         return ret;
6421 }
6422 #endif
6423
6424 /* System.Environment */
6425
6426 MonoStringHandle
6427 ves_icall_System_Environment_get_UserName (MonoError *error)
6428 {
6429         error_init (error);
6430         /* using glib is more portable */
6431         return mono_string_new_handle (mono_domain_get (), g_get_user_name (), error);
6432 }
6433
6434 #ifndef HOST_WIN32
6435 static MonoStringHandle
6436 mono_icall_get_machine_name (MonoError *error)
6437 {
6438         error_init (error);
6439 #if !defined(DISABLE_SOCKETS)
6440         MonoStringHandle result;
6441         char *buf;
6442         int n;
6443 #if defined _SC_HOST_NAME_MAX
6444         n = sysconf (_SC_HOST_NAME_MAX);
6445         if (n == -1)
6446 #endif
6447         n = 512;
6448         buf = g_malloc (n+1);
6449         
6450         if (gethostname (buf, n) == 0){
6451                 buf [n] = 0;
6452                 result = mono_string_new_handle (mono_domain_get (), buf, error);
6453         } else
6454                 result = MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
6455         g_free (buf);
6456         
6457         return result;
6458 #else
6459         return mono_string_new_handle (mono_domain_get (), "mono", error);
6460 #endif
6461 }
6462 #endif /* !HOST_WIN32 */
6463
6464 ICALL_EXPORT MonoStringHandle
6465 ves_icall_System_Environment_get_MachineName (MonoError *error)
6466 {
6467         error_init (error);
6468         return mono_icall_get_machine_name (error);
6469 }
6470
6471 #ifndef HOST_WIN32
6472 static inline int
6473 mono_icall_get_platform (void)
6474 {
6475 #if defined(__MACH__)
6476         /* OSX */
6477         //
6478         // Notice that the value is hidden from user code, and only exposed
6479         // to mscorlib.   This is due to Mono's Unix/MacOS code predating the
6480         // define and making assumptions based on Unix/128/4 values before there
6481         // was a MacOS define.    Lots of code would assume that not-Unix meant
6482         // Windows, but in this case, it would be OSX. 
6483         //
6484         return 6;
6485 #else
6486         /* Unix */
6487         return 4;
6488 #endif
6489 }
6490 #endif /* !HOST_WIN32 */
6491
6492 ICALL_EXPORT int
6493 ves_icall_System_Environment_get_Platform (void)
6494 {
6495         return mono_icall_get_platform ();
6496 }
6497
6498 #ifndef HOST_WIN32
6499 static inline MonoStringHandle
6500 mono_icall_get_new_line (MonoError *error)
6501 {
6502         error_init (error);
6503         return mono_string_new_handle (mono_domain_get (), "\n", error);
6504 }
6505 #endif /* !HOST_WIN32 */
6506
6507 ICALL_EXPORT MonoStringHandle
6508 ves_icall_System_Environment_get_NewLine (MonoError *error)
6509 {
6510         return mono_icall_get_new_line (error);
6511 }
6512
6513 #ifndef HOST_WIN32
6514 static inline MonoBoolean
6515 mono_icall_is_64bit_os (void)
6516 {
6517 #if SIZEOF_VOID_P == 8
6518         return TRUE;
6519 #else
6520 #if defined(HAVE_SYS_UTSNAME_H)
6521         struct utsname name;
6522
6523         if (uname (&name) >= 0) {
6524                 return strcmp (name.machine, "x86_64") == 0 || strncmp (name.machine, "aarch64", 7) == 0 || strncmp (name.machine, "ppc64", 5) == 0;
6525         }
6526 #endif
6527         return FALSE;
6528 #endif
6529 }
6530 #endif /* !HOST_WIN32 */
6531
6532 ICALL_EXPORT MonoBoolean
6533 ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
6534 {
6535         return mono_icall_is_64bit_os ();
6536 }
6537
6538 ICALL_EXPORT MonoStringHandle
6539 ves_icall_System_Environment_GetEnvironmentVariable_native (const gchar *utf8_name, MonoError *error)
6540 {
6541         gchar *value;
6542
6543         if (utf8_name == NULL)
6544                 return NULL_HANDLE_STRING;
6545
6546         value = g_getenv (utf8_name);
6547
6548         if (value == 0)
6549                 return NULL_HANDLE_STRING;
6550         
6551         MonoStringHandle res = mono_string_new_handle (mono_domain_get (), value, error);
6552         g_free (value);
6553         return res;
6554 }
6555
6556 /*
6557  * There is no standard way to get at environ.
6558  */
6559 #ifndef _MSC_VER
6560 #ifndef __MINGW32_VERSION
6561 #if defined(__APPLE__)
6562 #if defined (TARGET_OSX)
6563 /* Apple defines this in crt_externs.h but doesn't provide that header for 
6564  * arm-apple-darwin9.  We'll manually define the symbol on Apple as it does
6565  * in fact exist on all implementations (so far) 
6566  */
6567 gchar ***_NSGetEnviron(void);
6568 #define environ (*_NSGetEnviron())
6569 #else
6570 static char *mono_environ[1] = { NULL };
6571 #define environ mono_environ
6572 #endif /* defined (TARGET_OSX) */
6573 #else
6574 extern
6575 char **environ;
6576 #endif
6577 #endif
6578 #endif
6579
6580 ICALL_EXPORT MonoArray *
6581 ves_icall_System_Environment_GetCommandLineArgs (void)
6582 {
6583         MonoError error;
6584         MonoArray *result = mono_runtime_get_main_args_checked (&error);
6585         mono_error_set_pending_exception (&error);
6586         return result;
6587 }
6588
6589 #ifndef HOST_WIN32
6590 static MonoArray *
6591 mono_icall_get_environment_variable_names (MonoError *error)
6592 {
6593         MonoArray *names;
6594         MonoDomain *domain;
6595         MonoString *str;
6596         gchar **e, **parts;
6597         int n;
6598
6599         error_init (error);
6600         n = 0;
6601         for (e = environ; *e != 0; ++ e)
6602                 ++ n;
6603
6604         domain = mono_domain_get ();
6605         names = mono_array_new_checked (domain, mono_defaults.string_class, n, error);
6606         return_val_if_nok (error, NULL);
6607
6608         n = 0;
6609         for (e = environ; *e != 0; ++ e) {
6610                 parts = g_strsplit (*e, "=", 2);
6611                 if (*parts != 0) {
6612                         str = mono_string_new_checked (domain, *parts, error);
6613                         if (!is_ok (error)) {
6614                                 g_strfreev (parts);
6615                                 return NULL;
6616                         }
6617                         mono_array_setref (names, n, str);
6618                 }
6619
6620                 g_strfreev (parts);
6621
6622                 ++ n;
6623         }
6624
6625         return names;
6626 }
6627 #endif /* !HOST_WIN32 */
6628
6629 ICALL_EXPORT MonoArray *
6630 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
6631 {
6632         MonoError error;
6633         MonoArray *result = mono_icall_get_environment_variable_names (&error);
6634         mono_error_set_pending_exception (&error);
6635         return result;
6636 }
6637
6638 #ifndef HOST_WIN32
6639 static void
6640 mono_icall_set_environment_variable (MonoString *name, MonoString *value)
6641 {
6642         gchar *utf8_name, *utf8_value;
6643         MonoError error;
6644
6645         utf8_name = mono_string_to_utf8_checked (name, &error); /* FIXME: this should be ascii */
6646         if (mono_error_set_pending_exception (&error))
6647                 return;
6648
6649         if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
6650                 g_unsetenv (utf8_name);
6651                 g_free (utf8_name);
6652                 return;
6653         }
6654
6655         utf8_value = mono_string_to_utf8_checked (value, &error);
6656         if (!mono_error_ok (&error)) {
6657                 g_free (utf8_name);
6658                 mono_error_set_pending_exception (&error);
6659                 return;
6660         }
6661         g_setenv (utf8_name, utf8_value, TRUE);
6662
6663         g_free (utf8_name);
6664         g_free (utf8_value);
6665 }
6666 #endif /* !HOST_WIN32 */
6667
6668 ICALL_EXPORT void
6669 ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
6670 {
6671         mono_icall_set_environment_variable (name, value);
6672 }
6673
6674 ICALL_EXPORT void
6675 ves_icall_System_Environment_Exit (int result)
6676 {
6677         mono_environment_exitcode_set (result);
6678
6679 /* FIXME: There are some cleanup hangs that should be worked out, but
6680  * if the program is going to exit, everything will be cleaned up when
6681  * NaCl exits anyway.
6682  */
6683 #ifndef __native_client__
6684         if (!mono_runtime_try_shutdown ())
6685                 mono_thread_exit ();
6686
6687         /* Suspend all managed threads since the runtime is going away */
6688         mono_thread_suspend_all_other_threads ();
6689
6690         mono_runtime_quit ();
6691 #endif
6692
6693         /* we may need to do some cleanup here... */
6694         exit (result);
6695 }
6696
6697 ICALL_EXPORT MonoStringHandle
6698 ves_icall_System_Environment_GetGacPath (MonoError *error)
6699 {
6700         return mono_string_new_handle (mono_domain_get (), mono_assembly_getrootdir (), error);
6701 }
6702
6703 #ifndef HOST_WIN32
6704 static inline MonoStringHandle
6705 mono_icall_get_windows_folder_path (int folder, MonoError *error)
6706 {
6707         error_init (error);
6708         g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
6709         return mono_string_new_handle (mono_domain_get (), "", error);
6710 }
6711 #endif /* !HOST_WIN32 */
6712
6713 ICALL_EXPORT MonoStringHandle
6714 ves_icall_System_Environment_GetWindowsFolderPath (int folder, MonoError *error)
6715 {
6716         return mono_icall_get_windows_folder_path (folder, error);
6717 }
6718
6719 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
6720 static MonoArray *
6721 mono_icall_get_logical_drives (void)
6722 {
6723         MonoError error;
6724         gunichar2 buf [256], *ptr, *dname;
6725         gunichar2 *u16;
6726         guint initial_size = 127, size = 128;
6727         gint ndrives;
6728         MonoArray *result;
6729         MonoString *drivestr;
6730         MonoDomain *domain = mono_domain_get ();
6731         gint len;
6732
6733         buf [0] = '\0';
6734         ptr = buf;
6735
6736         while (size > initial_size) {
6737                 size = (guint) mono_w32file_get_logical_drive (initial_size, ptr);
6738                 if (size > initial_size) {
6739                         if (ptr != buf)
6740                                 g_free (ptr);
6741                         ptr = (gunichar2 *)g_malloc0 ((size + 1) * sizeof (gunichar2));
6742                         initial_size = size;
6743                         size++;
6744                 }
6745         }
6746
6747         /* Count strings */
6748         dname = ptr;
6749         ndrives = 0;
6750         do {
6751                 while (*dname++);
6752                 ndrives++;
6753         } while (*dname);
6754
6755         dname = ptr;
6756         result = mono_array_new_checked (domain, mono_defaults.string_class, ndrives, &error);
6757         if (mono_error_set_pending_exception (&error))
6758                 goto leave;
6759
6760         ndrives = 0;
6761         do {
6762                 len = 0;
6763                 u16 = dname;
6764                 while (*u16) { u16++; len ++; }
6765                 drivestr = mono_string_new_utf16_checked (domain, dname, len, &error);
6766                 if (mono_error_set_pending_exception (&error))
6767                         goto leave;
6768
6769                 mono_array_setref (result, ndrives++, drivestr);
6770                 while (*dname++);
6771         } while (*dname);
6772
6773 leave:
6774         if (ptr != buf)
6775                 g_free (ptr);
6776
6777         return result;
6778 }
6779 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
6780
6781 ICALL_EXPORT MonoArray *
6782 ves_icall_System_Environment_GetLogicalDrives (void)
6783 {
6784         return mono_icall_get_logical_drives ();
6785 }
6786
6787 ICALL_EXPORT MonoString *
6788 ves_icall_System_IO_DriveInfo_GetDriveFormat (MonoString *path)
6789 {
6790         MonoError error;
6791         gunichar2 volume_name [MAX_PATH + 1];
6792         
6793         if (mono_w32file_get_volume_information (mono_string_chars (path), NULL, 0, NULL, NULL, NULL, volume_name, MAX_PATH + 1) == FALSE)
6794                 return NULL;
6795         MonoString *result = mono_string_from_utf16_checked (volume_name, &error);
6796         mono_error_set_pending_exception (&error);
6797         return result;
6798 }
6799
6800 ICALL_EXPORT MonoStringHandle
6801 ves_icall_System_Environment_InternalGetHome (MonoError *error)
6802 {
6803         return mono_string_new_handle (mono_domain_get (), g_get_home_dir (), error);
6804 }
6805
6806 static const char *encodings [] = {
6807         (char *) 1,
6808                 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
6809                 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
6810                 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
6811         (char *) 2,
6812                 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
6813                 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
6814                 "x_unicode_2_0_utf_7",
6815         (char *) 3,
6816                 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
6817                 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
6818         (char *) 4,
6819                 "utf_16", "UTF_16LE", "ucs_2", "unicode",
6820                 "iso_10646_ucs2",
6821         (char *) 5,
6822                 "unicodefffe", "utf_16be",
6823         (char *) 6,
6824                 "iso_8859_1",
6825         (char *) 0
6826 };
6827
6828 /*
6829  * Returns the internal codepage, if the value of "int_code_page" is
6830  * 1 at entry, and we can not compute a suitable code page number,
6831  * returns the code page as a string
6832  */
6833 ICALL_EXPORT MonoStringHandle
6834 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page, MonoError *error)
6835 {
6836         error_init (error);
6837         const char *cset;
6838         const char *p;
6839         char *c;
6840         char *codepage = NULL;
6841         int code;
6842         int want_name = *int_code_page;
6843         int i;
6844         
6845         *int_code_page = -1;
6846
6847         g_get_charset (&cset);
6848         c = codepage = g_strdup (cset);
6849         for (c = codepage; *c; c++){
6850                 if (isascii (*c) && isalpha (*c))
6851                         *c = tolower (*c);
6852                 if (*c == '-')
6853                         *c = '_';
6854         }
6855         /* g_print ("charset: %s\n", cset); */
6856         
6857         /* handle some common aliases */
6858         p = encodings [0];
6859         code = 0;
6860         for (i = 0; p != 0; ){
6861                 if ((gsize) p < 7){
6862                         code = (gssize) p;
6863                         p = encodings [++i];
6864                         continue;
6865                 }
6866                 if (strcmp (p, codepage) == 0){
6867                         *int_code_page = code;
6868                         break;
6869                 }
6870                 p = encodings [++i];
6871         }
6872         
6873         if (strstr (codepage, "utf_8") != NULL)
6874                 *int_code_page |= 0x10000000;
6875         g_free (codepage);
6876         
6877         if (want_name && *int_code_page == -1)
6878                 return mono_string_new_handle (mono_domain_get (), cset, error);
6879         else
6880                 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
6881 }
6882
6883 ICALL_EXPORT MonoBoolean
6884 ves_icall_System_Environment_get_HasShutdownStarted (void)
6885 {
6886         if (mono_runtime_is_shutting_down ())
6887                 return TRUE;
6888
6889         if (mono_domain_is_unloading (mono_domain_get ()))
6890                 return TRUE;
6891
6892         return FALSE;
6893 }
6894
6895 #ifndef HOST_WIN32
6896 static inline MonoBoolean
6897 mono_icall_broadcast_setting_change (MonoError *error)
6898 {
6899         error_init (error);
6900         return TRUE;
6901 }
6902 #endif /* !HOST_WIN32 */
6903
6904 ICALL_EXPORT void
6905 ves_icall_System_Environment_BroadcastSettingChange (MonoError *error)
6906 {
6907         error_init (error);
6908         mono_icall_broadcast_setting_change (error);
6909 }
6910
6911 ICALL_EXPORT
6912 gint32
6913 ves_icall_System_Environment_get_TickCount (void)
6914 {
6915         /* this will overflow after ~24 days */
6916         return (gint32) (mono_msec_boottime () & 0xffffffff);
6917 }
6918
6919 ICALL_EXPORT gint32
6920 ves_icall_System_Runtime_Versioning_VersioningHelper_GetRuntimeId (void)
6921 {
6922         return 9;
6923 }
6924
6925 #ifndef DISABLE_REMOTING
6926 ICALL_EXPORT MonoBoolean
6927 ves_icall_IsTransparentProxy (MonoObjectHandle proxy, MonoError *error)
6928 {
6929         error_init (error);
6930         if (MONO_HANDLE_IS_NULL (proxy))
6931                 return 0;
6932
6933         if (mono_class_is_transparent_proxy (mono_handle_class (proxy)))
6934                 return 1;
6935
6936         return 0;
6937 }
6938
6939 ICALL_EXPORT MonoReflectionMethodHandle
6940 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
6941         MonoReflectionTypeHandle rtype, MonoReflectionMethodHandle rmethod, MonoError *error)
6942 {
6943         MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE);
6944
6945         error_init (error);
6946         if (MONO_HANDLE_IS_NULL (rtype)) {
6947                 mono_error_set_argument_null (error, "type", "");
6948                 return ret;
6949         }
6950         if (MONO_HANDLE_IS_NULL (rmethod)) {
6951                 mono_error_set_argument_null (error, "method", "");
6952                 return ret;
6953         }
6954
6955         MonoMethod *method = MONO_HANDLE_GETVAL (rmethod, method);
6956         MonoType *type = MONO_HANDLE_GETVAL (rtype, type);
6957         MonoClass *klass = mono_class_from_mono_type (type);
6958         mono_class_init_checked (klass, error);
6959         return_val_if_nok (error, ret);
6960
6961         if (MONO_CLASS_IS_INTERFACE (klass))
6962                 return ret;
6963
6964         if (method->flags & METHOD_ATTRIBUTE_STATIC)
6965                 return ret;
6966
6967         if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6968                 if (klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE))
6969                         ret = rmethod;
6970                 return ret;
6971         }
6972
6973         mono_class_setup_vtable (klass);
6974         MonoMethod **vtable = klass->vtable;
6975
6976         MonoMethod *res = NULL;
6977         if (mono_class_is_interface (method->klass)) {
6978                 gboolean variance_used = FALSE;
6979                 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
6980                 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
6981                 if (offs >= 0)
6982                         res = vtable [offs + method->slot];
6983         } else {
6984                 if (!(klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE)))
6985                         return ret;
6986
6987                 if (method->slot != -1)
6988                         res = vtable [method->slot];
6989         }
6990
6991         if (!res)
6992                 return ret;
6993
6994         ret = mono_method_get_object_handle (mono_domain_get (), res, NULL, error);
6995         return ret;
6996 }
6997
6998 ICALL_EXPORT void
6999 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
7000 {
7001         error_init (error);
7002
7003         MonoClass *klass = mono_class_from_mono_type (MONO_HANDLE_GETVAL (type, type));
7004         MonoVTable *vtable = mono_class_vtable_full (mono_domain_get (), klass, error);
7005         return_if_nok (error);
7006
7007         mono_vtable_set_is_remote (vtable, enable);
7008 }
7009
7010 #else /* DISABLE_REMOTING */
7011
7012 ICALL_EXPORT void
7013 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionTypeHandle type, MonoBoolean enable, MonoError *error)
7014 {
7015         error_init (error);
7016         g_assert_not_reached ();
7017 }
7018
7019 #endif
7020
7021 ICALL_EXPORT MonoObjectHandle
7022 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionTypeHandle type, MonoError *error)
7023 {
7024         error_init (error);
7025         
7026         MonoDomain *domain = MONO_HANDLE_DOMAIN (type);
7027         MonoClass *klass = mono_class_from_mono_type (MONO_HANDLE_GETVAL (type, type));
7028         mono_class_init_checked (klass, error);
7029         return_val_if_nok (error, NULL_HANDLE);
7030
7031         if (MONO_CLASS_IS_INTERFACE (klass) || mono_class_is_abstract (klass)) {
7032                 mono_error_set_argument (error, "type", "Type cannot be instantiated");
7033                 return NULL_HANDLE;
7034         }
7035
7036         if (klass->rank >= 1) {
7037                 g_assert (klass->rank == 1);
7038                 return MONO_HANDLE_CAST (MonoObject, mono_array_new_handle (domain, klass->element_class, 0, error));
7039         } else {
7040                 MonoVTable *vtable = mono_class_vtable_full (domain, klass, error);
7041                 return_val_if_nok (error, NULL_HANDLE);
7042
7043                 /* Bypass remoting object creation check */
7044                 return MONO_HANDLE_NEW (MonoObject, mono_object_new_alloc_specific_checked (vtable, error));
7045         }
7046 }
7047
7048 ICALL_EXPORT MonoStringHandle
7049 ves_icall_System_IO_get_temp_path (MonoError *error)
7050 {
7051         return mono_string_new_handle (mono_domain_get (), g_get_tmp_dir (), error);
7052 }
7053
7054 #ifndef PLATFORM_NO_DRIVEINFO
7055 ICALL_EXPORT MonoBoolean
7056 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (MonoString *path_name, guint64 *free_bytes_avail,
7057                                                 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
7058                                                 gint32 *error)
7059 {
7060         gboolean result;
7061
7062         *error = ERROR_SUCCESS;
7063
7064         result = mono_w32file_get_disk_free_space (mono_string_chars (path_name), free_bytes_avail, total_number_of_bytes, total_number_of_free_bytes);
7065         if (!result)
7066                 *error = mono_w32error_get_last ();
7067
7068         return result;
7069 }
7070
7071 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
7072 static inline guint32
7073 mono_icall_drive_info_get_drive_type (MonoString *root_path_name)
7074 {
7075         return mono_w32file_get_drive_type (mono_string_chars (root_path_name));
7076 }
7077 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
7078
7079 ICALL_EXPORT guint32
7080 ves_icall_System_IO_DriveInfo_GetDriveType (MonoString *root_path_name)
7081 {
7082         return mono_icall_drive_info_get_drive_type (root_path_name);
7083 }
7084
7085 #endif /* PLATFORM_NO_DRIVEINFO */
7086
7087 ICALL_EXPORT gpointer
7088 ves_icall_RuntimeMethodHandle_GetFunctionPointer (MonoMethod *method, MonoError *error)
7089 {
7090         error_init (error);
7091         return mono_compile_method_checked (method, error);
7092 }
7093
7094 ICALL_EXPORT MonoStringHandle
7095 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (MonoError *error)
7096 {
7097         error_init (error);
7098         gchar *path;
7099
7100         path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
7101
7102         mono_icall_make_platform_path (path);
7103
7104         MonoStringHandle mcpath = mono_string_new_handle (mono_domain_get (), path, error);
7105         g_free (path);
7106
7107         mono_error_assert_ok (error);
7108
7109         return mcpath;
7110 }
7111
7112 static MonoStringHandle
7113 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_app_config (MonoError *error)
7114 {
7115         error_init (error);
7116         const gchar *app_config;
7117         MonoDomain *domain;
7118         gchar *config_file_name, *config_file_path;
7119         gsize len, config_file_path_length, config_ext_length;
7120         gchar *module;
7121
7122         domain = mono_domain_get ();
7123         MonoStringHandle file = MONO_HANDLE_NEW (MonoString, domain->setup->configuration_file);
7124         if (MONO_HANDLE_IS_NULL (file) || MONO_HANDLE_GETVAL (file, length) == 0)
7125                 return NULL;
7126
7127         // Retrieve config file and remove the extension
7128         config_file_name = mono_string_handle_to_utf8 (file, error);
7129         return_val_if_nok (error, MONO_HANDLE_CAST (MonoString, NULL_HANDLE));
7130
7131         config_file_path = mono_portability_find_file (config_file_name, TRUE);
7132         if (!config_file_path)
7133                 config_file_path = config_file_name;
7134
7135         config_file_path_length = strlen (config_file_path);
7136         config_ext_length = strlen (".config");
7137         if (config_file_path_length <= config_ext_length) {
7138                 if (config_file_name != config_file_path)
7139                         g_free (config_file_name);
7140                 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
7141         }
7142
7143         len = config_file_path_length - config_ext_length;
7144         module = (gchar *)g_malloc0 (len + 1);
7145         memcpy (module, config_file_path, len);
7146         // Get the config file from the module name
7147         app_config = mono_config_string_for_assembly_file (module);
7148         // Clean-up
7149         g_free (module);
7150         if (config_file_name != config_file_path)
7151                 g_free (config_file_name);
7152         g_free (config_file_path);
7153
7154         if (!app_config)
7155                 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
7156
7157         return mono_string_new_handle (mono_domain_get (), app_config, error);
7158 }
7159
7160 static MonoStringHandle
7161 get_bundled_machine_config (MonoError *error)
7162 {
7163         const gchar *machine_config;
7164
7165         machine_config = mono_get_machine_config ();
7166
7167         if (!machine_config)
7168                 return NULL_HANDLE_STRING;
7169
7170         return mono_string_new_handle (mono_domain_get (), machine_config, error);
7171 }
7172
7173 ICALL_EXPORT MonoStringHandle
7174 ves_icall_System_Environment_get_bundled_machine_config (MonoError *error)
7175 {
7176         return get_bundled_machine_config (error);
7177 }
7178
7179
7180 ICALL_EXPORT MonoStringHandle
7181 ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
7182 {
7183         return get_bundled_machine_config (error);
7184 }
7185
7186 ICALL_EXPORT MonoStringHandle
7187 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
7188 {
7189         return get_bundled_machine_config (error);
7190 }
7191
7192
7193 ICALL_EXPORT MonoStringHandle
7194 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (MonoError *error)
7195 {
7196         error_init (error);
7197         gchar *path;
7198
7199         path = g_path_get_dirname (mono_get_config_dir ());
7200
7201         mono_icall_make_platform_path (path);
7202
7203         MonoStringHandle ipath = mono_string_new_handle (mono_domain_get (), path, error);
7204         g_free (path);
7205
7206         return ipath;
7207 }
7208
7209 ICALL_EXPORT gboolean
7210 ves_icall_get_resources_ptr (MonoReflectionAssemblyHandle assembly, gpointer *result, gint32 *size, MonoError *error)
7211 {
7212         error_init (error);
7213         MonoPEResourceDataEntry *entry;
7214         MonoImage *image;
7215
7216         if (!assembly || !result || !size)
7217                 return FALSE;
7218
7219         *result = NULL;
7220         *size = 0;
7221         MonoAssembly *assm = MONO_HANDLE_GETVAL (assembly, assembly);
7222         image = assm->image;
7223         entry = (MonoPEResourceDataEntry *)mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
7224         if (!entry)
7225                 return FALSE;
7226
7227         *result = mono_image_rva_map (image, entry->rde_data_offset);
7228         if (!(*result)) {
7229                 g_free (entry);
7230                 return FALSE;
7231         }
7232         *size = entry->rde_size;
7233         g_free (entry);
7234         return TRUE;
7235 }
7236
7237 ICALL_EXPORT MonoBoolean
7238 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (void)
7239 {
7240         return mono_is_debugger_attached ();
7241 }
7242
7243 ICALL_EXPORT MonoBoolean
7244 ves_icall_System_Diagnostics_Debugger_IsLogging (void)
7245 {
7246         if (mono_get_runtime_callbacks ()->debug_log_is_enabled)
7247                 return mono_get_runtime_callbacks ()->debug_log_is_enabled ();
7248         else
7249                 return FALSE;
7250 }
7251
7252 ICALL_EXPORT void
7253 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoString *category, MonoString *message)
7254 {
7255         if (mono_get_runtime_callbacks ()->debug_log)
7256                 mono_get_runtime_callbacks ()->debug_log (level, category, message);
7257 }
7258
7259 #ifndef HOST_WIN32
7260 static inline void
7261 mono_icall_write_windows_debug_string (MonoString *message)
7262 {
7263         g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
7264 }
7265 #endif /* !HOST_WIN32 */
7266
7267 ICALL_EXPORT void
7268 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
7269 {
7270         mono_icall_write_windows_debug_string (message);
7271 }
7272
7273 /* Only used for value types */
7274 ICALL_EXPORT MonoObjectHandle
7275 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
7276 {
7277         error_init (error);
7278         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
7279         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7280         MonoClass *klass = mono_class_from_mono_type (type);
7281
7282         mono_class_init_checked (klass, error);
7283         if (!is_ok (error))
7284                 return NULL_HANDLE;
7285
7286         if (mono_class_is_nullable (klass))
7287                 /* No arguments -> null */
7288                 return NULL_HANDLE;
7289
7290         return MONO_HANDLE_NEW (MonoObject, mono_object_new_checked (domain, klass, error));
7291 }
7292
7293 ICALL_EXPORT MonoReflectionMethodHandle
7294 ves_icall_MonoMethod_get_base_method (MonoReflectionMethodHandle m, gboolean definition, MonoError *error)
7295 {
7296         error_init (error);
7297         MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
7298
7299         MonoMethod *base = mono_method_get_base_method (method, definition, error);
7300         return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
7301         if (base == method) {
7302                 /* we want to short-circuit and return 'm' here. But we should
7303                    return the same method object that
7304                    mono_method_get_object_handle, below would return.  Since
7305                    that call takes NULL for the reftype argument, it will take
7306                    base->klass as the reflected type for the MonoMethod.  So we
7307                    need to check that m also has base->klass as the reflected
7308                    type. */
7309                 MonoReflectionTypeHandle orig_reftype = MONO_HANDLE_NEW_GET (MonoReflectionType, m, reftype);
7310                 MonoClass *orig_klass = mono_class_from_mono_type (MONO_HANDLE_GETVAL (orig_reftype, type));
7311                 if (base->klass == orig_klass)
7312                         return m;
7313         }
7314         return mono_method_get_object_handle (mono_domain_get (), base, NULL, error);
7315 }
7316
7317 ICALL_EXPORT MonoStringHandle
7318 ves_icall_MonoMethod_get_name (MonoReflectionMethodHandle m, MonoError *error)
7319 {
7320         error_init (error);
7321         MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
7322
7323         MonoStringHandle s = mono_string_new_handle (MONO_HANDLE_DOMAIN (m), method->name, error);
7324         if (!is_ok (error))
7325                 return NULL_HANDLE_STRING;
7326         MONO_HANDLE_SET (m, name, s);
7327         return s;
7328 }
7329
7330 ICALL_EXPORT void
7331 mono_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
7332 {
7333         iter->sig = *(MonoMethodSignature**)argsp;
7334         
7335         g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
7336         g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
7337
7338         iter->next_arg = 0;
7339         /* FIXME: it's not documented what start is exactly... */
7340         if (start) {
7341                 iter->args = start;
7342         } else {
7343                 iter->args = argsp + sizeof (gpointer);
7344         }
7345         iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
7346
7347         /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
7348 }
7349
7350 ICALL_EXPORT MonoTypedRef
7351 mono_ArgIterator_IntGetNextArg (MonoArgIterator *iter)
7352 {
7353         guint32 i, arg_size;
7354         gint32 align;
7355         MonoTypedRef res;
7356
7357         i = iter->sig->sentinelpos + iter->next_arg;
7358
7359         g_assert (i < iter->sig->param_count);
7360
7361         res.type = iter->sig->params [i];
7362         res.klass = mono_class_from_mono_type (res.type);
7363         arg_size = mono_type_stack_size (res.type, &align);
7364 #if defined(__arm__) || defined(__mips__)
7365         iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7366 #endif
7367         res.value = iter->args;
7368 #if defined(__native_client__) && SIZEOF_REGISTER == 8
7369         /* Values are stored as 8 byte register sized objects, but 'value'
7370          * is dereferenced as a pointer in other routines.
7371          */
7372         res.value = (char*)res.value + 4;
7373 #endif
7374 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
7375         if (arg_size <= sizeof (gpointer)) {
7376                 int dummy;
7377                 int padding = arg_size - mono_type_size (res.type, &dummy);
7378                 res.value = (guint8*)res.value + padding;
7379         }
7380 #endif
7381         iter->args = (char*)iter->args + arg_size;
7382         iter->next_arg++;
7383
7384         /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7385
7386         return res;
7387 }
7388
7389 ICALL_EXPORT MonoTypedRef
7390 mono_ArgIterator_IntGetNextArgT (MonoArgIterator *iter, MonoType *type)
7391 {
7392         guint32 i, arg_size;
7393         gint32 align;
7394         MonoTypedRef res;
7395
7396         i = iter->sig->sentinelpos + iter->next_arg;
7397
7398         g_assert (i < iter->sig->param_count);
7399
7400         while (i < iter->sig->param_count) {
7401                 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
7402                         continue;
7403                 res.type = iter->sig->params [i];
7404                 res.klass = mono_class_from_mono_type (res.type);
7405                 /* FIXME: endianess issue... */
7406                 arg_size = mono_type_stack_size (res.type, &align);
7407 #if defined(__arm__) || defined(__mips__)
7408                 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7409 #endif
7410                 res.value = iter->args;
7411                 iter->args = (char*)iter->args + arg_size;
7412                 iter->next_arg++;
7413                 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7414                 return res;
7415         }
7416         /* g_print ("arg type 0x%02x not found\n", res.type->type); */
7417
7418         res.type = NULL;
7419         res.value = NULL;
7420         res.klass = NULL;
7421         return res;
7422 }
7423
7424 ICALL_EXPORT MonoType*
7425 mono_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
7426 {
7427         gint i;
7428         
7429         i = iter->sig->sentinelpos + iter->next_arg;
7430
7431         g_assert (i < iter->sig->param_count);
7432
7433         return iter->sig->params [i];
7434 }
7435
7436 ICALL_EXPORT MonoObject*
7437 mono_TypedReference_ToObject (MonoTypedRef* tref)
7438 {
7439         MonoError error;
7440         MonoObject *result = NULL;
7441         if (MONO_TYPE_IS_REFERENCE (tref->type)) {
7442                 MonoObject** objp = (MonoObject **)tref->value;
7443                 return *objp;
7444         }
7445
7446         result = mono_value_box_checked (mono_domain_get (), tref->klass, tref->value, &error);
7447         mono_error_set_pending_exception (&error);
7448         return result;
7449 }
7450
7451 ICALL_EXPORT MonoTypedRef
7452 mono_TypedReference_MakeTypedReferenceInternal (MonoObject *target, MonoArray *fields)
7453 {
7454         MonoTypedRef res;
7455         MonoReflectionField *f;
7456         MonoClass *klass;
7457         MonoType *ftype = NULL;
7458         guint8 *p = NULL;
7459         int i;
7460
7461         memset (&res, 0, sizeof (res));
7462
7463         g_assert (fields);
7464         g_assert (mono_array_length (fields) > 0);
7465
7466         klass = target->vtable->klass;
7467
7468         for (i = 0; i < mono_array_length (fields); ++i) {
7469                 f = mono_array_get (fields, MonoReflectionField*, i);
7470                 if (f == NULL) {
7471                         mono_set_pending_exception (mono_get_exception_argument_null ("field"));
7472                         return res;
7473                 }
7474                 if (f->field->parent != klass) {
7475                         mono_set_pending_exception (mono_get_exception_argument ("field", ""));
7476                         return res;
7477                 }
7478                 if (i == 0)
7479                         p = (guint8*)target + f->field->offset;
7480                 else
7481                         p += f->field->offset - sizeof (MonoObject);
7482                 klass = mono_class_from_mono_type (f->field->type);
7483                 ftype = f->field->type;
7484         }
7485
7486         res.type = ftype;
7487         res.klass = mono_class_from_mono_type (ftype);
7488         res.value = p;
7489
7490         return res;
7491 }
7492
7493 static void
7494 prelink_method (MonoMethod *method, MonoError *error)
7495 {
7496         const char *exc_class, *exc_arg;
7497
7498         error_init (error);
7499         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7500                 return;
7501         mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7502         if (exc_class) {
7503                 mono_error_set_generic_error (error, "System", exc_class, "%s", exc_arg);
7504                 return;
7505         }
7506         /* create the wrapper, too? */
7507 }
7508
7509 ICALL_EXPORT void
7510 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethodHandle method, MonoError *error)
7511 {
7512         error_init (error);
7513
7514         prelink_method (MONO_HANDLE_GETVAL (method, method), error);
7515 }
7516
7517 ICALL_EXPORT void
7518 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionTypeHandle type, MonoError *error)
7519 {
7520         error_init (error);
7521         MonoClass *klass = mono_class_from_mono_type (MONO_HANDLE_GETVAL (type, type));
7522         MonoMethod* m;
7523         gpointer iter = NULL;
7524
7525         mono_class_init_checked (klass, error);
7526         return_if_nok (error);
7527
7528         while ((m = mono_class_get_methods (klass, &iter))) {
7529                 prelink_method (m, error);
7530                 return_if_nok (error);
7531         }
7532 }
7533
7534 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
7535 ICALL_EXPORT void
7536 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
7537                                             gint32 const **exponents,
7538                                             gunichar2 const **digitLowerTable,
7539                                             gunichar2 const **digitUpperTable,
7540                                             gint64 const **tenPowersList,
7541                                             gint32 const **decHexDigits)
7542 {
7543         *mantissas = Formatter_MantissaBitsTable;
7544         *exponents = Formatter_TensExponentTable;
7545         *digitLowerTable = Formatter_DigitLowerTable;
7546         *digitUpperTable = Formatter_DigitUpperTable;
7547         *tenPowersList = Formatter_TenPowersList;
7548         *decHexDigits = Formatter_DecHexDigits;
7549 }
7550
7551 static gboolean
7552 add_modifier_to_array (MonoDomain *domain, MonoImage *image, MonoCustomMod *modifier, MonoArrayHandle dest, int dest_idx, MonoError *error)
7553 {
7554         HANDLE_FUNCTION_ENTER ();
7555         error_init (error);
7556         MonoClass *klass = mono_class_get_checked (image, modifier->token, error);
7557         if (!is_ok (error))
7558                 goto leave;
7559
7560         MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &klass->byval_arg, error);
7561         if (!is_ok (error))
7562                 goto leave;
7563
7564         MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rt);
7565 leave:
7566         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
7567 }
7568
7569 /*
7570  * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
7571  * and avoid useless allocations.
7572  */
7573 static MonoArrayHandle
7574 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error)
7575 {
7576         int i, count = 0;
7577         MonoDomain *domain = mono_domain_get ();
7578
7579         error_init (error);
7580         for (i = 0; i < type->num_mods; ++i) {
7581                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required))
7582                         count++;
7583         }
7584         if (!count)
7585                 return MONO_HANDLE_NEW (MonoArray, NULL);
7586
7587         MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
7588         if (!is_ok (error))
7589                 goto fail;
7590         count = 0;
7591         for (i = 0; i < type->num_mods; ++i) {
7592                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required)) {
7593                         if (!add_modifier_to_array (domain, image, &type->modifiers[i], res, count , error))
7594                                 goto fail;
7595                         count++;
7596                 }
7597         }
7598         return res;
7599 fail:
7600         return MONO_HANDLE_NEW (MonoArray, NULL);
7601 }
7602
7603 ICALL_EXPORT MonoArrayHandle
7604 ves_icall_ParameterInfo_GetTypeModifiers (MonoReflectionParameterHandle param, MonoBoolean optional, MonoError *error)
7605 {
7606         error_init (error);
7607         MonoReflectionTypeHandle rt = MONO_HANDLE_NEW (MonoReflectionType, NULL);
7608         MONO_HANDLE_GET (rt, param, ClassImpl);
7609         MonoType *type = MONO_HANDLE_GETVAL (rt, type);
7610         MonoObjectHandle member = MONO_HANDLE_NEW (MonoObject, NULL);
7611         MONO_HANDLE_GET (member, param, MemberImpl);
7612         MonoClass *member_class = mono_handle_class (member);
7613         MonoMethod *method = NULL;
7614         MonoImage *image;
7615         int pos;
7616         MonoMethodSignature *sig;
7617
7618         if (mono_class_is_reflection_method_or_constructor (member_class)) {
7619                 method = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionMethod, member), method);
7620         } else if (member_class->image == mono_defaults.corlib && !strcmp ("MonoProperty", member_class->name)) {
7621                 MonoProperty *prop = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionProperty, member), property);
7622                 if (!(method = prop->get))
7623                         method = prop->set;
7624                 g_assert (method);      
7625         } else {
7626                 char *type_name = mono_type_get_full_name (member_class);
7627                 mono_error_set_not_supported (error, "Custom modifiers on a ParamInfo with member %s are not supported", type_name);
7628                 g_free (type_name);
7629                 return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
7630         }
7631
7632         image = method->klass->image;
7633         pos = MONO_HANDLE_GETVAL (param, PositionImpl);
7634         sig = mono_method_signature (method);
7635         if (pos == -1)
7636                 type = sig->ret;
7637         else
7638                 type = sig->params [pos];
7639
7640         return type_array_from_modifiers (image, type, optional, error);
7641 }
7642
7643 static MonoType*
7644 get_property_type (MonoProperty *prop)
7645 {
7646         MonoMethodSignature *sig;
7647         if (prop->get) {
7648                 sig = mono_method_signature (prop->get);
7649                 return sig->ret;
7650         } else if (prop->set) {
7651                 sig = mono_method_signature (prop->set);
7652                 return sig->params [sig->param_count - 1];
7653         }
7654         return NULL;
7655 }
7656
7657 ICALL_EXPORT MonoArrayHandle
7658 ves_icall_MonoPropertyInfo_GetTypeModifiers (MonoReflectionPropertyHandle property, MonoBoolean optional, MonoError *error)
7659 {
7660         error_init (error);
7661         MonoProperty *prop = MONO_HANDLE_GETVAL (property, property);
7662         MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
7663         MonoType *type = get_property_type (prop);
7664         MonoImage *image = klass->image;
7665
7666         if (!type)
7667                 return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
7668         return type_array_from_modifiers (image, type, optional, error);
7669 }
7670
7671 /*
7672  *Construct a MonoType suited to be used to decode a constant blob object.
7673  *
7674  * @type is the target type which will be constructed
7675  * @blob_type is the blob type, for example, that comes from the constant table
7676  * @real_type is the expected constructed type.
7677  */
7678 static void
7679 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
7680 {
7681         type->type = blob_type;
7682         type->data.klass = NULL;
7683         if (blob_type == MONO_TYPE_CLASS)
7684                 type->data.klass = mono_defaults.object_class;
7685         else if (real_type->type == MONO_TYPE_VALUETYPE && real_type->data.klass->enumtype) {
7686                 /* For enums, we need to use the base type */
7687                 type->type = MONO_TYPE_VALUETYPE;
7688                 type->data.klass = mono_class_from_mono_type (real_type);
7689         } else
7690                 type->data.klass = mono_class_from_mono_type (real_type);
7691 }
7692
7693 ICALL_EXPORT MonoObject*
7694 property_info_get_default_value (MonoReflectionProperty *property)
7695 {
7696         MonoError error;
7697         MonoType blob_type;
7698         MonoProperty *prop = property->property;
7699         MonoType *type = get_property_type (prop);
7700         MonoDomain *domain = mono_object_domain (property); 
7701         MonoTypeEnum def_type;
7702         const char *def_value;
7703         MonoObject *o;
7704
7705         mono_class_init (prop->parent);
7706
7707         if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT)) {
7708                 mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
7709                 return NULL;
7710         }
7711
7712         def_value = mono_class_get_property_default_value (prop, &def_type);
7713
7714         mono_type_from_blob_type (&blob_type, def_type, type);
7715         o = mono_get_object_from_blob (domain, &blob_type, def_value, &error);
7716
7717         mono_error_set_pending_exception (&error);
7718         return o;
7719 }
7720
7721 ICALL_EXPORT MonoBoolean
7722 ves_icall_MonoCustomAttrs_IsDefinedInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, MonoError *error)
7723 {
7724         error_init (error);
7725         MonoClass *attr_class = mono_class_from_mono_type (MONO_HANDLE_GETVAL (attr_type, type));
7726
7727         mono_class_init_checked (attr_class, error);
7728         return_val_if_nok (error, FALSE);
7729
7730         MonoCustomAttrInfo *cinfo = mono_reflection_get_custom_attrs_info_checked (obj, error);
7731         return_val_if_nok (error, FALSE);
7732
7733         if (!cinfo)
7734                 return FALSE;
7735         gboolean found = mono_custom_attrs_has_attr (cinfo, attr_class);
7736         if (!cinfo->cached)
7737                 mono_custom_attrs_free (cinfo);
7738         return found;
7739 }
7740
7741 ICALL_EXPORT MonoArrayHandle
7742 ves_icall_MonoCustomAttrs_GetCustomAttributesInternal (MonoObjectHandle obj, MonoReflectionTypeHandle attr_type, mono_bool pseudoattrs, MonoError *error)
7743 {
7744         MonoClass *attr_class;
7745         if (MONO_HANDLE_IS_NULL (attr_type))
7746                 attr_class = NULL;
7747         else
7748                 attr_class = mono_class_from_mono_type (MONO_HANDLE_GETVAL (attr_type, type));
7749
7750         if (attr_class) {
7751                 mono_class_init_checked (attr_class, error);
7752                 if (!is_ok (error))
7753                         return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
7754         }
7755
7756         return mono_reflection_get_custom_attrs_by_type_handle (obj, attr_class, error);
7757 }
7758
7759 ICALL_EXPORT MonoArrayHandle
7760 ves_icall_MonoCustomAttrs_GetCustomAttributesDataInternal (MonoObjectHandle obj, MonoError *error)
7761 {
7762         error_init (error);
7763         return mono_reflection_get_custom_attrs_data_checked (obj, error);
7764 }
7765
7766
7767 ICALL_EXPORT MonoStringHandle
7768 ves_icall_Mono_Runtime_GetDisplayName (MonoError *error)
7769 {
7770         char *info;
7771         MonoStringHandle display_name;
7772
7773         error_init (error);
7774         info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
7775         display_name = mono_string_new_handle (mono_domain_get (), info, error);
7776         g_free (info);
7777         return display_name;
7778 }
7779
7780 #ifndef HOST_WIN32
7781 static inline gint32
7782 mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
7783 {
7784         return WAIT_TIMEOUT;
7785 }
7786 #endif /* !HOST_WIN32 */
7787
7788 ICALL_EXPORT gint32
7789 ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle (gpointer handle, gint32 milliseconds)
7790 {
7791         return mono_icall_wait_for_input_idle (handle, milliseconds);
7792 }
7793
7794 ICALL_EXPORT gint32
7795 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcessId (void)
7796 {
7797         return mono_process_current_pid ();
7798 }
7799
7800 ICALL_EXPORT MonoBoolean
7801 ves_icall_Mono_TlsProviderFactory_IsBtlsSupported (void)
7802 {
7803 #if HAVE_BTLS
7804         return TRUE;
7805 #else
7806         return FALSE;
7807 #endif
7808 }
7809
7810 #ifndef DISABLE_COM
7811
7812 ICALL_EXPORT int
7813 ves_icall_System_Runtime_InteropServices_Marshal_GetHRForException_WinRT(MonoException* ex)
7814 {
7815         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.Marshal.GetHRForException_WinRT internal call is not implemented."));
7816         return 0;
7817 }
7818
7819 ICALL_EXPORT MonoObject*
7820 ves_icall_System_Runtime_InteropServices_Marshal_GetNativeActivationFactory(MonoObject* type)
7821 {
7822         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.Marshal.GetNativeActivationFactory internal call is not implemented."));
7823         return NULL;
7824 }
7825
7826 ICALL_EXPORT void*
7827 ves_icall_System_Runtime_InteropServices_Marshal_GetRawIUnknownForComObjectNoAddRef(MonoObject* obj)
7828 {
7829         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.Marshal.GetRawIUnknownForComObjectNoAddRef internal call is not implemented."));
7830         return NULL;
7831 }
7832
7833 ICALL_EXPORT MonoObject*
7834 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_GetRestrictedErrorInfo()
7835 {
7836         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.GetRestrictedErrorInfo internal call is not implemented."));
7837         return NULL;
7838 }
7839
7840 ICALL_EXPORT MonoBoolean
7841 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoOriginateLanguageException(int error, MonoString* message, void* languageException)
7842 {
7843         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoOriginateLanguageException internal call is not implemented."));
7844         return FALSE;
7845 }
7846
7847 ICALL_EXPORT void
7848 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoReportUnhandledError(MonoObject* error)
7849 {
7850         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoReportUnhandledError internal call is not implemented."));
7851 }
7852
7853 ICALL_EXPORT int
7854 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsCreateString(MonoString* sourceString, int length, void** hstring)
7855 {
7856         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString internal call is not implemented."));
7857         return 0;
7858 }
7859
7860 ICALL_EXPORT int
7861 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsDeleteString(void* hstring)
7862 {
7863         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString internal call is not implemented."));
7864         return 0;
7865 }
7866
7867 ICALL_EXPORT mono_unichar2*
7868 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsGetStringRawBuffer(void* hstring, unsigned* length)
7869 {
7870         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsGetStringRawBuffer internal call is not implemented."));
7871         return NULL;
7872 }
7873
7874 #endif
7875
7876
7877 #ifndef DISABLE_ICALL_TABLES
7878
7879 #define ICALL_TYPE(id,name,first)
7880 #define ICALL(id,name,func) Icall_ ## id,
7881 #define HANDLES(inner) inner
7882
7883 enum {
7884 #include "metadata/icall-def.h"
7885         Icall_last
7886 };
7887
7888 #undef ICALL_TYPE
7889 #undef ICALL
7890 #define ICALL_TYPE(id,name,first) Icall_type_ ## id,
7891 #define ICALL(id,name,func)
7892 #undef HANDLES
7893 #define HANDLES(inner) inner
7894 enum {
7895 #include "metadata/icall-def.h"
7896         Icall_type_num
7897 };
7898
7899 #undef ICALL_TYPE
7900 #undef ICALL
7901 #define ICALL_TYPE(id,name,firstic) {(Icall_ ## firstic)},
7902 #define ICALL(id,name,func)
7903 #undef HANDLES
7904 #define HANDLES(inner) inner
7905 typedef struct {
7906         guint16 first_icall;
7907 } IcallTypeDesc;
7908
7909 static const IcallTypeDesc
7910 icall_type_descs [] = {
7911 #include "metadata/icall-def.h"
7912         {Icall_last}
7913 };
7914
7915 #define icall_desc_num_icalls(desc) ((desc) [1].first_icall - (desc) [0].first_icall)
7916
7917 #undef HANDLES
7918 #define HANDLES(inner) inner
7919 #undef ICALL_TYPE
7920 #define ICALL_TYPE(id,name,first)
7921 #undef ICALL
7922
7923 #ifdef HAVE_ARRAY_ELEM_INIT
7924 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
7925 #define MSGSTRFIELD1(line) str##line
7926
7927 static const struct msgstrtn_t {
7928 #define ICALL(id,name,func)
7929 #undef ICALL_TYPE
7930 #define ICALL_TYPE(id,name,first) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7931 #include "metadata/icall-def.h"
7932 #undef ICALL_TYPE
7933 } icall_type_names_str = {
7934 #define ICALL_TYPE(id,name,first) (name),
7935 #include "metadata/icall-def.h"
7936 #undef ICALL_TYPE
7937 };
7938 static const guint16 icall_type_names_idx [] = {
7939 #define ICALL_TYPE(id,name,first) [Icall_type_ ## id] = offsetof (struct msgstrtn_t, MSGSTRFIELD(__LINE__)),
7940 #include "metadata/icall-def.h"
7941 #undef ICALL_TYPE
7942 };
7943 #define icall_type_name_get(id) ((const char*)&icall_type_names_str + icall_type_names_idx [(id)])
7944
7945 static const struct msgstr_t {
7946 #undef ICALL
7947 #define ICALL_TYPE(id,name,first)
7948 #define ICALL(id,name,func) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7949 #include "metadata/icall-def.h"
7950 #undef ICALL
7951 } icall_names_str = {
7952 #define ICALL(id,name,func) (name),
7953 #include "metadata/icall-def.h"
7954 #undef ICALL
7955 };
7956 static const guint16 icall_names_idx [] = {
7957 #define ICALL(id,name,func) [Icall_ ## id] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
7958 #include "metadata/icall-def.h"
7959 #undef ICALL
7960 };
7961 #define icall_name_get(id) ((const char*)&icall_names_str + icall_names_idx [(id)])
7962
7963 #else
7964
7965 #undef ICALL_TYPE
7966 #undef ICALL
7967 #define ICALL_TYPE(id,name,first) name,
7968 #define ICALL(id,name,func)
7969 static const char* const
7970 icall_type_names [] = {
7971 #include "metadata/icall-def.h"
7972         NULL
7973 };
7974
7975 #define icall_type_name_get(id) (icall_type_names [(id)])
7976
7977 #undef ICALL_TYPE
7978 #undef ICALL
7979 #define ICALL_TYPE(id,name,first)
7980 #define ICALL(id,name,func) name,
7981 static const char* const
7982 icall_names [] = {
7983 #include "metadata/icall-def.h"
7984         NULL
7985 };
7986 #define icall_name_get(id) icall_names [(id)]
7987
7988 #endif /* !HAVE_ARRAY_ELEM_INIT */
7989
7990 #undef HANDLES
7991 #define HANDLES(inner) inner
7992 #undef ICALL_TYPE
7993 #undef ICALL
7994 #define ICALL_TYPE(id,name,first)
7995 #define ICALL(id,name,func) func,
7996 static const gconstpointer
7997 icall_functions [] = {
7998 #include "metadata/icall-def.h"
7999         NULL
8000 };
8001
8002 #ifdef ENABLE_ICALL_SYMBOL_MAP
8003 #undef HANDLES
8004 #define HANDLES(inner) inner
8005 #undef ICALL_TYPE
8006 #undef ICALL
8007 #define ICALL_TYPE(id,name,first)
8008 #define ICALL(id,name,func) #func,
8009 static const gconstpointer
8010 icall_symbols [] = {
8011 #include "metadata/icall-def.h"
8012         NULL
8013 };
8014 #endif
8015
8016 #undef ICALL_TYPE
8017 #undef ICALL
8018 #define ICALL_TYPE(id,name,first)
8019 #define ICALL(id,name,func) 0,
8020 #undef HANDLES
8021 #define HANDLES(inner) 1,
8022 static const guchar
8023 icall_uses_handles [] = {
8024 #include "metadata/icall-def.h"
8025 #undef ICALL
8026 #undef HANDLES
8027 };
8028
8029 #endif /* DISABLE_ICALL_TABLES */
8030
8031 static mono_mutex_t icall_mutex;
8032 static GHashTable *icall_hash = NULL;
8033 static GHashTable *jit_icall_hash_name = NULL;
8034 static GHashTable *jit_icall_hash_addr = NULL;
8035
8036 void
8037 mono_icall_init (void)
8038 {
8039 #ifndef DISABLE_ICALL_TABLES
8040         int i = 0;
8041
8042         /* check that tables are sorted: disable in release */
8043         if (TRUE) {
8044                 int j;
8045                 const char *prev_class = NULL;
8046                 const char *prev_method;
8047                 
8048                 for (i = 0; i < Icall_type_num; ++i) {
8049                         const IcallTypeDesc *desc;
8050                         int num_icalls;
8051                         prev_method = NULL;
8052                         if (prev_class && strcmp (prev_class, icall_type_name_get (i)) >= 0)
8053                                 g_print ("class %s should come before class %s\n", icall_type_name_get (i), prev_class);
8054                         prev_class = icall_type_name_get (i);
8055                         desc = &icall_type_descs [i];
8056                         num_icalls = icall_desc_num_icalls (desc);
8057                         /*g_print ("class %s has %d icalls starting at %d\n", prev_class, num_icalls, desc->first_icall);*/
8058                         for (j = 0; j < num_icalls; ++j) {
8059                                 const char *methodn = icall_name_get (desc->first_icall + j);
8060                                 if (prev_method && strcmp (prev_method, methodn) >= 0)
8061                                         g_print ("method %s should come before method %s\n", methodn, prev_method);
8062                                 prev_method = methodn;
8063                         }
8064                 }
8065         }
8066 #endif
8067
8068         icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8069         mono_os_mutex_init (&icall_mutex);
8070 }
8071
8072 static void
8073 mono_icall_lock (void)
8074 {
8075         mono_locks_os_acquire (&icall_mutex, IcallLock);
8076 }
8077
8078 static void
8079 mono_icall_unlock (void)
8080 {
8081         mono_locks_os_release (&icall_mutex, IcallLock);
8082 }
8083
8084 void
8085 mono_icall_cleanup (void)
8086 {
8087         g_hash_table_destroy (icall_hash);
8088         g_hash_table_destroy (jit_icall_hash_name);
8089         g_hash_table_destroy (jit_icall_hash_addr);
8090         mono_os_mutex_destroy (&icall_mutex);
8091 }
8092
8093 /**
8094  * mono_add_internal_call:
8095  * \param name method specification to surface to the managed world
8096  * \param method pointer to a C method to invoke when the method is called
8097  *
8098  * This method surfaces the C function pointed by \p method as a method
8099  * that has been surfaced in managed code with the method specified in
8100  * \p name as an internal call.
8101  *
8102  * Internal calls are surfaced to all app domains loaded and they are
8103  * accessibly by a type with the specified name.
8104  *
8105  * You must provide a fully qualified type name, that is namespaces
8106  * and type name, followed by a colon and the method name, with an
8107  * optional signature to bind.
8108  *
8109  * For example, the following are all valid declarations:
8110  *
8111  * \c MyApp.Services.ScriptService:Accelerate
8112  *
8113  * \c MyApp.Services.ScriptService:Slowdown(int,bool)
8114  *
8115  * You use method parameters in cases where there might be more than
8116  * one surface method to managed code.  That way you can register different
8117  * internal calls for different method overloads.
8118  *
8119  * The internal calls are invoked with no marshalling.   This means that .NET
8120  * types like \c System.String are exposed as \c MonoString* parameters.   This is
8121  * different than the way that strings are surfaced in P/Invoke.
8122  *
8123  * For more information on how the parameters are marshalled, see the
8124  * <a href="http://www.mono-project.com/docs/advanced/embedding/">Mono Embedding</a>
8125  * page.
8126  *
8127  * See the <a  href="mono-api-methods.html#method-desc">Method Description</a>
8128  * reference for more information on the format of method descriptions.
8129  */
8130 void
8131 mono_add_internal_call (const char *name, gconstpointer method)
8132 {
8133         mono_icall_lock ();
8134
8135         g_hash_table_insert (icall_hash, g_strdup (name), (gpointer) method);
8136
8137         mono_icall_unlock ();
8138 }
8139
8140 #ifndef DISABLE_ICALL_TABLES
8141
8142 #ifdef HAVE_ARRAY_ELEM_INIT
8143 static int
8144 compare_method_imap (const void *key, const void *elem)
8145 {
8146         const char* method_name = (const char*)&icall_names_str + (*(guint16*)elem);
8147         return strcmp (key, method_name);
8148 }
8149
8150 static gsize
8151 find_slot_icall (const IcallTypeDesc *imap, const char *name)
8152 {
8153         const guint16 *nameslot = (const guint16 *)mono_binary_search (name, icall_names_idx + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names_idx [0]), compare_method_imap);
8154         if (!nameslot)
8155                 return -1;
8156         return (nameslot - &icall_names_idx [0]);
8157 }
8158
8159 static gboolean
8160 find_uses_handles_icall (const IcallTypeDesc *imap, const char *name)
8161 {
8162         gsize slotnum = find_slot_icall (imap, name);
8163         if (slotnum == -1)
8164                 return FALSE;
8165         return (gboolean)icall_uses_handles [slotnum];
8166 }
8167
8168 static gpointer
8169 find_method_icall (const IcallTypeDesc *imap, const char *name)
8170 {
8171         gsize slotnum = find_slot_icall (imap, name);
8172         if (slotnum == -1)
8173                 return NULL;
8174         return (gpointer)icall_functions [slotnum];
8175 }
8176
8177 static int
8178 compare_class_imap (const void *key, const void *elem)
8179 {
8180         const char* class_name = (const char*)&icall_type_names_str + (*(guint16*)elem);
8181         return strcmp (key, class_name);
8182 }
8183
8184 static const IcallTypeDesc*
8185 find_class_icalls (const char *name)
8186 {
8187         const guint16 *nameslot = (const guint16 *)mono_binary_search (name, icall_type_names_idx, Icall_type_num, sizeof (icall_type_names_idx [0]), compare_class_imap);
8188         if (!nameslot)
8189                 return NULL;
8190         return &icall_type_descs [nameslot - &icall_type_names_idx [0]];
8191 }
8192
8193 #else /* HAVE_ARRAY_ELEM_INIT */
8194
8195 static int
8196 compare_method_imap (const void *key, const void *elem)
8197 {
8198         const char** method_name = (const char**)elem;
8199         return strcmp (key, *method_name);
8200 }
8201
8202 static gsize
8203 find_slot_icall (const IcallTypeDesc *imap, const char *name)
8204 {
8205         const char **nameslot = mono_binary_search (name, icall_names + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names [0]), compare_method_imap);
8206         if (!nameslot)
8207                 return -1;
8208         return nameslot - icall_names;
8209 }
8210
8211 static gpointer
8212 find_method_icall (const IcallTypeDesc *imap, const char *name)
8213 {
8214         gsize slotnum = find_slot_icall (imap, name);
8215         if (slotnum == -1)
8216                 return NULL;
8217         return (gpointer)icall_functions [slotnum];
8218 }
8219
8220 static gboolean
8221 find_uses_handles_icall (const IcallTypeDesc *imap, const char *name)
8222 {
8223         gsize slotnum = find_slot_icall (imap, name);
8224         if (slotnum == -1)
8225                 return FALSE;
8226         return (gboolean)icall_uses_handles [slotnum];
8227 }
8228
8229 static int
8230 compare_class_imap (const void *key, const void *elem)
8231 {
8232         const char** class_name = (const char**)elem;
8233         return strcmp (key, *class_name);
8234 }
8235
8236 static const IcallTypeDesc*
8237 find_class_icalls (const char *name)
8238 {
8239         const char **nameslot = mono_binary_search (name, icall_type_names, Icall_type_num, sizeof (icall_type_names [0]), compare_class_imap);
8240         if (!nameslot)
8241                 return NULL;
8242         return &icall_type_descs [nameslot - icall_type_names];
8243 }
8244
8245 #endif /* HAVE_ARRAY_ELEM_INIT */
8246
8247 #endif /* DISABLE_ICALL_TABLES */
8248
8249 /* 
8250  * we should probably export this as an helper (handle nested types).
8251  * Returns the number of chars written in buf.
8252  */
8253 static int
8254 concat_class_name (char *buf, int bufsize, MonoClass *klass)
8255 {
8256         int nspacelen, cnamelen;
8257         nspacelen = strlen (klass->name_space);
8258         cnamelen = strlen (klass->name);
8259         if (nspacelen + cnamelen + 2 > bufsize)
8260                 return 0;
8261         if (nspacelen) {
8262                 memcpy (buf, klass->name_space, nspacelen);
8263                 buf [nspacelen ++] = '.';
8264         }
8265         memcpy (buf + nspacelen, klass->name, cnamelen);
8266         buf [nspacelen + cnamelen] = 0;
8267         return nspacelen + cnamelen;
8268 }
8269
8270 #ifdef DISABLE_ICALL_TABLES
8271 static void
8272 no_icall_table (void)
8273 {
8274         g_assert_not_reached ();
8275 }
8276 #endif
8277
8278 /**
8279  * mono_lookup_internal_call_full:
8280  * \param method the method to look up
8281  * \param uses_handles out argument if method needs handles around managed objects.
8282  * \returns a pointer to the icall code for the given method.  If
8283  * \p uses_handles is not NULL, it will be set to TRUE if the method
8284  * needs managed objects wrapped using the infrastructure in handle.h
8285  *
8286  * If the method is not found, warns and returns NULL.
8287  */
8288 gpointer
8289 mono_lookup_internal_call_full (MonoMethod *method, mono_bool *uses_handles)
8290 {
8291         char *sigstart;
8292         char *tmpsig;
8293         char mname [2048];
8294         int typelen = 0, mlen, siglen;
8295         gpointer res;
8296 #ifndef DISABLE_ICALL_TABLES
8297         const IcallTypeDesc *imap = NULL;
8298 #endif
8299
8300         g_assert (method != NULL);
8301
8302         if (method->is_inflated)
8303                 method = ((MonoMethodInflated *) method)->declaring;
8304
8305         if (method->klass->nested_in) {
8306                 int pos = concat_class_name (mname, sizeof (mname)-2, method->klass->nested_in);
8307                 if (!pos)
8308                         return NULL;
8309
8310                 mname [pos++] = '/';
8311                 mname [pos] = 0;
8312
8313                 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
8314                 if (!typelen)
8315                         return NULL;
8316
8317                 typelen += pos;
8318         } else {
8319                 typelen = concat_class_name (mname, sizeof (mname), method->klass);
8320                 if (!typelen)
8321                         return NULL;
8322         }
8323
8324 #ifndef DISABLE_ICALL_TABLES
8325         imap = find_class_icalls (mname);
8326 #endif
8327
8328         mname [typelen] = ':';
8329         mname [typelen + 1] = ':';
8330
8331         mlen = strlen (method->name);
8332         memcpy (mname + typelen + 2, method->name, mlen);
8333         sigstart = mname + typelen + 2 + mlen;
8334         *sigstart = 0;
8335
8336         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
8337         siglen = strlen (tmpsig);
8338         if (typelen + mlen + siglen + 6 > sizeof (mname))
8339                 return NULL;
8340         sigstart [0] = '(';
8341         memcpy (sigstart + 1, tmpsig, siglen);
8342         sigstart [siglen + 1] = ')';
8343         sigstart [siglen + 2] = 0;
8344         g_free (tmpsig);
8345         
8346         mono_icall_lock ();
8347
8348         res = g_hash_table_lookup (icall_hash, mname);
8349         if (res) {
8350                 if (uses_handles)
8351                         *uses_handles = FALSE;
8352                 mono_icall_unlock ();;
8353                 return res;
8354         }
8355         /* try without signature */
8356         *sigstart = 0;
8357         res = g_hash_table_lookup (icall_hash, mname);
8358         if (res) {
8359                 if (uses_handles)
8360                         *uses_handles = FALSE;
8361                 mono_icall_unlock ();
8362                 return res;
8363         }
8364
8365 #ifdef DISABLE_ICALL_TABLES
8366         mono_icall_unlock ();
8367         /* Fail only when the result is actually used */
8368         /* mono_marshal_get_native_wrapper () depends on this */
8369         if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor"))
8370                 return ves_icall_System_String_ctor_RedirectToCreateString;
8371         else
8372                 return no_icall_table;
8373 #else
8374         /* it wasn't found in the static call tables */
8375         if (!imap) {
8376                 if (uses_handles)
8377                         *uses_handles = FALSE;
8378                 mono_icall_unlock ();
8379                 return NULL;
8380         }
8381         res = find_method_icall (imap, sigstart - mlen);
8382         if (res) {
8383                 if (uses_handles)
8384                         *uses_handles = find_uses_handles_icall (imap, sigstart - mlen);
8385                 mono_icall_unlock ();
8386                 return res;
8387         }
8388         /* try _with_ signature */
8389         *sigstart = '(';
8390         res = find_method_icall (imap, sigstart - mlen);
8391         if (res) {
8392                 if (uses_handles)
8393                         *uses_handles = find_uses_handles_icall (imap, sigstart - mlen);
8394                 mono_icall_unlock ();
8395                 return res;
8396         }
8397
8398         g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
8399         g_print ("\nYour mono runtime and class libraries are out of sync.\n");
8400         g_print ("The out of sync library is: %s\n", method->klass->image->name);
8401         g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
8402         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");
8403         g_print ("If you see other errors or faults after this message they are probably related\n");
8404         g_print ("and you need to fix your mono install first.\n");
8405
8406         mono_icall_unlock ();
8407
8408         return NULL;
8409 #endif
8410 }
8411
8412 /**
8413  * mono_lookup_internal_call:
8414  */
8415 gpointer
8416 mono_lookup_internal_call (MonoMethod *method)
8417 {
8418         return mono_lookup_internal_call_full (method, NULL);
8419 }
8420
8421 #ifdef ENABLE_ICALL_SYMBOL_MAP
8422 static int
8423 func_cmp (gconstpointer key, gconstpointer p)
8424 {
8425         return (gsize)key - (gsize)*(gsize*)p;
8426 }
8427 #endif
8428
8429 /*
8430  * mono_lookup_icall_symbol:
8431  *
8432  *   Given the icall METHOD, returns its C symbol.
8433  */
8434 const char*
8435 mono_lookup_icall_symbol (MonoMethod *m)
8436 {
8437 #ifdef DISABLE_ICALL_TABLES
8438         g_assert_not_reached ();
8439         return NULL;
8440 #else
8441 #ifdef ENABLE_ICALL_SYMBOL_MAP
8442         gpointer func;
8443         int i;
8444         gpointer slot;
8445         static gconstpointer *functions_sorted;
8446         static const char**symbols_sorted;
8447         static gboolean inited;
8448
8449         if (!inited) {
8450                 gboolean changed;
8451
8452                 functions_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
8453                 memcpy (functions_sorted, icall_functions, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
8454                 symbols_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
8455                 memcpy (symbols_sorted, icall_symbols, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
8456                 /* Bubble sort the two arrays */
8457                 changed = TRUE;
8458                 while (changed) {
8459                         changed = FALSE;
8460                         for (i = 0; i < G_N_ELEMENTS (icall_functions) - 1; ++i) {
8461                                 if (functions_sorted [i] > functions_sorted [i + 1]) {
8462                                         gconstpointer tmp;
8463
8464                                         tmp = functions_sorted [i];
8465                                         functions_sorted [i] = functions_sorted [i + 1];
8466                                         functions_sorted [i + 1] = tmp;
8467                                         tmp = symbols_sorted [i];
8468                                         symbols_sorted [i] = symbols_sorted [i + 1];
8469                                         symbols_sorted [i + 1] = tmp;
8470                                         changed = TRUE;
8471                                 }
8472                         }
8473                 }
8474         }
8475
8476         func = mono_lookup_internal_call (m);
8477         if (!func)
8478                 return NULL;
8479         slot = mono_binary_search (func, functions_sorted, G_N_ELEMENTS (icall_functions), sizeof (gpointer), func_cmp);
8480         if (!slot)
8481                 return NULL;
8482         g_assert (slot);
8483         return symbols_sorted [(gpointer*)slot - (gpointer*)functions_sorted];
8484 #else
8485         fprintf (stderr, "icall symbol maps not enabled, pass --enable-icall-symbol-map to configure.\n");
8486         g_assert_not_reached ();
8487         return 0;
8488 #endif
8489 #endif
8490 }
8491
8492 static MonoType*
8493 type_from_typename (char *type_name)
8494 {
8495         MonoClass *klass = NULL;        /* assignment to shut GCC warning up */
8496
8497         if (!strcmp (type_name, "int"))
8498                 klass = mono_defaults.int_class;
8499         else if (!strcmp (type_name, "ptr"))
8500                 klass = mono_defaults.int_class;
8501         else if (!strcmp (type_name, "void"))
8502                 klass = mono_defaults.void_class;
8503         else if (!strcmp (type_name, "int32"))
8504                 klass = mono_defaults.int32_class;
8505         else if (!strcmp (type_name, "uint32"))
8506                 klass = mono_defaults.uint32_class;
8507         else if (!strcmp (type_name, "int8"))
8508                 klass = mono_defaults.sbyte_class;
8509         else if (!strcmp (type_name, "uint8"))
8510                 klass = mono_defaults.byte_class;
8511         else if (!strcmp (type_name, "int16"))
8512                 klass = mono_defaults.int16_class;
8513         else if (!strcmp (type_name, "uint16"))
8514                 klass = mono_defaults.uint16_class;
8515         else if (!strcmp (type_name, "long"))
8516                 klass = mono_defaults.int64_class;
8517         else if (!strcmp (type_name, "ulong"))
8518                 klass = mono_defaults.uint64_class;
8519         else if (!strcmp (type_name, "float"))
8520                 klass = mono_defaults.single_class;
8521         else if (!strcmp (type_name, "double"))
8522                 klass = mono_defaults.double_class;
8523         else if (!strcmp (type_name, "object"))
8524                 klass = mono_defaults.object_class;
8525         else if (!strcmp (type_name, "obj"))
8526                 klass = mono_defaults.object_class;
8527         else if (!strcmp (type_name, "string"))
8528                 klass = mono_defaults.string_class;
8529         else if (!strcmp (type_name, "bool"))
8530                 klass = mono_defaults.boolean_class;
8531         else if (!strcmp (type_name, "boolean"))
8532                 klass = mono_defaults.boolean_class;
8533         else {
8534                 g_error ("%s", type_name);
8535                 g_assert_not_reached ();
8536         }
8537         return &klass->byval_arg;
8538 }
8539
8540 /**
8541  * LOCKING: Take the corlib image lock.
8542  */
8543 MonoMethodSignature*
8544 mono_create_icall_signature (const char *sigstr)
8545 {
8546         gchar **parts;
8547         int i, len;
8548         gchar **tmp;
8549         MonoMethodSignature *res, *res2;
8550         MonoImage *corlib = mono_defaults.corlib;
8551
8552         mono_image_lock (corlib);
8553         res = (MonoMethodSignature *)g_hash_table_lookup (corlib->helper_signatures, sigstr);
8554         mono_image_unlock (corlib);
8555
8556         if (res)
8557                 return res;
8558
8559         parts = g_strsplit (sigstr, " ", 256);
8560
8561         tmp = parts;
8562         len = 0;
8563         while (*tmp) {
8564                 len ++;
8565                 tmp ++;
8566         }
8567
8568         res = mono_metadata_signature_alloc (corlib, len - 1);
8569         res->pinvoke = 1;
8570
8571 #ifdef TARGET_WIN32
8572         /* 
8573          * Under windows, the default pinvoke calling convention is STDCALL but
8574          * we need CDECL.
8575          */
8576         res->call_convention = MONO_CALL_C;
8577 #endif
8578
8579         res->ret = type_from_typename (parts [0]);
8580         for (i = 1; i < len; ++i) {
8581                 res->params [i - 1] = type_from_typename (parts [i]);
8582         }
8583
8584         g_strfreev (parts);
8585
8586         mono_image_lock (corlib);
8587         res2 = (MonoMethodSignature *)g_hash_table_lookup (corlib->helper_signatures, sigstr);
8588         if (res2)
8589                 res = res2; /*Value is allocated in the image pool*/
8590         else
8591                 g_hash_table_insert (corlib->helper_signatures, (gpointer)sigstr, res);
8592         mono_image_unlock (corlib);
8593
8594         return res;
8595 }
8596
8597 MonoJitICallInfo *
8598 mono_find_jit_icall_by_name (const char *name)
8599 {
8600         MonoJitICallInfo *info;
8601         g_assert (jit_icall_hash_name);
8602
8603         mono_icall_lock ();
8604         info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name);
8605         mono_icall_unlock ();
8606         return info;
8607 }
8608
8609 MonoJitICallInfo *
8610 mono_find_jit_icall_by_addr (gconstpointer addr)
8611 {
8612         MonoJitICallInfo *info;
8613         g_assert (jit_icall_hash_addr);
8614
8615         mono_icall_lock ();
8616         info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
8617         mono_icall_unlock ();
8618
8619         return info;
8620 }
8621
8622 /*
8623  * mono_get_jit_icall_info:
8624  *
8625  *   Return the hashtable mapping JIT icall names to MonoJitICallInfo structures. The
8626  * caller should access it while holding the icall lock.
8627  */
8628 GHashTable*
8629 mono_get_jit_icall_info (void)
8630 {
8631         return jit_icall_hash_name;
8632 }
8633
8634 /*
8635  * mono_lookup_jit_icall_symbol:
8636  *
8637  *   Given the jit icall NAME, returns its C symbol if possible, or NULL.
8638  */
8639 const char*
8640 mono_lookup_jit_icall_symbol (const char *name)
8641 {
8642         MonoJitICallInfo *info;
8643         const char *res = NULL;
8644
8645         mono_icall_lock ();
8646         info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name);
8647         if (info)
8648                 res = info->c_symbol;
8649         mono_icall_unlock ();
8650         return res;
8651 }
8652
8653 void
8654 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
8655 {
8656         mono_icall_lock ();
8657         g_hash_table_insert (jit_icall_hash_addr, (gpointer)wrapper, info);
8658         mono_icall_unlock ();
8659 }
8660
8661 /*
8662  * If NO_RAISE is set, that means the icall is not calling mono_raise_exception () directly or indirectly. The JIT might be able to call these
8663  * icalls without wrappers in some cases.
8664  */
8665 MonoJitICallInfo *
8666 mono_register_jit_icall_full (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save, gboolean no_raise, const char *c_symbol)
8667 {
8668         MonoJitICallInfo *info;
8669         
8670         g_assert (func);
8671         g_assert (name);
8672
8673         mono_icall_lock ();
8674
8675         if (!jit_icall_hash_name) {
8676                 jit_icall_hash_name = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
8677                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
8678         }
8679
8680         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
8681                 g_warning ("jit icall already defined \"%s\"\n", name);
8682                 g_assert_not_reached ();
8683         }
8684
8685         info = g_new0 (MonoJitICallInfo, 1);
8686         
8687         info->name = name;
8688         info->func = func;
8689         info->sig = sig;
8690         info->c_symbol = c_symbol;
8691         info->no_raise = no_raise;
8692
8693         if (is_save) {
8694                 info->wrapper = func;
8695         } else {
8696                 info->wrapper = NULL;
8697         }
8698
8699         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
8700         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
8701
8702         mono_icall_unlock ();
8703         return info;
8704 }
8705
8706 MonoJitICallInfo *
8707 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
8708 {
8709         return mono_register_jit_icall_full (func, name, sig, is_save, FALSE, NULL);
8710 }
8711