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