[reflection] Set correct reflected type in MonoMethod.get_base_method
[mono.git] / mono / metadata / icall.c
1 /*
2  * icall.c:
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Paolo Molaro (lupus@ximian.com)
7  *       Patrik Torstensson (patrik.torstensson@labs2.com)
8  *   Marek Safar (marek.safar@gmail.com)
9  *   Aleksey Kliger (aleksey@xamarin.com)
10  *
11  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
12  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
13  * Copyright 2011-2015 Xamarin Inc (http://www.xamarin.com).
14  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15  */
16
17 #include <config.h>
18 #include <glib.h>
19 #include <stdarg.h>
20 #include <string.h>
21 #include <ctype.h>
22 #ifdef HAVE_ALLOCA_H
23 #include <alloca.h>
24 #endif
25 #ifdef HAVE_SYS_TIME_H
26 #include <sys/time.h>
27 #endif
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #if defined (HAVE_WCHAR_H)
32 #include <wchar.h>
33 #endif
34 #include "mono/metadata/icall-internals.h"
35 #include "mono/utils/mono-membar.h"
36 #include <mono/metadata/object.h>
37 #include <mono/metadata/threads.h>
38 #include <mono/metadata/threads-types.h>
39 #include <mono/metadata/threadpool.h>
40 #include <mono/metadata/threadpool-io.h>
41 #include <mono/metadata/monitor.h>
42 #include <mono/metadata/reflection.h>
43 #include <mono/metadata/image-internals.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/assembly-internals.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/exception.h>
48 #include <mono/metadata/exception-internals.h>
49 #include <mono/metadata/w32file.h>
50 #include <mono/metadata/console-io.h>
51 #include <mono/metadata/mono-route.h>
52 #include <mono/metadata/w32socket.h>
53 #include <mono/metadata/mono-endian.h>
54 #include <mono/metadata/tokentype.h>
55 #include <mono/metadata/metadata-internals.h>
56 #include <mono/metadata/class-internals.h>
57 #include <mono/metadata/reflection-internals.h>
58 #include <mono/metadata/marshal.h>
59 #include <mono/metadata/gc-internals.h>
60 #include <mono/metadata/mono-gc.h>
61 #include <mono/metadata/rand.h>
62 #include <mono/metadata/sysmath.h>
63 #include <mono/metadata/appdomain-icalls.h>
64 #include <mono/metadata/string-icalls.h>
65 #include <mono/metadata/debug-helpers.h>
66 #include <mono/metadata/w32process.h>
67 #include <mono/metadata/environment.h>
68 #include <mono/metadata/profiler-private.h>
69 #include <mono/metadata/locales.h>
70 #include <mono/metadata/filewatcher.h>
71 #include <mono/metadata/security.h>
72 #include <mono/metadata/mono-config.h>
73 #include <mono/metadata/cil-coff.h>
74 #include <mono/metadata/number-formatter.h>
75 #include <mono/metadata/security-manager.h>
76 #include <mono/metadata/security-core-clr.h>
77 #include <mono/metadata/mono-perfcounters.h>
78 #include <mono/metadata/mono-debug.h>
79 #include <mono/metadata/mono-ptr-array.h>
80 #include <mono/metadata/verify-internals.h>
81 #include <mono/metadata/runtime.h>
82 #include <mono/metadata/file-mmap.h>
83 #include <mono/metadata/seq-points-data.h>
84 #include <mono/metadata/handle.h>
85 #include <mono/metadata/w32mutex.h>
86 #include <mono/metadata/w32semaphore.h>
87 #include <mono/metadata/w32event.h>
88 #include <mono/utils/monobitset.h>
89 #include <mono/utils/mono-time.h>
90 #include <mono/utils/mono-proclib.h>
91 #include <mono/utils/mono-string.h>
92 #include <mono/utils/mono-error-internals.h>
93 #include <mono/utils/mono-mmap.h>
94 #include <mono/utils/mono-io-portability.h>
95 #include <mono/utils/mono-digest.h>
96 #include <mono/utils/bsearch.h>
97 #include <mono/utils/mono-os-mutex.h>
98 #include <mono/utils/mono-threads.h>
99 #include <mono/metadata/w32error.h>
100 #include <mono/utils/w32api.h>
101
102 #include "decimal-ms.h"
103 #include "number-ms.h"
104
105 #if !defined(HOST_WIN32) && defined(HAVE_SYS_UTSNAME_H)
106 #include <sys/utsname.h>
107 #endif
108
109 extern MonoString* ves_icall_System_Environment_GetOSVersionString (void);
110
111 ICALL_EXPORT MonoReflectionAssemblyHandle ves_icall_System_Reflection_Assembly_GetCallingAssembly (MonoError *error);
112
113 /* Lazy class loading functions */
114 static GENERATE_GET_CLASS_WITH_CACHE (system_version, "System", "Version")
115 static GENERATE_GET_CLASS_WITH_CACHE (assembly_name, "System.Reflection", "AssemblyName")
116 static GENERATE_GET_CLASS_WITH_CACHE (constructor_info, "System.Reflection", "ConstructorInfo")
117 static GENERATE_GET_CLASS_WITH_CACHE (property_info, "System.Reflection", "PropertyInfo")
118 static GENERATE_GET_CLASS_WITH_CACHE (event_info, "System.Reflection", "EventInfo")
119 static GENERATE_GET_CLASS_WITH_CACHE (module, "System.Reflection", "Module")
120
121 static MonoArrayHandle
122 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error);
123
124 static inline MonoBoolean
125 is_generic_parameter (MonoType *type)
126 {
127         return !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR);
128 }
129
130 static void
131 mono_class_init_checked (MonoClass *klass, MonoError *error)
132 {
133         error_init (error);
134
135         if (!mono_class_init (klass))
136                 mono_error_set_for_class_failure (error, klass);
137 }
138
139 #ifndef HOST_WIN32
140 static inline void
141 mono_icall_make_platform_path (gchar *path)
142 {
143         return;
144 }
145
146 static inline const gchar *
147 mono_icall_get_file_path_prefix (const gchar *path)
148 {
149         return "file://";
150 }
151 #endif /* HOST_WIN32 */
152
153 ICALL_EXPORT MonoObject *
154 ves_icall_System_Array_GetValueImpl (MonoArray *arr, guint32 pos)
155 {
156         MonoError error;
157         MonoClass *ac;
158         gint32 esize;
159         gpointer *ea;
160         MonoObject *result = NULL;
161
162         ac = (MonoClass *)arr->obj.vtable->klass;
163
164         esize = mono_array_element_size (ac);
165         ea = (gpointer*)((char*)arr->vector + (pos * esize));
166
167         if (ac->element_class->valuetype) {
168                 result = mono_value_box_checked (arr->obj.vtable->domain, ac->element_class, ea, &error);
169                 mono_error_set_pending_exception (&error);
170         } else
171                 result = (MonoObject *)*ea;
172         return result;
173 }
174
175 ICALL_EXPORT MonoObject *
176 ves_icall_System_Array_GetValue (MonoArray *arr, MonoArray *idxs)
177 {
178         MonoClass *ac, *ic;
179         MonoArray *io;
180         gint32 i, pos, *ind;
181
182         MONO_CHECK_ARG_NULL (idxs, NULL);
183
184         io = idxs;
185         ic = (MonoClass *)io->obj.vtable->klass;
186         
187         ac = (MonoClass *)arr->obj.vtable->klass;
188
189         g_assert (ic->rank == 1);
190         if (io->bounds != NULL || io->max_length !=  ac->rank) {
191                 mono_set_pending_exception (mono_get_exception_argument (NULL, NULL));
192                 return NULL;
193         }
194
195         ind = (gint32 *)io->vector;
196
197         if (arr->bounds == NULL) {
198                 if (*ind < 0 || *ind >= arr->max_length) {
199                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
200                         return NULL;
201                 }
202
203                 return ves_icall_System_Array_GetValueImpl (arr, *ind);
204         }
205         
206         for (i = 0; i < ac->rank; i++) {
207                 if ((ind [i] < arr->bounds [i].lower_bound) ||
208                     (ind [i] >=  (mono_array_lower_bound_t)arr->bounds [i].length + arr->bounds [i].lower_bound)) {
209                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
210                         return NULL;
211                 }
212         }
213
214         pos = ind [0] - arr->bounds [0].lower_bound;
215         for (i = 1; i < ac->rank; i++)
216                 pos = pos * arr->bounds [i].length + ind [i] - 
217                         arr->bounds [i].lower_bound;
218
219         return ves_icall_System_Array_GetValueImpl (arr, pos);
220 }
221
222 ICALL_EXPORT void
223 ves_icall_System_Array_SetValueImpl (MonoArray *arr, MonoObject *value, guint32 pos)
224 {
225         MonoError error;
226         MonoClass *ac, *vc, *ec;
227         gint32 esize, vsize;
228         gpointer *ea, *va;
229         int et, vt;
230
231         guint64 u64 = 0;
232         gint64 i64 = 0;
233         gdouble r64 = 0;
234
235         error_init (&error);
236
237         if (value)
238                 vc = value->vtable->klass;
239         else
240                 vc = NULL;
241
242         ac = arr->obj.vtable->klass;
243         ec = ac->element_class;
244
245         esize = mono_array_element_size (ac);
246         ea = (gpointer*)((char*)arr->vector + (pos * esize));
247         va = (gpointer*)((char*)value + sizeof (MonoObject));
248
249         if (mono_class_is_nullable (ec)) {
250                 mono_nullable_init ((guint8*)ea, value, ec);
251                 return;
252         }
253
254         if (!value) {
255                 mono_gc_bzero_atomic (ea, esize);
256                 return;
257         }
258
259 #define NO_WIDENING_CONVERSION G_STMT_START{\
260         mono_set_pending_exception (mono_get_exception_argument ( \
261                 "value", "not a widening conversion")); \
262         return; \
263 }G_STMT_END
264
265 #define CHECK_WIDENING_CONVERSION(extra) G_STMT_START{\
266                 if (esize < vsize + (extra)) {                                                    \
267                         mono_set_pending_exception (mono_get_exception_argument (       \
268                         "value", "not a widening conversion")); \
269                         return;                                                                 \
270                 } \
271 }G_STMT_END
272
273 #define INVALID_CAST G_STMT_START{ \
274                 mono_get_runtime_callbacks ()->set_cast_details (vc, ec); \
275         mono_set_pending_exception (mono_get_exception_invalid_cast ()); \
276         return; \
277 }G_STMT_END
278
279         /* Check element (destination) type. */
280         switch (ec->byval_arg.type) {
281         case MONO_TYPE_STRING:
282                 switch (vc->byval_arg.type) {
283                 case MONO_TYPE_STRING:
284                         break;
285                 default:
286                         INVALID_CAST;
287                 }
288                 break;
289         case MONO_TYPE_BOOLEAN:
290                 switch (vc->byval_arg.type) {
291                 case MONO_TYPE_BOOLEAN:
292                         break;
293                 case MONO_TYPE_CHAR:
294                 case MONO_TYPE_U1:
295                 case MONO_TYPE_U2:
296                 case MONO_TYPE_U4:
297                 case MONO_TYPE_U8:
298                 case MONO_TYPE_I1:
299                 case MONO_TYPE_I2:
300                 case MONO_TYPE_I4:
301                 case MONO_TYPE_I8:
302                 case MONO_TYPE_R4:
303                 case MONO_TYPE_R8:
304                         NO_WIDENING_CONVERSION;
305                 default:
306                         INVALID_CAST;
307                 }
308                 break;
309         default:
310                 break;
311         }
312
313         if (!ec->valuetype) {
314                 gboolean castOk = (NULL != mono_object_isinst_checked (value, ec, &error));
315                 if (mono_error_set_pending_exception (&error))
316                         return;
317                 if (!castOk)
318                         INVALID_CAST;
319                 mono_gc_wbarrier_set_arrayref (arr, ea, (MonoObject*)value);
320                 return;
321         }
322
323         if (mono_object_isinst_checked (value, ec, &error)) {
324                 if (ec->has_references)
325                         mono_value_copy (ea, (char*)value + sizeof (MonoObject), ec);
326                 else
327                         mono_gc_memmove_atomic (ea, (char *)value + sizeof (MonoObject), esize);
328                 return;
329         }
330         if (mono_error_set_pending_exception (&error))
331                 return;
332
333         if (!vc->valuetype)
334                 INVALID_CAST;
335
336         vsize = mono_class_instance_size (vc) - sizeof (MonoObject);
337
338         et = ec->byval_arg.type;
339         if (et == MONO_TYPE_VALUETYPE && ec->byval_arg.data.klass->enumtype)
340                 et = mono_class_enum_basetype (ec->byval_arg.data.klass)->type;
341
342         vt = vc->byval_arg.type;
343         if (vt == MONO_TYPE_VALUETYPE && vc->byval_arg.data.klass->enumtype)
344                 vt = mono_class_enum_basetype (vc->byval_arg.data.klass)->type;
345
346 #define ASSIGN_UNSIGNED(etype) G_STMT_START{\
347         switch (vt) { \
348         case MONO_TYPE_U1: \
349         case MONO_TYPE_U2: \
350         case MONO_TYPE_U4: \
351         case MONO_TYPE_U8: \
352         case MONO_TYPE_CHAR: \
353                 CHECK_WIDENING_CONVERSION(0); \
354                 *(etype *) ea = (etype) u64; \
355                 return; \
356         /* You can't assign a signed value to an unsigned array. */ \
357         case MONO_TYPE_I1: \
358         case MONO_TYPE_I2: \
359         case MONO_TYPE_I4: \
360         case MONO_TYPE_I8: \
361         /* You can't assign a floating point number to an integer array. */ \
362         case MONO_TYPE_R4: \
363         case MONO_TYPE_R8: \
364                 NO_WIDENING_CONVERSION; \
365         } \
366 }G_STMT_END
367
368 #define ASSIGN_SIGNED(etype) G_STMT_START{\
369         switch (vt) { \
370         case MONO_TYPE_I1: \
371         case MONO_TYPE_I2: \
372         case MONO_TYPE_I4: \
373         case MONO_TYPE_I8: \
374                 CHECK_WIDENING_CONVERSION(0); \
375                 *(etype *) ea = (etype) i64; \
376                 return; \
377         /* You can assign an unsigned value to a signed array if the array's */ \
378         /* element size is larger than the value size. */ \
379         case MONO_TYPE_U1: \
380         case MONO_TYPE_U2: \
381         case MONO_TYPE_U4: \
382         case MONO_TYPE_U8: \
383         case MONO_TYPE_CHAR: \
384                 CHECK_WIDENING_CONVERSION(1); \
385                 *(etype *) ea = (etype) u64; \
386                 return; \
387         /* You can't assign a floating point number to an integer array. */ \
388         case MONO_TYPE_R4: \
389         case MONO_TYPE_R8: \
390                 NO_WIDENING_CONVERSION; \
391         } \
392 }G_STMT_END
393
394 #define ASSIGN_REAL(etype) G_STMT_START{\
395         switch (vt) { \
396         case MONO_TYPE_R4: \
397         case MONO_TYPE_R8: \
398                 CHECK_WIDENING_CONVERSION(0); \
399                 *(etype *) ea = (etype) r64; \
400                 return; \
401         /* All integer values fit into a floating point array, so we don't */ \
402         /* need to CHECK_WIDENING_CONVERSION here. */ \
403         case MONO_TYPE_I1: \
404         case MONO_TYPE_I2: \
405         case MONO_TYPE_I4: \
406         case MONO_TYPE_I8: \
407                 *(etype *) ea = (etype) i64; \
408                 return; \
409         case MONO_TYPE_U1: \
410         case MONO_TYPE_U2: \
411         case MONO_TYPE_U4: \
412         case MONO_TYPE_U8: \
413         case MONO_TYPE_CHAR: \
414                 *(etype *) ea = (etype) u64; \
415                 return; \
416         } \
417 }G_STMT_END
418
419         switch (vt) {
420         case MONO_TYPE_U1:
421                 u64 = *(guint8 *) va;
422                 break;
423         case MONO_TYPE_U2:
424                 u64 = *(guint16 *) va;
425                 break;
426         case MONO_TYPE_U4:
427                 u64 = *(guint32 *) va;
428                 break;
429         case MONO_TYPE_U8:
430                 u64 = *(guint64 *) va;
431                 break;
432         case MONO_TYPE_I1:
433                 i64 = *(gint8 *) va;
434                 break;
435         case MONO_TYPE_I2:
436                 i64 = *(gint16 *) va;
437                 break;
438         case MONO_TYPE_I4:
439                 i64 = *(gint32 *) va;
440                 break;
441         case MONO_TYPE_I8:
442                 i64 = *(gint64 *) va;
443                 break;
444         case MONO_TYPE_R4:
445                 r64 = *(gfloat *) va;
446                 break;
447         case MONO_TYPE_R8:
448                 r64 = *(gdouble *) va;
449                 break;
450         case MONO_TYPE_CHAR:
451                 u64 = *(guint16 *) va;
452                 break;
453         case MONO_TYPE_BOOLEAN:
454                 /* Boolean is only compatible with itself. */
455                 switch (et) {
456                 case MONO_TYPE_CHAR:
457                 case MONO_TYPE_U1:
458                 case MONO_TYPE_U2:
459                 case MONO_TYPE_U4:
460                 case MONO_TYPE_U8:
461                 case MONO_TYPE_I1:
462                 case MONO_TYPE_I2:
463                 case MONO_TYPE_I4:
464                 case MONO_TYPE_I8:
465                 case MONO_TYPE_R4:
466                 case MONO_TYPE_R8:
467                         NO_WIDENING_CONVERSION;
468                 default:
469                         INVALID_CAST;
470                 }
471                 break;
472         }
473
474         /* If we can't do a direct copy, let's try a widening conversion. */
475         switch (et) {
476         case MONO_TYPE_CHAR:
477                 ASSIGN_UNSIGNED (guint16);
478         case MONO_TYPE_U1:
479                 ASSIGN_UNSIGNED (guint8);
480         case MONO_TYPE_U2:
481                 ASSIGN_UNSIGNED (guint16);
482         case MONO_TYPE_U4:
483                 ASSIGN_UNSIGNED (guint32);
484         case MONO_TYPE_U8:
485                 ASSIGN_UNSIGNED (guint64);
486         case MONO_TYPE_I1:
487                 ASSIGN_SIGNED (gint8);
488         case MONO_TYPE_I2:
489                 ASSIGN_SIGNED (gint16);
490         case MONO_TYPE_I4:
491                 ASSIGN_SIGNED (gint32);
492         case MONO_TYPE_I8:
493                 ASSIGN_SIGNED (gint64);
494         case MONO_TYPE_R4:
495                 ASSIGN_REAL (gfloat);
496         case MONO_TYPE_R8:
497                 ASSIGN_REAL (gdouble);
498         }
499
500         INVALID_CAST;
501         /* Not reached, INVALID_CAST does not return. Just to avoid a compiler warning ... */
502         return;
503
504 #undef INVALID_CAST
505 #undef NO_WIDENING_CONVERSION
506 #undef CHECK_WIDENING_CONVERSION
507 #undef ASSIGN_UNSIGNED
508 #undef ASSIGN_SIGNED
509 #undef ASSIGN_REAL
510 }
511
512 ICALL_EXPORT void 
513 ves_icall_System_Array_SetValue (MonoArray *arr, MonoObject *value,
514                                  MonoArray *idxs)
515 {
516         MonoClass *ac, *ic;
517         gint32 i, pos, *ind;
518
519         MONO_CHECK_ARG_NULL (idxs,);
520
521         ic = idxs->obj.vtable->klass;
522         ac = arr->obj.vtable->klass;
523
524         g_assert (ic->rank == 1);
525         if (idxs->bounds != NULL || idxs->max_length != ac->rank) {
526                 mono_set_pending_exception (mono_get_exception_argument (NULL, NULL));
527                 return;
528         }
529
530         ind = (gint32 *)idxs->vector;
531
532         if (arr->bounds == NULL) {
533                 if (*ind < 0 || *ind >= arr->max_length) {
534                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
535                         return;
536                 }
537
538                 ves_icall_System_Array_SetValueImpl (arr, value, *ind);
539                 return;
540         }
541         
542         for (i = 0; i < ac->rank; i++)
543                 if ((ind [i] < arr->bounds [i].lower_bound) ||
544                     (ind [i] >= (mono_array_lower_bound_t)arr->bounds [i].length + arr->bounds [i].lower_bound)) {
545                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
546                         return;
547                 }
548
549         pos = ind [0] - arr->bounds [0].lower_bound;
550         for (i = 1; i < ac->rank; i++)
551                 pos = pos * arr->bounds [i].length + ind [i] - 
552                         arr->bounds [i].lower_bound;
553
554         ves_icall_System_Array_SetValueImpl (arr, value, pos);
555 }
556
557 ICALL_EXPORT MonoArray *
558 ves_icall_System_Array_CreateInstanceImpl (MonoReflectionType *type, MonoArray *lengths, MonoArray *bounds)
559 {
560         MonoError error;
561         MonoClass *aklass, *klass;
562         MonoArray *array;
563         uintptr_t *sizes, i;
564         gboolean bounded = FALSE;
565
566         MONO_CHECK_ARG_NULL (type, NULL);
567         MONO_CHECK_ARG_NULL (lengths, NULL);
568
569         MONO_CHECK_ARG (lengths, mono_array_length (lengths) > 0, NULL);
570         if (bounds)
571                 MONO_CHECK_ARG (bounds, mono_array_length (lengths) == mono_array_length (bounds), NULL);
572
573         for (i = 0; i < mono_array_length (lengths); i++) {
574                 if (mono_array_get (lengths, gint32, i) < 0) {
575                         mono_set_pending_exception (mono_get_exception_argument_out_of_range (NULL));
576                         return NULL;
577                 }
578         }
579
580         klass = mono_class_from_mono_type (type->type);
581         mono_class_init_checked (klass, &error);
582         if (mono_error_set_pending_exception (&error))
583                 return NULL;
584
585         if (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 ICALL_EXPORT MonoArray*
736 ves_icall_System_Array_Clone (MonoArray *arr)
737 {
738         MonoError error;
739         MonoArray *result = mono_array_clone_checked (arr, &error);
740         mono_error_set_pending_exception (&error);
741         return result;
742 }
743
744 ICALL_EXPORT gboolean
745 ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* dest, int dest_idx, int length)
746 {
747         int element_size;
748         void * dest_addr;
749         void * source_addr;
750         MonoVTable *src_vtable;
751         MonoVTable *dest_vtable;
752         MonoClass *src_class;
753         MonoClass *dest_class;
754
755         src_vtable = source->obj.vtable;
756         dest_vtable = dest->obj.vtable;
757
758         if (src_vtable->rank != dest_vtable->rank)
759                 return FALSE;
760
761         if (source->bounds || dest->bounds)
762                 return FALSE;
763
764         /* there's no integer overflow since mono_array_length returns an unsigned integer */
765         if ((dest_idx + length > mono_array_length_fast (dest)) ||
766                 (source_idx + length > mono_array_length_fast (source)))
767                 return FALSE;
768
769         src_class = src_vtable->klass->element_class;
770         dest_class = dest_vtable->klass->element_class;
771
772         /*
773          * Handle common cases.
774          */
775
776         /* Case1: object[] -> valuetype[] (ArrayList::ToArray) 
777         We fallback to managed here since we need to typecheck each boxed valuetype before storing them in the dest array.
778         */
779         if (src_class == mono_defaults.object_class && dest_class->valuetype)
780                 return FALSE;
781
782         /* Check if we're copying a char[] <==> (u)short[] */
783         if (src_class != dest_class) {
784                 if (dest_class->valuetype || dest_class->enumtype || src_class->valuetype || src_class->enumtype)
785                         return FALSE;
786
787                 /* 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. */
788                 if (!mono_class_is_subclass_of (src_class, dest_class, FALSE))
789                         return FALSE;
790         }
791
792         if (dest_class->valuetype) {
793                 element_size = mono_array_element_size (source->obj.vtable->klass);
794                 source_addr = mono_array_addr_with_size_fast (source, element_size, source_idx);
795                 if (dest_class->has_references) {
796                         mono_value_copy_array (dest, dest_idx, source_addr, length);
797                 } else {
798                         dest_addr = mono_array_addr_with_size_fast (dest, element_size, dest_idx);
799                         mono_gc_memmove_atomic (dest_addr, source_addr, element_size * length);
800                 }
801         } else {
802                 mono_array_memcpy_refs_fast (dest, dest_idx, source, source_idx, length);
803         }
804
805         return TRUE;
806 }
807
808 ICALL_EXPORT void
809 ves_icall_System_Array_GetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
810 {
811         MonoClass *ac;
812         gint32 esize;
813         gpointer *ea;
814
815         ac = (MonoClass *)arr->obj.vtable->klass;
816
817         esize = mono_array_element_size (ac);
818         ea = (gpointer*)((char*)arr->vector + (pos * esize));
819
820         mono_gc_memmove_atomic (value, ea, esize);
821 }
822
823 ICALL_EXPORT void
824 ves_icall_System_Array_SetGenericValueImpl (MonoArray *arr, guint32 pos, gpointer value)
825 {
826         MonoClass *ac, *ec;
827         gint32 esize;
828         gpointer *ea;
829
830         ac = (MonoClass *)arr->obj.vtable->klass;
831         ec = ac->element_class;
832
833         esize = mono_array_element_size (ac);
834         ea = (gpointer*)((char*)arr->vector + (pos * esize));
835
836         if (MONO_TYPE_IS_REFERENCE (&ec->byval_arg)) {
837                 g_assert (esize == sizeof (gpointer));
838                 mono_gc_wbarrier_generic_store (ea, *(MonoObject **)value);
839         } else {
840                 g_assert (ec->inited);
841                 g_assert (esize == mono_class_value_size (ec, NULL));
842                 if (ec->has_references)
843                         mono_gc_wbarrier_value_copy (ea, value, 1, ec);
844                 else
845                         mono_gc_memmove_atomic (ea, value, esize);
846         }
847 }
848
849 ICALL_EXPORT void
850 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArrayHandle array, MonoClassField *field_handle, MonoError *error)
851 {
852         error_init (error);
853
854         MonoClass *klass = mono_handle_class (array);
855         guint32 size = mono_array_element_size (klass);
856         MonoType *type = mono_type_get_underlying_type (&klass->element_class->byval_arg);
857         int align;
858         const char *field_data;
859
860         if (MONO_TYPE_IS_REFERENCE (type) || type->type == MONO_TYPE_VALUETYPE) {
861                 mono_error_set_argument (error, "array", "Cannot initialize array of non-primitive type");
862                 return;
863         }
864
865         if (!(field_handle->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
866                 mono_error_set_argument (error, "field_handle", "Field '%s' doesn't have an RVA", mono_field_get_name (field_handle));
867                 return;
868         }
869
870         size *= MONO_HANDLE_GETVAL(array, max_length);
871         field_data = mono_field_get_data (field_handle);
872
873         if (size > mono_type_size (field_handle->type, &align)) {
874                 mono_error_set_argument (error, "field_handle", "Field not large enough to fill array");
875                 return;
876         }
877
878 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
879 #define SWAP(n) {                                                               \
880         guint ## n *data = (guint ## n *) mono_array_addr (MONO_HANDLE_RAW(array), char, 0); \
881         guint ## n *src = (guint ## n *) field_data;                            \
882         int i,                                                                  \
883             nEnt = (size / sizeof(guint ## n));                                 \
884                                                                                 \
885         for (i = 0; i < nEnt; i++) {                                            \
886                 data[i] = read ## n (&src[i]);                                  \
887         }                                                                       \
888 }
889
890         /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
891
892         switch (type->type) {
893         case MONO_TYPE_CHAR:
894         case MONO_TYPE_I2:
895         case MONO_TYPE_U2:
896                 SWAP (16);
897                 break;
898         case MONO_TYPE_I4:
899         case MONO_TYPE_U4:
900         case MONO_TYPE_R4:
901                 SWAP (32);
902                 break;
903         case MONO_TYPE_I8:
904         case MONO_TYPE_U8:
905         case MONO_TYPE_R8:
906                 SWAP (64);
907                 break;
908         default:
909                 memcpy (mono_array_addr (MONO_HANDLE_RAW(array), char, 0), field_data, size);
910                 break;
911         }
912 #else
913         memcpy (mono_array_addr (MONO_HANDLE_RAW(array), char, 0), field_data, size);
914 #endif
915 }
916
917 ICALL_EXPORT gint
918 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
919 {
920         return offsetof (MonoString, chars);
921 }
922
923 ICALL_EXPORT MonoObject *
924 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObject *obj)
925 {
926         if ((obj == NULL) || (! (obj->vtable->klass->valuetype)))
927                 return obj;
928         else {
929                 MonoError error;
930                 MonoObject *ret = mono_object_clone_checked (obj, &error);
931                 mono_error_set_pending_exception (&error);
932
933                 return ret;
934         }
935 }
936
937 ICALL_EXPORT void
938 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle)
939 {
940         MonoError error;
941         MonoClass *klass;
942         MonoVTable *vtable;
943
944         MONO_CHECK_ARG_NULL (handle,);
945
946         klass = mono_class_from_mono_type (handle);
947         MONO_CHECK_ARG (handle, klass,);
948
949         if (mono_class_is_gtd (klass))
950                 return;
951
952         vtable = mono_class_vtable_full (mono_domain_get (), klass, &error);
953         if (!is_ok (&error)) {
954                 mono_error_set_pending_exception (&error);
955                 return;
956         }
957
958         /* This will call the type constructor */
959         if (!mono_runtime_class_init_full (vtable, &error))
960                 mono_error_set_pending_exception (&error);
961 }
962
963 ICALL_EXPORT void
964 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (MonoImage *image)
965 {
966         MonoError error;
967
968         mono_image_check_for_module_cctor (image);
969         if (image->has_module_cctor) {
970                 MonoClass *module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, &error);
971                 if (!mono_error_ok (&error)) {
972                         mono_error_set_pending_exception (&error);
973                         return;
974                 }
975                 /*It's fine to raise the exception here*/
976                 MonoVTable * vtable = mono_class_vtable_full (mono_domain_get (), module_klass, &error);
977                 if (!is_ok (&error)) {
978                         mono_error_set_pending_exception (&error);
979                         return;
980                 }
981                 if (!mono_runtime_class_init_full (vtable, &error))
982                         mono_error_set_pending_exception (&error);
983         }
984 }
985
986 ICALL_EXPORT MonoBoolean
987 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
988 {
989 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
990         // It does not work on win32
991 #else
992         guint8 *stack_addr;
993         guint8 *current;
994         size_t stack_size;
995         int min_size;
996         MonoInternalThread *thread;
997
998         mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
999         /* if we have no info we are optimistic and assume there is enough room */
1000         if (!stack_addr)
1001                 return TRUE;
1002
1003         thread = mono_thread_internal_current ();
1004         // .net seems to check that at least 50% of stack is available
1005         min_size = thread->stack_size / 2;
1006
1007         // TODO: It's not always set
1008         if (!min_size)
1009                 return TRUE;
1010
1011         current = (guint8 *)&stack_addr;
1012         if (current > stack_addr) {
1013                 if ((current - stack_addr) < min_size)
1014                         return FALSE;
1015         } else {
1016                 if (current - (stack_addr - stack_size) < min_size)
1017                         return FALSE;
1018         }
1019 #endif
1020         return TRUE;
1021 }
1022
1023 ICALL_EXPORT MonoObject *
1024 ves_icall_System_Object_MemberwiseClone (MonoObject *this_obj)
1025 {
1026         MonoError error;
1027         MonoObject *ret = mono_object_clone_checked (this_obj, &error);
1028         mono_error_set_pending_exception (&error);
1029
1030         return ret;
1031 }
1032
1033 ICALL_EXPORT gint32
1034 ves_icall_System_ValueType_InternalGetHashCode (MonoObject *this_obj, MonoArray **fields)
1035 {
1036         MonoError error;
1037         MonoClass *klass;
1038         MonoObject **values = NULL;
1039         MonoObject *o;
1040         int count = 0;
1041         gint32 result = (int)(gsize)mono_defaults.int32_class;
1042         MonoClassField* field;
1043         gpointer iter;
1044
1045         klass = mono_object_class (this_obj);
1046
1047         if (mono_class_num_fields (klass) == 0)
1048                 return result;
1049
1050         /*
1051          * Compute the starting value of the hashcode for fields of primitive
1052          * types, and return the remaining fields in an array to the managed side.
1053          * This way, we can avoid costly reflection operations in managed code.
1054          */
1055         iter = NULL;
1056         while ((field = mono_class_get_fields (klass, &iter))) {
1057                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1058                         continue;
1059                 if (mono_field_is_deleted (field))
1060                         continue;
1061                 /* FIXME: Add more types */
1062                 switch (field->type->type) {
1063                 case MONO_TYPE_I4:
1064                         result ^= *(gint32*)((guint8*)this_obj + field->offset);
1065                         break;
1066                 case MONO_TYPE_STRING: {
1067                         MonoString *s;
1068                         s = *(MonoString**)((guint8*)this_obj + field->offset);
1069                         if (s != NULL)
1070                                 result ^= mono_string_hash (s);
1071                         break;
1072                 }
1073                 default:
1074                         if (!values)
1075                                 values = g_newa (MonoObject*, mono_class_num_fields (klass));
1076                         o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, this_obj, &error);
1077                         if (!is_ok (&error)) {
1078                                 mono_error_set_pending_exception (&error);
1079                                 return 0;
1080                         }
1081                         values [count++] = o;
1082                 }
1083         }
1084
1085         if (values) {
1086                 int i;
1087                 MonoArray *fields_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.object_class, count, &error);
1088                 if (mono_error_set_pending_exception (&error))
1089                         return 0;
1090                 mono_gc_wbarrier_generic_store (fields, (MonoObject*) fields_arr);
1091                 for (i = 0; i < count; ++i)
1092                         mono_array_setref (*fields, i, values [i]);
1093         } else {
1094                 *fields = NULL;
1095         }
1096         return result;
1097 }
1098
1099 ICALL_EXPORT MonoBoolean
1100 ves_icall_System_ValueType_Equals (MonoObject *this_obj, MonoObject *that, MonoArray **fields)
1101 {
1102         MonoError error;
1103         MonoClass *klass;
1104         MonoObject **values = NULL;
1105         MonoObject *o;
1106         MonoClassField* field;
1107         gpointer iter;
1108         int count = 0;
1109
1110         MONO_CHECK_ARG_NULL (that, FALSE);
1111
1112         if (this_obj->vtable != that->vtable)
1113                 return FALSE;
1114
1115         klass = mono_object_class (this_obj);
1116
1117         if (klass->enumtype && mono_class_enum_basetype (klass) && mono_class_enum_basetype (klass)->type == MONO_TYPE_I4)
1118                 return (*(gint32*)((guint8*)this_obj + sizeof (MonoObject)) == *(gint32*)((guint8*)that + sizeof (MonoObject)));
1119
1120         /*
1121          * Do the comparison for fields of primitive type and return a result if
1122          * possible. Otherwise, return the remaining fields in an array to the 
1123          * managed side. This way, we can avoid costly reflection operations in 
1124          * managed code.
1125          */
1126         *fields = NULL;
1127         iter = NULL;
1128         while ((field = mono_class_get_fields (klass, &iter))) {
1129                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1130                         continue;
1131                 if (mono_field_is_deleted (field))
1132                         continue;
1133                 /* FIXME: Add more types */
1134                 switch (field->type->type) {
1135                 case MONO_TYPE_U1:
1136                 case MONO_TYPE_I1:
1137                 case MONO_TYPE_BOOLEAN:
1138                         if (*((guint8*)this_obj + field->offset) != *((guint8*)that + field->offset))
1139                                 return FALSE;
1140                         break;
1141                 case MONO_TYPE_U2:
1142                 case MONO_TYPE_I2:
1143                 case MONO_TYPE_CHAR:
1144                         if (*(gint16*)((guint8*)this_obj + field->offset) != *(gint16*)((guint8*)that + field->offset))
1145                                 return FALSE;
1146                         break;
1147                 case MONO_TYPE_U4:
1148                 case MONO_TYPE_I4:
1149                         if (*(gint32*)((guint8*)this_obj + field->offset) != *(gint32*)((guint8*)that + field->offset))
1150                                 return FALSE;
1151                         break;
1152                 case MONO_TYPE_U8:
1153                 case MONO_TYPE_I8:
1154                         if (*(gint64*)((guint8*)this_obj + field->offset) != *(gint64*)((guint8*)that + field->offset))
1155                                 return FALSE;
1156                         break;
1157                 case MONO_TYPE_R4:
1158                         if (*(float*)((guint8*)this_obj + field->offset) != *(float*)((guint8*)that + field->offset))
1159                                 return FALSE;
1160                         break;
1161                 case MONO_TYPE_R8:
1162                         if (*(double*)((guint8*)this_obj + field->offset) != *(double*)((guint8*)that + field->offset))
1163                                 return FALSE;
1164                         break;
1165
1166
1167                 case MONO_TYPE_STRING: {
1168                         MonoString *s1, *s2;
1169                         guint32 s1len, s2len;
1170                         s1 = *(MonoString**)((guint8*)this_obj + field->offset);
1171                         s2 = *(MonoString**)((guint8*)that + field->offset);
1172                         if (s1 == s2)
1173                                 break;
1174                         if ((s1 == NULL) || (s2 == NULL))
1175                                 return FALSE;
1176                         s1len = mono_string_length (s1);
1177                         s2len = mono_string_length (s2);
1178                         if (s1len != s2len)
1179                                 return FALSE;
1180
1181                         if (memcmp (mono_string_chars (s1), mono_string_chars (s2), s1len * sizeof (gunichar2)) != 0)
1182                                 return FALSE;
1183                         break;
1184                 }
1185                 default:
1186                         if (!values)
1187                                 values = g_newa (MonoObject*, mono_class_num_fields (klass) * 2);
1188                         o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, this_obj, &error);
1189                         if (!is_ok (&error)) {
1190                                 mono_error_set_pending_exception (&error);
1191                                 return FALSE;
1192                         }
1193                         values [count++] = o;
1194                         o = mono_field_get_value_object_checked (mono_object_domain (this_obj), field, that, &error);
1195                         if (!is_ok (&error)) {
1196                                 mono_error_set_pending_exception (&error);
1197                                 return FALSE;
1198                         }
1199                         values [count++] = o;
1200                 }
1201
1202                 if (klass->enumtype)
1203                         /* enums only have one non-static field */
1204                         break;
1205         }
1206
1207         if (values) {
1208                 int i;
1209                 MonoArray *fields_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.object_class, count, &error);
1210                 if (mono_error_set_pending_exception (&error))
1211                         return FALSE;
1212                 mono_gc_wbarrier_generic_store (fields, (MonoObject*) fields_arr);
1213                 for (i = 0; i < count; ++i)
1214                         mono_array_setref_fast (*fields, i, values [i]);
1215                 return FALSE;
1216         } else {
1217                 return TRUE;
1218         }
1219 }
1220
1221 ICALL_EXPORT MonoReflectionTypeHandle
1222 ves_icall_System_Object_GetType (MonoObjectHandle obj, MonoError *error)
1223 {
1224         error_init (error);
1225         MonoDomain *domain = MONO_HANDLE_DOMAIN (obj);
1226         MonoClass *klass = mono_handle_class (obj);
1227 #ifndef DISABLE_REMOTING
1228         if (mono_class_is_transparent_proxy (klass)) {
1229                 MonoTransparentProxyHandle proxy_obj = MONO_HANDLE_CAST (MonoTransparentProxy, obj);
1230                 MonoRemoteClass *remote_class = MONO_HANDLE_GETVAL (proxy_obj, remote_class);
1231                 MonoType *proxy_type = &remote_class->proxy_class->byval_arg;
1232                 return mono_type_get_object_handle (domain, proxy_type, error);
1233         } else
1234 #endif
1235                 return mono_type_get_object_handle (domain, &klass->byval_arg, error);
1236 }
1237
1238 static gboolean
1239 get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1240 {
1241         MonoMethod **dest = (MonoMethod **)data;
1242
1243         /* skip unmanaged frames */
1244         if (!managed)
1245                 return FALSE;
1246
1247         if (!(*dest)) {
1248                 if (!strcmp (m->klass->name_space, "System.Reflection"))
1249                         return FALSE;
1250                 *dest = m;
1251                 return TRUE;
1252         }
1253         return FALSE;
1254 }
1255
1256 static gboolean
1257 get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1258 {
1259         MonoMethod **dest = (MonoMethod **)data;
1260
1261         /* skip unmanaged frames */
1262         if (!managed)
1263                 return FALSE;
1264
1265         if (m->wrapper_type != MONO_WRAPPER_NONE)
1266                 return FALSE;
1267
1268         if (m == *dest) {
1269                 *dest = NULL;
1270                 return FALSE;
1271         }
1272
1273         if (m->klass->image == mono_defaults.corlib && !strcmp (m->klass->name_space, "System.Reflection"))
1274                 return FALSE;
1275
1276         if (!(*dest)) {
1277                 *dest = m;
1278                 return TRUE;
1279         }
1280         return FALSE;
1281 }
1282
1283 static gboolean
1284 get_caller_no_system_or_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1285 {
1286         MonoMethod **dest = (MonoMethod **)data;
1287
1288         /* skip unmanaged frames */
1289         if (!managed)
1290                 return FALSE;
1291
1292         if (m->wrapper_type != MONO_WRAPPER_NONE)
1293                 return FALSE;
1294
1295         if (m == *dest) {
1296                 *dest = NULL;
1297                 return FALSE;
1298         }
1299
1300         if (m->klass->image == mono_defaults.corlib && ((!strcmp (m->klass->name_space, "System.Reflection"))
1301                                                                                                         || (!strcmp (m->klass->name_space, "System"))))
1302                 return FALSE;
1303
1304         if (!(*dest)) {
1305                 *dest = m;
1306                 return TRUE;
1307         }
1308         return FALSE;
1309 }
1310
1311 static MonoReflectionTypeHandle
1312 type_from_parsed_name (MonoTypeNameParse *info, MonoBoolean ignoreCase, MonoAssembly **caller_assembly, MonoError *error)
1313 {
1314         MonoMethod *m, *dest;
1315
1316         MonoType *type = NULL;
1317         MonoAssembly *assembly = NULL;
1318         gboolean type_resolve = FALSE;
1319         MonoImage *rootimage = NULL;
1320
1321         error_init (error);
1322
1323         /*
1324          * We must compute the calling assembly as type loading must happen under a metadata context.
1325          * For example. The main assembly is a.exe and Type.GetType is called from dir/b.dll. Without
1326          * the metadata context (basedir currently) set to dir/b.dll we won't be able to load a dir/c.dll.
1327          */
1328         m = mono_method_get_last_managed ();
1329         dest = m;
1330         if (m && m->klass->image != mono_defaults.corlib) {
1331                 /* Happens with inlining */
1332         } else {
1333                 /* Ugly hack: type_from_parsed_name is called from
1334                  * System.Type.internal_from_name, which is called most
1335                  * directly from System.Type.GetType(string,bool,bool) but
1336                  * also indirectly from places such as
1337                  * System.Type.GetType(string,func,func) (via
1338                  * System.TypeNameParser.GetType and System.TypeSpec.Resolve)
1339                  * so we need to skip over all of those to find the true caller.
1340                  *
1341                  * It would be nice if we had stack marks.
1342                  */
1343                 mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
1344                 if (!dest)
1345                         dest = m;
1346         }
1347
1348         /*
1349          * FIXME: mono_method_get_last_managed() sometimes returns NULL, thus
1350          *        causing ves_icall_System_Reflection_Assembly_GetCallingAssembly()
1351          *        to crash.  This only seems to happen in some strange remoting
1352          *        scenarios and I was unable to figure out what's happening there.
1353          *        Dec 10, 2005 - Martin.
1354          */
1355
1356         if (dest) {
1357                 assembly = dest->klass->image->assembly;
1358                 type_resolve = TRUE;
1359                 rootimage = assembly->image;
1360         } else {
1361                 g_warning (G_STRLOC);
1362         }
1363         *caller_assembly = assembly;
1364
1365         if (info->assembly.name)
1366                 assembly = mono_assembly_load (&info->assembly, assembly ? assembly->basedir : NULL, NULL);
1367
1368         if (assembly) {
1369                 /* When loading from the current assembly, AppDomain.TypeResolve will not be called yet */
1370                 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
1371                 if (!is_ok (error))
1372                         goto fail;
1373         }
1374
1375         // XXXX - aleksey -
1376         //  Say we're looking for System.Generic.Dict<int, Local>
1377         //  we FAIL the get type above, because S.G.Dict isn't in assembly->image.  So we drop down here.
1378         //  but then we FAIL AGAIN because now we pass null as the image and the rootimage and everything
1379         //  is messed up when we go to construct the Local as the type arg...
1380         //
1381         // By contrast, if we started with Mine<System.Generic.Dict<int, Local>> we'd go in with assembly->image
1382         // as the root and then even the detour into generics would still not screw us when we went to load Local.
1383         if (!info->assembly.name && !type) {
1384                 /* try mscorlib */
1385                 type = mono_reflection_get_type_checked (rootimage, NULL, info, ignoreCase, &type_resolve, error);
1386                 if (!is_ok (error))
1387                         goto fail;
1388         }
1389         if (assembly && !type && type_resolve) {
1390                 type_resolve = FALSE; /* This will invoke TypeResolve if not done in the first 'if' */
1391                 type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
1392                 if (!is_ok (error))
1393                         goto fail;
1394         }
1395
1396         if (!type) 
1397                 goto fail;
1398
1399         return mono_type_get_object_handle (mono_domain_get (), type, error);
1400 fail:
1401         return MONO_HANDLE_NEW (MonoReflectionType, NULL);
1402 }
1403
1404 ICALL_EXPORT MonoReflectionTypeHandle
1405 ves_icall_System_Type_internal_from_name (MonoStringHandle name,
1406                                           MonoBoolean throwOnError,
1407                                           MonoBoolean ignoreCase,
1408                                           MonoError *error)
1409 {
1410         error_init (error);
1411         MonoTypeNameParse info;
1412         gboolean parsedOk;
1413         MonoAssembly *caller_assembly;
1414         MonoReflectionTypeHandle type = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1415
1416         char *str = mono_string_handle_to_utf8 (name, error);
1417         if (!is_ok (error))
1418                 goto leave;
1419
1420         parsedOk = mono_reflection_parse_type (str, &info);
1421
1422         /* mono_reflection_parse_type() mangles the string */
1423         if (!parsedOk) {
1424                 mono_reflection_free_type_info (&info);
1425                 if (throwOnError)
1426                         mono_error_set_argument (error, "typeName", "failed parse: %s", str);
1427                 goto leave;
1428         }
1429
1430         MONO_HANDLE_ASSIGN (type, type_from_parsed_name (&info, ignoreCase, &caller_assembly, error));
1431
1432         if (!is_ok (error)) {
1433                 mono_reflection_free_type_info (&info);
1434                 goto leave;
1435         }
1436
1437         if (MONO_HANDLE_IS_NULL (type)) {
1438                 if (throwOnError) {
1439                         char *tname = info.name_space ? g_strdup_printf ("%s.%s", info.name_space, info.name) : g_strdup (info.name);
1440                         char *aname;
1441                         if (info.assembly.name)
1442                                 aname = mono_stringify_assembly_name (&info.assembly);
1443                         else if (caller_assembly)
1444                                 aname = mono_stringify_assembly_name (mono_assembly_get_name (caller_assembly));
1445                         else
1446                                 aname = g_strdup ("");
1447                         mono_error_set_type_load_name (error, tname, aname, "");
1448                 }
1449                 mono_reflection_free_type_info (&info);
1450                 goto leave;
1451         }
1452         
1453 leave:
1454         g_free (str);
1455         if (!is_ok (error)) {
1456                 if (!throwOnError)
1457                         mono_error_cleanup (error);
1458                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
1459         }
1460
1461         return type;
1462 }
1463
1464
1465 ICALL_EXPORT MonoReflectionTypeHandle
1466 ves_icall_System_Type_internal_from_handle (MonoType *handle, MonoError *error)
1467 {
1468         error_init (error);
1469         MonoDomain *domain = mono_domain_get (); 
1470
1471         return mono_type_get_object_handle (domain, handle, error);
1472 }
1473
1474 ICALL_EXPORT MonoType*
1475 ves_icall_Mono_RuntimeClassHandle_GetTypeFromClass (MonoClass *klass)
1476 {
1477         return mono_class_get_type (klass);
1478 }
1479
1480 ICALL_EXPORT void
1481 ves_icall_Mono_RuntimeGPtrArrayHandle_GPtrArrayFree (GPtrArray *ptr_array)
1482 {
1483         g_ptr_array_free (ptr_array, TRUE);
1484 }
1485
1486 ICALL_EXPORT void
1487 ves_icall_Mono_SafeStringMarshal_GFree (void *c_str)
1488 {
1489         g_free (c_str);
1490 }
1491
1492 ICALL_EXPORT char*
1493 ves_icall_Mono_SafeStringMarshal_StringToUtf8 (MonoString *s)
1494 {
1495         MonoError error;
1496         char *res = mono_string_to_utf8_checked (s, &error);
1497         mono_error_set_pending_exception (&error);
1498         return res;
1499 }
1500
1501 /* System.TypeCode */
1502 typedef enum {
1503         TYPECODE_EMPTY,
1504         TYPECODE_OBJECT,
1505         TYPECODE_DBNULL,
1506         TYPECODE_BOOLEAN,
1507         TYPECODE_CHAR,
1508         TYPECODE_SBYTE,
1509         TYPECODE_BYTE,
1510         TYPECODE_INT16,
1511         TYPECODE_UINT16,
1512         TYPECODE_INT32,
1513         TYPECODE_UINT32,
1514         TYPECODE_INT64,
1515         TYPECODE_UINT64,
1516         TYPECODE_SINGLE,
1517         TYPECODE_DOUBLE,
1518         TYPECODE_DECIMAL,
1519         TYPECODE_DATETIME,
1520         TYPECODE_STRING = 18
1521 } TypeCode;
1522
1523 ICALL_EXPORT guint32
1524 ves_icall_type_GetTypeCodeInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
1525 {
1526         error_init (error);
1527         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1528         int t = type->type;
1529
1530         if (type->byref)
1531                 return TYPECODE_OBJECT;
1532
1533 handle_enum:
1534         switch (t) {
1535         case MONO_TYPE_VOID:
1536                 return TYPECODE_OBJECT;
1537         case MONO_TYPE_BOOLEAN:
1538                 return TYPECODE_BOOLEAN;
1539         case MONO_TYPE_U1:
1540                 return TYPECODE_BYTE;
1541         case MONO_TYPE_I1:
1542                 return TYPECODE_SBYTE;
1543         case MONO_TYPE_U2:
1544                 return TYPECODE_UINT16;
1545         case MONO_TYPE_I2:
1546                 return TYPECODE_INT16;
1547         case MONO_TYPE_CHAR:
1548                 return TYPECODE_CHAR;
1549         case MONO_TYPE_PTR:
1550         case MONO_TYPE_U:
1551         case MONO_TYPE_I:
1552                 return TYPECODE_OBJECT;
1553         case MONO_TYPE_U4:
1554                 return TYPECODE_UINT32;
1555         case MONO_TYPE_I4:
1556                 return TYPECODE_INT32;
1557         case MONO_TYPE_U8:
1558                 return TYPECODE_UINT64;
1559         case MONO_TYPE_I8:
1560                 return TYPECODE_INT64;
1561         case MONO_TYPE_R4:
1562                 return TYPECODE_SINGLE;
1563         case MONO_TYPE_R8:
1564                 return TYPECODE_DOUBLE;
1565         case MONO_TYPE_VALUETYPE: {
1566                 MonoClass *klass = type->data.klass;
1567                 
1568                 if (klass->enumtype) {
1569                         t = mono_class_enum_basetype (klass)->type;
1570                         goto handle_enum;
1571                 } else if (mono_is_corlib_image (klass->image)) {
1572                         if (strcmp (klass->name_space, "System") == 0) {
1573                                 if (strcmp (klass->name, "Decimal") == 0)
1574                                         return TYPECODE_DECIMAL;
1575                                 else if (strcmp (klass->name, "DateTime") == 0)
1576                                         return TYPECODE_DATETIME;
1577                         }
1578                 }
1579                 return TYPECODE_OBJECT;
1580         }
1581         case MONO_TYPE_STRING:
1582                 return TYPECODE_STRING;
1583         case MONO_TYPE_SZARRAY:
1584         case MONO_TYPE_ARRAY:
1585         case MONO_TYPE_OBJECT:
1586         case MONO_TYPE_VAR:
1587         case MONO_TYPE_MVAR:
1588         case MONO_TYPE_TYPEDBYREF:
1589                 return TYPECODE_OBJECT;
1590         case MONO_TYPE_CLASS:
1591                 {
1592                         MonoClass *klass =  type->data.klass;
1593                         if (klass->image == mono_defaults.corlib && strcmp (klass->name_space, "System") == 0) {
1594                                 if (strcmp (klass->name, "DBNull") == 0)
1595                                         return TYPECODE_DBNULL;
1596                         }
1597                 }
1598                 return TYPECODE_OBJECT;
1599         case MONO_TYPE_GENERICINST:
1600                 return TYPECODE_OBJECT;
1601         default:
1602                 g_error ("type 0x%02x not handled in GetTypeCode()", t);
1603         }
1604         return 0;
1605 }
1606
1607 static MonoType*
1608 mono_type_get_underlying_type_ignore_byref (MonoType *type)
1609 {
1610         if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
1611                 return mono_class_enum_basetype (type->data.klass);
1612         if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
1613                 return mono_class_enum_basetype (type->data.generic_class->container_class);
1614         return type;
1615 }
1616
1617 ICALL_EXPORT guint32
1618 ves_icall_RuntimeTypeHandle_type_is_assignable_from (MonoReflectionTypeHandle ref_type, MonoReflectionTypeHandle ref_c, MonoError *error)
1619 {
1620         error_init (error);
1621
1622         g_assert (!MONO_HANDLE_IS_NULL (ref_type));
1623         
1624         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1625         MonoClass *klass = mono_class_from_mono_type (type);
1626         MonoType *ctype = MONO_HANDLE_GETVAL (ref_c, type);
1627         MonoClass *klassc = mono_class_from_mono_type (ctype);
1628
1629         if (type->byref ^ ctype->byref)
1630                 return FALSE;
1631
1632         if (type->byref) {
1633                 MonoType *t = mono_type_get_underlying_type_ignore_byref (type);
1634                 MonoType *ot = mono_type_get_underlying_type_ignore_byref (ctype);
1635
1636                 klass = mono_class_from_mono_type (t);
1637                 klassc = mono_class_from_mono_type (ot);
1638
1639                 if (mono_type_is_primitive (t)) {
1640                         return mono_type_is_primitive (ot) && klass->instance_size == klassc->instance_size;
1641                 } else if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) {
1642                         return t->type == ot->type && t->data.generic_param->num == ot->data.generic_param->num;
1643                 } else if (t->type == MONO_TYPE_PTR || t->type == MONO_TYPE_FNPTR) {
1644                         return t->type == ot->type;
1645                 } else {
1646                          if (ot->type == MONO_TYPE_VAR || ot->type == MONO_TYPE_MVAR)
1647                                  return FALSE;
1648
1649                          if (klass->valuetype)
1650                                 return klass == klassc;
1651                         return klass->valuetype == klassc->valuetype;
1652                 }
1653         }
1654         return mono_class_is_assignable_from (klass, klassc);
1655 }
1656
1657 ICALL_EXPORT guint32
1658 ves_icall_RuntimeTypeHandle_IsInstanceOfType (MonoReflectionTypeHandle ref_type, MonoObjectHandle obj, MonoError *error)
1659 {
1660         error_init (error);
1661         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1662         MonoClass *klass = mono_class_from_mono_type (type);
1663         mono_class_init_checked (klass, error);
1664         return_val_if_nok (error, FALSE);
1665         MonoObjectHandle inst = mono_object_handle_isinst (obj, klass, error);
1666         return_val_if_nok (error, FALSE);
1667         return !MONO_HANDLE_IS_NULL (inst);
1668 }
1669
1670 ICALL_EXPORT guint32
1671 ves_icall_RuntimeTypeHandle_GetAttributes (MonoReflectionTypeHandle ref_type, MonoError *error)
1672 {
1673         error_init (error);
1674         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
1675         MonoClass *klass = mono_class_from_mono_type (type);
1676         return mono_class_get_flags (klass);
1677 }
1678
1679 ICALL_EXPORT MonoReflectionMarshalAsAttributeHandle
1680 ves_icall_System_Reflection_FieldInfo_get_marshal_info (MonoReflectionFieldHandle field_h, MonoError *error)
1681 {
1682         error_init (error);
1683         MonoDomain *domain = MONO_HANDLE_DOMAIN (field_h);
1684         MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
1685         MonoClass *klass = field->parent;
1686
1687         MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
1688         if (mono_class_is_gtd (klass) ||
1689             (gklass && gklass->context.class_inst->is_open))
1690                 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1691
1692         MonoType *ftype = mono_field_get_type (field);
1693         if (ftype && !(ftype->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL))
1694                 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1695
1696         MonoMarshalType *info = mono_marshal_load_type_info (klass);
1697
1698         for (int i = 0; i < info->num_fields; ++i) {
1699                 if (info->fields [i].field == field) {
1700                         if (!info->fields [i].mspec)
1701                                 return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1702                         else {
1703                                 return mono_reflection_marshal_as_attribute_from_marshal_spec (domain, klass, info->fields [i].mspec, error);
1704                         }
1705                 }
1706         }
1707
1708         return MONO_HANDLE_CAST (MonoReflectionMarshalAsAttribute, NULL_HANDLE);
1709 }
1710
1711 ICALL_EXPORT MonoReflectionFieldHandle
1712 ves_icall_System_Reflection_FieldInfo_internal_from_handle_type (MonoClassField *handle, MonoType *type, MonoError *error)
1713 {
1714         MonoClass *klass;
1715
1716         g_assert (handle);
1717
1718         error_init (error);
1719
1720         if (!type) {
1721                 klass = handle->parent;
1722         } else {
1723                 klass = mono_class_from_mono_type (type);
1724
1725                 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1726
1727                 if (!found)
1728                         /* The managed code will throw the exception */
1729                         return MONO_HANDLE_CAST (MonoReflectionField, NULL_HANDLE);
1730         }
1731
1732         return mono_field_get_object_handle (mono_domain_get (), klass, handle, error);
1733 }
1734
1735 ICALL_EXPORT MonoReflectionEventHandle
1736 ves_icall_System_Reflection_EventInfo_internal_from_handle_type (MonoEvent *handle, MonoType *type, MonoError *error)
1737 {
1738         MonoClass *klass;
1739
1740         g_assert (handle);
1741
1742         error_init (error);
1743
1744         if (!type) {
1745                 klass = handle->parent;
1746         } else {
1747                 klass = mono_class_from_mono_type (type);
1748
1749                 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1750                 if (!found)
1751                         /* Managed code will throw an exception */
1752                         return MONO_HANDLE_CAST (MonoReflectionEvent, NULL_HANDLE);
1753         }
1754
1755         return mono_event_get_object_handle (mono_domain_get (), klass, handle, error);
1756 }
1757
1758
1759 ICALL_EXPORT MonoReflectionPropertyHandle
1760 ves_icall_System_Reflection_PropertyInfo_internal_from_handle_type (MonoProperty *handle, MonoType *type, MonoError *error)
1761 {
1762         error_init (error);
1763         MonoClass *klass;
1764
1765         g_assert (handle);
1766
1767         if (!type) {
1768                 klass = handle->parent;
1769         } else {
1770                 klass = mono_class_from_mono_type (type);
1771
1772                 gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent);
1773                 if (!found)
1774                         /* Managed code will throw an exception */
1775                         return MONO_HANDLE_CAST (MonoReflectionProperty, NULL_HANDLE);
1776         }
1777
1778         return mono_property_get_object_handle (mono_domain_get (), klass, handle, error);
1779 }
1780
1781 ICALL_EXPORT MonoArrayHandle
1782 ves_icall_System_Reflection_FieldInfo_GetTypeModifiers (MonoReflectionFieldHandle field_h, MonoBoolean optional, MonoError *error)
1783 {
1784         error_init (error);
1785         MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field);
1786
1787         MonoType *type = mono_field_get_type_checked (field, error);
1788         if (!is_ok (error))
1789                 return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
1790
1791         return type_array_from_modifiers (field->parent->image, type, optional, error);
1792 }
1793
1794 ICALL_EXPORT int
1795 vell_icall_get_method_attributes (MonoMethod *method)
1796 {
1797         return method->flags;
1798 }
1799
1800 ICALL_EXPORT void
1801 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info, MonoError *error)
1802 {
1803         MonoDomain *domain = mono_domain_get ();
1804
1805         MonoMethodSignature* sig = mono_method_signature_checked (method, error);
1806         return_if_nok (error);
1807
1808         MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &method->klass->byval_arg, error);
1809         return_if_nok (error);
1810
1811         MONO_STRUCT_SETREF (info, parent, MONO_HANDLE_RAW (rt));
1812
1813         MONO_HANDLE_ASSIGN (rt, mono_type_get_object_handle (domain, sig->ret, error));
1814         return_if_nok (error);
1815
1816         MONO_STRUCT_SETREF (info, ret, MONO_HANDLE_RAW (rt));
1817
1818         info->attrs = method->flags;
1819         info->implattrs = method->iflags;
1820         guint32 callconv;
1821         if (sig->call_convention == MONO_CALL_DEFAULT)
1822                 callconv = sig->sentinelpos >= 0 ? 2 : 1;
1823         else {
1824                 if (sig->call_convention == MONO_CALL_VARARG || sig->sentinelpos >= 0)
1825                         callconv = 2;
1826                 else
1827                         callconv = 1;
1828         }
1829         callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6);
1830         info->callconv = callconv;
1831 }
1832
1833 ICALL_EXPORT MonoArrayHandle
1834 ves_icall_System_Reflection_MonoMethodInfo_get_parameter_info (MonoMethod *method, MonoReflectionMethodHandle member, MonoError *error)
1835 {
1836         error_init (error);
1837         MonoDomain *domain = mono_domain_get (); 
1838
1839         MonoReflectionTypeHandle reftype = MONO_HANDLE_NEW (MonoReflectionType, NULL);
1840         MONO_HANDLE_GET (reftype, member, reftype);
1841         MonoClass *klass = NULL;
1842         if (!MONO_HANDLE_IS_NULL (reftype))
1843                 klass = mono_class_from_mono_type (MONO_HANDLE_GETVAL (reftype, type));
1844         return mono_param_get_objects_internal (domain, method, klass, error);
1845 }
1846
1847 ICALL_EXPORT MonoReflectionMarshalAsAttributeHandle
1848 ves_icall_System_MonoMethodInfo_get_retval_marshal (MonoMethod *method, MonoError *error)
1849 {
1850         error_init (error);
1851         MonoDomain *domain = mono_domain_get (); 
1852         MonoReflectionMarshalAsAttributeHandle res = MONO_HANDLE_NEW (MonoReflectionMarshalAsAttribute, NULL);
1853
1854         MonoMarshalSpec **mspecs = g_new (MonoMarshalSpec*, mono_method_signature (method)->param_count + 1);
1855         mono_method_get_marshal_info (method, mspecs);
1856
1857         if (mspecs [0]) {
1858                 MONO_HANDLE_ASSIGN (res, mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [0], error));
1859                 if (!is_ok (error))
1860                         goto leave;
1861         }
1862                 
1863 leave:
1864         for (int i = mono_method_signature (method)->param_count; i >= 0; i--)
1865                 if (mspecs [i])
1866                         mono_metadata_free_marshal_spec (mspecs [i]);
1867         g_free (mspecs);
1868
1869         return res;
1870 }
1871
1872 ICALL_EXPORT gint32
1873 ves_icall_MonoField_GetFieldOffset (MonoReflectionField *field)
1874 {
1875         MonoClass *parent = field->field->parent;
1876         mono_class_setup_fields (parent);
1877
1878         return field->field->offset - sizeof (MonoObject);
1879 }
1880
1881 ICALL_EXPORT MonoReflectionTypeHandle
1882 ves_icall_MonoField_GetParentType (MonoReflectionFieldHandle field, MonoBoolean declaring, MonoError *error)
1883 {
1884         error_init (error);
1885         MonoDomain *domain = MONO_HANDLE_DOMAIN (field);
1886         MonoClass *parent;
1887
1888         if (declaring) {
1889                 MonoClassField *f = MONO_HANDLE_GETVAL (field, field);
1890                 parent = f->parent;
1891         } else {
1892                 parent = MONO_HANDLE_GETVAL (field, klass);
1893         }
1894
1895         return mono_type_get_object_handle (domain, &parent->byval_arg, error);
1896 }
1897
1898 ICALL_EXPORT MonoObject *
1899 ves_icall_MonoField_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
1900 {       
1901         MonoError error;
1902         MonoClass *fklass = field->klass;
1903         MonoClassField *cf = field->field;
1904         MonoDomain *domain = mono_object_domain (field);
1905
1906         if (fklass->image->assembly->ref_only) {
1907                 mono_set_pending_exception (mono_get_exception_invalid_operation (
1908                                         "It is illegal to get the value on a field on a type loaded using the ReflectionOnly methods."));
1909                 return NULL;
1910         }
1911
1912         if (mono_security_core_clr_enabled () &&
1913             !mono_security_core_clr_ensure_reflection_access_field (cf, &error)) {
1914                 mono_error_set_pending_exception (&error);
1915                 return NULL;
1916         }
1917
1918         MonoObject * result = mono_field_get_value_object_checked (domain, cf, obj, &error);
1919         mono_error_set_pending_exception (&error);
1920         return result;
1921 }
1922
1923 ICALL_EXPORT void
1924 ves_icall_MonoField_SetValueInternal (MonoReflectionField *field, MonoObject *obj, MonoObject *value)
1925 {
1926         MonoError error;
1927         MonoClassField *cf = field->field;
1928         MonoType *type;
1929         gchar *v;
1930
1931         if (field->klass->image->assembly->ref_only) {
1932                 mono_set_pending_exception (mono_get_exception_invalid_operation (
1933                                         "It is illegal to set the value on a field on a type loaded using the ReflectionOnly methods."));
1934                 return;
1935         }
1936
1937         if (mono_security_core_clr_enabled () &&
1938             !mono_security_core_clr_ensure_reflection_access_field (cf, &error)) {
1939                 mono_error_set_pending_exception (&error);
1940                 return;
1941         }
1942
1943         type = mono_field_get_type_checked (cf, &error);
1944         if (!mono_error_ok (&error)) {
1945                 mono_error_set_pending_exception (&error);
1946                 return;
1947         }
1948
1949         v = (gchar *) value;
1950         if (!type->byref) {
1951                 switch (type->type) {
1952                 case MONO_TYPE_U1:
1953                 case MONO_TYPE_I1:
1954                 case MONO_TYPE_BOOLEAN:
1955                 case MONO_TYPE_U2:
1956                 case MONO_TYPE_I2:
1957                 case MONO_TYPE_CHAR:
1958                 case MONO_TYPE_U:
1959                 case MONO_TYPE_I:
1960                 case MONO_TYPE_U4:
1961                 case MONO_TYPE_I4:
1962                 case MONO_TYPE_R4:
1963                 case MONO_TYPE_U8:
1964                 case MONO_TYPE_I8:
1965                 case MONO_TYPE_R8:
1966                 case MONO_TYPE_VALUETYPE:
1967                 case MONO_TYPE_PTR:
1968                         if (v != NULL)
1969                                 v += sizeof (MonoObject);
1970                         break;
1971                 case MONO_TYPE_STRING:
1972                 case MONO_TYPE_OBJECT:
1973                 case MONO_TYPE_CLASS:
1974                 case MONO_TYPE_ARRAY:
1975                 case MONO_TYPE_SZARRAY:
1976                         /* Do nothing */
1977                         break;
1978                 case MONO_TYPE_GENERICINST: {
1979                         MonoGenericClass *gclass = type->data.generic_class;
1980                         g_assert (!gclass->context.class_inst->is_open);
1981
1982                         if (mono_class_is_nullable (mono_class_from_mono_type (type))) {
1983                                 MonoClass *nklass = mono_class_from_mono_type (type);
1984                                 MonoObject *nullable;
1985
1986                                 /* 
1987                                  * Convert the boxed vtype into a Nullable structure.
1988                                  * This is complicated by the fact that Nullables have
1989                                  * a variable structure.
1990                                  */
1991                                 nullable = mono_object_new_checked (mono_domain_get (), nklass, &error);
1992                                 if (!mono_error_ok (&error)) {
1993                                         mono_error_set_pending_exception (&error);
1994                                         return;
1995                                 }
1996
1997                                 mono_nullable_init ((guint8 *)mono_object_unbox (nullable), value, nklass);
1998
1999                                 v = (gchar *)mono_object_unbox (nullable);
2000                         }
2001                         else 
2002                                 if (gclass->container_class->valuetype && (v != NULL))
2003                                         v += sizeof (MonoObject);
2004                         break;
2005                 }
2006                 default:
2007                         g_error ("type 0x%x not handled in "
2008                                  "ves_icall_FieldInfo_SetValueInternal", type->type);
2009                         return;
2010                 }
2011         }
2012
2013         if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
2014                 MonoVTable *vtable = mono_class_vtable_full (mono_object_domain (field), cf->parent, &error);
2015                 if (!is_ok (&error)) {
2016                         mono_error_set_pending_exception (&error);
2017                         return;
2018                 }
2019                 if (!vtable->initialized) {
2020                         if (!mono_runtime_class_init_full (vtable, &error)) {
2021                                 mono_error_set_pending_exception (&error);
2022                                 return;
2023                         }
2024                 }
2025                 mono_field_static_set_value (vtable, cf, v);
2026         } else {
2027                 mono_field_set_value (obj, cf, v);
2028         }
2029 }
2030
2031 ICALL_EXPORT void
2032 ves_icall_System_RuntimeFieldHandle_SetValueDirect (MonoReflectionField *field, MonoReflectionType *field_type, MonoTypedRef *obj, MonoObject *value, MonoReflectionType *context_type)
2033 {
2034         MonoClassField *f;
2035
2036         g_assert (field);
2037         g_assert (obj);
2038         g_assert (value);
2039
2040         f = field->field;
2041         if (!MONO_TYPE_ISSTRUCT (&f->parent->byval_arg)) {
2042                 mono_set_pending_exception (mono_get_exception_not_implemented (NULL));
2043                 return;
2044         }
2045
2046         if (MONO_TYPE_IS_REFERENCE (f->type))
2047                 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), value, FALSE);
2048         else
2049                 mono_copy_value (f->type, (guint8*)obj->value + f->offset - sizeof (MonoObject), mono_object_unbox (value), FALSE);
2050 }
2051
2052 ICALL_EXPORT MonoObject *
2053 ves_icall_MonoField_GetRawConstantValue (MonoReflectionField *rfield)
2054 {       
2055         MonoObject *o = NULL;
2056         MonoClassField *field = rfield->field;
2057         MonoClass *klass;
2058         MonoDomain *domain = mono_object_domain (rfield);
2059         gchar *v;
2060         MonoTypeEnum def_type;
2061         const char *def_value;
2062         MonoType *t;
2063         MonoError error;
2064
2065         mono_class_init (field->parent);
2066
2067         t = mono_field_get_type_checked (field, &error);
2068         if (!mono_error_ok (&error)) {
2069                 mono_error_set_pending_exception (&error);
2070                 return NULL;
2071         }
2072
2073         if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT)) {
2074                 mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
2075                 return NULL;
2076         }
2077
2078         if (image_is_dynamic (field->parent->image)) {
2079                 MonoClass *klass = field->parent;
2080                 int fidx = field - klass->fields;
2081                 MonoFieldDefaultValue *def_values = mono_class_get_field_def_values (klass);
2082
2083                 g_assert (def_values);
2084                 def_type = def_values [fidx].def_type;
2085                 def_value = def_values [fidx].data;
2086
2087                 if (def_type == MONO_TYPE_END) {
2088                         mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
2089                         return NULL;
2090                 }
2091         } else {
2092                 def_value = mono_class_get_field_default_value (field, &def_type);
2093                 /* FIXME, maybe we should try to raise TLE if field->parent is broken */
2094                 if (!def_value) {
2095                         mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
2096                         return NULL;
2097                 }
2098         }
2099
2100         /*FIXME unify this with reflection.c:mono_get_object_from_blob*/
2101         switch (def_type) {
2102         case MONO_TYPE_U1:
2103         case MONO_TYPE_I1:
2104         case MONO_TYPE_BOOLEAN:
2105         case MONO_TYPE_U2:
2106         case MONO_TYPE_I2:
2107         case MONO_TYPE_CHAR:
2108         case MONO_TYPE_U:
2109         case MONO_TYPE_I:
2110         case MONO_TYPE_U4:
2111         case MONO_TYPE_I4:
2112         case MONO_TYPE_R4:
2113         case MONO_TYPE_U8:
2114         case MONO_TYPE_I8:
2115         case MONO_TYPE_R8: {
2116                 MonoType *t;
2117
2118                 /* boxed value type */
2119                 t = g_new0 (MonoType, 1);
2120                 t->type = def_type;
2121                 klass = mono_class_from_mono_type (t);
2122                 g_free (t);
2123                 o = mono_object_new_checked (domain, klass, &error);
2124                 if (!mono_error_ok (&error)) {
2125                         mono_error_set_pending_exception (&error);
2126                         return NULL;
2127                 }
2128                 v = ((gchar *) o) + sizeof (MonoObject);
2129                 mono_get_constant_value_from_blob (domain, def_type, def_value, v, &error);
2130                 if (mono_error_set_pending_exception (&error))
2131                         return NULL;
2132                 break;
2133         }
2134         case MONO_TYPE_STRING:
2135         case MONO_TYPE_CLASS:
2136                 mono_get_constant_value_from_blob (domain, def_type, def_value, &o, &error);
2137                 if (mono_error_set_pending_exception (&error))
2138                         return NULL;
2139                 break;
2140         default:
2141                 g_assert_not_reached ();
2142         }
2143
2144         return o;
2145 }
2146
2147 ICALL_EXPORT MonoReflectionTypeHandle
2148 ves_icall_MonoField_ResolveType (MonoReflectionFieldHandle ref_field, MonoError *error)
2149 {
2150         error_init (error);
2151         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_field);
2152         MonoClassField *field = MONO_HANDLE_GETVAL (ref_field, field);
2153         MonoType *type = mono_field_get_type_checked (field, error);
2154         if (!is_ok (error)) {
2155                 return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE);
2156         }
2157         return mono_type_get_object_handle (domain, type, error);
2158 }
2159
2160 /* From MonoProperty.cs */
2161 typedef enum {
2162         PInfo_Attributes = 1,
2163         PInfo_GetMethod  = 1 << 1,
2164         PInfo_SetMethod  = 1 << 2,
2165         PInfo_ReflectedType = 1 << 3,
2166         PInfo_DeclaringType = 1 << 4,
2167         PInfo_Name = 1 << 5
2168 } PInfo;
2169
2170 ICALL_EXPORT void
2171 ves_icall_MonoPropertyInfo_get_property_info (MonoReflectionPropertyHandle property, MonoPropertyInfo *info, PInfo req_info, MonoError *error)
2172 {
2173         error_init (error);
2174         MonoDomain *domain = MONO_HANDLE_DOMAIN (property); 
2175         const MonoProperty *pproperty = MONO_HANDLE_GETVAL (property, property);
2176
2177         if ((req_info & PInfo_ReflectedType) != 0) {
2178                 MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
2179                 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &klass->byval_arg, error);
2180                 return_if_nok (error);
2181
2182                 MONO_STRUCT_SETREF (info, parent, MONO_HANDLE_RAW (rt));
2183         }
2184         if ((req_info & PInfo_DeclaringType) != 0) {
2185                 MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &pproperty->parent->byval_arg, error);
2186                 return_if_nok (error);
2187
2188                 MONO_STRUCT_SETREF (info, declaring_type, MONO_HANDLE_RAW (rt));
2189         }
2190
2191         if ((req_info & PInfo_Name) != 0) {
2192                 MonoStringHandle name = mono_string_new_handle (domain, pproperty->name, error);
2193                 return_if_nok (error);
2194
2195                 MONO_STRUCT_SETREF (info, name, MONO_HANDLE_RAW (name));
2196         }
2197
2198         if ((req_info & PInfo_Attributes) != 0)
2199                 info->attrs = pproperty->attrs;
2200
2201         if ((req_info & PInfo_GetMethod) != 0) {
2202                 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2203                 MonoReflectionMethodHandle rm;
2204                 if (pproperty->get &&
2205                     (((pproperty->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2206                      pproperty->get->klass == property_klass)) {
2207                         rm = mono_method_get_object_handle (domain, pproperty->get, property_klass, error);
2208                         return_if_nok (error);
2209                 } else {
2210                         rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2211                 }
2212
2213                 MONO_STRUCT_SETREF (info, get, MONO_HANDLE_RAW (rm));
2214         }
2215         if ((req_info & PInfo_SetMethod) != 0) {
2216                 MonoClass *property_klass = MONO_HANDLE_GETVAL (property, klass);
2217                 MonoReflectionMethodHandle rm;
2218                 if (pproperty->set &&
2219                     (((pproperty->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
2220                      pproperty->set->klass == property_klass)) {
2221                         rm =  mono_method_get_object_handle (domain, pproperty->set, property_klass, error);
2222                         return_if_nok (error);
2223                 } else {
2224                         rm = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
2225                 }
2226
2227                 MONO_STRUCT_SETREF (info, set, MONO_HANDLE_RAW (rm));
2228         }
2229         /* 
2230          * There may be other methods defined for properties, though, it seems they are not exposed 
2231          * in the reflection API 
2232          */
2233 }
2234
2235 ICALL_EXPORT void
2236 ves_icall_MonoEventInfo_get_event_info (MonoReflectionMonoEvent *event, MonoEventInfo *info)
2237 {
2238         MonoError error;
2239         MonoReflectionType *rt;
2240         MonoReflectionMethod *rm;
2241         MonoDomain *domain = mono_object_domain (event); 
2242
2243         rt = mono_type_get_object_checked (domain, &event->klass->byval_arg, &error);
2244         if (mono_error_set_pending_exception (&error))
2245                 return;
2246
2247         MONO_STRUCT_SETREF (info, reflected_type, rt);
2248
2249         rt = mono_type_get_object_checked (domain, &event->event->parent->byval_arg, &error);
2250         if (mono_error_set_pending_exception (&error))
2251                 return;
2252
2253         MONO_STRUCT_SETREF (info, declaring_type, rt);
2254
2255         MONO_STRUCT_SETREF (info, name, mono_string_new (domain, event->event->name));
2256         info->attrs = event->event->attrs;
2257
2258         if (event->event->add) {
2259                 rm = mono_method_get_object_checked (domain, event->event->add, NULL, &error);
2260                 if (mono_error_set_pending_exception (&error))
2261                         return;
2262         } else {
2263                 rm = NULL;
2264         }
2265
2266         MONO_STRUCT_SETREF (info, add_method, rm);
2267
2268         if (event->event->remove) {
2269                 rm = mono_method_get_object_checked (domain, event->event->remove, NULL, &error);
2270                 if (mono_error_set_pending_exception (&error))
2271                         return;
2272         } else {
2273                 rm = NULL;
2274         }
2275
2276         MONO_STRUCT_SETREF (info, remove_method, rm);
2277
2278         if (event->event->raise) {
2279                 rm = mono_method_get_object_checked (domain, event->event->raise, NULL, &error);
2280                 if (mono_error_set_pending_exception (&error))
2281                         return;
2282         } else {
2283                 rm = NULL;
2284         }
2285
2286         MONO_STRUCT_SETREF (info, raise_method, rm);
2287
2288 #ifndef MONO_SMALL_CONFIG
2289         if (event->event->other) {
2290                 int i, n = 0;
2291                 while (event->event->other [n])
2292                         n++;
2293                 MonoArray *info_arr = mono_array_new_checked (domain, mono_defaults.method_info_class, n, &error);
2294                 if (mono_error_set_pending_exception (&error))
2295                         return;
2296                 MONO_STRUCT_SETREF (info, other_methods, info_arr);
2297
2298                 for (i = 0; i < n; i++) {
2299                         rm = mono_method_get_object_checked (domain, event->event->other [i], NULL, &error);
2300                         if (mono_error_set_pending_exception (&error))
2301                                 return;
2302                         mono_array_setref (info->other_methods, i, rm);
2303                 }
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         MonoReflectionType *ret = mono_type_get_object_checked (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg, &error);
6408         mono_error_set_pending_exception (&error);
6409
6410         return ret;
6411 }
6412 #endif
6413
6414 /* System.Environment */
6415
6416 MonoString*
6417 ves_icall_System_Environment_get_UserName (void)
6418 {
6419         /* using glib is more portable */
6420         return mono_string_new (mono_domain_get (), g_get_user_name ());
6421 }
6422
6423 #ifndef HOST_WIN32
6424 static MonoString *
6425 mono_icall_get_machine_name (void)
6426 {
6427 #if !defined(DISABLE_SOCKETS)
6428         MonoString *result;
6429         char *buf;
6430         int n;
6431 #if defined _SC_HOST_NAME_MAX
6432         n = sysconf (_SC_HOST_NAME_MAX);
6433         if (n == -1)
6434 #endif
6435         n = 512;
6436         buf = g_malloc (n+1);
6437         
6438         if (gethostname (buf, n) == 0){
6439                 buf [n] = 0;
6440                 result = mono_string_new (mono_domain_get (), buf);
6441         } else
6442                 result = NULL;
6443         g_free (buf);
6444         
6445         return result;
6446 #else
6447         return mono_string_new (mono_domain_get (), "mono");
6448 #endif
6449 }
6450 #endif /* !HOST_WIN32 */
6451
6452 ICALL_EXPORT MonoString *
6453 ves_icall_System_Environment_get_MachineName (void)
6454 {
6455         return mono_icall_get_machine_name ();
6456 }
6457
6458 #ifndef HOST_WIN32
6459 static inline int
6460 mono_icall_get_platform (void)
6461 {
6462 #if defined(__MACH__)
6463         /* OSX */
6464         //
6465         // Notice that the value is hidden from user code, and only exposed
6466         // to mscorlib.   This is due to Mono's Unix/MacOS code predating the
6467         // define and making assumptions based on Unix/128/4 values before there
6468         // was a MacOS define.    Lots of code would assume that not-Unix meant
6469         // Windows, but in this case, it would be OSX. 
6470         //
6471         return 6;
6472 #else
6473         /* Unix */
6474         return 4;
6475 #endif
6476 }
6477 #endif /* !HOST_WIN32 */
6478
6479 ICALL_EXPORT int
6480 ves_icall_System_Environment_get_Platform (void)
6481 {
6482         return mono_icall_get_platform ();
6483 }
6484
6485 #ifndef HOST_WIN32
6486 static inline MonoString *
6487 mono_icall_get_new_line (void)
6488 {
6489         return mono_string_new (mono_domain_get (), "\n");
6490 }
6491 #endif /* !HOST_WIN32 */
6492
6493 ICALL_EXPORT MonoString *
6494 ves_icall_System_Environment_get_NewLine (void)
6495 {
6496         return mono_icall_get_new_line ();
6497 }
6498
6499 #ifndef HOST_WIN32
6500 static inline MonoBoolean
6501 mono_icall_is_64bit_os (void)
6502 {
6503 #if SIZEOF_VOID_P == 8
6504         return TRUE;
6505 #else
6506 #if defined(HAVE_SYS_UTSNAME_H)
6507         struct utsname name;
6508
6509         if (uname (&name) >= 0) {
6510                 return strcmp (name.machine, "x86_64") == 0 || strncmp (name.machine, "aarch64", 7) == 0 || strncmp (name.machine, "ppc64", 5) == 0;
6511         }
6512 #endif
6513         return FALSE;
6514 #endif
6515 }
6516 #endif /* !HOST_WIN32 */
6517
6518 ICALL_EXPORT MonoBoolean
6519 ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
6520 {
6521         return mono_icall_is_64bit_os ();
6522 }
6523
6524 ICALL_EXPORT MonoStringHandle
6525 ves_icall_System_Environment_GetEnvironmentVariable_native (const gchar *utf8_name, MonoError *error)
6526 {
6527         const gchar *value;
6528
6529         if (utf8_name == NULL)
6530                 return NULL_HANDLE_STRING;
6531
6532         value = g_getenv (utf8_name);
6533
6534         if (value == 0)
6535                 return NULL_HANDLE_STRING;
6536         
6537         return mono_string_new_handle (mono_domain_get (), value, error);
6538 }
6539
6540 /*
6541  * There is no standard way to get at environ.
6542  */
6543 #ifndef _MSC_VER
6544 #ifndef __MINGW32_VERSION
6545 #if defined(__APPLE__)
6546 #if defined (TARGET_OSX)
6547 /* Apple defines this in crt_externs.h but doesn't provide that header for 
6548  * arm-apple-darwin9.  We'll manually define the symbol on Apple as it does
6549  * in fact exist on all implementations (so far) 
6550  */
6551 gchar ***_NSGetEnviron(void);
6552 #define environ (*_NSGetEnviron())
6553 #else
6554 static char *mono_environ[1] = { NULL };
6555 #define environ mono_environ
6556 #endif /* defined (TARGET_OSX) */
6557 #else
6558 extern
6559 char **environ;
6560 #endif
6561 #endif
6562 #endif
6563
6564 ICALL_EXPORT MonoArray *
6565 ves_icall_System_Environment_GetCoomandLineArgs (void)
6566 {
6567         MonoError error;
6568         MonoArray *result = mono_runtime_get_main_args_checked (&error);
6569         mono_error_set_pending_exception (&error);
6570         return result;
6571 }
6572
6573 #ifndef HOST_WIN32
6574 static MonoArray *
6575 mono_icall_get_environment_variable_names (void)
6576 {
6577         MonoError error;
6578         MonoArray *names;
6579         MonoDomain *domain;
6580         MonoString *str;
6581         gchar **e, **parts;
6582         int n;
6583
6584         n = 0;
6585         for (e = environ; *e != 0; ++ e)
6586                 ++ n;
6587
6588         domain = mono_domain_get ();
6589         names = mono_array_new_checked (domain, mono_defaults.string_class, n, &error);
6590         if (mono_error_set_pending_exception (&error))
6591                 return NULL;
6592
6593         n = 0;
6594         for (e = environ; *e != 0; ++ e) {
6595                 parts = g_strsplit (*e, "=", 2);
6596                 if (*parts != 0) {
6597                         str = mono_string_new (domain, *parts);
6598                         mono_array_setref (names, n, str);
6599                 }
6600
6601                 g_strfreev (parts);
6602
6603                 ++ n;
6604         }
6605
6606         return names;
6607 }
6608 #endif /* !HOST_WIN32 */
6609
6610 ICALL_EXPORT MonoArray *
6611 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
6612 {
6613         return mono_icall_get_environment_variable_names ();
6614 }
6615
6616 #ifndef HOST_WIN32
6617 static void
6618 mono_icall_set_environment_variable (MonoString *name, MonoString *value)
6619 {
6620         gchar *utf8_name, *utf8_value;
6621         MonoError error;
6622
6623         utf8_name = mono_string_to_utf8_checked (name, &error); /* FIXME: this should be ascii */
6624         if (mono_error_set_pending_exception (&error))
6625                 return;
6626
6627         if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
6628                 g_unsetenv (utf8_name);
6629                 g_free (utf8_name);
6630                 return;
6631         }
6632
6633         utf8_value = mono_string_to_utf8_checked (value, &error);
6634         if (!mono_error_ok (&error)) {
6635                 g_free (utf8_name);
6636                 mono_error_set_pending_exception (&error);
6637                 return;
6638         }
6639         g_setenv (utf8_name, utf8_value, TRUE);
6640
6641         g_free (utf8_name);
6642         g_free (utf8_value);
6643 }
6644 #endif /* !HOST_WIN32 */
6645
6646 ICALL_EXPORT void
6647 ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
6648 {
6649         mono_icall_set_environment_variable (name, value);
6650 }
6651
6652 ICALL_EXPORT void
6653 ves_icall_System_Environment_Exit (int result)
6654 {
6655         mono_environment_exitcode_set (result);
6656
6657 /* FIXME: There are some cleanup hangs that should be worked out, but
6658  * if the program is going to exit, everything will be cleaned up when
6659  * NaCl exits anyway.
6660  */
6661 #ifndef __native_client__
6662         if (!mono_runtime_try_shutdown ())
6663                 mono_thread_exit ();
6664
6665         /* Suspend all managed threads since the runtime is going away */
6666         mono_thread_suspend_all_other_threads ();
6667
6668         mono_runtime_quit ();
6669 #endif
6670
6671         /* we may need to do some cleanup here... */
6672         exit (result);
6673 }
6674
6675 ICALL_EXPORT MonoStringHandle
6676 ves_icall_System_Environment_GetGacPath (MonoError *error)
6677 {
6678         return mono_string_new_handle (mono_domain_get (), mono_assembly_getrootdir (), error);
6679 }
6680
6681 #ifndef HOST_WIN32
6682 static inline MonoString *
6683 mono_icall_get_windows_folder_path (int folder)
6684 {
6685         g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
6686         return mono_string_new (mono_domain_get (), "");
6687 }
6688 #endif /* !HOST_WIN32 */
6689
6690 ICALL_EXPORT MonoString*
6691 ves_icall_System_Environment_GetWindowsFolderPath (int folder)
6692 {
6693         return mono_icall_get_windows_folder_path (folder);
6694 }
6695
6696 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
6697 static MonoArray *
6698 mono_icall_get_logical_drives (void)
6699 {
6700         MonoError error;
6701         gunichar2 buf [256], *ptr, *dname;
6702         gunichar2 *u16;
6703         guint initial_size = 127, size = 128;
6704         gint ndrives;
6705         MonoArray *result;
6706         MonoString *drivestr;
6707         MonoDomain *domain = mono_domain_get ();
6708         gint len;
6709
6710         buf [0] = '\0';
6711         ptr = buf;
6712
6713         while (size > initial_size) {
6714                 size = (guint) mono_w32file_get_logical_drive (initial_size, ptr);
6715                 if (size > initial_size) {
6716                         if (ptr != buf)
6717                                 g_free (ptr);
6718                         ptr = (gunichar2 *)g_malloc0 ((size + 1) * sizeof (gunichar2));
6719                         initial_size = size;
6720                         size++;
6721                 }
6722         }
6723
6724         /* Count strings */
6725         dname = ptr;
6726         ndrives = 0;
6727         do {
6728                 while (*dname++);
6729                 ndrives++;
6730         } while (*dname);
6731
6732         dname = ptr;
6733         result = mono_array_new_checked (domain, mono_defaults.string_class, ndrives, &error);
6734         if (mono_error_set_pending_exception (&error))
6735                 goto leave;
6736
6737         ndrives = 0;
6738         do {
6739                 len = 0;
6740                 u16 = dname;
6741                 while (*u16) { u16++; len ++; }
6742                 drivestr = mono_string_new_utf16_checked (domain, dname, len, &error);
6743                 if (mono_error_set_pending_exception (&error))
6744                         goto leave;
6745
6746                 mono_array_setref (result, ndrives++, drivestr);
6747                 while (*dname++);
6748         } while (*dname);
6749
6750 leave:
6751         if (ptr != buf)
6752                 g_free (ptr);
6753
6754         return result;
6755 }
6756 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
6757
6758 ICALL_EXPORT MonoArray *
6759 ves_icall_System_Environment_GetLogicalDrives (void)
6760 {
6761         return mono_icall_get_logical_drives ();
6762 }
6763
6764 ICALL_EXPORT MonoString *
6765 ves_icall_System_IO_DriveInfo_GetDriveFormat (MonoString *path)
6766 {
6767         MonoError error;
6768         gunichar2 volume_name [MAX_PATH + 1];
6769         
6770         if (mono_w32file_get_volume_information (mono_string_chars (path), NULL, 0, NULL, NULL, NULL, volume_name, MAX_PATH + 1) == FALSE)
6771                 return NULL;
6772         MonoString *result = mono_string_from_utf16_checked (volume_name, &error);
6773         mono_error_set_pending_exception (&error);
6774         return result;
6775 }
6776
6777 ICALL_EXPORT MonoStringHandle
6778 ves_icall_System_Environment_InternalGetHome (MonoError *error)
6779 {
6780         return mono_string_new_handle (mono_domain_get (), g_get_home_dir (), error);
6781 }
6782
6783 static const char *encodings [] = {
6784         (char *) 1,
6785                 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
6786                 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
6787                 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
6788         (char *) 2,
6789                 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
6790                 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
6791                 "x_unicode_2_0_utf_7",
6792         (char *) 3,
6793                 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
6794                 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
6795         (char *) 4,
6796                 "utf_16", "UTF_16LE", "ucs_2", "unicode",
6797                 "iso_10646_ucs2",
6798         (char *) 5,
6799                 "unicodefffe", "utf_16be",
6800         (char *) 6,
6801                 "iso_8859_1",
6802         (char *) 0
6803 };
6804
6805 /*
6806  * Returns the internal codepage, if the value of "int_code_page" is
6807  * 1 at entry, and we can not compute a suitable code page number,
6808  * returns the code page as a string
6809  */
6810 ICALL_EXPORT MonoString*
6811 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page) 
6812 {
6813         const char *cset;
6814         const char *p;
6815         char *c;
6816         char *codepage = NULL;
6817         int code;
6818         int want_name = *int_code_page;
6819         int i;
6820         
6821         *int_code_page = -1;
6822
6823         g_get_charset (&cset);
6824         c = codepage = g_strdup (cset);
6825         for (c = codepage; *c; c++){
6826                 if (isascii (*c) && isalpha (*c))
6827                         *c = tolower (*c);
6828                 if (*c == '-')
6829                         *c = '_';
6830         }
6831         /* g_print ("charset: %s\n", cset); */
6832         
6833         /* handle some common aliases */
6834         p = encodings [0];
6835         code = 0;
6836         for (i = 0; p != 0; ){
6837                 if ((gsize) p < 7){
6838                         code = (gssize) p;
6839                         p = encodings [++i];
6840                         continue;
6841                 }
6842                 if (strcmp (p, codepage) == 0){
6843                         *int_code_page = code;
6844                         break;
6845                 }
6846                 p = encodings [++i];
6847         }
6848         
6849         if (strstr (codepage, "utf_8") != NULL)
6850                 *int_code_page |= 0x10000000;
6851         g_free (codepage);
6852         
6853         if (want_name && *int_code_page == -1)
6854                 return mono_string_new (mono_domain_get (), cset);
6855         else
6856                 return NULL;
6857 }
6858
6859 ICALL_EXPORT MonoBoolean
6860 ves_icall_System_Environment_get_HasShutdownStarted (void)
6861 {
6862         if (mono_runtime_is_shutting_down ())
6863                 return TRUE;
6864
6865         if (mono_domain_is_unloading (mono_domain_get ()))
6866                 return TRUE;
6867
6868         return FALSE;
6869 }
6870
6871 #ifndef HOST_WIN32
6872 static inline void
6873 mono_icall_broadcast_setting_change (void)
6874 {
6875         return;
6876 }
6877 #endif /* !HOST_WIN32 */
6878
6879 ICALL_EXPORT void
6880 ves_icall_System_Environment_BroadcastSettingChange (void)
6881 {
6882         mono_icall_broadcast_setting_change ();
6883 }
6884
6885 ICALL_EXPORT
6886 gint32
6887 ves_icall_System_Environment_get_TickCount (void)
6888 {
6889         /* this will overflow after ~24 days */
6890         return (gint32) (mono_msec_boottime () & 0xffffffff);
6891 }
6892
6893 ICALL_EXPORT gint32
6894 ves_icall_System_Runtime_Versioning_VersioningHelper_GetRuntimeId (void)
6895 {
6896         return 9;
6897 }
6898
6899 #ifndef DISABLE_REMOTING
6900 ICALL_EXPORT MonoBoolean
6901 ves_icall_IsTransparentProxy (MonoObject *proxy)
6902 {
6903         if (!proxy)
6904                 return 0;
6905
6906         if (mono_object_is_transparent_proxy (proxy))
6907                 return 1;
6908
6909         return 0;
6910 }
6911
6912 ICALL_EXPORT MonoReflectionMethod *
6913 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
6914         MonoReflectionType *rtype, MonoReflectionMethod *rmethod)
6915 {
6916         MonoReflectionMethod *ret = NULL;
6917         MonoError error;
6918
6919         MonoClass *klass;
6920         MonoMethod *method;
6921         MonoMethod **vtable;
6922         MonoMethod *res = NULL;
6923
6924         MONO_CHECK_ARG_NULL (rtype, NULL);
6925         MONO_CHECK_ARG_NULL (rmethod, NULL);
6926
6927         method = rmethod->method;
6928         klass = mono_class_from_mono_type (rtype->type);
6929         mono_class_init_checked (klass, &error);
6930         if (mono_error_set_pending_exception (&error))
6931                 return NULL;
6932
6933         if (MONO_CLASS_IS_INTERFACE (klass))
6934                 return NULL;
6935
6936         if (method->flags & METHOD_ATTRIBUTE_STATIC)
6937                 return NULL;
6938
6939         if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6940                 if (klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE))
6941                         return rmethod;
6942                 else
6943                         return NULL;
6944         }
6945
6946         mono_class_setup_vtable (klass);
6947         vtable = klass->vtable;
6948
6949         if (mono_class_is_interface (method->klass)) {
6950                 gboolean variance_used = FALSE;
6951                 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
6952                 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
6953                 if (offs >= 0)
6954                         res = vtable [offs + method->slot];
6955         } else {
6956                 if (!(klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE)))
6957                         return NULL;
6958
6959                 if (method->slot != -1)
6960                         res = vtable [method->slot];
6961         }
6962
6963         if (!res)
6964                 return NULL;
6965
6966         ret = mono_method_get_object_checked (mono_domain_get (), res, NULL, &error);
6967         mono_error_set_pending_exception (&error);
6968         return ret;
6969 }
6970
6971 ICALL_EXPORT void
6972 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6973 {
6974         MonoError error;
6975         MonoClass *klass;
6976         MonoVTable* vtable;
6977
6978         klass = mono_class_from_mono_type (type->type);
6979         vtable = mono_class_vtable_full (mono_domain_get (), klass, &error);
6980         if (!is_ok (&error)) {
6981                 mono_error_set_pending_exception (&error);
6982                 return;
6983         }
6984
6985         mono_vtable_set_is_remote (vtable, enable);
6986 }
6987
6988 #else /* DISABLE_REMOTING */
6989
6990 ICALL_EXPORT void
6991 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6992 {
6993         g_assert_not_reached ();
6994 }
6995
6996 #endif
6997
6998 ICALL_EXPORT MonoObject *
6999 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionType *type)
7000 {
7001         MonoError error;
7002         MonoClass *klass;
7003         MonoDomain *domain;
7004         MonoObject *ret;
7005         
7006         domain = mono_object_domain (type);
7007         klass = mono_class_from_mono_type (type->type);
7008         mono_class_init_checked (klass, &error);
7009         if (mono_error_set_pending_exception (&error))
7010                 return NULL;
7011
7012         if (MONO_CLASS_IS_INTERFACE (klass) || mono_class_is_abstract (klass)) {
7013                 mono_set_pending_exception (mono_get_exception_argument ("type", "Type cannot be instantiated"));
7014                 return NULL;
7015         }
7016
7017         if (klass->rank >= 1) {
7018                 g_assert (klass->rank == 1);
7019                 ret = (MonoObject *) mono_array_new_checked (domain, klass->element_class, 0, &error);
7020                 mono_error_set_pending_exception (&error);
7021                 return ret;
7022         } else {
7023                 MonoVTable *vtable = mono_class_vtable_full (domain, klass, &error);
7024                 if (!is_ok (&error)) {
7025                         mono_error_set_pending_exception (&error);
7026                         return NULL;
7027                 }
7028                 /* Bypass remoting object creation check */
7029                 ret = mono_object_new_alloc_specific_checked (vtable, &error);
7030                 mono_error_set_pending_exception (&error);
7031
7032                 return ret;
7033         }
7034 }
7035
7036 ICALL_EXPORT MonoStringHandle
7037 ves_icall_System_IO_get_temp_path (MonoError *error)
7038 {
7039         return mono_string_new_handle (mono_domain_get (), g_get_tmp_dir (), error);
7040 }
7041
7042 #ifndef PLATFORM_NO_DRIVEINFO
7043 ICALL_EXPORT MonoBoolean
7044 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (MonoString *path_name, guint64 *free_bytes_avail,
7045                                                 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
7046                                                 gint32 *error)
7047 {
7048         gboolean result;
7049
7050         *error = ERROR_SUCCESS;
7051
7052         result = mono_w32file_get_disk_free_space (mono_string_chars (path_name), free_bytes_avail, total_number_of_bytes, total_number_of_free_bytes);
7053         if (!result)
7054                 *error = mono_w32error_get_last ();
7055
7056         return result;
7057 }
7058
7059 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
7060 static inline guint32
7061 mono_icall_drive_info_get_drive_type (MonoString *root_path_name)
7062 {
7063         return mono_w32file_get_drive_type (mono_string_chars (root_path_name));
7064 }
7065 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
7066
7067 ICALL_EXPORT guint32
7068 ves_icall_System_IO_DriveInfo_GetDriveType (MonoString *root_path_name)
7069 {
7070         return mono_icall_drive_info_get_drive_type (root_path_name);
7071 }
7072
7073 #endif /* PLATFORM_NO_DRIVEINFO */
7074
7075 ICALL_EXPORT gpointer
7076 ves_icall_RuntimeMethodHandle_GetFunctionPointer (MonoMethod *method)
7077 {
7078         MonoError error;
7079         gpointer result = mono_compile_method_checked (method, &error);
7080         mono_error_set_pending_exception (&error);
7081         return result;
7082 }
7083
7084 ICALL_EXPORT MonoString *
7085 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
7086 {
7087         MonoString *mcpath;
7088         gchar *path;
7089
7090         path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
7091
7092         mono_icall_make_platform_path (path);
7093
7094         mcpath = mono_string_new (mono_domain_get (), path);
7095         g_free (path);
7096
7097         return mcpath;
7098 }
7099
7100 /* this is an icall */
7101 static MonoString *
7102 get_bundled_app_config (void)
7103 {
7104         MonoError error;
7105         const gchar *app_config;
7106         MonoDomain *domain;
7107         MonoString *file;
7108         gchar *config_file_name, *config_file_path;
7109         gsize len, config_file_path_length, config_ext_length;
7110         gchar *module;
7111
7112         domain = mono_domain_get ();
7113         file = domain->setup->configuration_file;
7114         if (!file || file->length == 0)
7115                 return NULL;
7116
7117         // Retrieve config file and remove the extension
7118         config_file_name = mono_string_to_utf8_checked (file, &error);
7119         if (mono_error_set_pending_exception (&error))
7120                 return NULL;
7121         config_file_path = mono_portability_find_file (config_file_name, TRUE);
7122         if (!config_file_path)
7123                 config_file_path = config_file_name;
7124
7125         config_file_path_length = strlen (config_file_path);
7126         config_ext_length = strlen (".config");
7127         if (config_file_path_length <= config_ext_length)
7128                 return NULL;
7129
7130         len = config_file_path_length - config_ext_length;
7131         module = (gchar *)g_malloc0 (len + 1);
7132         memcpy (module, config_file_path, len);
7133         // Get the config file from the module name
7134         app_config = mono_config_string_for_assembly_file (module);
7135         // Clean-up
7136         g_free (module);
7137         if (config_file_name != config_file_path)
7138                 g_free (config_file_name);
7139         g_free (config_file_path);
7140
7141         if (!app_config)
7142                 return NULL;
7143
7144         return mono_string_new (mono_domain_get (), app_config);
7145 }
7146
7147 static MonoStringHandle
7148 get_bundled_machine_config (MonoError *error)
7149 {
7150         const gchar *machine_config;
7151
7152         machine_config = mono_get_machine_config ();
7153
7154         if (!machine_config)
7155                 return NULL_HANDLE_STRING;
7156
7157         return mono_string_new_handle (mono_domain_get (), machine_config, error);
7158 }
7159
7160 ICALL_EXPORT MonoStringHandle
7161 ves_icall_System_Environment_get_bundled_machine_config (MonoError *error)
7162 {
7163         return get_bundled_machine_config (error);
7164 }
7165
7166
7167 ICALL_EXPORT MonoStringHandle
7168 ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
7169 {
7170         return get_bundled_machine_config (error);
7171 }
7172
7173 ICALL_EXPORT MonoStringHandle
7174 ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
7175 {
7176         return get_bundled_machine_config (error);
7177 }
7178
7179
7180 ICALL_EXPORT MonoString *
7181 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
7182 {
7183         MonoString *ipath;
7184         gchar *path;
7185
7186         path = g_path_get_dirname (mono_get_config_dir ());
7187
7188         mono_icall_make_platform_path (path);
7189
7190         ipath = mono_string_new (mono_domain_get (), path);
7191         g_free (path);
7192
7193         return ipath;
7194 }
7195
7196 ICALL_EXPORT gboolean
7197 ves_icall_get_resources_ptr (MonoReflectionAssemblyHandle assembly, gpointer *result, gint32 *size, MonoError *error)
7198 {
7199         error_init (error);
7200         MonoPEResourceDataEntry *entry;
7201         MonoImage *image;
7202
7203         if (!assembly || !result || !size)
7204                 return FALSE;
7205
7206         *result = NULL;
7207         *size = 0;
7208         MonoAssembly *assm = MONO_HANDLE_GETVAL (assembly, assembly);
7209         image = assm->image;
7210         entry = (MonoPEResourceDataEntry *)mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
7211         if (!entry)
7212                 return FALSE;
7213
7214         *result = mono_image_rva_map (image, entry->rde_data_offset);
7215         if (!(*result)) {
7216                 g_free (entry);
7217                 return FALSE;
7218         }
7219         *size = entry->rde_size;
7220         g_free (entry);
7221         return TRUE;
7222 }
7223
7224 ICALL_EXPORT MonoBoolean
7225 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (void)
7226 {
7227         return mono_is_debugger_attached ();
7228 }
7229
7230 ICALL_EXPORT MonoBoolean
7231 ves_icall_System_Diagnostics_Debugger_IsLogging (void)
7232 {
7233         if (mono_get_runtime_callbacks ()->debug_log_is_enabled)
7234                 return mono_get_runtime_callbacks ()->debug_log_is_enabled ();
7235         else
7236                 return FALSE;
7237 }
7238
7239 ICALL_EXPORT void
7240 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoString *category, MonoString *message)
7241 {
7242         if (mono_get_runtime_callbacks ()->debug_log)
7243                 mono_get_runtime_callbacks ()->debug_log (level, category, message);
7244 }
7245
7246 #ifndef HOST_WIN32
7247 static inline void
7248 mono_icall_write_windows_debug_string (MonoString *message)
7249 {
7250         g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
7251 }
7252 #endif /* !HOST_WIN32 */
7253
7254 ICALL_EXPORT void
7255 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
7256 {
7257         mono_icall_write_windows_debug_string (message);
7258 }
7259
7260 /* Only used for value types */
7261 ICALL_EXPORT MonoObjectHandle
7262 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
7263 {
7264         error_init (error);
7265         MonoDomain *domain = MONO_HANDLE_DOMAIN (ref_type);
7266         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
7267         MonoClass *klass = mono_class_from_mono_type (type);
7268
7269         mono_class_init_checked (klass, error);
7270         if (!is_ok (error))
7271                 return NULL_HANDLE;
7272
7273         if (mono_class_is_nullable (klass))
7274                 /* No arguments -> null */
7275                 return NULL_HANDLE;
7276
7277         return MONO_HANDLE_NEW (MonoObject, mono_object_new_checked (domain, klass, error));
7278 }
7279
7280 ICALL_EXPORT MonoReflectionMethodHandle
7281 ves_icall_MonoMethod_get_base_method (MonoReflectionMethodHandle m, gboolean definition, MonoError *error)
7282 {
7283         error_init (error);
7284         MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
7285
7286         MonoMethod *base = mono_method_get_base_method (method, definition, error);
7287         return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE));
7288         if (base == method) {
7289                 /* we want to short-circuit and return 'm' here. But we should
7290                    return the same method object that
7291                    mono_method_get_object_handle, below would return.  Since
7292                    that call takes NULL for the reftype argument, it will take
7293                    base->klass as the reflected type for the MonoMethod.  So we
7294                    need to check that m also has base->klass as the reflected
7295                    type. */
7296                 MonoReflectionTypeHandle orig_reftype = MONO_HANDLE_NEW_GET (MonoReflectionType, m, reftype);
7297                 MonoClass *orig_klass = mono_class_from_mono_type (MONO_HANDLE_GETVAL (orig_reftype, type));
7298                 if (base->klass == orig_klass)
7299                         return m;
7300         }
7301         return mono_method_get_object_handle (mono_domain_get (), base, NULL, error);
7302 }
7303
7304 ICALL_EXPORT MonoStringHandle
7305 ves_icall_MonoMethod_get_name (MonoReflectionMethodHandle m, MonoError *error)
7306 {
7307         error_init (error);
7308         MonoMethod *method = MONO_HANDLE_GETVAL (m, method);
7309
7310         MonoStringHandle s = mono_string_new_handle (MONO_HANDLE_DOMAIN (m), method->name, error);
7311         if (!is_ok (error))
7312                 return NULL_HANDLE_STRING;
7313         MONO_HANDLE_SET (m, name, s);
7314         return s;
7315 }
7316
7317 ICALL_EXPORT void
7318 mono_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
7319 {
7320         iter->sig = *(MonoMethodSignature**)argsp;
7321         
7322         g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
7323         g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
7324
7325         iter->next_arg = 0;
7326         /* FIXME: it's not documented what start is exactly... */
7327         if (start) {
7328                 iter->args = start;
7329         } else {
7330                 iter->args = argsp + sizeof (gpointer);
7331         }
7332         iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
7333
7334         /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
7335 }
7336
7337 ICALL_EXPORT MonoTypedRef
7338 mono_ArgIterator_IntGetNextArg (MonoArgIterator *iter)
7339 {
7340         guint32 i, arg_size;
7341         gint32 align;
7342         MonoTypedRef res;
7343
7344         i = iter->sig->sentinelpos + iter->next_arg;
7345
7346         g_assert (i < iter->sig->param_count);
7347
7348         res.type = iter->sig->params [i];
7349         res.klass = mono_class_from_mono_type (res.type);
7350         arg_size = mono_type_stack_size (res.type, &align);
7351 #if defined(__arm__) || defined(__mips__)
7352         iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7353 #endif
7354         res.value = iter->args;
7355 #if defined(__native_client__) && SIZEOF_REGISTER == 8
7356         /* Values are stored as 8 byte register sized objects, but 'value'
7357          * is dereferenced as a pointer in other routines.
7358          */
7359         res.value = (char*)res.value + 4;
7360 #endif
7361 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
7362         if (arg_size <= sizeof (gpointer)) {
7363                 int dummy;
7364                 int padding = arg_size - mono_type_size (res.type, &dummy);
7365                 res.value = (guint8*)res.value + padding;
7366         }
7367 #endif
7368         iter->args = (char*)iter->args + arg_size;
7369         iter->next_arg++;
7370
7371         /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7372
7373         return res;
7374 }
7375
7376 ICALL_EXPORT MonoTypedRef
7377 mono_ArgIterator_IntGetNextArgT (MonoArgIterator *iter, MonoType *type)
7378 {
7379         guint32 i, arg_size;
7380         gint32 align;
7381         MonoTypedRef res;
7382
7383         i = iter->sig->sentinelpos + iter->next_arg;
7384
7385         g_assert (i < iter->sig->param_count);
7386
7387         while (i < iter->sig->param_count) {
7388                 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
7389                         continue;
7390                 res.type = iter->sig->params [i];
7391                 res.klass = mono_class_from_mono_type (res.type);
7392                 /* FIXME: endianess issue... */
7393                 arg_size = mono_type_stack_size (res.type, &align);
7394 #if defined(__arm__) || defined(__mips__)
7395                 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7396 #endif
7397                 res.value = iter->args;
7398                 iter->args = (char*)iter->args + arg_size;
7399                 iter->next_arg++;
7400                 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7401                 return res;
7402         }
7403         /* g_print ("arg type 0x%02x not found\n", res.type->type); */
7404
7405         res.type = NULL;
7406         res.value = NULL;
7407         res.klass = NULL;
7408         return res;
7409 }
7410
7411 ICALL_EXPORT MonoType*
7412 mono_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
7413 {
7414         gint i;
7415         
7416         i = iter->sig->sentinelpos + iter->next_arg;
7417
7418         g_assert (i < iter->sig->param_count);
7419
7420         return iter->sig->params [i];
7421 }
7422
7423 ICALL_EXPORT MonoObject*
7424 mono_TypedReference_ToObject (MonoTypedRef* tref)
7425 {
7426         MonoError error;
7427         MonoObject *result = NULL;
7428         if (MONO_TYPE_IS_REFERENCE (tref->type)) {
7429                 MonoObject** objp = (MonoObject **)tref->value;
7430                 return *objp;
7431         }
7432
7433         result = mono_value_box_checked (mono_domain_get (), tref->klass, tref->value, &error);
7434         mono_error_set_pending_exception (&error);
7435         return result;
7436 }
7437
7438 ICALL_EXPORT MonoTypedRef
7439 mono_TypedReference_MakeTypedReferenceInternal (MonoObject *target, MonoArray *fields)
7440 {
7441         MonoTypedRef res;
7442         MonoReflectionField *f;
7443         MonoClass *klass;
7444         MonoType *ftype = NULL;
7445         guint8 *p = NULL;
7446         int i;
7447
7448         memset (&res, 0, sizeof (res));
7449
7450         g_assert (fields);
7451         g_assert (mono_array_length (fields) > 0);
7452
7453         klass = target->vtable->klass;
7454
7455         for (i = 0; i < mono_array_length (fields); ++i) {
7456                 f = mono_array_get (fields, MonoReflectionField*, i);
7457                 if (f == NULL) {
7458                         mono_set_pending_exception (mono_get_exception_argument_null ("field"));
7459                         return res;
7460                 }
7461                 if (f->field->parent != klass) {
7462                         mono_set_pending_exception (mono_get_exception_argument ("field", ""));
7463                         return res;
7464                 }
7465                 if (i == 0)
7466                         p = (guint8*)target + f->field->offset;
7467                 else
7468                         p += f->field->offset - sizeof (MonoObject);
7469                 klass = mono_class_from_mono_type (f->field->type);
7470                 ftype = f->field->type;
7471         }
7472
7473         res.type = ftype;
7474         res.klass = mono_class_from_mono_type (ftype);
7475         res.value = p;
7476
7477         return res;
7478 }
7479
7480 static void
7481 prelink_method (MonoMethod *method, MonoError *error)
7482 {
7483         const char *exc_class, *exc_arg;
7484
7485         error_init (error);
7486         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7487                 return;
7488         mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7489         if (exc_class) {
7490                 mono_error_set_exception_instance (error,
7491                         mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg));
7492                 return;
7493         }
7494         /* create the wrapper, too? */
7495 }
7496
7497 ICALL_EXPORT void
7498 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethod *method)
7499 {
7500         MonoError error;
7501
7502         prelink_method (method->method, &error);
7503         mono_error_set_pending_exception (&error);
7504 }
7505
7506 ICALL_EXPORT void
7507 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionType *type)
7508 {
7509         MonoError error;
7510         MonoClass *klass = mono_class_from_mono_type (type->type);
7511         MonoMethod* m;
7512         gpointer iter = NULL;
7513
7514         mono_class_init_checked (klass, &error);
7515         if (mono_error_set_pending_exception (&error))
7516                 return;
7517
7518         while ((m = mono_class_get_methods (klass, &iter))) {
7519                 prelink_method (m, &error);
7520                 if (mono_error_set_pending_exception (&error))
7521                         return;
7522         }
7523 }
7524
7525 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
7526 ICALL_EXPORT void
7527 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
7528                                             gint32 const **exponents,
7529                                             gunichar2 const **digitLowerTable,
7530                                             gunichar2 const **digitUpperTable,
7531                                             gint64 const **tenPowersList,
7532                                             gint32 const **decHexDigits)
7533 {
7534         *mantissas = Formatter_MantissaBitsTable;
7535         *exponents = Formatter_TensExponentTable;
7536         *digitLowerTable = Formatter_DigitLowerTable;
7537         *digitUpperTable = Formatter_DigitUpperTable;
7538         *tenPowersList = Formatter_TenPowersList;
7539         *decHexDigits = Formatter_DecHexDigits;
7540 }
7541
7542 static gboolean
7543 add_modifier_to_array (MonoDomain *domain, MonoImage *image, MonoCustomMod *modifier, MonoArrayHandle dest, int dest_idx, MonoError *error)
7544 {
7545         HANDLE_FUNCTION_ENTER ();
7546         error_init (error);
7547         MonoClass *klass = mono_class_get_checked (image, modifier->token, error);
7548         if (!is_ok (error))
7549                 goto leave;
7550
7551         MonoReflectionTypeHandle rt = mono_type_get_object_handle (domain, &klass->byval_arg, error);
7552         if (!is_ok (error))
7553                 goto leave;
7554
7555         MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, rt);
7556 leave:
7557         HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
7558 }
7559
7560 /*
7561  * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
7562  * and avoid useless allocations.
7563  */
7564 static MonoArrayHandle
7565 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoError *error)
7566 {
7567         int i, count = 0;
7568         MonoDomain *domain = mono_domain_get ();
7569
7570         error_init (error);
7571         for (i = 0; i < type->num_mods; ++i) {
7572                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required))
7573                         count++;
7574         }
7575         if (!count)
7576                 return MONO_HANDLE_NEW (MonoArray, NULL);
7577
7578         MonoArrayHandle res = mono_array_new_handle (domain, mono_defaults.systemtype_class, count, error);
7579         if (!is_ok (error))
7580                 goto fail;
7581         count = 0;
7582         for (i = 0; i < type->num_mods; ++i) {
7583                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required)) {
7584                         if (!add_modifier_to_array (domain, image, &type->modifiers[i], res, count , error))
7585                                 goto fail;
7586                         count++;
7587                 }
7588         }
7589         return res;
7590 fail:
7591         return MONO_HANDLE_NEW (MonoArray, NULL);
7592 }
7593
7594 ICALL_EXPORT MonoArrayHandle
7595 ves_icall_ParameterInfo_GetTypeModifiers (MonoReflectionParameterHandle param, MonoBoolean optional, MonoError *error)
7596 {
7597         error_init (error);
7598         MonoReflectionTypeHandle rt = MONO_HANDLE_NEW (MonoReflectionType, NULL);
7599         MONO_HANDLE_GET (rt, param, ClassImpl);
7600         MonoType *type = MONO_HANDLE_GETVAL (rt, type);
7601         MonoObjectHandle member = MONO_HANDLE_NEW (MonoObject, NULL);
7602         MONO_HANDLE_GET (member, param, MemberImpl);
7603         MonoClass *member_class = mono_handle_class (member);
7604         MonoMethod *method = NULL;
7605         MonoImage *image;
7606         int pos;
7607         MonoMethodSignature *sig;
7608
7609         if (mono_class_is_reflection_method_or_constructor (member_class)) {
7610                 method = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionMethod, member), method);
7611         } else if (member_class->image == mono_defaults.corlib && !strcmp ("MonoProperty", member_class->name)) {
7612                 MonoProperty *prop = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionProperty, member), property);
7613                 if (!(method = prop->get))
7614                         method = prop->set;
7615                 g_assert (method);      
7616         } else {
7617                 char *type_name = mono_type_get_full_name (member_class);
7618                 mono_error_set_not_supported (error, "Custom modifiers on a ParamInfo with member %s are not supported", type_name);
7619                 g_free (type_name);
7620                 return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
7621         }
7622
7623         image = method->klass->image;
7624         pos = MONO_HANDLE_GETVAL (param, PositionImpl);
7625         sig = mono_method_signature (method);
7626         if (pos == -1)
7627                 type = sig->ret;
7628         else
7629                 type = sig->params [pos];
7630
7631         return type_array_from_modifiers (image, type, optional, error);
7632 }
7633
7634 static MonoType*
7635 get_property_type (MonoProperty *prop)
7636 {
7637         MonoMethodSignature *sig;
7638         if (prop->get) {
7639                 sig = mono_method_signature (prop->get);
7640                 return sig->ret;
7641         } else if (prop->set) {
7642                 sig = mono_method_signature (prop->set);
7643                 return sig->params [sig->param_count - 1];
7644         }
7645         return NULL;
7646 }
7647
7648 ICALL_EXPORT MonoArrayHandle
7649 ves_icall_MonoPropertyInfo_GetTypeModifiers (MonoReflectionPropertyHandle property, MonoBoolean optional, MonoError *error)
7650 {
7651         error_init (error);
7652         MonoProperty *prop = MONO_HANDLE_GETVAL (property, property);
7653         MonoClass *klass = MONO_HANDLE_GETVAL (property, klass);
7654         MonoType *type = get_property_type (prop);
7655         MonoImage *image = klass->image;
7656
7657         if (!type)
7658                 return MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
7659         return type_array_from_modifiers (image, type, optional, error);
7660 }
7661
7662 /*
7663  *Construct a MonoType suited to be used to decode a constant blob object.
7664  *
7665  * @type is the target type which will be constructed
7666  * @blob_type is the blob type, for example, that comes from the constant table
7667  * @real_type is the expected constructed type.
7668  */
7669 static void
7670 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
7671 {
7672         type->type = blob_type;
7673         type->data.klass = NULL;
7674         if (blob_type == MONO_TYPE_CLASS)
7675                 type->data.klass = mono_defaults.object_class;
7676         else if (real_type->type == MONO_TYPE_VALUETYPE && real_type->data.klass->enumtype) {
7677                 /* For enums, we need to use the base type */
7678                 type->type = MONO_TYPE_VALUETYPE;
7679                 type->data.klass = mono_class_from_mono_type (real_type);
7680         } else
7681                 type->data.klass = mono_class_from_mono_type (real_type);
7682 }
7683
7684 ICALL_EXPORT MonoObject*
7685 property_info_get_default_value (MonoReflectionProperty *property)
7686 {
7687         MonoError error;
7688         MonoType blob_type;
7689         MonoProperty *prop = property->property;
7690         MonoType *type = get_property_type (prop);
7691         MonoDomain *domain = mono_object_domain (property); 
7692         MonoTypeEnum def_type;
7693         const char *def_value;
7694         MonoObject *o;
7695
7696         mono_class_init (prop->parent);
7697
7698         if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT)) {
7699                 mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
7700                 return NULL;
7701         }
7702
7703         def_value = mono_class_get_property_default_value (prop, &def_type);
7704
7705         mono_type_from_blob_type (&blob_type, def_type, type);
7706         o = mono_get_object_from_blob (domain, &blob_type, def_value, &error);
7707
7708         mono_error_set_pending_exception (&error);
7709         return o;
7710 }
7711
7712 ICALL_EXPORT MonoBoolean
7713 custom_attrs_defined_internal (MonoObject *obj, MonoReflectionType *attr_type)
7714 {
7715         MonoError error;
7716         MonoClass *attr_class = mono_class_from_mono_type (attr_type->type);
7717         MonoCustomAttrInfo *cinfo;
7718         gboolean found;
7719
7720         mono_class_init_checked (attr_class, &error);
7721         if (mono_error_set_pending_exception (&error))
7722                 return FALSE;
7723
7724         cinfo = mono_reflection_get_custom_attrs_info_checked (obj, &error);
7725         if (!is_ok (&error)) {
7726                 mono_error_set_pending_exception (&error);
7727                 return FALSE;
7728         }
7729         if (!cinfo)
7730                 return FALSE;
7731         found = mono_custom_attrs_has_attr (cinfo, attr_class);
7732         if (!cinfo->cached)
7733                 mono_custom_attrs_free (cinfo);
7734         return found;
7735 }
7736
7737 ICALL_EXPORT MonoArray*
7738 custom_attrs_get_by_type (MonoObject *obj, MonoReflectionType *attr_type)
7739 {
7740         MonoClass *attr_class = attr_type ? mono_class_from_mono_type (attr_type->type) : NULL;
7741         MonoArray *res;
7742         MonoError error;
7743
7744         if (attr_class) {
7745                 mono_class_init_checked (attr_class, &error);
7746                 if (mono_error_set_pending_exception (&error))
7747                         return NULL;
7748         }
7749
7750         res = mono_reflection_get_custom_attrs_by_type (obj, attr_class, &error);
7751         if (!mono_error_ok (&error)) {
7752                 mono_error_set_pending_exception (&error);
7753                 return NULL;
7754         }
7755
7756         return res;
7757 }
7758
7759 ICALL_EXPORT MonoArray*
7760 ves_icall_MonoCustomAttrs_GetCustomAttributesDataInternal (MonoObject *obj)
7761 {
7762         MonoError error;
7763         MonoArray *result;
7764         result = mono_reflection_get_custom_attrs_data_checked (obj, &error);
7765         mono_error_set_pending_exception (&error);
7766         return result;
7767 }
7768
7769
7770 ICALL_EXPORT MonoStringHandle
7771 ves_icall_Mono_Runtime_GetDisplayName (MonoError *error)
7772 {
7773         char *info;
7774         MonoStringHandle display_name;
7775
7776         error_init (error);
7777         info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
7778         display_name = mono_string_new_handle (mono_domain_get (), info, error);
7779         g_free (info);
7780         return display_name;
7781 }
7782
7783 #ifndef HOST_WIN32
7784 static inline gint32
7785 mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
7786 {
7787         return WAIT_TIMEOUT;
7788 }
7789 #endif /* !HOST_WIN32 */
7790
7791 ICALL_EXPORT gint32
7792 ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle (gpointer handle, gint32 milliseconds)
7793 {
7794         return mono_icall_wait_for_input_idle (handle, milliseconds);
7795 }
7796
7797 ICALL_EXPORT gint32
7798 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcessId (void)
7799 {
7800         return mono_process_current_pid ();
7801 }
7802
7803 ICALL_EXPORT MonoBoolean
7804 ves_icall_Mono_TlsProviderFactory_IsBtlsSupported (void)
7805 {
7806 #if HAVE_BTLS
7807         return TRUE;
7808 #else
7809         return FALSE;
7810 #endif
7811 }
7812
7813 #ifndef DISABLE_COM
7814
7815 ICALL_EXPORT int
7816 ves_icall_System_Runtime_InteropServices_Marshal_GetHRForException_WinRT(MonoException* ex)
7817 {
7818         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.Marshal.GetHRForException_WinRT internal call is not implemented."));
7819         return 0;
7820 }
7821
7822 ICALL_EXPORT MonoObject*
7823 ves_icall_System_Runtime_InteropServices_Marshal_GetNativeActivationFactory(MonoObject* type)
7824 {
7825         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.Marshal.GetNativeActivationFactory internal call is not implemented."));
7826         return NULL;
7827 }
7828
7829 ICALL_EXPORT void*
7830 ves_icall_System_Runtime_InteropServices_Marshal_GetRawIUnknownForComObjectNoAddRef(MonoObject* obj)
7831 {
7832         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.Marshal.GetRawIUnknownForComObjectNoAddRef internal call is not implemented."));
7833         return NULL;
7834 }
7835
7836 ICALL_EXPORT MonoObject*
7837 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_GetRestrictedErrorInfo()
7838 {
7839         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.GetRestrictedErrorInfo internal call is not implemented."));
7840         return NULL;
7841 }
7842
7843 ICALL_EXPORT MonoBoolean
7844 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoOriginateLanguageException(int error, MonoString* message, void* languageException)
7845 {
7846         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoOriginateLanguageException internal call is not implemented."));
7847         return FALSE;
7848 }
7849
7850 ICALL_EXPORT void
7851 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_RoReportUnhandledError(MonoObject* error)
7852 {
7853         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.RoReportUnhandledError internal call is not implemented."));
7854 }
7855
7856 ICALL_EXPORT int
7857 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsCreateString(MonoString* sourceString, int length, void** hstring)
7858 {
7859         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString internal call is not implemented."));
7860         return 0;
7861 }
7862
7863 ICALL_EXPORT int
7864 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsDeleteString(void* hstring)
7865 {
7866         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString internal call is not implemented."));
7867         return 0;
7868 }
7869
7870 ICALL_EXPORT mono_unichar2*
7871 ves_icall_System_Runtime_InteropServices_WindowsRuntime_UnsafeNativeMethods_WindowsGetStringRawBuffer(void* hstring, unsigned* length)
7872 {
7873         mono_set_pending_exception(mono_get_exception_not_implemented("System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsGetStringRawBuffer internal call is not implemented."));
7874         return NULL;
7875 }
7876
7877 #endif
7878
7879
7880 #ifndef DISABLE_ICALL_TABLES
7881
7882 #define ICALL_TYPE(id,name,first)
7883 #define ICALL(id,name,func) Icall_ ## id,
7884 #define HANDLES(inner) inner
7885
7886 enum {
7887 #include "metadata/icall-def.h"
7888         Icall_last
7889 };
7890
7891 #undef ICALL_TYPE
7892 #undef ICALL
7893 #define ICALL_TYPE(id,name,first) Icall_type_ ## id,
7894 #define ICALL(id,name,func)
7895 #undef HANDLES
7896 #define HANDLES(inner) inner
7897 enum {
7898 #include "metadata/icall-def.h"
7899         Icall_type_num
7900 };
7901
7902 #undef ICALL_TYPE
7903 #undef ICALL
7904 #define ICALL_TYPE(id,name,firstic) {(Icall_ ## firstic)},
7905 #define ICALL(id,name,func)
7906 #undef HANDLES
7907 #define HANDLES(inner) inner
7908 typedef struct {
7909         guint16 first_icall;
7910 } IcallTypeDesc;
7911
7912 static const IcallTypeDesc
7913 icall_type_descs [] = {
7914 #include "metadata/icall-def.h"
7915         {Icall_last}
7916 };
7917
7918 #define icall_desc_num_icalls(desc) ((desc) [1].first_icall - (desc) [0].first_icall)
7919
7920 #undef HANDLES
7921 #define HANDLES(inner) inner
7922 #undef ICALL_TYPE
7923 #define ICALL_TYPE(id,name,first)
7924 #undef ICALL
7925
7926 #ifdef HAVE_ARRAY_ELEM_INIT
7927 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
7928 #define MSGSTRFIELD1(line) str##line
7929
7930 static const struct msgstrtn_t {
7931 #define ICALL(id,name,func)
7932 #undef ICALL_TYPE
7933 #define ICALL_TYPE(id,name,first) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7934 #include "metadata/icall-def.h"
7935 #undef ICALL_TYPE
7936 } icall_type_names_str = {
7937 #define ICALL_TYPE(id,name,first) (name),
7938 #include "metadata/icall-def.h"
7939 #undef ICALL_TYPE
7940 };
7941 static const guint16 icall_type_names_idx [] = {
7942 #define ICALL_TYPE(id,name,first) [Icall_type_ ## id] = offsetof (struct msgstrtn_t, MSGSTRFIELD(__LINE__)),
7943 #include "metadata/icall-def.h"
7944 #undef ICALL_TYPE
7945 };
7946 #define icall_type_name_get(id) ((const char*)&icall_type_names_str + icall_type_names_idx [(id)])
7947
7948 static const struct msgstr_t {
7949 #undef ICALL
7950 #define ICALL_TYPE(id,name,first)
7951 #define ICALL(id,name,func) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7952 #include "metadata/icall-def.h"
7953 #undef ICALL
7954 } icall_names_str = {
7955 #define ICALL(id,name,func) (name),
7956 #include "metadata/icall-def.h"
7957 #undef ICALL
7958 };
7959 static const guint16 icall_names_idx [] = {
7960 #define ICALL(id,name,func) [Icall_ ## id] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
7961 #include "metadata/icall-def.h"
7962 #undef ICALL
7963 };
7964 #define icall_name_get(id) ((const char*)&icall_names_str + icall_names_idx [(id)])
7965
7966 #else
7967
7968 #undef ICALL_TYPE
7969 #undef ICALL
7970 #define ICALL_TYPE(id,name,first) name,
7971 #define ICALL(id,name,func)
7972 static const char* const
7973 icall_type_names [] = {
7974 #include "metadata/icall-def.h"
7975         NULL
7976 };
7977
7978 #define icall_type_name_get(id) (icall_type_names [(id)])
7979
7980 #undef ICALL_TYPE
7981 #undef ICALL
7982 #define ICALL_TYPE(id,name,first)
7983 #define ICALL(id,name,func) name,
7984 static const char* const
7985 icall_names [] = {
7986 #include "metadata/icall-def.h"
7987         NULL
7988 };
7989 #define icall_name_get(id) icall_names [(id)]
7990
7991 #endif /* !HAVE_ARRAY_ELEM_INIT */
7992
7993 #undef HANDLES
7994 #define HANDLES(inner) inner
7995 #undef ICALL_TYPE
7996 #undef ICALL
7997 #define ICALL_TYPE(id,name,first)
7998 #define ICALL(id,name,func) func,
7999 static const gconstpointer
8000 icall_functions [] = {
8001 #include "metadata/icall-def.h"
8002         NULL
8003 };
8004
8005 #ifdef ENABLE_ICALL_SYMBOL_MAP
8006 #undef HANDLES
8007 #define HANDLES(inner) inner
8008 #undef ICALL_TYPE
8009 #undef ICALL
8010 #define ICALL_TYPE(id,name,first)
8011 #define ICALL(id,name,func) #func,
8012 static const gconstpointer
8013 icall_symbols [] = {
8014 #include "metadata/icall-def.h"
8015         NULL
8016 };
8017 #endif
8018
8019 #undef ICALL_TYPE
8020 #undef ICALL
8021 #define ICALL_TYPE(id,name,first)
8022 #define ICALL(id,name,func) 0,
8023 #undef HANDLES
8024 #define HANDLES(inner) 1,
8025 static const guchar
8026 icall_uses_handles [] = {
8027 #include "metadata/icall-def.h"
8028 #undef ICALL
8029 #undef HANDLES
8030 };
8031
8032 #endif /* DISABLE_ICALL_TABLES */
8033
8034 static mono_mutex_t icall_mutex;
8035 static GHashTable *icall_hash = NULL;
8036 static GHashTable *jit_icall_hash_name = NULL;
8037 static GHashTable *jit_icall_hash_addr = NULL;
8038
8039 void
8040 mono_icall_init (void)
8041 {
8042 #ifndef DISABLE_ICALL_TABLES
8043         int i = 0;
8044
8045         /* check that tables are sorted: disable in release */
8046         if (TRUE) {
8047                 int j;
8048                 const char *prev_class = NULL;
8049                 const char *prev_method;
8050                 
8051                 for (i = 0; i < Icall_type_num; ++i) {
8052                         const IcallTypeDesc *desc;
8053                         int num_icalls;
8054                         prev_method = NULL;
8055                         if (prev_class && strcmp (prev_class, icall_type_name_get (i)) >= 0)
8056                                 g_print ("class %s should come before class %s\n", icall_type_name_get (i), prev_class);
8057                         prev_class = icall_type_name_get (i);
8058                         desc = &icall_type_descs [i];
8059                         num_icalls = icall_desc_num_icalls (desc);
8060                         /*g_print ("class %s has %d icalls starting at %d\n", prev_class, num_icalls, desc->first_icall);*/
8061                         for (j = 0; j < num_icalls; ++j) {
8062                                 const char *methodn = icall_name_get (desc->first_icall + j);
8063                                 if (prev_method && strcmp (prev_method, methodn) >= 0)
8064                                         g_print ("method %s should come before method %s\n", methodn, prev_method);
8065                                 prev_method = methodn;
8066                         }
8067                 }
8068         }
8069 #endif
8070
8071         icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8072         mono_os_mutex_init (&icall_mutex);
8073 }
8074
8075 static void
8076 mono_icall_lock (void)
8077 {
8078         mono_locks_os_acquire (&icall_mutex, IcallLock);
8079 }
8080
8081 static void
8082 mono_icall_unlock (void)
8083 {
8084         mono_locks_os_release (&icall_mutex, IcallLock);
8085 }
8086
8087 void
8088 mono_icall_cleanup (void)
8089 {
8090         g_hash_table_destroy (icall_hash);
8091         g_hash_table_destroy (jit_icall_hash_name);
8092         g_hash_table_destroy (jit_icall_hash_addr);
8093         mono_os_mutex_destroy (&icall_mutex);
8094 }
8095
8096 /**
8097  * mono_add_internal_call:
8098  * @name: method specification to surface to the managed world
8099  * @method: pointer to a C method to invoke when the method is called
8100  *
8101  * This method surfaces the C function pointed by @method as a method
8102  * that has been surfaced in managed code with the method specified in
8103  * @name as an internal call.
8104  *
8105  * Internal calls are surfaced to all app domains loaded and they are
8106  * accessibly by a type with the specified name.
8107  *
8108  * You must provide a fully qualified type name, that is namespaces
8109  * and type name, followed by a colon and the method name, with an
8110  * optional signature to bind.
8111  *
8112  * For example, the following are all valid declarations:
8113  *
8114  * "MyApp.Services.ScriptService:Accelerate"
8115  * "MyApp.Services.ScriptService:Slowdown(int,bool)"
8116  *
8117  * You use method parameters in cases where there might be more than
8118  * one surface method to managed code.  That way you can register different
8119  * internal calls for different method overloads.
8120  *
8121  * The internal calls are invoked with no marshalling.   This means that .NET
8122  * types like System.String are exposed as `MonoString *` parameters.   This is
8123  * different than the way that strings are surfaced in P/Invoke.
8124  *
8125  * For more information on how the parameters are marshalled, see the
8126  * <a href="http://www.mono-project.com/docs/advanced/embedding/">Mono Embedding</a>
8127  * page.
8128  *
8129  * See the <a  href="mono-api-methods.html#method-desc">Method Description</a>
8130  * reference for more information on the format of method descriptions.
8131  */
8132 void
8133 mono_add_internal_call (const char *name, gconstpointer method)
8134 {
8135         mono_icall_lock ();
8136
8137         g_hash_table_insert (icall_hash, g_strdup (name), (gpointer) method);
8138
8139         mono_icall_unlock ();
8140 }
8141
8142 #ifndef DISABLE_ICALL_TABLES
8143
8144 #ifdef HAVE_ARRAY_ELEM_INIT
8145 static int
8146 compare_method_imap (const void *key, const void *elem)
8147 {
8148         const char* method_name = (const char*)&icall_names_str + (*(guint16*)elem);
8149         return strcmp (key, method_name);
8150 }
8151
8152 static gsize
8153 find_slot_icall (const IcallTypeDesc *imap, const char *name)
8154 {
8155         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);
8156         if (!nameslot)
8157                 return -1;
8158         return (nameslot - &icall_names_idx [0]);
8159 }
8160
8161 static gboolean
8162 find_uses_handles_icall (const IcallTypeDesc *imap, const char *name)
8163 {
8164         gsize slotnum = find_slot_icall (imap, name);
8165         if (slotnum == -1)
8166                 return FALSE;
8167         return (gboolean)icall_uses_handles [slotnum];
8168 }
8169
8170 static gpointer
8171 find_method_icall (const IcallTypeDesc *imap, const char *name)
8172 {
8173         gsize slotnum = find_slot_icall (imap, name);
8174         if (slotnum == -1)
8175                 return NULL;
8176         return (gpointer)icall_functions [slotnum];
8177 }
8178
8179 static int
8180 compare_class_imap (const void *key, const void *elem)
8181 {
8182         const char* class_name = (const char*)&icall_type_names_str + (*(guint16*)elem);
8183         return strcmp (key, class_name);
8184 }
8185
8186 static const IcallTypeDesc*
8187 find_class_icalls (const char *name)
8188 {
8189         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);
8190         if (!nameslot)
8191                 return NULL;
8192         return &icall_type_descs [nameslot - &icall_type_names_idx [0]];
8193 }
8194
8195 #else /* HAVE_ARRAY_ELEM_INIT */
8196
8197 static int
8198 compare_method_imap (const void *key, const void *elem)
8199 {
8200         const char** method_name = (const char**)elem;
8201         return strcmp (key, *method_name);
8202 }
8203
8204 static gsize
8205 find_slot_icall (const IcallTypeDesc *imap, const char *name)
8206 {
8207         const char **nameslot = mono_binary_search (name, icall_names + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names [0]), compare_method_imap);
8208         if (!nameslot)
8209                 return -1;
8210         return nameslot - icall_names;
8211 }
8212
8213 static gpointer
8214 find_method_icall (const IcallTypeDesc *imap, const char *name)
8215 {
8216         gsize slotnum = find_slot_icall (imap, name);
8217         if (slotnum == -1)
8218                 return NULL;
8219         return (gpointer)icall_functions [slotnum];
8220 }
8221
8222 static gboolean
8223 find_uses_handles_icall (const IcallTypeDesc *imap, const char *name)
8224 {
8225         gsize slotnum = find_slot_icall (imap, name);
8226         if (slotnum == -1)
8227                 return FALSE;
8228         return (gboolean)icall_uses_handles [slotnum];
8229 }
8230
8231 static int
8232 compare_class_imap (const void *key, const void *elem)
8233 {
8234         const char** class_name = (const char**)elem;
8235         return strcmp (key, *class_name);
8236 }
8237
8238 static const IcallTypeDesc*
8239 find_class_icalls (const char *name)
8240 {
8241         const char **nameslot = mono_binary_search (name, icall_type_names, Icall_type_num, sizeof (icall_type_names [0]), compare_class_imap);
8242         if (!nameslot)
8243                 return NULL;
8244         return &icall_type_descs [nameslot - icall_type_names];
8245 }
8246
8247 #endif /* HAVE_ARRAY_ELEM_INIT */
8248
8249 #endif /* DISABLE_ICALL_TABLES */
8250
8251 /* 
8252  * we should probably export this as an helper (handle nested types).
8253  * Returns the number of chars written in buf.
8254  */
8255 static int
8256 concat_class_name (char *buf, int bufsize, MonoClass *klass)
8257 {
8258         int nspacelen, cnamelen;
8259         nspacelen = strlen (klass->name_space);
8260         cnamelen = strlen (klass->name);
8261         if (nspacelen + cnamelen + 2 > bufsize)
8262                 return 0;
8263         if (nspacelen) {
8264                 memcpy (buf, klass->name_space, nspacelen);
8265                 buf [nspacelen ++] = '.';
8266         }
8267         memcpy (buf + nspacelen, klass->name, cnamelen);
8268         buf [nspacelen + cnamelen] = 0;
8269         return nspacelen + cnamelen;
8270 }
8271
8272 #ifdef DISABLE_ICALL_TABLES
8273 static void
8274 no_icall_table (void)
8275 {
8276         g_assert_not_reached ();
8277 }
8278 #endif
8279
8280 /**
8281  * mono_lookup_internal_call_full:
8282  * @method: the method to look up
8283  * @uses_handles: out argument if method needs handles around managed objects.
8284  *
8285  * Returns a pointer to the icall code for the given method.  If
8286  * uses_handles is not NULL, it will be set to TRUE if the method
8287  * needs managed objects wrapped using the infrastructure in handle.h
8288  *
8289  * If the method is not found, warns and returns NULL.
8290  */
8291 gpointer
8292 mono_lookup_internal_call_full (MonoMethod *method, mono_bool *uses_handles)
8293 {
8294         char *sigstart;
8295         char *tmpsig;
8296         char mname [2048];
8297         int typelen = 0, mlen, siglen;
8298         gpointer res;
8299 #ifndef DISABLE_ICALL_TABLES
8300         const IcallTypeDesc *imap = NULL;
8301 #endif
8302
8303         g_assert (method != NULL);
8304
8305         if (method->is_inflated)
8306                 method = ((MonoMethodInflated *) method)->declaring;
8307
8308         if (method->klass->nested_in) {
8309                 int pos = concat_class_name (mname, sizeof (mname)-2, method->klass->nested_in);
8310                 if (!pos)
8311                         return NULL;
8312
8313                 mname [pos++] = '/';
8314                 mname [pos] = 0;
8315
8316                 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
8317                 if (!typelen)
8318                         return NULL;
8319
8320                 typelen += pos;
8321         } else {
8322                 typelen = concat_class_name (mname, sizeof (mname), method->klass);
8323                 if (!typelen)
8324                         return NULL;
8325         }
8326
8327 #ifndef DISABLE_ICALL_TABLES
8328         imap = find_class_icalls (mname);
8329 #endif
8330
8331         mname [typelen] = ':';
8332         mname [typelen + 1] = ':';
8333
8334         mlen = strlen (method->name);
8335         memcpy (mname + typelen + 2, method->name, mlen);
8336         sigstart = mname + typelen + 2 + mlen;
8337         *sigstart = 0;
8338
8339         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
8340         siglen = strlen (tmpsig);
8341         if (typelen + mlen + siglen + 6 > sizeof (mname))
8342                 return NULL;
8343         sigstart [0] = '(';
8344         memcpy (sigstart + 1, tmpsig, siglen);
8345         sigstart [siglen + 1] = ')';
8346         sigstart [siglen + 2] = 0;
8347         g_free (tmpsig);
8348         
8349         mono_icall_lock ();
8350
8351         res = g_hash_table_lookup (icall_hash, mname);
8352         if (res) {
8353                 if (uses_handles)
8354                         *uses_handles = FALSE;
8355                 mono_icall_unlock ();;
8356                 return res;
8357         }
8358         /* try without signature */
8359         *sigstart = 0;
8360         res = g_hash_table_lookup (icall_hash, mname);
8361         if (res) {
8362                 if (uses_handles)
8363                         *uses_handles = FALSE;
8364                 mono_icall_unlock ();
8365                 return res;
8366         }
8367
8368 #ifdef DISABLE_ICALL_TABLES
8369         mono_icall_unlock ();
8370         /* Fail only when the result is actually used */
8371         /* mono_marshal_get_native_wrapper () depends on this */
8372         if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor"))
8373                 return ves_icall_System_String_ctor_RedirectToCreateString;
8374         else
8375                 return no_icall_table;
8376 #else
8377         /* it wasn't found in the static call tables */
8378         if (!imap) {
8379                 if (uses_handles)
8380                         *uses_handles = FALSE;
8381                 mono_icall_unlock ();
8382                 return NULL;
8383         }
8384         res = find_method_icall (imap, sigstart - mlen);
8385         if (res) {
8386                 if (uses_handles)
8387                         *uses_handles = find_uses_handles_icall (imap, sigstart - mlen);
8388                 mono_icall_unlock ();
8389                 return res;
8390         }
8391         /* try _with_ signature */
8392         *sigstart = '(';
8393         res = find_method_icall (imap, sigstart - mlen);
8394         if (res) {
8395                 if (uses_handles)
8396                         *uses_handles = find_uses_handles_icall (imap, sigstart - mlen);
8397                 mono_icall_unlock ();
8398                 return res;
8399         }
8400
8401         g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
8402         g_print ("\nYour mono runtime and class libraries are out of sync.\n");
8403         g_print ("The out of sync library is: %s\n", method->klass->image->name);
8404         g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
8405         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");
8406         g_print ("If you see other errors or faults after this message they are probably related\n");
8407         g_print ("and you need to fix your mono install first.\n");
8408
8409         mono_icall_unlock ();
8410
8411         return NULL;
8412 #endif
8413 }
8414
8415 gpointer
8416 mono_lookup_internal_call (MonoMethod *method)
8417 {
8418         return mono_lookup_internal_call_full (method, NULL);
8419 }
8420
8421 #ifdef ENABLE_ICALL_SYMBOL_MAP
8422 static int
8423 func_cmp (gconstpointer key, gconstpointer p)
8424 {
8425         return (gsize)key - (gsize)*(gsize*)p;
8426 }
8427 #endif
8428
8429 /*
8430  * mono_lookup_icall_symbol:
8431  *
8432  *   Given the icall METHOD, returns its C symbol.
8433  */
8434 const char*
8435 mono_lookup_icall_symbol (MonoMethod *m)
8436 {
8437 #ifdef DISABLE_ICALL_TABLES
8438         g_assert_not_reached ();
8439         return NULL;
8440 #else
8441 #ifdef ENABLE_ICALL_SYMBOL_MAP
8442         gpointer func;
8443         int i;
8444         gpointer slot;
8445         static gconstpointer *functions_sorted;
8446         static const char**symbols_sorted;
8447         static gboolean inited;
8448
8449         if (!inited) {
8450                 gboolean changed;
8451
8452                 functions_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
8453                 memcpy (functions_sorted, icall_functions, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
8454                 symbols_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
8455                 memcpy (symbols_sorted, icall_symbols, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
8456                 /* Bubble sort the two arrays */
8457                 changed = TRUE;
8458                 while (changed) {
8459                         changed = FALSE;
8460                         for (i = 0; i < G_N_ELEMENTS (icall_functions) - 1; ++i) {
8461                                 if (functions_sorted [i] > functions_sorted [i + 1]) {
8462                                         gconstpointer tmp;
8463
8464                                         tmp = functions_sorted [i];
8465                                         functions_sorted [i] = functions_sorted [i + 1];
8466                                         functions_sorted [i + 1] = tmp;
8467                                         tmp = symbols_sorted [i];
8468                                         symbols_sorted [i] = symbols_sorted [i + 1];
8469                                         symbols_sorted [i + 1] = tmp;
8470                                         changed = TRUE;
8471                                 }
8472                         }
8473                 }
8474         }
8475
8476         func = mono_lookup_internal_call (m);
8477         if (!func)
8478                 return NULL;
8479         slot = mono_binary_search (func, functions_sorted, G_N_ELEMENTS (icall_functions), sizeof (gpointer), func_cmp);
8480         if (!slot)
8481                 return NULL;
8482         g_assert (slot);
8483         return symbols_sorted [(gpointer*)slot - (gpointer*)functions_sorted];
8484 #else
8485         fprintf (stderr, "icall symbol maps not enabled, pass --enable-icall-symbol-map to configure.\n");
8486         g_assert_not_reached ();
8487         return 0;
8488 #endif
8489 #endif
8490 }
8491
8492 static MonoType*
8493 type_from_typename (char *type_name)
8494 {
8495         MonoClass *klass = NULL;        /* assignment to shut GCC warning up */
8496
8497         if (!strcmp (type_name, "int"))
8498                 klass = mono_defaults.int_class;
8499         else if (!strcmp (type_name, "ptr"))
8500                 klass = mono_defaults.int_class;
8501         else if (!strcmp (type_name, "void"))
8502                 klass = mono_defaults.void_class;
8503         else if (!strcmp (type_name, "int32"))
8504                 klass = mono_defaults.int32_class;
8505         else if (!strcmp (type_name, "uint32"))
8506                 klass = mono_defaults.uint32_class;
8507         else if (!strcmp (type_name, "int8"))
8508                 klass = mono_defaults.sbyte_class;
8509         else if (!strcmp (type_name, "uint8"))
8510                 klass = mono_defaults.byte_class;
8511         else if (!strcmp (type_name, "int16"))
8512                 klass = mono_defaults.int16_class;
8513         else if (!strcmp (type_name, "uint16"))
8514                 klass = mono_defaults.uint16_class;
8515         else if (!strcmp (type_name, "long"))
8516                 klass = mono_defaults.int64_class;
8517         else if (!strcmp (type_name, "ulong"))
8518                 klass = mono_defaults.uint64_class;
8519         else if (!strcmp (type_name, "float"))
8520                 klass = mono_defaults.single_class;
8521         else if (!strcmp (type_name, "double"))
8522                 klass = mono_defaults.double_class;
8523         else if (!strcmp (type_name, "object"))
8524                 klass = mono_defaults.object_class;
8525         else if (!strcmp (type_name, "obj"))
8526                 klass = mono_defaults.object_class;
8527         else if (!strcmp (type_name, "string"))
8528                 klass = mono_defaults.string_class;
8529         else if (!strcmp (type_name, "bool"))
8530                 klass = mono_defaults.boolean_class;
8531         else if (!strcmp (type_name, "boolean"))
8532                 klass = mono_defaults.boolean_class;
8533         else {
8534                 g_error ("%s", type_name);
8535                 g_assert_not_reached ();
8536         }
8537         return &klass->byval_arg;
8538 }
8539
8540 /**
8541  * LOCKING: Take the corlib image lock.
8542  */
8543 MonoMethodSignature*
8544 mono_create_icall_signature (const char *sigstr)
8545 {
8546         gchar **parts;
8547         int i, len;
8548         gchar **tmp;
8549         MonoMethodSignature *res, *res2;
8550         MonoImage *corlib = mono_defaults.corlib;
8551
8552         mono_image_lock (corlib);
8553         res = (MonoMethodSignature *)g_hash_table_lookup (corlib->helper_signatures, sigstr);
8554         mono_image_unlock (corlib);
8555
8556         if (res)
8557                 return res;
8558
8559         parts = g_strsplit (sigstr, " ", 256);
8560
8561         tmp = parts;
8562         len = 0;
8563         while (*tmp) {
8564                 len ++;
8565                 tmp ++;
8566         }
8567
8568         res = mono_metadata_signature_alloc (corlib, len - 1);
8569         res->pinvoke = 1;
8570
8571 #ifdef TARGET_WIN32
8572         /* 
8573          * Under windows, the default pinvoke calling convention is STDCALL but
8574          * we need CDECL.
8575          */
8576         res->call_convention = MONO_CALL_C;
8577 #endif
8578
8579         res->ret = type_from_typename (parts [0]);
8580         for (i = 1; i < len; ++i) {
8581                 res->params [i - 1] = type_from_typename (parts [i]);
8582         }
8583
8584         g_strfreev (parts);
8585
8586         mono_image_lock (corlib);
8587         res2 = (MonoMethodSignature *)g_hash_table_lookup (corlib->helper_signatures, sigstr);
8588         if (res2)
8589                 res = res2; /*Value is allocated in the image pool*/
8590         else
8591                 g_hash_table_insert (corlib->helper_signatures, (gpointer)sigstr, res);
8592         mono_image_unlock (corlib);
8593
8594         return res;
8595 }
8596
8597 MonoJitICallInfo *
8598 mono_find_jit_icall_by_name (const char *name)
8599 {
8600         MonoJitICallInfo *info;
8601         g_assert (jit_icall_hash_name);
8602
8603         mono_icall_lock ();
8604         info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name);
8605         mono_icall_unlock ();
8606         return info;
8607 }
8608
8609 MonoJitICallInfo *
8610 mono_find_jit_icall_by_addr (gconstpointer addr)
8611 {
8612         MonoJitICallInfo *info;
8613         g_assert (jit_icall_hash_addr);
8614
8615         mono_icall_lock ();
8616         info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
8617         mono_icall_unlock ();
8618
8619         return info;
8620 }
8621
8622 /*
8623  * mono_get_jit_icall_info:
8624  *
8625  *   Return the hashtable mapping JIT icall names to MonoJitICallInfo structures. The
8626  * caller should access it while holding the icall lock.
8627  */
8628 GHashTable*
8629 mono_get_jit_icall_info (void)
8630 {
8631         return jit_icall_hash_name;
8632 }
8633
8634 /*
8635  * mono_lookup_jit_icall_symbol:
8636  *
8637  *   Given the jit icall NAME, returns its C symbol if possible, or NULL.
8638  */
8639 const char*
8640 mono_lookup_jit_icall_symbol (const char *name)
8641 {
8642         MonoJitICallInfo *info;
8643         const char *res = NULL;
8644
8645         mono_icall_lock ();
8646         info = (MonoJitICallInfo *)g_hash_table_lookup (jit_icall_hash_name, name);
8647         if (info)
8648                 res = info->c_symbol;
8649         mono_icall_unlock ();
8650         return res;
8651 }
8652
8653 void
8654 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
8655 {
8656         mono_icall_lock ();
8657         g_hash_table_insert (jit_icall_hash_addr, (gpointer)wrapper, info);
8658         mono_icall_unlock ();
8659 }
8660
8661 /*
8662  * If NO_RAISE is set, that means the icall is not calling mono_raise_exception () directly or indirectly. The JIT might be able to call these
8663  * icalls without wrappers in some cases.
8664  */
8665 MonoJitICallInfo *
8666 mono_register_jit_icall_full (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save, gboolean no_raise, const char *c_symbol)
8667 {
8668         MonoJitICallInfo *info;
8669         
8670         g_assert (func);
8671         g_assert (name);
8672
8673         mono_icall_lock ();
8674
8675         if (!jit_icall_hash_name) {
8676                 jit_icall_hash_name = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
8677                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
8678         }
8679
8680         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
8681                 g_warning ("jit icall already defined \"%s\"\n", name);
8682                 g_assert_not_reached ();
8683         }
8684
8685         info = g_new0 (MonoJitICallInfo, 1);
8686         
8687         info->name = name;
8688         info->func = func;
8689         info->sig = sig;
8690         info->c_symbol = c_symbol;
8691         info->no_raise = no_raise;
8692
8693         if (is_save) {
8694                 info->wrapper = func;
8695         } else {
8696                 info->wrapper = NULL;
8697         }
8698
8699         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
8700         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
8701
8702         mono_icall_unlock ();
8703         return info;
8704 }
8705
8706 MonoJitICallInfo *
8707 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
8708 {
8709         return mono_register_jit_icall_full (func, name, sig, is_save, FALSE, NULL);
8710 }
8711