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