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