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