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