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