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