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