* marshal.c: Iter usage.
[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  *
9  * (C) 2001 Ximian, Inc.
10  */
11
12 #include <config.h>
13 #include <glib.h>
14 #include <stdarg.h>
15 #include <string.h>
16 #include <ctype.h>
17 #include <sys/time.h>
18 #include <unistd.h>
19 #if defined (PLATFORM_WIN32)
20 #include <stdlib.h>
21 #endif
22
23 #include <mono/metadata/object.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/metadata/threadpool.h>
27 #include <mono/metadata/monitor.h>
28 #include <mono/metadata/reflection.h>
29 #include <mono/metadata/assembly.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/exception.h>
32 #include <mono/metadata/file-io.h>
33 #include <mono/metadata/console-io.h>
34 #include <mono/metadata/socket-io.h>
35 #include <mono/metadata/mono-endian.h>
36 #include <mono/metadata/tokentype.h>
37 #include <mono/metadata/unicode.h>
38 #include <mono/metadata/domain-internals.h>
39 #include <mono/metadata/metadata-internals.h>
40 #include <mono/metadata/class-internals.h>
41 #include <mono/metadata/marshal.h>
42 #include <mono/metadata/gc-internal.h>
43 #include <mono/metadata/rand.h>
44 #include <mono/metadata/sysmath.h>
45 #include <mono/metadata/string-icalls.h>
46 #include <mono/metadata/mono-debug-debugger.h>
47 #include <mono/metadata/process.h>
48 #include <mono/metadata/environment.h>
49 #include <mono/metadata/profiler-private.h>
50 #include <mono/metadata/locales.h>
51 #include <mono/metadata/filewatcher.h>
52 #include <mono/metadata/char-conversions.h>
53 #include <mono/metadata/security.h>
54 #include <mono/metadata/mono-config.h>
55 #include <mono/metadata/cil-coff.h>
56 #include <mono/metadata/security-manager.h>
57 #include <mono/io-layer/io-layer.h>
58 #include <mono/utils/strtod.h>
59 #include <mono/utils/monobitset.h>
60
61 #if defined (PLATFORM_WIN32)
62 #include <windows.h>
63 #include <shlobj.h>
64 #endif
65 #include "decimal.h"
66
67 static MonoReflectionAssembly* ves_icall_System_Reflection_Assembly_GetCallingAssembly (void);
68
69
70 /*
71  * We expect a pointer to a char, not a string
72  */
73 static double
74 mono_double_ParseImpl (char *ptr)
75 {
76         gchar *endptr = NULL;
77         gdouble result = 0.0;
78
79         MONO_ARCH_SAVE_REGS;
80
81         if (*ptr)
82                 result = bsd_strtod (ptr, &endptr);
83
84         if (!*ptr || (endptr && *endptr))
85                 mono_raise_exception (mono_exception_from_name (mono_defaults.corlib,
86                                                                 "System",
87                                                                 "FormatException"));
88         
89         return result;
90 }
91
92 static void
93 ves_icall_System_Double_AssertEndianity (double *value)
94 {
95         MONO_ARCH_SAVE_REGS;
96
97         MONO_DOUBLE_ASSERT_ENDIANITY (value);
98 }
99
100 static MonoObject *
101 ves_icall_System_Array_GetValueImpl (MonoObject *this, guint32 pos)
102 {
103         MonoClass *ac;
104         MonoArray *ao;
105         gint32 esize;
106         gpointer *ea;
107
108         MONO_ARCH_SAVE_REGS;
109
110         ao = (MonoArray *)this;
111         ac = (MonoClass *)ao->obj.vtable->klass;
112
113         esize = mono_array_element_size (ac);
114         ea = (gpointer*)((char*)ao->vector + (pos * esize));
115
116         if (ac->element_class->valuetype)
117                 return mono_value_box (this->vtable->domain, ac->element_class, ea);
118         else
119                 return *ea;
120 }
121
122 static MonoObject *
123 ves_icall_System_Array_GetValue (MonoObject *this, MonoObject *idxs)
124 {
125         MonoClass *ac, *ic;
126         MonoArray *ao, *io;
127         gint32 i, pos, *ind;
128
129         MONO_ARCH_SAVE_REGS;
130
131         MONO_CHECK_ARG_NULL (idxs);
132
133         io = (MonoArray *)idxs;
134         ic = (MonoClass *)io->obj.vtable->klass;
135         
136         ao = (MonoArray *)this;
137         ac = (MonoClass *)ao->obj.vtable->klass;
138
139         g_assert (ic->rank == 1);
140         if (io->bounds != NULL || io->max_length !=  ac->rank)
141                 mono_raise_exception (mono_get_exception_argument (NULL, NULL));
142
143         ind = (guint32 *)io->vector;
144
145         if (ao->bounds == NULL) {
146                 if (*ind < 0 || *ind >= ao->max_length)
147                         mono_raise_exception (mono_get_exception_index_out_of_range ());
148
149                 return ves_icall_System_Array_GetValueImpl (this, *ind);
150         }
151         
152         for (i = 0; i < ac->rank; i++)
153                 if ((ind [i] < ao->bounds [i].lower_bound) ||
154                     (ind [i] >= ao->bounds [i].length + ao->bounds [i].lower_bound))
155                         mono_raise_exception (mono_get_exception_index_out_of_range ());
156
157         pos = ind [0] - ao->bounds [0].lower_bound;
158         for (i = 1; i < ac->rank; i++)
159                 pos = pos*ao->bounds [i].length + ind [i] - 
160                         ao->bounds [i].lower_bound;
161
162         return ves_icall_System_Array_GetValueImpl (this, pos);
163 }
164
165 static void
166 ves_icall_System_Array_SetValueImpl (MonoArray *this, MonoObject *value, guint32 pos)
167 {
168         MonoClass *ac, *vc, *ec;
169         gint32 esize, vsize;
170         gpointer *ea, *va;
171
172         guint64 u64 = 0;
173         gint64 i64 = 0;
174         gdouble r64 = 0;
175
176         MONO_ARCH_SAVE_REGS;
177
178         if (value)
179                 vc = value->vtable->klass;
180         else
181                 vc = NULL;
182
183         ac = this->obj.vtable->klass;
184         ec = ac->element_class;
185
186         esize = mono_array_element_size (ac);
187         ea = (gpointer*)((char*)this->vector + (pos * esize));
188         va = (gpointer*)((char*)value + sizeof (MonoObject));
189
190         if (!value) {
191                 memset (ea, 0,  esize);
192                 return;
193         }
194
195 #define NO_WIDENING_CONVERSION G_STMT_START{\
196         mono_raise_exception (mono_get_exception_argument ( \
197                 "value", "not a widening conversion")); \
198 }G_STMT_END
199
200 #define CHECK_WIDENING_CONVERSION(extra) G_STMT_START{\
201         if (esize < vsize + (extra)) \
202                 mono_raise_exception (mono_get_exception_argument ( \
203                         "value", "not a widening conversion")); \
204 }G_STMT_END
205
206 #define INVALID_CAST G_STMT_START{\
207         mono_raise_exception (mono_get_exception_invalid_cast ()); \
208 }G_STMT_END
209
210         /* Check element (destination) type. */
211         switch (ec->byval_arg.type) {
212         case MONO_TYPE_STRING:
213                 switch (vc->byval_arg.type) {
214                 case MONO_TYPE_STRING:
215                         break;
216                 default:
217                         INVALID_CAST;
218                 }
219                 break;
220         case MONO_TYPE_BOOLEAN:
221                 switch (vc->byval_arg.type) {
222                 case MONO_TYPE_BOOLEAN:
223                         break;
224                 case MONO_TYPE_CHAR:
225                 case MONO_TYPE_U1:
226                 case MONO_TYPE_U2:
227                 case MONO_TYPE_U4:
228                 case MONO_TYPE_U8:
229                 case MONO_TYPE_I1:
230                 case MONO_TYPE_I2:
231                 case MONO_TYPE_I4:
232                 case MONO_TYPE_I8:
233                 case MONO_TYPE_R4:
234                 case MONO_TYPE_R8:
235                         NO_WIDENING_CONVERSION;
236                 default:
237                         INVALID_CAST;
238                 }
239                 break;
240         }
241
242         if (!ec->valuetype) {
243                 if (!mono_object_isinst (value, ec))
244                         INVALID_CAST;
245                 *ea = (gpointer)value;
246                 return;
247         }
248
249         if (mono_object_isinst (value, ec)) {
250                 memcpy (ea, (char *)value + sizeof (MonoObject), esize);
251                 return;
252         }
253
254         if (!vc->valuetype)
255                 INVALID_CAST;
256
257         vsize = mono_class_instance_size (vc) - sizeof (MonoObject);
258
259 #define ASSIGN_UNSIGNED(etype) G_STMT_START{\
260         switch (vc->byval_arg.type) { \
261         case MONO_TYPE_U1: \
262         case MONO_TYPE_U2: \
263         case MONO_TYPE_U4: \
264         case MONO_TYPE_U8: \
265         case MONO_TYPE_CHAR: \
266                 CHECK_WIDENING_CONVERSION(0); \
267                 *(etype *) ea = (etype) u64; \
268                 return; \
269         /* You can't assign a signed value to an unsigned array. */ \
270         case MONO_TYPE_I1: \
271         case MONO_TYPE_I2: \
272         case MONO_TYPE_I4: \
273         case MONO_TYPE_I8: \
274         /* You can't assign a floating point number to an integer array. */ \
275         case MONO_TYPE_R4: \
276         case MONO_TYPE_R8: \
277                 NO_WIDENING_CONVERSION; \
278         } \
279 }G_STMT_END
280
281 #define ASSIGN_SIGNED(etype) G_STMT_START{\
282         switch (vc->byval_arg.type) { \
283         case MONO_TYPE_I1: \
284         case MONO_TYPE_I2: \
285         case MONO_TYPE_I4: \
286         case MONO_TYPE_I8: \
287                 CHECK_WIDENING_CONVERSION(0); \
288                 *(etype *) ea = (etype) i64; \
289                 return; \
290         /* You can assign an unsigned value to a signed array if the array's */ \
291         /* element size is larger than the value size. */ \
292         case MONO_TYPE_U1: \
293         case MONO_TYPE_U2: \
294         case MONO_TYPE_U4: \
295         case MONO_TYPE_U8: \
296         case MONO_TYPE_CHAR: \
297                 CHECK_WIDENING_CONVERSION(1); \
298                 *(etype *) ea = (etype) u64; \
299                 return; \
300         /* You can't assign a floating point number to an integer array. */ \
301         case MONO_TYPE_R4: \
302         case MONO_TYPE_R8: \
303                 NO_WIDENING_CONVERSION; \
304         } \
305 }G_STMT_END
306
307 #define ASSIGN_REAL(etype) G_STMT_START{\
308         switch (vc->byval_arg.type) { \
309         case MONO_TYPE_R4: \
310         case MONO_TYPE_R8: \
311                 CHECK_WIDENING_CONVERSION(0); \
312                 *(etype *) ea = (etype) r64; \
313                 return; \
314         /* All integer values fit into a floating point array, so we don't */ \
315         /* need to CHECK_WIDENING_CONVERSION here. */ \
316         case MONO_TYPE_I1: \
317         case MONO_TYPE_I2: \
318         case MONO_TYPE_I4: \
319         case MONO_TYPE_I8: \
320                 *(etype *) ea = (etype) i64; \
321                 return; \
322         case MONO_TYPE_U1: \
323         case MONO_TYPE_U2: \
324         case MONO_TYPE_U4: \
325         case MONO_TYPE_U8: \
326         case MONO_TYPE_CHAR: \
327                 *(etype *) ea = (etype) u64; \
328                 return; \
329         } \
330 }G_STMT_END
331
332         switch (vc->byval_arg.type) {
333         case MONO_TYPE_U1:
334                 u64 = *(guint8 *) va;
335                 break;
336         case MONO_TYPE_U2:
337                 u64 = *(guint16 *) va;
338                 break;
339         case MONO_TYPE_U4:
340                 u64 = *(guint32 *) va;
341                 break;
342         case MONO_TYPE_U8:
343                 u64 = *(guint64 *) va;
344                 break;
345         case MONO_TYPE_I1:
346                 i64 = *(gint8 *) va;
347                 break;
348         case MONO_TYPE_I2:
349                 i64 = *(gint16 *) va;
350                 break;
351         case MONO_TYPE_I4:
352                 i64 = *(gint32 *) va;
353                 break;
354         case MONO_TYPE_I8:
355                 i64 = *(gint64 *) va;
356                 break;
357         case MONO_TYPE_R4:
358                 r64 = *(gfloat *) va;
359                 break;
360         case MONO_TYPE_R8:
361                 r64 = *(gdouble *) va;
362                 break;
363         case MONO_TYPE_CHAR:
364                 u64 = *(guint16 *) va;
365                 break;
366         case MONO_TYPE_BOOLEAN:
367                 /* Boolean is only compatible with itself. */
368                 switch (ec->byval_arg.type) {
369                 case MONO_TYPE_CHAR:
370                 case MONO_TYPE_U1:
371                 case MONO_TYPE_U2:
372                 case MONO_TYPE_U4:
373                 case MONO_TYPE_U8:
374                 case MONO_TYPE_I1:
375                 case MONO_TYPE_I2:
376                 case MONO_TYPE_I4:
377                 case MONO_TYPE_I8:
378                 case MONO_TYPE_R4:
379                 case MONO_TYPE_R8:
380                         NO_WIDENING_CONVERSION;
381                 default:
382                         INVALID_CAST;
383                 }
384                 break;
385         }
386
387         /* If we can't do a direct copy, let's try a widening conversion. */
388         switch (ec->byval_arg.type) {
389         case MONO_TYPE_CHAR:
390                 ASSIGN_UNSIGNED (guint16);
391         case MONO_TYPE_U1:
392                 ASSIGN_UNSIGNED (guint8);
393         case MONO_TYPE_U2:
394                 ASSIGN_UNSIGNED (guint16);
395         case MONO_TYPE_U4:
396                 ASSIGN_UNSIGNED (guint32);
397         case MONO_TYPE_U8:
398                 ASSIGN_UNSIGNED (guint64);
399         case MONO_TYPE_I1:
400                 ASSIGN_SIGNED (gint8);
401         case MONO_TYPE_I2:
402                 ASSIGN_SIGNED (gint16);
403         case MONO_TYPE_I4:
404                 ASSIGN_SIGNED (gint32);
405         case MONO_TYPE_I8:
406                 ASSIGN_SIGNED (gint64);
407         case MONO_TYPE_R4:
408                 ASSIGN_REAL (gfloat);
409         case MONO_TYPE_R8:
410                 ASSIGN_REAL (gdouble);
411         }
412
413         INVALID_CAST;
414         /* Not reached, INVALID_CAST does not return. Just to avoid a compiler warning ... */
415         return;
416
417 #undef INVALID_CAST
418 #undef NO_WIDENING_CONVERSION
419 #undef CHECK_WIDENING_CONVERSION
420 #undef ASSIGN_UNSIGNED
421 #undef ASSIGN_SIGNED
422 #undef ASSIGN_REAL
423 }
424
425 static void 
426 ves_icall_System_Array_SetValue (MonoArray *this, MonoObject *value,
427                                  MonoArray *idxs)
428 {
429         MonoClass *ac, *ic;
430         gint32 i, pos, *ind;
431
432         MONO_ARCH_SAVE_REGS;
433
434         MONO_CHECK_ARG_NULL (idxs);
435
436         ic = idxs->obj.vtable->klass;
437         ac = this->obj.vtable->klass;
438
439         g_assert (ic->rank == 1);
440         if (idxs->bounds != NULL || idxs->max_length != ac->rank)
441                 mono_raise_exception (mono_get_exception_argument (NULL, NULL));
442
443         ind = (guint32 *)idxs->vector;
444
445         if (this->bounds == NULL) {
446                 if (*ind < 0 || *ind >= this->max_length)
447                         mono_raise_exception (mono_get_exception_index_out_of_range ());
448
449                 ves_icall_System_Array_SetValueImpl (this, value, *ind);
450                 return;
451         }
452         
453         for (i = 0; i < ac->rank; i++)
454                 if ((ind [i] < this->bounds [i].lower_bound) ||
455                     (ind [i] >= this->bounds [i].length + this->bounds [i].lower_bound))
456                         mono_raise_exception (mono_get_exception_index_out_of_range ());
457
458         pos = ind [0] - this->bounds [0].lower_bound;
459         for (i = 1; i < ac->rank; i++)
460                 pos = pos * this->bounds [i].length + ind [i] - 
461                         this->bounds [i].lower_bound;
462
463         ves_icall_System_Array_SetValueImpl (this, value, pos);
464 }
465
466 static MonoArray *
467 ves_icall_System_Array_CreateInstanceImpl (MonoReflectionType *type, MonoArray *lengths, MonoArray *bounds)
468 {
469         MonoClass *aklass;
470         MonoArray *array;
471         gint32 *sizes, i;
472         gboolean bounded = FALSE;
473
474         MONO_ARCH_SAVE_REGS;
475
476         MONO_CHECK_ARG_NULL (type);
477         MONO_CHECK_ARG_NULL (lengths);
478
479         MONO_CHECK_ARG (lengths, mono_array_length (lengths) > 0);
480         if (bounds)
481                 MONO_CHECK_ARG (bounds, mono_array_length (lengths) == mono_array_length (bounds));
482
483         for (i = 0; i < mono_array_length (lengths); i++)
484                 if (mono_array_get (lengths, gint32, i) < 0)
485                         mono_raise_exception (mono_get_exception_argument_out_of_range (NULL));
486
487         if (bounds && (mono_array_length (bounds) == 1) && (mono_array_get (bounds, gint32, 0) != 0))
488                 /* vectors are not the same as one dimensional arrays with no-zero bounds */
489                 bounded = TRUE;
490         else
491                 bounded = FALSE;
492
493         aklass = mono_bounded_array_class_get (mono_class_from_mono_type (type->type), mono_array_length (lengths), bounded);
494
495         sizes = alloca (aklass->rank * sizeof(guint32) * 2);
496         for (i = 0; i < aklass->rank; ++i) {
497                 sizes [i] = mono_array_get (lengths, gint32, i);
498                 if (bounds)
499                         sizes [i + aklass->rank] = mono_array_get (bounds, gint32, i);
500                 else
501                         sizes [i + aklass->rank] = 0;
502         }
503
504         array = mono_array_new_full (mono_object_domain (type), aklass, sizes, sizes + aklass->rank);
505
506         return array;
507 }
508
509 static gint32 
510 ves_icall_System_Array_GetRank (MonoObject *this)
511 {
512         MONO_ARCH_SAVE_REGS;
513
514         return this->vtable->klass->rank;
515 }
516
517 static gint32
518 ves_icall_System_Array_GetLength (MonoArray *this, gint32 dimension)
519 {
520         gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
521
522         MONO_ARCH_SAVE_REGS;
523
524         if ((dimension < 0) || (dimension >= rank))
525                 mono_raise_exception (mono_get_exception_index_out_of_range ());
526         
527         if (this->bounds == NULL)
528                 return this->max_length;
529         
530         return this->bounds [dimension].length;
531 }
532
533 static gint32
534 ves_icall_System_Array_GetLowerBound (MonoArray *this, gint32 dimension)
535 {
536         gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
537
538         MONO_ARCH_SAVE_REGS;
539
540         if ((dimension < 0) || (dimension >= rank))
541                 mono_raise_exception (mono_get_exception_index_out_of_range ());
542         
543         if (this->bounds == NULL)
544                 return 0;
545         
546         return this->bounds [dimension].lower_bound;
547 }
548
549 static void
550 ves_icall_System_Array_ClearInternal (MonoArray *arr, int idx, int length)
551 {
552         int sz = mono_array_element_size (mono_object_class (arr));
553         memset (mono_array_addr_with_size (arr, idx, sz), 0, length * sz);
554 }
555
556 static gboolean
557 ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* dest, int dest_idx, int length)
558 {
559         int element_size;
560         void * dest_addr;
561         void * source_addr;
562         MonoClass *src_class;
563         MonoClass *dest_class;
564         int i;
565
566         MONO_ARCH_SAVE_REGS;
567
568         if (source->obj.vtable->klass->rank != dest->obj.vtable->klass->rank)
569                 return FALSE;
570
571         if (source->bounds || dest->bounds)
572                 return FALSE;
573
574         if ((dest_idx + length > mono_array_length (dest)) ||
575                 (source_idx + length > mono_array_length (source)))
576                 return FALSE;
577
578         element_size = mono_array_element_size (source->obj.vtable->klass);
579         dest_addr = mono_array_addr_with_size (dest, element_size, dest_idx);
580         source_addr = mono_array_addr_with_size (source, element_size, source_idx);
581
582         src_class = source->obj.vtable->klass->element_class;
583         dest_class = dest->obj.vtable->klass->element_class;
584
585         /*
586          * Handle common cases.
587          */
588
589         /* Case1: object[] -> valuetype[] (ArrayList::ToArray) */
590         if (src_class == mono_defaults.object_class && dest_class->valuetype) {
591                 for (i = source_idx; i < source_idx + length; ++i) {
592                         MonoObject *elem = mono_array_get (source, MonoObject*, i);
593                         if (elem && !mono_object_isinst (elem, dest_class))
594                                 return FALSE;
595                 }
596
597                 element_size = mono_array_element_size (dest->obj.vtable->klass);
598                 for (i = 0; i < length; ++i) {
599                         MonoObject *elem = mono_array_get (source, MonoObject*, source_idx + i);
600                         void *addr = mono_array_addr_with_size (dest, element_size, dest_idx + i);
601                         if (!elem)
602                                 memset (addr, 0, element_size);
603                         else
604                                 memcpy (addr, (char *)elem + sizeof (MonoObject), element_size);
605                 }
606                 return TRUE;
607         }
608
609         if (src_class != dest_class) {
610                 if (dest_class->valuetype || dest_class->enumtype || src_class->valuetype || src_class->enumtype)
611                         return FALSE;
612
613                 if (mono_class_is_subclass_of (src_class, dest_class, FALSE))
614                         ;
615                 /* Case2: object[] -> reftype[] (ArrayList::ToArray) */
616                 else if (mono_class_is_subclass_of (dest_class, src_class, FALSE))
617                         for (i = source_idx; i < source_idx + length; ++i) {
618                                 MonoObject *elem = mono_array_get (source, MonoObject*, i);
619                                 if (elem && !mono_object_isinst (elem, dest_class))
620                                         return FALSE;
621                         }
622                 else
623                         return FALSE;
624         }
625
626         memmove (dest_addr, source_addr, element_size * length);
627
628         return TRUE;
629 }
630
631 static void
632 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArray *array, MonoClassField *field_handle)
633 {
634         MonoClass *klass = array->obj.vtable->klass;
635         guint32 size = mono_array_element_size (klass);
636         int i;
637
638         MONO_ARCH_SAVE_REGS;
639
640         if (array->bounds == NULL)
641                 size *= array->max_length;
642         else
643                 for (i = 0; i < klass->rank; ++i) 
644                         size *= array->bounds [i].length;
645
646         memcpy (mono_array_addr (array, char, 0), field_handle->data, size);
647
648 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
649 #define SWAP(n) {\
650         gint i; \
651         guint ## n tmp; \
652         guint ## n *data = (guint ## n *) mono_array_addr (array, char, 0); \
653 \
654         for (i = 0; i < size; i += n/8, data++) { \
655                 tmp = read ## n (data); \
656                 *data = tmp; \
657         } \
658 }
659
660         /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
661
662         switch (mono_type_get_underlying_type (&klass->element_class->byval_arg)->type) {
663         case MONO_TYPE_CHAR:
664         case MONO_TYPE_I2:
665         case MONO_TYPE_U2:
666                 SWAP (16);
667                 break;
668         case MONO_TYPE_I4:
669         case MONO_TYPE_U4:
670                 SWAP (32);
671                 break;
672         case MONO_TYPE_I8:
673         case MONO_TYPE_U8:
674                 SWAP (64);
675                 break;
676         }
677                  
678 #endif
679 }
680
681 static gint
682 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
683 {
684         MONO_ARCH_SAVE_REGS;
685
686         return offsetof (MonoString, chars);
687 }
688
689 static MonoObject *
690 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObject *obj)
691 {
692         MONO_ARCH_SAVE_REGS;
693
694         if ((obj == NULL) || (! (obj->vtable->klass->valuetype)))
695                 return obj;
696         else
697                 return mono_object_clone (obj);
698 }
699
700 static void
701 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle)
702 {
703         MonoClass *klass;
704
705         MONO_ARCH_SAVE_REGS;
706
707         MONO_CHECK_ARG_NULL (handle);
708
709         klass = mono_class_from_mono_type (handle);
710         MONO_CHECK_ARG (handle, klass);
711
712         /* This will call the type constructor */
713         if (! (klass->flags & TYPE_ATTRIBUTE_INTERFACE))
714                 mono_runtime_class_init (mono_class_vtable (mono_domain_get (), klass));
715 }
716
717 static MonoObject *
718 ves_icall_System_Object_MemberwiseClone (MonoObject *this)
719 {
720         MONO_ARCH_SAVE_REGS;
721
722         return mono_object_clone (this);
723 }
724
725 #define MONO_OBJECT_ALIGNMENT_SHIFT     3
726
727 /*
728  * Return hashcode based on object address. This function will need to be
729  * smarter in the presence of a moving garbage collector, which will cache
730  * the address hash before relocating the object.
731  *
732  * Wang's address-based hash function:
733  *   http://www.concentric.net/~Ttwang/tech/addrhash.htm
734  */
735 static gint32
736 ves_icall_System_Object_GetHashCode (MonoObject *this)
737 {
738         MONO_ARCH_SAVE_REGS;
739
740         return (GPOINTER_TO_UINT (this) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
741 }
742
743 static gint32
744 ves_icall_System_ValueType_InternalGetHashCode (MonoObject *this, MonoArray **fields)
745 {
746         MonoClass *klass;
747         MonoObject **values = NULL;
748         MonoObject *o;
749         int count = 0;
750         gint32 result = 0;
751         MonoClassField* field;
752         gpointer iter;
753
754         MONO_ARCH_SAVE_REGS;
755
756         klass = mono_object_class (this);
757
758         if (mono_class_num_fields (klass) == 0)
759                 return ves_icall_System_Object_GetHashCode (this);
760
761         /*
762          * Compute the starting value of the hashcode for fields of primitive
763          * types, and return the remaining fields in an array to the managed side.
764          * This way, we can avoid costly reflection operations in managed code.
765          */
766         iter = NULL;
767         while ((field = mono_class_get_fields (klass, &iter))) {
768                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
769                         continue;
770                 if (mono_field_is_deleted (field))
771                         continue;
772                 /* FIXME: Add more types */
773                 switch (field->type->type) {
774                 case MONO_TYPE_I4:
775                         result ^= *(gint32*)((guint8*)this + field->offset);
776                         break;
777                 case MONO_TYPE_STRING: {
778                         MonoString *s;
779                         s = *(MonoString**)((guint8*)this + field->offset);
780                         if (s != NULL)
781                                 result ^= ves_icall_System_String_GetHashCode (s);
782                         break;
783                 }
784                 default:
785                         if (!values)
786                                 values = g_newa (MonoObject*, mono_class_num_fields (klass));
787                         o = mono_field_get_value_object (mono_object_domain (this), field, this);
788                         values [count++] = o;
789                 }
790         }
791
792         if (values) {
793                 *fields = mono_array_new (mono_domain_get (), mono_defaults.object_class, count);
794                 memcpy (mono_array_addr (*fields, MonoObject*, 0), values, count * sizeof (MonoObject*));
795         }
796         else
797                 *fields = NULL;
798         return result;
799 }
800
801 static MonoBoolean
802 ves_icall_System_ValueType_Equals (MonoObject *this, MonoObject *that, MonoArray **fields)
803 {
804         MonoClass *klass;
805         MonoObject **values = NULL;
806         MonoObject *o;
807         MonoClassField* field;
808         gpointer iter;
809         int count = 0;
810
811         MONO_ARCH_SAVE_REGS;
812
813         MONO_CHECK_ARG_NULL (that);
814
815         if (this->vtable != that->vtable)
816                 return FALSE;
817
818         klass = mono_object_class (this);
819
820         /*
821          * Do the comparison for fields of primitive type and return a result if
822          * possible. Otherwise, return the remaining fields in an array to the 
823          * managed side. This way, we can avoid costly reflection operations in 
824          * managed code.
825          */
826         *fields = NULL;
827         iter = NULL;
828         while ((field = mono_class_get_fields (klass, &iter))) {
829                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
830                         continue;
831                 if (mono_field_is_deleted (field))
832                         continue;
833                 /* FIXME: Add more types */
834                 switch (field->type->type) {
835                 case MONO_TYPE_I4:
836                         if (*(gint32*)((guint8*)this + field->offset) != *(gint32*)((guint8*)that + field->offset))
837                                 return FALSE;
838                         break;
839                 case MONO_TYPE_STRING: {
840                         MonoString *s1, *s2;
841                         guint32 s1len, s2len;
842                         s1 = *(MonoString**)((guint8*)this + field->offset);
843                         s2 = *(MonoString**)((guint8*)that + field->offset);
844                         if (s1 == s2)
845                                 break;
846                         if ((s1 == NULL) || (s2 == NULL))
847                                 return FALSE;
848                         s1len = mono_string_length (s1);
849                         s2len = mono_string_length (s2);
850                         if (s1len != s2len)
851                                 return FALSE;
852
853                         if (memcmp (mono_string_chars (s1), mono_string_chars (s2), s1len * sizeof (gunichar2)) != 0)
854                                 return FALSE;
855                         break;
856                 }
857                 default:
858                         if (!values)
859                                 values = g_newa (MonoObject*, mono_class_num_fields (klass) * 2);
860                         o = mono_field_get_value_object (mono_object_domain (this), field, this);
861                         values [count++] = o;
862                         o = mono_field_get_value_object (mono_object_domain (this), field, that);
863                         values [count++] = o;
864                 }
865         }
866
867         if (values) {
868                 *fields = mono_array_new (mono_domain_get (), mono_defaults.object_class, count);
869                 memcpy (mono_array_addr (*fields, MonoObject*, 0), values, count * sizeof (MonoObject*));
870
871                 return FALSE;
872         }
873         else
874                 return TRUE;
875 }
876
877 static MonoReflectionType *
878 ves_icall_System_Object_GetType (MonoObject *obj)
879 {
880         MONO_ARCH_SAVE_REGS;
881
882         if (obj->vtable->klass != mono_defaults.transparent_proxy_class)
883                 return mono_type_get_object (mono_object_domain (obj), &obj->vtable->klass->byval_arg);
884         else
885                 return mono_type_get_object (mono_object_domain (obj), &((MonoTransparentProxy*)obj)->remote_class->proxy_class->byval_arg);
886 }
887
888 static void
889 mono_type_type_from_obj (MonoReflectionType *mtype, MonoObject *obj)
890 {
891         MONO_ARCH_SAVE_REGS;
892
893         mtype->type = &obj->vtable->klass->byval_arg;
894         g_assert (mtype->type->type);
895 }
896
897 static gint32
898 ves_icall_ModuleBuilder_getToken (MonoReflectionModuleBuilder *mb, MonoObject *obj)
899 {
900         MONO_ARCH_SAVE_REGS;
901         
902         MONO_CHECK_ARG_NULL (obj);
903         
904         return mono_image_create_token (mb->dynamic_image, obj, TRUE);
905 }
906
907 static gint32
908 ves_icall_ModuleBuilder_getMethodToken (MonoReflectionModuleBuilder *mb,
909                                         MonoReflectionMethod *method,
910                                         MonoArray *opt_param_types)
911 {
912         MONO_ARCH_SAVE_REGS;
913
914         MONO_CHECK_ARG_NULL (method);
915         
916         return mono_image_create_method_token (
917                 mb->dynamic_image, (MonoObject *) method, opt_param_types);
918 }
919
920 static void
921 ves_icall_ModuleBuilder_WriteToFile (MonoReflectionModuleBuilder *mb, HANDLE file)
922 {
923         MONO_ARCH_SAVE_REGS;
924
925         mono_image_create_pefile (mb, file);
926 }
927
928 static void
929 ves_icall_ModuleBuilder_build_metadata (MonoReflectionModuleBuilder *mb)
930 {
931         MONO_ARCH_SAVE_REGS;
932
933         mono_image_build_metadata (mb);
934 }
935
936 static MonoReflectionType *
937 type_from_name (const char *str, MonoBoolean ignoreCase)
938 {
939         MonoType *type = NULL;
940         MonoAssembly *assembly;
941         MonoTypeNameParse info;
942         char *temp_str = g_strdup (str);
943         gboolean type_resolve = FALSE;
944
945         MONO_ARCH_SAVE_REGS;
946
947         /* mono_reflection_parse_type() mangles the string */
948         if (!mono_reflection_parse_type (temp_str, &info)) {
949                 g_list_free (info.modifiers);
950                 g_list_free (info.nested);
951                 g_free (temp_str);
952                 return NULL;
953         }
954
955         if (info.assembly.name) {
956                 assembly = mono_assembly_load (&info.assembly, NULL, NULL);
957         } else {
958                 MonoReflectionAssembly *refass;
959
960                 refass = ves_icall_System_Reflection_Assembly_GetCallingAssembly  ();
961                 assembly = refass->assembly;
962         }
963
964         if (assembly)
965                 type = mono_reflection_get_type (assembly->image, &info, ignoreCase, &type_resolve);
966         
967         if (!info.assembly.name && !type) /* try mscorlib */
968                 type = mono_reflection_get_type (NULL, &info, ignoreCase, &type_resolve);
969
970         g_list_free (info.modifiers);
971         g_list_free (info.nested);
972         g_free (temp_str);
973
974         if (!type) 
975                 return NULL;
976
977         return mono_type_get_object (mono_domain_get (), type);
978 }
979
980 #ifdef UNUSED
981 MonoReflectionType *
982 mono_type_get (const char *str)
983 {
984         char *copy = g_strdup (str);
985         MonoReflectionType *type = type_from_name (copy, FALSE);
986
987         g_free (copy);
988         return type;
989 }
990 #endif
991
992 static MonoReflectionType*
993 ves_icall_type_from_name (MonoString *name,
994                           MonoBoolean throwOnError,
995                           MonoBoolean ignoreCase)
996 {
997         char *str = mono_string_to_utf8 (name);
998         MonoReflectionType *type;
999
1000         type = type_from_name (str, ignoreCase);
1001         g_free (str);
1002         if (type == NULL){
1003                 if (throwOnError)
1004                         mono_raise_exception (mono_get_exception_type_load (name));
1005         }
1006         
1007         return type;
1008 }
1009
1010
1011 static MonoReflectionType*
1012 ves_icall_type_from_handle (MonoType *handle)
1013 {
1014         MonoDomain *domain = mono_domain_get (); 
1015         MonoClass *klass = mono_class_from_mono_type (handle);
1016
1017         MONO_ARCH_SAVE_REGS;
1018
1019         mono_class_init (klass);
1020         return mono_type_get_object (domain, handle);
1021 }
1022
1023 static guint32
1024 ves_icall_type_Equals (MonoReflectionType *type, MonoReflectionType *c)
1025 {
1026         MONO_ARCH_SAVE_REGS;
1027
1028         if (type->type && c->type)
1029                 return mono_metadata_type_equal (type->type, c->type);
1030         g_print ("type equals\n");
1031         return 0;
1032 }
1033
1034 /* System.TypeCode */
1035 typedef enum {
1036         TYPECODE_EMPTY,
1037         TYPECODE_OBJECT,
1038         TYPECODE_DBNULL,
1039         TYPECODE_BOOLEAN,
1040         TYPECODE_CHAR,
1041         TYPECODE_SBYTE,
1042         TYPECODE_BYTE,
1043         TYPECODE_INT16,
1044         TYPECODE_UINT16,
1045         TYPECODE_INT32,
1046         TYPECODE_UINT32,
1047         TYPECODE_INT64,
1048         TYPECODE_UINT64,
1049         TYPECODE_SINGLE,
1050         TYPECODE_DOUBLE,
1051         TYPECODE_DECIMAL,
1052         TYPECODE_DATETIME,
1053         TYPECODE_STRING = 18
1054 } TypeCode;
1055
1056 static guint32
1057 ves_icall_type_GetTypeCode (MonoReflectionType *type)
1058 {
1059         int t = type->type->type;
1060
1061         MONO_ARCH_SAVE_REGS;
1062
1063         if (type->type->byref)
1064                 return TYPECODE_OBJECT;
1065
1066 handle_enum:
1067         switch (t) {
1068         case MONO_TYPE_VOID:
1069                 return TYPECODE_OBJECT;
1070         case MONO_TYPE_BOOLEAN:
1071                 return TYPECODE_BOOLEAN;
1072         case MONO_TYPE_U1:
1073                 return TYPECODE_BYTE;
1074         case MONO_TYPE_I1:
1075                 return TYPECODE_SBYTE;
1076         case MONO_TYPE_U2:
1077                 return TYPECODE_UINT16;
1078         case MONO_TYPE_I2:
1079                 return TYPECODE_INT16;
1080         case MONO_TYPE_CHAR:
1081                 return TYPECODE_CHAR;
1082         case MONO_TYPE_PTR:
1083         case MONO_TYPE_U:
1084         case MONO_TYPE_I:
1085                 return TYPECODE_OBJECT;
1086         case MONO_TYPE_U4:
1087                 return TYPECODE_UINT32;
1088         case MONO_TYPE_I4:
1089                 return TYPECODE_INT32;
1090         case MONO_TYPE_U8:
1091                 return TYPECODE_UINT64;
1092         case MONO_TYPE_I8:
1093                 return TYPECODE_INT64;
1094         case MONO_TYPE_R4:
1095                 return TYPECODE_SINGLE;
1096         case MONO_TYPE_R8:
1097                 return TYPECODE_DOUBLE;
1098         case MONO_TYPE_VALUETYPE:
1099                 if (type->type->data.klass->enumtype) {
1100                         t = type->type->data.klass->enum_basetype->type;
1101                         goto handle_enum;
1102                 } else {
1103                         MonoClass *k =  type->type->data.klass;
1104                         if (strcmp (k->name_space, "System") == 0) {
1105                                 if (strcmp (k->name, "Decimal") == 0)
1106                                         return TYPECODE_DECIMAL;
1107                                 else if (strcmp (k->name, "DateTime") == 0)
1108                                         return TYPECODE_DATETIME;
1109                         }
1110                 }
1111                 return TYPECODE_OBJECT;
1112         case MONO_TYPE_STRING:
1113                 return TYPECODE_STRING;
1114         case MONO_TYPE_SZARRAY:
1115         case MONO_TYPE_ARRAY:
1116         case MONO_TYPE_OBJECT:
1117         case MONO_TYPE_VAR:
1118         case MONO_TYPE_MVAR:
1119                 return TYPECODE_OBJECT;
1120         case MONO_TYPE_CLASS:
1121                 {
1122                         MonoClass *k =  type->type->data.klass;
1123                         if (strcmp (k->name_space, "System") == 0) {
1124                                 if (strcmp (k->name, "DBNull") == 0)
1125                                         return TYPECODE_DBNULL;
1126                         }
1127                 }
1128                 return TYPECODE_OBJECT;
1129         case MONO_TYPE_GENERICINST:
1130                 return TYPECODE_OBJECT;
1131         default:
1132                 g_error ("type 0x%02x not handled in GetTypeCode()", t);
1133         }
1134         return 0;
1135 }
1136
1137 static guint32
1138 ves_icall_type_is_subtype_of (MonoReflectionType *type, MonoReflectionType *c, MonoBoolean check_interfaces)
1139 {
1140         MonoDomain *domain; 
1141         MonoClass *klass;
1142         MonoClass *klassc;
1143
1144         MONO_ARCH_SAVE_REGS;
1145
1146         g_assert (type != NULL);
1147         
1148         domain = ((MonoObject *)type)->vtable->domain;
1149
1150         if (!c) /* FIXME: dont know what do do here */
1151                 return 0;
1152
1153         klass = mono_class_from_mono_type (type->type);
1154         klassc = mono_class_from_mono_type (c->type);
1155
1156         if (type->type->byref)
1157                 return klassc == mono_defaults.object_class;
1158
1159         return mono_class_is_subclass_of (klass, klassc, check_interfaces);
1160 }
1161
1162 static guint32
1163 ves_icall_type_is_assignable_from (MonoReflectionType *type, MonoReflectionType *c)
1164 {
1165         MonoDomain *domain; 
1166         MonoClass *klass;
1167         MonoClass *klassc;
1168
1169         MONO_ARCH_SAVE_REGS;
1170
1171         g_assert (type != NULL);
1172         
1173         domain = ((MonoObject *)type)->vtable->domain;
1174
1175         klass = mono_class_from_mono_type (type->type);
1176         klassc = mono_class_from_mono_type (c->type);
1177
1178         if (type->type->byref && !c->type->byref)
1179                 return FALSE;
1180
1181         return mono_class_is_assignable_from (klass, klassc);
1182 }
1183
1184 static guint32
1185 ves_icall_type_IsInstanceOfType (MonoReflectionType *type, MonoObject *obj)
1186 {
1187         MonoClass *klass = mono_class_from_mono_type (type->type);
1188         return mono_object_isinst (obj, klass) != NULL;
1189 }
1190
1191 static guint32
1192 ves_icall_get_attributes (MonoReflectionType *type)
1193 {
1194         MonoClass *klass = mono_class_from_mono_type (type->type);
1195
1196         MONO_ARCH_SAVE_REGS;
1197
1198         return klass->flags;
1199 }
1200
1201 static MonoReflectionMarshal*
1202 ves_icall_System_Reflection_FieldInfo_GetUnmanagedMarshal (MonoReflectionField *field)
1203 {
1204         MonoClass *klass = field->field->parent;
1205         MonoMarshalType *info;
1206         int i;
1207
1208         if (klass->generic_container ||
1209             (klass->generic_class && klass->generic_class->inst->is_open))
1210                 return NULL;
1211
1212         info = mono_marshal_load_type_info (klass);
1213
1214         for (i = 0; i < info->num_fields; ++i) {
1215                 if (info->fields [i].field == field->field) {
1216                         if (!info->fields [i].mspec)
1217                                 return NULL;
1218                         else
1219                                 return mono_reflection_marshal_from_marshal_spec (field->object.vtable->domain, klass, info->fields [i].mspec);
1220                 }
1221         }
1222
1223         return NULL;
1224 }
1225
1226 static MonoReflectionField*
1227 ves_icall_System_Reflection_FieldInfo_internal_from_handle (MonoClassField *handle)
1228 {
1229         MONO_ARCH_SAVE_REGS;
1230
1231         g_assert (handle);
1232
1233         return mono_field_get_object (mono_domain_get (), handle->parent, handle);
1234 }
1235
1236 static void
1237 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info)
1238 {
1239         MonoDomain *domain = mono_domain_get ();
1240         MonoMethodSignature* sig;
1241         MONO_ARCH_SAVE_REGS;
1242
1243         if (method->is_inflated)
1244                 method = mono_get_inflated_method (method);
1245
1246         sig = mono_method_signature (method);
1247         
1248         info->parent = mono_type_get_object (domain, &method->klass->byval_arg);
1249         info->ret = mono_type_get_object (domain, sig->ret);
1250         info->attrs = method->flags;
1251         info->implattrs = method->iflags;
1252         if (sig->call_convention == MONO_CALL_DEFAULT)
1253                 info->callconv = 1;
1254         else {
1255                 if (sig->call_convention == MONO_CALL_VARARG)
1256                         info->callconv = 2;
1257                 else
1258                         info->callconv = 0;
1259         }
1260         info->callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6); 
1261 }
1262
1263 static MonoArray*
1264 ves_icall_get_parameter_info (MonoMethod *method)
1265 {
1266         MonoDomain *domain = mono_domain_get (); 
1267
1268         MONO_ARCH_SAVE_REGS;
1269
1270         if (method->is_inflated)
1271                 method = mono_get_inflated_method (method);
1272
1273         return mono_param_get_objects (domain, method);
1274 }
1275
1276 static gint32
1277 ves_icall_MonoField_GetFieldOffset (MonoReflectionField *field)
1278 {
1279         return field->field->offset - sizeof (MonoObject);
1280 }
1281
1282 static MonoReflectionType*
1283 ves_icall_MonoField_GetParentType (MonoReflectionField *field, MonoBoolean declaring)
1284 {
1285         MonoClass *parent;
1286         MONO_ARCH_SAVE_REGS;
1287
1288         parent = declaring? field->field->parent: field->klass;
1289
1290         return mono_type_get_object (mono_object_domain (field), &parent->byval_arg);
1291 }
1292
1293 static MonoObject *
1294 ves_icall_MonoField_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
1295 {       
1296         MonoObject *o;
1297         MonoClassField *cf = field->field;
1298         MonoClass *klass;
1299         MonoVTable *vtable;
1300         MonoDomain *domain = mono_object_domain (field); 
1301         gchar *v;
1302         gboolean is_static = FALSE;
1303         gboolean is_ref = FALSE;
1304
1305         MONO_ARCH_SAVE_REGS;
1306
1307         mono_class_init (field->klass);
1308
1309         switch (cf->type->type) {
1310         case MONO_TYPE_STRING:
1311         case MONO_TYPE_OBJECT:
1312         case MONO_TYPE_CLASS:
1313         case MONO_TYPE_ARRAY:
1314         case MONO_TYPE_SZARRAY:
1315                 is_ref = TRUE;
1316                 break;
1317         case MONO_TYPE_U1:
1318         case MONO_TYPE_I1:
1319         case MONO_TYPE_BOOLEAN:
1320         case MONO_TYPE_U2:
1321         case MONO_TYPE_I2:
1322         case MONO_TYPE_CHAR:
1323         case MONO_TYPE_U:
1324         case MONO_TYPE_I:
1325         case MONO_TYPE_U4:
1326         case MONO_TYPE_I4:
1327         case MONO_TYPE_R4:
1328         case MONO_TYPE_U8:
1329         case MONO_TYPE_I8:
1330         case MONO_TYPE_R8:
1331         case MONO_TYPE_VALUETYPE:
1332                 is_ref = cf->type->byref;
1333                 break;
1334         default:
1335                 g_error ("type 0x%x not handled in "
1336                          "ves_icall_Monofield_GetValue", cf->type->type);
1337                 return NULL;
1338         }
1339
1340         vtable = NULL;
1341         if (cf->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1342                 is_static = TRUE;
1343                 vtable = mono_class_vtable (domain, field->klass);
1344                 if (!vtable->initialized && !(cf->type->attrs & FIELD_ATTRIBUTE_LITERAL))
1345                         mono_runtime_class_init (vtable);
1346         }
1347         
1348         if (is_ref) {
1349                 if (is_static) {
1350                         mono_field_static_get_value (vtable, cf, &o);
1351                 } else {
1352                         mono_field_get_value (obj, cf, &o);
1353                 }
1354                 return o;
1355         }
1356
1357         /* boxed value type */
1358         klass = mono_class_from_mono_type (cf->type);
1359         o = mono_object_new (domain, klass);
1360         v = ((gchar *) o) + sizeof (MonoObject);
1361         if (is_static) {
1362                 mono_field_static_get_value (vtable, cf, v);
1363         } else {
1364                 mono_field_get_value (obj, cf, v);
1365         }
1366
1367         return o;
1368 }
1369
1370 static void
1371 ves_icall_FieldInfo_SetValueInternal (MonoReflectionField *field, MonoObject *obj, MonoObject *value)
1372 {
1373         MonoClassField *cf = field->field;
1374         gchar *v;
1375
1376         MONO_ARCH_SAVE_REGS;
1377
1378         v = (gchar *) value;
1379         if (!cf->type->byref) {
1380                 switch (cf->type->type) {
1381                 case MONO_TYPE_U1:
1382                 case MONO_TYPE_I1:
1383                 case MONO_TYPE_BOOLEAN:
1384                 case MONO_TYPE_U2:
1385                 case MONO_TYPE_I2:
1386                 case MONO_TYPE_CHAR:
1387                 case MONO_TYPE_U:
1388                 case MONO_TYPE_I:
1389                 case MONO_TYPE_U4:
1390                 case MONO_TYPE_I4:
1391                 case MONO_TYPE_R4:
1392                 case MONO_TYPE_U8:
1393                 case MONO_TYPE_I8:
1394                 case MONO_TYPE_R8:
1395                 case MONO_TYPE_VALUETYPE:
1396                         if (v != NULL)
1397                                 v += sizeof (MonoObject);
1398                         break;
1399                 case MONO_TYPE_STRING:
1400                 case MONO_TYPE_OBJECT:
1401                 case MONO_TYPE_CLASS:
1402                 case MONO_TYPE_ARRAY:
1403                 case MONO_TYPE_SZARRAY:
1404                         /* Do nothing */
1405                         break;
1406                 default:
1407                         g_error ("type 0x%x not handled in "
1408                                  "ves_icall_FieldInfo_SetValueInternal", cf->type->type);
1409                         return;
1410                 }
1411         }
1412
1413         if (cf->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1414                 MonoVTable *vtable = mono_class_vtable (mono_object_domain (field), field->klass);
1415                 if (!vtable->initialized)
1416                         mono_runtime_class_init (vtable);
1417                 mono_field_static_set_value (vtable, cf, v);
1418         } else {
1419                 mono_field_set_value (obj, cf, v);
1420         }
1421 }
1422
1423 static MonoReflectionField*
1424 ves_icall_MonoField_Mono_GetGenericFieldDefinition (MonoReflectionField *field)
1425 {
1426         MONO_ARCH_SAVE_REGS;
1427
1428         if (field->field->generic_info && field->field->generic_info->reflection_info)
1429                 return field->field->generic_info->reflection_info;
1430
1431         return field;
1432 }
1433
1434 static MonoReflectionType*
1435 ves_icall_MonoGenericMethod_get_ReflectedType (MonoReflectionGenericMethod *rmethod)
1436 {
1437         MonoMethod *method = mono_get_inflated_method (rmethod->method.method);
1438
1439         return mono_type_get_object (mono_object_domain (rmethod), &method->klass->byval_arg);
1440 }
1441
1442 /* From MonoProperty.cs */
1443 typedef enum {
1444         PInfo_Attributes = 1,
1445         PInfo_GetMethod  = 1 << 1,
1446         PInfo_SetMethod  = 1 << 2,
1447         PInfo_ReflectedType = 1 << 3,
1448         PInfo_DeclaringType = 1 << 4,
1449         PInfo_Name = 1 << 5
1450 } PInfo;
1451
1452 static void
1453 ves_icall_get_property_info (MonoReflectionProperty *property, MonoPropertyInfo *info, PInfo req_info)
1454 {
1455         MonoDomain *domain = mono_object_domain (property); 
1456
1457         MONO_ARCH_SAVE_REGS;
1458
1459         if ((req_info & PInfo_ReflectedType) != 0)
1460                 info->parent = mono_type_get_object (domain, &property->klass->byval_arg);
1461         else if ((req_info & PInfo_DeclaringType) != 0)
1462                 info->parent = mono_type_get_object (domain, &property->property->parent->byval_arg);
1463
1464         if ((req_info & PInfo_Name) != 0)
1465                 info->name = mono_string_new (domain, property->property->name);
1466
1467         if ((req_info & PInfo_Attributes) != 0)
1468                 info->attrs = property->property->attrs;
1469
1470         if ((req_info & PInfo_GetMethod) != 0)
1471                 info->get = property->property->get ?
1472                             mono_method_get_object (domain, property->property->get, NULL): NULL;
1473         
1474         if ((req_info & PInfo_SetMethod) != 0)
1475                 info->set = property->property->set ?
1476                             mono_method_get_object (domain, property->property->set, NULL): NULL;
1477         /* 
1478          * There may be other methods defined for properties, though, it seems they are not exposed 
1479          * in the reflection API 
1480          */
1481 }
1482
1483 static void
1484 ves_icall_get_event_info (MonoReflectionEvent *event, MonoEventInfo *info)
1485 {
1486         MonoDomain *domain = mono_object_domain (event); 
1487
1488         MONO_ARCH_SAVE_REGS;
1489
1490         info->declaring_type = mono_type_get_object (domain, &event->klass->byval_arg);
1491         info->reflected_type = mono_type_get_object (domain, &event->event->parent->byval_arg);
1492
1493         info->name = mono_string_new (domain, event->event->name);
1494         info->attrs = event->event->attrs;
1495         info->add_method = event->event->add ? mono_method_get_object (domain, event->event->add, NULL): NULL;
1496         info->remove_method = event->event->remove ? mono_method_get_object (domain, event->event->remove, NULL): NULL;
1497         info->raise_method = event->event->raise ? mono_method_get_object (domain, event->event->raise, NULL): NULL;
1498
1499         if (event->event->other) {
1500                 int i, n = 0;
1501                 while (event->event->other [n])
1502                         n++;
1503                 info->other_methods = mono_array_new (domain, mono_defaults.method_info_class, n);
1504
1505                 for (i = 0; i < n; i++)
1506                         mono_array_set (info->other_methods, gpointer, i,
1507                                                         mono_method_get_object (domain, event->event->other [i], NULL));
1508         }               
1509 }
1510
1511 static MonoArray*
1512 ves_icall_Type_GetInterfaces (MonoReflectionType* type)
1513 {
1514         MonoDomain *domain = mono_object_domain (type); 
1515         MonoArray *intf;
1516         GPtrArray *ifaces = NULL;
1517         int i;
1518         MonoClass *class = mono_class_from_mono_type (type->type);
1519         MonoClass *parent;
1520         MonoBitSet *slots = mono_bitset_new (class->max_interface_id + 1, 0);
1521
1522         MONO_ARCH_SAVE_REGS;
1523
1524         if (class->rank) {
1525                 /* GetInterfaces() returns an empty array in MS.NET (this may be a bug) */
1526                 mono_bitset_free (slots);
1527                 return mono_array_new (domain, mono_defaults.monotype_class, 0);
1528         }
1529
1530         for (parent = class; parent; parent = parent->parent) {
1531                 GPtrArray *tmp_ifaces = mono_class_get_implemented_interfaces (parent);
1532                 if (tmp_ifaces) {
1533                         for (i = 0; i < tmp_ifaces->len; ++i) {
1534                                 MonoClass *ic = g_ptr_array_index (tmp_ifaces, i);
1535
1536                                 if (mono_bitset_test (slots, ic->interface_id))
1537                                         continue;
1538
1539                                 mono_bitset_set (slots, ic->interface_id);
1540                                 if (ifaces == NULL)
1541                                         ifaces = g_ptr_array_new ();
1542                                 g_ptr_array_add (ifaces, ic);
1543                         }
1544                         g_ptr_array_free (tmp_ifaces, TRUE);
1545                 }
1546         }
1547         mono_bitset_free (slots);
1548
1549         if (!ifaces)
1550                 return mono_array_new (domain, mono_defaults.monotype_class, 0);
1551                 
1552         intf = mono_array_new (domain, mono_defaults.monotype_class, ifaces->len);
1553         for (i = 0; i < ifaces->len; ++i) {
1554                 MonoClass *ic = g_ptr_array_index (ifaces, i);
1555                 
1556                 mono_array_set (intf, gpointer, i,
1557                                                 mono_type_get_object (domain, &ic->byval_arg));
1558         }
1559         g_ptr_array_free (ifaces, TRUE);
1560
1561         return intf;
1562 }
1563
1564 static void
1565 ves_icall_Type_GetInterfaceMapData (MonoReflectionType *type, MonoReflectionType *iface, MonoArray **targets, MonoArray **methods)
1566 {
1567         MonoClass *class = mono_class_from_mono_type (type->type);
1568         MonoClass *iclass = mono_class_from_mono_type (iface->type);
1569         MonoReflectionMethod *member;
1570         MonoMethod* method;
1571         gpointer iter;
1572         int i = 0, len, ioffset;
1573         MonoDomain *domain;
1574
1575         MONO_ARCH_SAVE_REGS;
1576
1577         /* type doesn't implement iface: the exception is thrown in managed code */
1578         if ((iclass->interface_id > class->max_interface_id) || !class->interface_offsets [iclass->interface_id])
1579                         return;
1580
1581         len = mono_class_num_methods (iclass);
1582         ioffset = class->interface_offsets [iclass->interface_id];
1583         domain = mono_object_domain (type);
1584         *targets = mono_array_new (domain, mono_defaults.method_info_class, len);
1585         *methods = mono_array_new (domain, mono_defaults.method_info_class, len);
1586         iter = NULL;
1587         iter = NULL;
1588         while ((method = mono_class_get_methods (iclass, &iter))) {
1589                 member = mono_method_get_object (domain, method, iclass);
1590                 mono_array_set (*methods, gpointer, i, member);
1591                 member = mono_method_get_object (domain, class->vtable [i + ioffset], class);
1592                 mono_array_set (*targets, gpointer, i, member);
1593                 
1594                 i ++;
1595         }
1596 }
1597
1598 static void
1599 ves_icall_Type_GetPacking (MonoReflectionType *type, guint32 *packing, guint32 *size)
1600 {
1601         MonoClass *klass = mono_class_from_mono_type (type->type);
1602
1603         g_assert (!klass->image->dynamic);
1604
1605         mono_metadata_packing_from_typedef (klass->image, klass->type_token, packing, size);
1606 }
1607
1608 static MonoReflectionType*
1609 ves_icall_MonoType_GetElementType (MonoReflectionType *type)
1610 {
1611         MonoClass *class = mono_class_from_mono_type (type->type);
1612
1613         MONO_ARCH_SAVE_REGS;
1614
1615         // GelElementType should only return a type for:
1616         // Array Pointer PassedByRef
1617         if (type->type->byref)
1618                 return mono_type_get_object (mono_object_domain (type), &class->byval_arg);
1619         if (class->enumtype && class->enum_basetype) /* types that are modifierd typebuilkders may not have enum_basetype set */
1620                 return mono_type_get_object (mono_object_domain (type), class->enum_basetype);
1621         else if (class->element_class && MONO_CLASS_IS_ARRAY (class))
1622                 return mono_type_get_object (mono_object_domain (type), &class->element_class->byval_arg);
1623         else if (class->element_class && type->type->type == MONO_TYPE_PTR)
1624                 return mono_type_get_object (mono_object_domain (type), &class->element_class->byval_arg);
1625         else
1626                 return NULL;
1627 }
1628
1629 static MonoReflectionType*
1630 ves_icall_get_type_parent (MonoReflectionType *type)
1631 {
1632         MonoClass *class = mono_class_from_mono_type (type->type);
1633
1634         MONO_ARCH_SAVE_REGS;
1635
1636         return class->parent ? mono_type_get_object (mono_object_domain (type), &class->parent->byval_arg): NULL;
1637 }
1638
1639 static MonoBoolean
1640 ves_icall_type_ispointer (MonoReflectionType *type)
1641 {
1642         MONO_ARCH_SAVE_REGS;
1643
1644         return type->type->type == MONO_TYPE_PTR;
1645 }
1646
1647 static MonoBoolean
1648 ves_icall_type_isprimitive (MonoReflectionType *type)
1649 {
1650         MONO_ARCH_SAVE_REGS;
1651
1652         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)));
1653 }
1654
1655 static MonoBoolean
1656 ves_icall_type_isbyref (MonoReflectionType *type)
1657 {
1658         MONO_ARCH_SAVE_REGS;
1659
1660         return type->type->byref;
1661 }
1662
1663 static MonoReflectionModule*
1664 ves_icall_MonoType_get_Module (MonoReflectionType *type)
1665 {
1666         MonoClass *class = mono_class_from_mono_type (type->type);
1667
1668         MONO_ARCH_SAVE_REGS;
1669
1670         return mono_module_get_object (mono_object_domain (type), class->image);
1671 }
1672
1673 static MonoReflectionAssembly*
1674 ves_icall_MonoType_get_Assembly (MonoReflectionType *type)
1675 {
1676         MonoDomain *domain = mono_domain_get (); 
1677         MonoClass *class = mono_class_from_mono_type (type->type);
1678
1679         MONO_ARCH_SAVE_REGS;
1680
1681         return mono_assembly_get_object (domain, class->image->assembly);
1682 }
1683
1684 static MonoReflectionType*
1685 ves_icall_MonoType_get_DeclaringType (MonoReflectionType *type)
1686 {
1687         MonoDomain *domain = mono_domain_get (); 
1688         MonoClass *class = mono_class_from_mono_type (type->type);
1689
1690         MONO_ARCH_SAVE_REGS;
1691
1692         return class->nested_in ? mono_type_get_object (domain, &class->nested_in->byval_arg) : NULL;
1693 }
1694
1695 static MonoReflectionType*
1696 ves_icall_MonoType_get_UnderlyingSystemType (MonoReflectionType *type)
1697 {
1698         MonoDomain *domain = mono_domain_get (); 
1699         MonoClass *class = mono_class_from_mono_type (type->type);
1700
1701         MONO_ARCH_SAVE_REGS;
1702
1703         if (class->enumtype && class->enum_basetype) /* types that are modified typebuilders may not have enum_basetype set */
1704                 return mono_type_get_object (domain, class->enum_basetype);
1705         else if (class->element_class)
1706                 return mono_type_get_object (domain, &class->element_class->byval_arg);
1707         else
1708                 return NULL;
1709 }
1710
1711 static MonoString*
1712 ves_icall_MonoType_get_Name (MonoReflectionType *type)
1713 {
1714         MonoDomain *domain = mono_domain_get (); 
1715         MonoClass *class = mono_class_from_mono_type (type->type);
1716
1717         MONO_ARCH_SAVE_REGS;
1718
1719         return mono_string_new (domain, class->name);
1720 }
1721
1722 static MonoString*
1723 ves_icall_MonoType_get_Namespace (MonoReflectionType *type)
1724 {
1725         MonoDomain *domain = mono_domain_get (); 
1726         MonoClass *class = mono_class_from_mono_type (type->type);
1727
1728         MONO_ARCH_SAVE_REGS;
1729
1730         while (class->nested_in)
1731                 class = class->nested_in;
1732
1733         if (class->name_space [0] == '\0')
1734                 return NULL;
1735         else
1736                 return mono_string_new (domain, class->name_space);
1737 }
1738
1739 static gint32
1740 ves_icall_MonoType_GetArrayRank (MonoReflectionType *type)
1741 {
1742         MonoClass *class = mono_class_from_mono_type (type->type);
1743
1744         MONO_ARCH_SAVE_REGS;
1745
1746         return class->rank;
1747 }
1748
1749 static MonoArray*
1750 ves_icall_MonoType_GetGenericArguments (MonoReflectionType *type)
1751 {
1752         MonoArray *res;
1753         MonoClass *klass, *pklass;
1754         int i;
1755         MONO_ARCH_SAVE_REGS;
1756
1757         klass = mono_class_from_mono_type (type->type);
1758
1759         if (klass->generic_container) {
1760                 MonoGenericContainer *container = klass->generic_container;
1761                 res = mono_array_new (mono_object_domain (type), mono_defaults.monotype_class, container->type_argc);
1762                 for (i = 0; i < container->type_argc; ++i) {
1763                         pklass = mono_class_from_generic_parameter (&container->type_params [i], klass->image, FALSE);
1764                         mono_array_set (res, gpointer, i, mono_type_get_object (mono_object_domain (type), &pklass->byval_arg));
1765                 }
1766         } else if (klass->generic_class) {
1767                 MonoGenericInst *inst = klass->generic_class->inst;
1768                 res = mono_array_new (mono_object_domain (type), mono_defaults.monotype_class, inst->type_argc);
1769                 for (i = 0; i < inst->type_argc; ++i) {
1770                         mono_array_set (res, gpointer, i, mono_type_get_object (mono_object_domain (type), inst->type_argv [i]));
1771                 }
1772         } else {
1773                 res = mono_array_new (mono_object_domain (type), mono_defaults.monotype_class, 0);
1774         }
1775         return res;
1776 }
1777
1778 static gboolean
1779 ves_icall_Type_get_IsGenericTypeDefinition (MonoReflectionType *type)
1780 {
1781         MonoClass *klass;
1782         MONO_ARCH_SAVE_REGS;
1783
1784         klass = mono_class_from_mono_type (type->type);
1785
1786         return klass->generic_container != NULL;
1787 }
1788
1789 static MonoReflectionType*
1790 ves_icall_Type_GetGenericTypeDefinition_impl (MonoReflectionType *type)
1791 {
1792         MonoClass *klass;
1793         MONO_ARCH_SAVE_REGS;
1794
1795         klass = mono_class_from_mono_type (type->type);
1796         if (klass->generic_container) {
1797                 return type; /* check this one */
1798         }
1799         if (klass->generic_class) {
1800                 MonoClass *generic_class = klass->generic_class->container_class;
1801
1802                 if (generic_class->wastypebuilder && generic_class->reflection_info)
1803                         return generic_class->reflection_info;
1804                 else
1805                         return mono_type_get_object (mono_object_domain (type), &generic_class->byval_arg);
1806         }
1807         return NULL;
1808 }
1809
1810 static MonoReflectionType*
1811 ves_icall_Type_BindGenericParameters (MonoReflectionType *type, MonoArray *type_array)
1812 {
1813         MonoType *geninst, **types;
1814         int i, count;
1815
1816         MONO_ARCH_SAVE_REGS;
1817
1818         count = mono_array_length (type_array);
1819         types = g_new0 (MonoType *, count);
1820
1821         for (i = 0; i < count; i++) {
1822                 MonoReflectionType *t = mono_array_get (type_array, gpointer, i);
1823                 types [i] = t->type;
1824         }
1825
1826         geninst = mono_reflection_bind_generic_parameters (type, count, types);
1827
1828         return mono_type_get_object (mono_object_domain (type), geninst);
1829 }
1830
1831 static gboolean
1832 ves_icall_Type_get_IsGenericInstance (MonoReflectionType *type)
1833 {
1834         MonoClass *klass;
1835         MONO_ARCH_SAVE_REGS;
1836
1837         klass = mono_class_from_mono_type (type->type);
1838         return klass->generic_class != NULL;
1839 }
1840
1841 static gint32
1842 ves_icall_Type_GetGenericParameterPosition (MonoReflectionType *type)
1843 {
1844         MONO_ARCH_SAVE_REGS;
1845
1846         if (type->type->type == MONO_TYPE_VAR || type->type->type == MONO_TYPE_MVAR)
1847                 return type->type->data.generic_param->num;
1848         return -1;
1849 }
1850
1851 static GenericParameterAttributes
1852 ves_icall_Type_GetGenericParameterAttributes (MonoReflectionType *type)
1853 {
1854         MONO_ARCH_SAVE_REGS;
1855         return type->type->data.generic_param->flags;
1856 }
1857
1858 static MonoArray *
1859 ves_icall_Type_GetGenericParameterConstraints (MonoReflectionType *type)
1860 {
1861         MonoGenericParam *param;
1862         MonoDomain *domain;
1863         MonoClass **ptr;
1864         MonoArray *res;
1865         int i, count;
1866
1867         MONO_ARCH_SAVE_REGS;
1868
1869         domain = mono_object_domain (type);
1870         param = type->type->data.generic_param;
1871         for (count = 0, ptr = param->constraints; ptr && *ptr; ptr++, count++)
1872                 ;
1873
1874         res = mono_array_new (domain, mono_defaults.monotype_class, count);
1875         for (i = 0; i < count; i++)
1876                 mono_array_set (res, gpointer, i,
1877                                 mono_type_get_object (domain, &param->constraints [i]->byval_arg));
1878
1879
1880         return res;
1881 }
1882
1883 static MonoBoolean
1884 ves_icall_MonoType_get_HasGenericArguments (MonoReflectionType *type)
1885 {
1886         MonoClass *klass;
1887         MONO_ARCH_SAVE_REGS;
1888
1889         klass = mono_class_from_mono_type (type->type);
1890         if (klass->generic_container || klass->generic_class)
1891                 return TRUE;
1892         return FALSE;
1893 }
1894
1895 static MonoBoolean
1896 ves_icall_MonoType_get_IsGenericParameter (MonoReflectionType *type)
1897 {
1898         MONO_ARCH_SAVE_REGS;
1899
1900         if (type->type->type == MONO_TYPE_VAR || type->type->type == MONO_TYPE_MVAR)
1901                 return TRUE;
1902         return FALSE;
1903 }
1904
1905 static MonoBoolean
1906 ves_icall_TypeBuilder_get_IsGenericParameter (MonoReflectionTypeBuilder *tb)
1907 {
1908         MONO_ARCH_SAVE_REGS;
1909
1910         if (tb->type.type->type == MONO_TYPE_VAR || tb->type.type->type == MONO_TYPE_MVAR)
1911                 return TRUE;
1912         return FALSE;
1913 }
1914
1915 static void
1916 ves_icall_EnumBuilder_setup_enum_type (MonoReflectionType *enumtype,
1917                                                                            MonoReflectionType *t)
1918 {
1919         enumtype->type = t->type;
1920 }
1921
1922 static MonoReflectionType*
1923 ves_icall_MonoGenericClass_GetParentType (MonoReflectionGenericClass *type)
1924 {
1925         MonoGenericClass *gclass;
1926         MonoClass *klass;
1927
1928         MONO_ARCH_SAVE_REGS;
1929
1930         gclass = type->type.type->data.generic_class;
1931         if (!gclass || !gclass->parent || (gclass->parent->type != MONO_TYPE_GENERICINST))
1932                 return NULL;
1933
1934         klass = mono_class_from_mono_type (gclass->parent);
1935         if (!klass->generic_class && !klass->generic_container)
1936                 return NULL;
1937
1938         return mono_type_get_object (mono_object_domain (type), gclass->parent);
1939 }
1940
1941 static MonoArray*
1942 ves_icall_MonoGenericClass_GetInterfaces (MonoReflectionGenericClass *type)
1943 {
1944         static MonoClass *System_Reflection_MonoGenericClass;
1945         MonoGenericClass *gclass;
1946         MonoDomain *domain;
1947         MonoClass *klass;
1948         MonoArray *res;
1949         int i;
1950
1951         MONO_ARCH_SAVE_REGS;
1952
1953         if (!System_Reflection_MonoGenericClass) {
1954                 System_Reflection_MonoGenericClass = mono_class_from_name (
1955                         mono_defaults.corlib, "System.Reflection", "MonoGenericClass");
1956                 g_assert (System_Reflection_MonoGenericClass);
1957         }
1958
1959         domain = mono_object_domain (type);
1960
1961         gclass = type->type.type->data.generic_class;
1962         if (!gclass || !gclass->ifaces)
1963                 return mono_array_new (domain, System_Reflection_MonoGenericClass, 0);
1964
1965         klass = gclass->container_class;
1966
1967         res = mono_array_new (domain, System_Reflection_MonoGenericClass, gclass->count_ifaces);
1968
1969         for (i = 0; i < gclass->count_ifaces; i++) {
1970                 MonoReflectionType *iface = mono_type_get_object (domain, gclass->ifaces [i]);
1971
1972                 mono_array_set (res, gpointer, i, iface);
1973         }
1974
1975         return res;
1976 }
1977
1978 static MonoArray*
1979 ves_icall_MonoGenericClass_GetMethods (MonoReflectionGenericClass *type,
1980                                        MonoReflectionType *reflected_type)
1981 {
1982         MonoGenericClass *gclass;
1983         MonoDynamicGenericClass *dgclass;
1984         MonoDomain *domain;
1985         MonoClass *refclass;
1986         MonoArray *res;
1987         int i;
1988
1989         MONO_ARCH_SAVE_REGS;
1990
1991         gclass = type->type.type->data.generic_class;
1992         g_assert (gclass->is_dynamic);
1993         dgclass = (MonoDynamicGenericClass *) gclass;
1994
1995         refclass = mono_class_from_mono_type (reflected_type->type);
1996
1997         domain = mono_object_domain (type);
1998         res = mono_array_new (domain, mono_defaults.method_info_class, dgclass->count_methods);
1999
2000         for (i = 0; i < dgclass->count_methods; i++)
2001                 mono_array_set (res, gpointer, i,
2002                                 mono_method_get_object (domain, dgclass->methods [i], refclass));
2003
2004         return res;
2005 }
2006
2007 static MonoArray*
2008 ves_icall_MonoGenericClass_GetConstructors (MonoReflectionGenericClass *type,
2009                                             MonoReflectionType *reflected_type)
2010 {
2011         static MonoClass *System_Reflection_ConstructorInfo;
2012         MonoGenericClass *gclass;
2013         MonoDynamicGenericClass *dgclass;
2014         MonoDomain *domain;
2015         MonoClass *refclass;
2016         MonoArray *res;
2017         int i;
2018
2019         MONO_ARCH_SAVE_REGS;
2020
2021         if (!System_Reflection_ConstructorInfo)
2022                 System_Reflection_ConstructorInfo = mono_class_from_name (
2023                         mono_defaults.corlib, "System.Reflection", "ConstructorInfo");
2024
2025         gclass = type->type.type->data.generic_class;
2026         g_assert (gclass->is_dynamic);
2027         dgclass = (MonoDynamicGenericClass *) gclass;
2028
2029         refclass = mono_class_from_mono_type (reflected_type->type);
2030
2031         domain = mono_object_domain (type);
2032         res = mono_array_new (domain, System_Reflection_ConstructorInfo, dgclass->count_ctors);
2033
2034         for (i = 0; i < dgclass->count_ctors; i++)
2035                 mono_array_set (res, gpointer, i,
2036                                 mono_method_get_object (domain, dgclass->ctors [i], refclass));
2037
2038         return res;
2039 }
2040
2041 static MonoArray*
2042 ves_icall_MonoGenericClass_GetFields (MonoReflectionGenericClass *type,
2043                                       MonoReflectionType *reflected_type)
2044 {
2045         MonoGenericClass *gclass;
2046         MonoDynamicGenericClass *dgclass;
2047         MonoDomain *domain;
2048         MonoClass *refclass;
2049         MonoArray *res;
2050         int i;
2051
2052         MONO_ARCH_SAVE_REGS;
2053
2054         gclass = type->type.type->data.generic_class;
2055         g_assert (gclass->is_dynamic);
2056         dgclass = (MonoDynamicGenericClass *) gclass;
2057
2058         refclass = mono_class_from_mono_type (reflected_type->type);
2059
2060         domain = mono_object_domain (type);
2061         res = mono_array_new (domain, mono_defaults.field_info_class, dgclass->count_fields);
2062
2063         for (i = 0; i < dgclass->count_fields; i++)
2064                 mono_array_set (res, gpointer, i,
2065                                 mono_field_get_object (domain, refclass, &dgclass->fields [i]));
2066
2067         return res;
2068 }
2069
2070 static MonoArray*
2071 ves_icall_MonoGenericClass_GetProperties (MonoReflectionGenericClass *type,
2072                                           MonoReflectionType *reflected_type)
2073 {
2074         static MonoClass *System_Reflection_PropertyInfo;
2075         MonoGenericClass *gclass;
2076         MonoDynamicGenericClass *dgclass;
2077         MonoDomain *domain;
2078         MonoClass *refclass;
2079         MonoArray *res;
2080         int i;
2081
2082         MONO_ARCH_SAVE_REGS;
2083
2084         if (!System_Reflection_PropertyInfo)
2085                 System_Reflection_PropertyInfo = mono_class_from_name (
2086                         mono_defaults.corlib, "System.Reflection", "PropertyInfo");
2087
2088         gclass = type->type.type->data.generic_class;
2089         g_assert (gclass->is_dynamic);
2090         dgclass = (MonoDynamicGenericClass *) gclass;
2091
2092         refclass = mono_class_from_mono_type (reflected_type->type);
2093
2094         domain = mono_object_domain (type);
2095         res = mono_array_new (domain, System_Reflection_PropertyInfo, dgclass->count_properties);
2096
2097         for (i = 0; i < dgclass->count_properties; i++)
2098                 mono_array_set (res, gpointer, i,
2099                                 mono_property_get_object (domain, refclass, &dgclass->properties [i]));
2100
2101         return res;
2102 }
2103
2104 static MonoArray*
2105 ves_icall_MonoGenericClass_GetEvents (MonoReflectionGenericClass *type,
2106                                       MonoReflectionType *reflected_type)
2107 {
2108         static MonoClass *System_Reflection_EventInfo;
2109         MonoGenericClass *gclass;
2110         MonoDynamicGenericClass *dgclass;
2111         MonoDomain *domain;
2112         MonoClass *refclass;
2113         MonoArray *res;
2114         int i;
2115
2116         MONO_ARCH_SAVE_REGS;
2117
2118         if (!System_Reflection_EventInfo)
2119                 System_Reflection_EventInfo = mono_class_from_name (
2120                         mono_defaults.corlib, "System.Reflection", "EventInfo");
2121
2122         gclass = type->type.type->data.generic_class;
2123         g_assert (gclass->is_dynamic);
2124         dgclass = (MonoDynamicGenericClass *) gclass;
2125
2126         refclass = mono_class_from_mono_type (reflected_type->type);
2127
2128         domain = mono_object_domain (type);
2129         res = mono_array_new (domain, System_Reflection_EventInfo, dgclass->count_events);
2130
2131         for (i = 0; i < dgclass->count_events; i++)
2132                 mono_array_set (res, gpointer, i,
2133                                 mono_event_get_object (domain, refclass, &dgclass->events [i]));
2134
2135         return res;
2136 }
2137
2138 static MonoReflectionMethod *
2139 ves_icall_MonoType_get_DeclaringMethod (MonoReflectionType *type)
2140 {
2141         MonoMethod *method;
2142         MonoClass *klass;
2143
2144         MONO_ARCH_SAVE_REGS;
2145
2146         method = type->type->data.generic_param->method;
2147         if (!method)
2148                 return NULL;
2149
2150         klass = mono_class_from_mono_type (type->type);
2151         return mono_method_get_object (mono_object_domain (type), method, klass);
2152 }
2153
2154 static MonoReflectionDllImportAttribute*
2155 ves_icall_MonoMethod_GetDllImportAttribute (MonoMethod *method)
2156 {
2157         static MonoClass *DllImportAttributeClass = NULL;
2158         MonoDomain *domain = mono_domain_get ();
2159         MonoReflectionDllImportAttribute *attr;
2160         MonoImage *image = method->klass->image;
2161         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
2162         MonoTableInfo *tables = image->tables;
2163         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
2164         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
2165         guint32 im_cols [MONO_IMPLMAP_SIZE];
2166         guint32 scope_token;
2167         const char *import = NULL;
2168         const char *scope = NULL;
2169         guint32 flags;
2170
2171         if (!method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
2172                 return NULL;
2173
2174         if (!DllImportAttributeClass) {
2175                 DllImportAttributeClass = 
2176                         mono_class_from_name (mono_defaults.corlib,
2177                                                                   "System.Runtime.InteropServices", "DllImportAttribute");
2178                 g_assert (DllImportAttributeClass);
2179         }
2180                                                                                                                 
2181         if (method->klass->image->dynamic) {
2182                 MonoReflectionMethodAux *method_aux = 
2183                         g_hash_table_lookup (
2184                                                                           ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2185                 if (method_aux) {
2186                         import = method_aux->dllentry;
2187                         scope = method_aux->dll;
2188                 }
2189         }
2190         else {
2191                 if (piinfo->implmap_idx) {
2192                         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
2193                         
2194                         piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
2195                         import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
2196                         scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
2197                         scope = mono_metadata_string_heap (image, scope_token);
2198                 }
2199         }
2200         flags = piinfo->piflags;
2201         
2202         attr = (MonoReflectionDllImportAttribute*)mono_object_new (domain, DllImportAttributeClass);
2203
2204         attr->dll = mono_string_new (domain, scope);
2205         attr->entry_point = mono_string_new (domain, import);
2206         attr->call_conv = (flags & 0x700) >> 8;
2207         attr->charset = ((flags & 0x6) >> 1) + 1;
2208         if (attr->charset == 1)
2209                 attr->charset = 2;
2210         attr->exact_spelling = (flags & 0x1) != 0;
2211         attr->set_last_error = (flags & 0x4) != 0;
2212         attr->best_fit_mapping = (flags & 0x10) != 0;
2213         attr->throw_on_unmappable = (flags & 0x1000) != 0;
2214         attr->preserve_sig = FALSE;
2215
2216         return attr;
2217 }
2218
2219 static MonoReflectionMethod *
2220 ves_icall_MonoMethod_GetGenericMethodDefinition (MonoReflectionMethod *method)
2221 {
2222         MonoMethodInflated *imethod;
2223
2224         MONO_ARCH_SAVE_REGS;
2225
2226         if (!method->method->is_inflated) {
2227                 if (mono_method_signature (method->method)->generic_param_count)
2228                         return method;
2229
2230                 return NULL;
2231         }
2232
2233         imethod = (MonoMethodInflated *) method->method;
2234         if (imethod->context->gmethod && imethod->context->gmethod->reflection_info)
2235                 return imethod->context->gmethod->reflection_info;
2236         else
2237                 return mono_method_get_object (
2238                         mono_object_domain (method), imethod->declaring, NULL);
2239 }
2240
2241 static gboolean
2242 ves_icall_MonoMethod_get_HasGenericParameters (MonoReflectionMethod *method)
2243 {
2244         MONO_ARCH_SAVE_REGS;
2245
2246         if ((method->method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2247             (method->method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
2248                 return FALSE;
2249
2250         return mono_method_signature (method->method)->generic_param_count != 0;
2251 }
2252
2253 static gboolean
2254 ves_icall_MonoMethod_get_Mono_IsInflatedMethod (MonoReflectionMethod *method)
2255 {
2256         MONO_ARCH_SAVE_REGS;
2257
2258         if ((method->method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2259             (method->method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
2260                 return FALSE;
2261
2262         return method->method->is_inflated;
2263 }
2264
2265 static gboolean
2266 ves_icall_MonoMethod_get_IsGenericMethodDefinition (MonoReflectionMethod *method)
2267 {
2268         MONO_ARCH_SAVE_REGS;
2269
2270         if ((method->method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2271             (method->method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
2272                 return FALSE;
2273
2274         return mono_method_signature (method->method)->generic_param_count != 0;
2275 }
2276
2277 static MonoArray*
2278 ves_icall_MonoMethod_GetGenericArguments (MonoReflectionMethod *method)
2279 {
2280         MonoArray *res;
2281         MonoDomain *domain;
2282         MonoMethodNormal *mn;
2283         int count, i;
2284         MONO_ARCH_SAVE_REGS;
2285
2286         domain = mono_object_domain (method);
2287
2288         if ((method->method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2289             (method->method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
2290                 return mono_array_new (domain, mono_defaults.monotype_class, 0);
2291
2292         if (method->method->is_inflated) {
2293                 MonoMethodInflated *imethod = (MonoMethodInflated *) method->method;
2294                 MonoGenericMethod *gmethod = imethod->context->gmethod;
2295
2296                 if (gmethod) {
2297                         count = gmethod->inst->type_argc;
2298                         res = mono_array_new (domain, mono_defaults.monotype_class, count);
2299
2300                         for (i = 0; i < count; i++) {
2301                                 MonoType *t = gmethod->inst->type_argv [i];
2302                                 mono_array_set (
2303                                         res, gpointer, i, mono_type_get_object (domain, t));
2304                         }
2305
2306                         return res;
2307                 }
2308         }
2309
2310         mn = (MonoMethodNormal *) method->method;
2311         count = mono_method_signature (method->method)->generic_param_count;
2312         res = mono_array_new (domain, mono_defaults.monotype_class, count);
2313
2314         for (i = 0; i < count; i++) {
2315                 MonoGenericParam *param = &mn->generic_container->type_params [i];
2316                 MonoClass *pklass = mono_class_from_generic_parameter (
2317                         param, method->method->klass->image, TRUE);
2318                 mono_array_set (res, gpointer, i,
2319                                 mono_type_get_object (domain, &pklass->byval_arg));
2320         }
2321
2322         return res;
2323 }
2324
2325 static MonoObject *
2326 ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this, MonoArray *params) 
2327 {
2328         /* 
2329          * Invoke from reflection is supposed to always be a virtual call (the API
2330          * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
2331          * greater flexibility.
2332          */
2333         MonoMethod *m = method->method;
2334         int pcount;
2335         void *obj = this;
2336
2337         MONO_ARCH_SAVE_REGS;
2338
2339         if (this) {
2340                 if (!mono_object_isinst (this, m->klass))
2341                         mono_raise_exception (mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetException"));
2342                 m = mono_object_get_virtual_method (this, m);
2343                 /* must pass the pointer to the value for valuetype methods */
2344                 if (m->klass->valuetype)
2345                         obj = mono_object_unbox (this);
2346         } else if (!(m->flags & METHOD_ATTRIBUTE_STATIC) && strcmp (m->name, ".ctor") && !m->wrapper_type)
2347                 mono_raise_exception (mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetException"));
2348
2349         pcount = params? mono_array_length (params): 0;
2350         if (pcount != mono_method_signature (m)->param_count)
2351                 mono_raise_exception (mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetParameterCountException"));
2352
2353         if ((m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT) && !strcmp (m->name, ".ctor"))
2354                 mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", "Cannot invoke constructor of an abstract class."));
2355
2356         if (m->klass->rank && !strcmp (m->name, ".ctor")) {
2357                 int i;
2358                 guint32 *lengths;
2359                 guint32 *lower_bounds;
2360                 pcount = mono_array_length (params);
2361                 lengths = alloca (sizeof (guint32) * pcount);
2362                 for (i = 0; i < pcount; ++i)
2363                         lengths [i] = *(gint32*) ((char*)mono_array_get (params, gpointer, i) + sizeof (MonoObject));
2364
2365                 if (m->klass->rank == pcount) {
2366                         /* Only lengths provided. */
2367                         lower_bounds = NULL;
2368                 } else {
2369                         g_assert (pcount == (m->klass->rank * 2));
2370                         /* lower bounds are first. */
2371                         lower_bounds = lengths;
2372                         lengths += m->klass->rank;
2373                 }
2374
2375                 return (MonoObject*)mono_array_new_full (mono_object_domain (params), m->klass, lengths, lower_bounds);
2376         }
2377         return mono_runtime_invoke_array (m, obj, params, NULL);
2378 }
2379
2380 static MonoObject *
2381 ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this, MonoArray *params, MonoArray **outArgs) 
2382 {
2383         MonoDomain *domain = mono_object_domain (method); 
2384         MonoMethod *m = method->method;
2385         MonoMethodSignature *sig = mono_method_signature (m);
2386         MonoArray *out_args;
2387         MonoObject *result;
2388         int i, j, outarg_count = 0;
2389
2390         MONO_ARCH_SAVE_REGS;
2391
2392         if (m->klass == mono_defaults.object_class) {
2393
2394                 if (!strcmp (m->name, "FieldGetter")) {
2395                         MonoClass *k = this->vtable->klass;
2396                         MonoString *name;
2397                         char *str;
2398                         
2399                         /* If this is a proxy, then it must be a CBO */
2400                         if (k == mono_defaults.transparent_proxy_class) {
2401                                 MonoTransparentProxy *tp = (MonoTransparentProxy*) this;
2402                                 this = tp->rp->unwrapped_server;
2403                                 g_assert (this);
2404                                 k = this->vtable->klass;
2405                         }
2406                         
2407                         name = mono_array_get (params, MonoString *, 1);
2408                         str = mono_string_to_utf8 (name);
2409                 
2410                         do {
2411                                 MonoClassField* field = mono_class_get_field_from_name (k, str);
2412                                 if (field) {
2413                                         MonoClass *field_klass =  mono_class_from_mono_type (field->type);
2414                                         if (field_klass->valuetype)
2415                                                 result = mono_value_box (domain, field_klass, (char *)this + field->offset);
2416                                         else 
2417                                                 result = *((gpointer *)((char *)this + field->offset));
2418                                 
2419                                         g_assert (result);
2420                                         out_args = mono_array_new (domain, mono_defaults.object_class, 1);
2421                                         *outArgs = out_args;
2422                                         mono_array_set (out_args, gpointer, 0, result);
2423                                         g_free (str);
2424                                         return NULL;
2425                                 }
2426                                 k = k->parent;
2427                         } while (k);
2428
2429                         g_free (str);
2430                         g_assert_not_reached ();
2431
2432                 } else if (!strcmp (m->name, "FieldSetter")) {
2433                         MonoClass *k = this->vtable->klass;
2434                         MonoString *name;
2435                         int size, align;
2436                         char *str;
2437                         
2438                         /* If this is a proxy, then it must be a CBO */
2439                         if (k == mono_defaults.transparent_proxy_class) {
2440                                 MonoTransparentProxy *tp = (MonoTransparentProxy*) this;
2441                                 this = tp->rp->unwrapped_server;
2442                                 g_assert (this);
2443                                 k = this->vtable->klass;
2444                         }
2445                         
2446                         name = mono_array_get (params, MonoString *, 1);
2447                         str = mono_string_to_utf8 (name);
2448                 
2449                         do {
2450                                 MonoClassField* field = mono_class_get_field_from_name (k, str);
2451                                 if (field) {
2452                                         MonoClass *field_klass =  mono_class_from_mono_type (field->type);
2453                                         MonoObject *val = mono_array_get (params, gpointer, 2);
2454
2455                                         if (field_klass->valuetype) {
2456                                                 size = mono_type_size (field->type, &align);
2457                                                 memcpy ((char *)this + field->offset, 
2458                                                         ((char *)val) + sizeof (MonoObject), size);
2459                                         } else 
2460                                                 *(MonoObject**)((char *)this + field->offset) = val;
2461                                 
2462                                         out_args = mono_array_new (domain, mono_defaults.object_class, 0);
2463                                         *outArgs = out_args;
2464
2465                                         g_free (str);
2466                                         return NULL;
2467                                 }
2468                                 
2469                                 k = k->parent;
2470                         } while (k);
2471
2472                         g_free (str);
2473                         g_assert_not_reached ();
2474
2475                 }
2476         }
2477
2478         for (i = 0; i < mono_array_length (params); i++) {
2479                 if (sig->params [i]->byref) 
2480                         outarg_count++;
2481         }
2482
2483         out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
2484         
2485         /* handle constructors only for objects already allocated */
2486         if (!strcmp (method->method->name, ".ctor"))
2487                 g_assert (this);
2488
2489         /* This can be called only on MBR objects, so no need to unbox for valuetypes. */
2490         g_assert (!method->method->klass->valuetype);
2491         result = mono_runtime_invoke_array (method->method, this, params, NULL);
2492
2493         for (i = 0, j = 0; i < mono_array_length (params); i++) {
2494                 if (sig->params [i]->byref) {
2495                         gpointer arg;
2496                         arg = mono_array_get (params, gpointer, i);
2497                         mono_array_set (out_args, gpointer, j, arg);
2498                         j++;
2499                 }
2500         }
2501
2502         *outArgs = out_args;
2503
2504         return result;
2505 }
2506
2507 static MonoObject *
2508 ves_icall_System_Enum_ToObject (MonoReflectionType *type, MonoObject *obj)
2509 {
2510         MonoDomain *domain; 
2511         MonoClass *enumc, *objc;
2512         gint32 s1, s2;
2513         MonoObject *res;
2514         
2515         MONO_ARCH_SAVE_REGS;
2516
2517         MONO_CHECK_ARG_NULL (type);
2518         MONO_CHECK_ARG_NULL (obj);
2519
2520         domain = mono_object_domain (type); 
2521         enumc = mono_class_from_mono_type (type->type);
2522         objc = obj->vtable->klass;
2523
2524         MONO_CHECK_ARG (obj, enumc->enumtype == TRUE);
2525         MONO_CHECK_ARG (obj, (objc->enumtype) || (objc->byval_arg.type >= MONO_TYPE_I1 &&
2526                                                   objc->byval_arg.type <= MONO_TYPE_U8));
2527         
2528         s1 = mono_class_value_size (enumc, NULL);
2529         s2 = mono_class_value_size (objc, NULL);
2530
2531         res = mono_object_new (domain, enumc);
2532
2533 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
2534         memcpy ((char *)res + sizeof (MonoObject), (char *)obj + sizeof (MonoObject), MIN (s1, s2));
2535 #else
2536         memcpy ((char *)res + sizeof (MonoObject) + (s1 > s2 ? s1 - s2 : 0),
2537                 (char *)obj + sizeof (MonoObject) + (s2 > s1 ? s2 - s1 : 0),
2538                 MIN (s1, s2));
2539 #endif
2540         return res;
2541 }
2542
2543 static MonoObject *
2544 ves_icall_System_Enum_get_value (MonoObject *this)
2545 {
2546         MonoObject *res;
2547         MonoClass *enumc;
2548         gpointer dst;
2549         gpointer src;
2550         int size;
2551
2552         MONO_ARCH_SAVE_REGS;
2553
2554         if (!this)
2555                 return NULL;
2556
2557         g_assert (this->vtable->klass->enumtype);
2558         
2559         enumc = mono_class_from_mono_type (this->vtable->klass->enum_basetype);
2560         res = mono_object_new (mono_object_domain (this), enumc);
2561         dst = (char *)res + sizeof (MonoObject);
2562         src = (char *)this + sizeof (MonoObject);
2563         size = mono_class_value_size (enumc, NULL);
2564
2565         memcpy (dst, src, size);
2566
2567         return res;
2568 }
2569
2570 static void
2571 ves_icall_get_enum_info (MonoReflectionType *type, MonoEnumInfo *info)
2572 {
2573         MonoDomain *domain = mono_object_domain (type); 
2574         MonoClass *enumc = mono_class_from_mono_type (type->type);
2575         guint j = 0, nvalues, crow;
2576         gpointer iter;
2577         MonoClassField *field;
2578
2579         MONO_ARCH_SAVE_REGS;
2580
2581         info->utype = mono_type_get_object (domain, enumc->enum_basetype);
2582         nvalues = mono_class_num_fields (enumc) ? mono_class_num_fields (enumc) - 1 : 0;
2583         info->names = mono_array_new (domain, mono_defaults.string_class, nvalues);
2584         info->values = mono_array_new (domain, enumc, nvalues);
2585         
2586         crow = -1;
2587         iter = NULL;
2588         while ((field = mono_class_get_fields (enumc, &iter))) {
2589                 const char *p;
2590                 int len;
2591                 
2592                 if (strcmp ("value__", field->name) == 0)
2593                         continue;
2594                 if (mono_field_is_deleted (field))
2595                         continue;
2596                 mono_array_set (info->names, gpointer, j, mono_string_new (domain, field->name));
2597
2598                 if (!field->data) {
2599                         crow = mono_metadata_get_constant_index (enumc->image, mono_class_get_field_token (field), crow + 1);
2600                         field->def_type = mono_metadata_decode_row_col (&enumc->image->tables [MONO_TABLE_CONSTANT], crow-1, MONO_CONSTANT_TYPE);
2601                         crow = mono_metadata_decode_row_col (&enumc->image->tables [MONO_TABLE_CONSTANT], crow-1, MONO_CONSTANT_VALUE);
2602                         field->data = (gpointer)mono_metadata_blob_heap (enumc->image, crow);
2603                 }
2604
2605                 p = field->data;
2606                 len = mono_metadata_decode_blob_size (p, &p);
2607                 switch (enumc->enum_basetype->type) {
2608                 case MONO_TYPE_U1:
2609                 case MONO_TYPE_I1:
2610                         mono_array_set (info->values, gchar, j, *p);
2611                         break;
2612                 case MONO_TYPE_CHAR:
2613                 case MONO_TYPE_U2:
2614                 case MONO_TYPE_I2:
2615                         mono_array_set (info->values, gint16, j, read16 (p));
2616                         break;
2617                 case MONO_TYPE_U4:
2618                 case MONO_TYPE_I4:
2619                         mono_array_set (info->values, gint32, j, read32 (p));
2620                         break;
2621                 case MONO_TYPE_U8:
2622                 case MONO_TYPE_I8:
2623                         mono_array_set (info->values, gint64, j, read64 (p));
2624                         break;
2625                 default:
2626                         g_error ("Implement type 0x%02x in get_enum_info", enumc->enum_basetype->type);
2627                 }
2628                 ++j;
2629         }
2630 }
2631
2632 enum {
2633         BFLAGS_IgnoreCase = 1,
2634         BFLAGS_DeclaredOnly = 2,
2635         BFLAGS_Instance = 4,
2636         BFLAGS_Static = 8,
2637         BFLAGS_Public = 0x10,
2638         BFLAGS_NonPublic = 0x20,
2639         BFLAGS_FlattenHierarchy = 0x40,
2640         BFLAGS_InvokeMethod = 0x100,
2641         BFLAGS_CreateInstance = 0x200,
2642         BFLAGS_GetField = 0x400,
2643         BFLAGS_SetField = 0x800,
2644         BFLAGS_GetProperty = 0x1000,
2645         BFLAGS_SetProperty = 0x2000,
2646         BFLAGS_ExactBinding = 0x10000,
2647         BFLAGS_SuppressChangeType = 0x20000,
2648         BFLAGS_OptionalParamBinding = 0x40000
2649 };
2650
2651 static MonoReflectionField *
2652 ves_icall_Type_GetField (MonoReflectionType *type, MonoString *name, guint32 bflags)
2653 {
2654         MonoDomain *domain; 
2655         MonoClass *startklass, *klass;
2656         int match;
2657         MonoClassField *field;
2658         gpointer iter;
2659         char *utf8_name;
2660         int (*compare_func) (const char *s1, const char *s2) = NULL;
2661         domain = ((MonoObject *)type)->vtable->domain;
2662         klass = startklass = mono_class_from_mono_type (type->type);
2663
2664         MONO_ARCH_SAVE_REGS;
2665
2666         if (!name)
2667                 mono_raise_exception (mono_get_exception_argument_null ("name"));
2668
2669         compare_func = (bflags & BFLAGS_IgnoreCase) ? g_strcasecmp : strcmp;
2670
2671 handle_parent:
2672         iter = NULL;
2673         while ((field = mono_class_get_fields (klass, &iter))) {
2674                 match = 0;
2675                 if (mono_field_is_deleted (field))
2676                         continue;
2677                 if ((field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
2678                         if (bflags & BFLAGS_Public)
2679                                 match++;
2680                 } else {
2681                         if (bflags & BFLAGS_NonPublic)
2682                                 match++;
2683                 }
2684                 if (!match)
2685                         continue;
2686                 match = 0;
2687                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
2688                         if (bflags & BFLAGS_Static)
2689                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
2690                                         match++;
2691                 } else {
2692                         if (bflags & BFLAGS_Instance)
2693                                 match++;
2694                 }
2695
2696                 if (!match)
2697                         continue;
2698                 
2699                 utf8_name = mono_string_to_utf8 (name);
2700
2701                 if (compare_func (field->name, utf8_name)) {
2702                         g_free (utf8_name);
2703                         continue;
2704                 }
2705                 g_free (utf8_name);
2706                 
2707                 return mono_field_get_object (domain, startklass, field);
2708         }
2709         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
2710                 goto handle_parent;
2711
2712         return NULL;
2713 }
2714
2715 static MonoArray*
2716 ves_icall_Type_GetFields_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
2717 {
2718         MonoDomain *domain; 
2719         GSList *l = NULL, *tmp;
2720         MonoClass *startklass, *klass, *refklass;
2721         MonoArray *res;
2722         MonoObject *member;
2723         int i, len, match;
2724         gpointer iter;
2725         MonoClassField *field;
2726
2727         MONO_ARCH_SAVE_REGS;
2728
2729         domain = ((MonoObject *)type)->vtable->domain;
2730         klass = startklass = mono_class_from_mono_type (type->type);
2731         refklass = mono_class_from_mono_type (reftype->type);
2732
2733 handle_parent:  
2734         iter = NULL;
2735         while ((field = mono_class_get_fields (klass, &iter))) {
2736                 match = 0;
2737                 if (mono_field_is_deleted (field))
2738                         continue;
2739                 if ((field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
2740                         if (bflags & BFLAGS_Public)
2741                                 match++;
2742                 } else {
2743                         if (bflags & BFLAGS_NonPublic)
2744                                 match++;
2745                 }
2746                 if (!match)
2747                         continue;
2748                 match = 0;
2749                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
2750                         if (bflags & BFLAGS_Static)
2751                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
2752                                         match++;
2753                 } else {
2754                         if (bflags & BFLAGS_Instance)
2755                                 match++;
2756                 }
2757
2758                 if (!match)
2759                         continue;
2760                 member = (MonoObject*)mono_field_get_object (domain, refklass, field);
2761                 l = g_slist_prepend (l, member);
2762         }
2763         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
2764                 goto handle_parent;
2765         len = g_slist_length (l);
2766         res = mono_array_new (domain, mono_defaults.field_info_class, len);
2767         i = 0;
2768         tmp = l = g_slist_reverse (l);
2769         for (; tmp; tmp = tmp->next, ++i)
2770                 mono_array_set (res, gpointer, i, tmp->data);
2771         g_slist_free (l);
2772         return res;
2773 }
2774
2775 static MonoArray*
2776 ves_icall_Type_GetMethodsByName (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoBoolean ignore_case, MonoReflectionType *reftype)
2777 {
2778         MonoDomain *domain; 
2779         GSList *l = NULL, *tmp;
2780         MonoClass *startklass, *klass, *refklass;
2781         MonoArray *res;
2782         MonoMethod *method;
2783         gpointer iter;
2784         MonoObject *member;
2785         int i, len, match;
2786         GHashTable *method_slots = g_hash_table_new (mono_aligned_addr_hash, NULL);
2787         gchar *mname = NULL;
2788         int (*compare_func) (const char *s1, const char *s2) = NULL;
2789                 
2790         MONO_ARCH_SAVE_REGS;
2791
2792         domain = ((MonoObject *)type)->vtable->domain;
2793         klass = startklass = mono_class_from_mono_type (type->type);
2794         refklass = mono_class_from_mono_type (reftype->type);
2795         len = 0;
2796         if (name != NULL) {
2797                 mname = mono_string_to_utf8 (name);
2798                 compare_func = (ignore_case) ? g_strcasecmp : strcmp;
2799         }
2800
2801 handle_parent:
2802         iter = NULL;
2803         while ((method = mono_class_get_methods (klass, &iter))) {
2804                 match = 0;
2805                 if (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)
2806                         continue;
2807                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
2808                         if (bflags & BFLAGS_Public)
2809                                 match++;
2810                 } else {
2811                         if (bflags & BFLAGS_NonPublic)
2812                                 match++;
2813                 }
2814                 if (!match)
2815                         continue;
2816                 match = 0;
2817                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
2818                         if (bflags & BFLAGS_Static)
2819                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
2820                                         match++;
2821                 } else {
2822                         if (bflags & BFLAGS_Instance)
2823                                 match++;
2824                 }
2825
2826                 if (!match)
2827                         continue;
2828
2829                 if (name != NULL) {
2830                         if (compare_func (mname, method->name))
2831                                 continue;
2832                 }
2833                 
2834                 match = 0;
2835                 if (method->slot != -1) {
2836                         if (g_hash_table_lookup (method_slots, GUINT_TO_POINTER (method->slot)))
2837                                 continue;
2838                         g_hash_table_insert (method_slots, GUINT_TO_POINTER (method->slot), method);
2839                 }
2840                 
2841                 member = (MonoObject*)mono_method_get_object (domain, method, refklass);
2842                 
2843                 l = g_slist_prepend (l, member);
2844                 len++;
2845         }
2846         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
2847                 goto handle_parent;
2848
2849         g_free (mname);
2850         res = mono_array_new (domain, mono_defaults.method_info_class, len);
2851         i = 0;
2852
2853         tmp = l = g_slist_reverse (l);
2854
2855         for (; tmp; tmp = tmp->next, ++i)
2856                 mono_array_set (res, gpointer, i, tmp->data);
2857         g_slist_free (l);
2858         g_hash_table_destroy (method_slots);
2859         return res;
2860 }
2861
2862 static MonoArray*
2863 ves_icall_Type_GetConstructors_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
2864 {
2865         MonoDomain *domain; 
2866         GSList *l = NULL, *tmp;
2867         static MonoClass *System_Reflection_ConstructorInfo;
2868         MonoClass *startklass, *klass, *refklass;
2869         MonoArray *res;
2870         MonoMethod *method;
2871         MonoObject *member;
2872         int i, len, match;
2873         gpointer iter = NULL;
2874         
2875         MONO_ARCH_SAVE_REGS;
2876
2877         domain = ((MonoObject *)type)->vtable->domain;
2878         klass = startklass = mono_class_from_mono_type (type->type);
2879         refklass = mono_class_from_mono_type (reftype->type);
2880
2881         iter = NULL;
2882         while ((method = mono_class_get_methods (klass, &iter))) {
2883                 match = 0;
2884                 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
2885                         continue;
2886                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
2887                         if (bflags & BFLAGS_Public)
2888                                 match++;
2889                 } else {
2890                         if (bflags & BFLAGS_NonPublic)
2891                                 match++;
2892                 }
2893                 if (!match)
2894                         continue;
2895                 match = 0;
2896                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
2897                         if (bflags & BFLAGS_Static)
2898                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
2899                                         match++;
2900                 } else {
2901                         if (bflags & BFLAGS_Instance)
2902                                 match++;
2903                 }
2904
2905                 if (!match)
2906                         continue;
2907                 member = (MonoObject*)mono_method_get_object (domain, method, refklass);
2908                         
2909                 l = g_slist_prepend (l, member);
2910         }
2911         len = g_slist_length (l);
2912         if (!System_Reflection_ConstructorInfo)
2913                 System_Reflection_ConstructorInfo = mono_class_from_name (
2914                         mono_defaults.corlib, "System.Reflection", "ConstructorInfo");
2915         res = mono_array_new (domain, System_Reflection_ConstructorInfo, len);
2916         i = 0;
2917         tmp = l = g_slist_reverse (l);
2918         for (; tmp; tmp = tmp->next, ++i)
2919                 mono_array_set (res, gpointer, i, tmp->data);
2920         g_slist_free (l);
2921         return res;
2922 }
2923
2924 static MonoArray*
2925 ves_icall_Type_GetPropertiesByName (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoBoolean ignore_case, MonoReflectionType *reftype)
2926 {
2927         MonoDomain *domain; 
2928         GSList *l = NULL, *tmp;
2929         static MonoClass *System_Reflection_PropertyInfo;
2930         MonoClass *startklass, *klass;
2931         MonoArray *res;
2932         MonoMethod *method;
2933         MonoProperty *prop;
2934         int i, match;
2935         int len = 0;
2936         guint32 flags;
2937         GHashTable *method_slots = g_hash_table_new (mono_aligned_addr_hash, NULL);
2938         gchar *propname = NULL;
2939         int (*compare_func) (const char *s1, const char *s2) = NULL;
2940         gpointer iter;
2941
2942         MONO_ARCH_SAVE_REGS;
2943
2944         domain = ((MonoObject *)type)->vtable->domain;
2945         klass = startklass = mono_class_from_mono_type (type->type);
2946         if (name != NULL) {
2947                 propname = mono_string_to_utf8 (name);
2948                 compare_func = (ignore_case) ? g_strcasecmp : strcmp;
2949         }
2950
2951 handle_parent:
2952         iter = NULL;
2953         while ((prop = mono_class_get_properties (klass, &iter))) {
2954                 match = 0;
2955                 method = prop->get;
2956                 if (!method)
2957                         method = prop->set;
2958                 if (method)
2959                         flags = method->flags;
2960                 else
2961                         flags = 0;
2962                 if ((prop->get && ((prop->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)) ||
2963                         (prop->set && ((prop->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC))) {
2964                         if (bflags & BFLAGS_Public)
2965                                 match++;
2966                 } else {
2967                         if (bflags & BFLAGS_NonPublic)
2968                                 match++;
2969                 }
2970                 if (!match)
2971                         continue;
2972                 match = 0;
2973                 if (flags & METHOD_ATTRIBUTE_STATIC) {
2974                         if (bflags & BFLAGS_Static)
2975                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
2976                                         match++;
2977                 } else {
2978                         if (bflags & BFLAGS_Instance)
2979                                 match++;
2980                 }
2981
2982                 if (!match)
2983                         continue;
2984                 match = 0;
2985
2986                 if (name != NULL) {
2987                         if (compare_func (propname, prop->name))
2988                                 continue;
2989                 }
2990                 
2991                 if (prop->get && prop->get->slot != -1) {
2992                         if (g_hash_table_lookup (method_slots, GUINT_TO_POINTER (prop->get->slot)))
2993                                 continue;
2994                         g_hash_table_insert (method_slots, GUINT_TO_POINTER (prop->get->slot), prop);
2995                 }
2996                 if (prop->set && prop->set->slot != -1) {
2997                         if (g_hash_table_lookup (method_slots, GUINT_TO_POINTER (prop->set->slot)))
2998                                 continue;
2999                         g_hash_table_insert (method_slots, GUINT_TO_POINTER (prop->set->slot), prop);
3000                 }
3001
3002                 l = g_slist_prepend (l, mono_property_get_object (domain, startklass, prop));
3003                 len++;
3004         }
3005         if ((!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent)))
3006                 goto handle_parent;
3007
3008         g_free (propname);
3009         if (!System_Reflection_PropertyInfo)
3010                 System_Reflection_PropertyInfo = mono_class_from_name (
3011                         mono_defaults.corlib, "System.Reflection", "PropertyInfo");
3012         res = mono_array_new (domain, System_Reflection_PropertyInfo, len);
3013         i = 0;
3014
3015         tmp = l = g_slist_reverse (l);
3016
3017         for (; tmp; tmp = tmp->next, ++i)
3018                 mono_array_set (res, gpointer, i, tmp->data);
3019         g_slist_free (l);
3020         g_hash_table_destroy (method_slots);
3021         return res;
3022 }
3023
3024 static MonoReflectionEvent *
3025 ves_icall_MonoType_GetEvent (MonoReflectionType *type, MonoString *name, guint32 bflags)
3026 {
3027         MonoDomain *domain;
3028         MonoClass *klass, *startklass;
3029         gpointer iter;
3030         MonoEvent *event;
3031         MonoMethod *method;
3032         gchar *event_name;
3033
3034         MONO_ARCH_SAVE_REGS;
3035
3036         event_name = mono_string_to_utf8 (name);
3037         klass = startklass = mono_class_from_mono_type (type->type);
3038         domain = mono_object_domain (type);
3039
3040 handle_parent:  
3041         iter = NULL;
3042         while ((event = mono_class_get_events (klass, &iter))) {
3043                 if (strcmp (event->name, event_name))
3044                         continue;
3045
3046                 method = event->add;
3047                 if (!method)
3048                         method = event->remove;
3049                 if (!method)
3050                         method = event->raise;
3051                 if (method) {
3052                         if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3053                                 if (!(bflags & BFLAGS_Public))
3054                                         continue;
3055                         } else {
3056                                 if (!(bflags & BFLAGS_NonPublic))
3057                                         continue;
3058                         }
3059                 }
3060                 else
3061                         if (!(bflags & BFLAGS_NonPublic))
3062                                 continue;
3063
3064                 g_free (event_name);
3065                 return mono_event_get_object (domain, startklass, event);
3066         }
3067
3068         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3069                 goto handle_parent;
3070
3071         g_free (event_name);
3072         return NULL;
3073 }
3074
3075 static MonoArray*
3076 ves_icall_Type_GetEvents_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
3077 {
3078         MonoDomain *domain; 
3079         GSList *l = NULL, *tmp;
3080         static MonoClass *System_Reflection_EventInfo;
3081         MonoClass *startklass, *klass;
3082         MonoArray *res;
3083         MonoMethod *method;
3084         MonoEvent *event;
3085         int i, len, match;
3086         gpointer iter;
3087
3088         MONO_ARCH_SAVE_REGS;
3089
3090         domain = mono_object_domain (type);
3091         klass = startklass = mono_class_from_mono_type (type->type);
3092
3093 handle_parent:  
3094         iter = NULL;
3095         while ((event = mono_class_get_events (klass, &iter))) {
3096                 match = 0;
3097                 method = event->add;
3098                 if (!method)
3099                         method = event->remove;
3100                 if (!method)
3101                         method = event->raise;
3102                 if (method) {
3103                         if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3104                                 if (bflags & BFLAGS_Public)
3105                                         match++;
3106                         } else {
3107                                 if (bflags & BFLAGS_NonPublic)
3108                                         match++;
3109                         }
3110                 }
3111                 else
3112                         if (bflags & BFLAGS_NonPublic)
3113                                 match ++;
3114                 if (!match)
3115                         continue;
3116                 match = 0;
3117                 if (method) {
3118                         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3119                                 if (bflags & BFLAGS_Static)
3120                                         if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3121                                                 match++;
3122                         } else {
3123                                 if (bflags & BFLAGS_Instance)
3124                                         match++;
3125                         }
3126                 }
3127                 else
3128                         if (bflags & BFLAGS_Instance)
3129                                 match ++;
3130                 if (!match)
3131                         continue;
3132                 match = 0;
3133                 l = g_slist_prepend (l, mono_event_get_object (domain, klass, event));
3134         }
3135         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3136                 goto handle_parent;
3137         len = g_slist_length (l);
3138         if (!System_Reflection_EventInfo)
3139                 System_Reflection_EventInfo = mono_class_from_name (
3140                         mono_defaults.corlib, "System.Reflection", "EventInfo");
3141         res = mono_array_new (domain, System_Reflection_EventInfo, len);
3142         i = 0;
3143
3144         tmp = l = g_slist_reverse (l);
3145
3146         for (; tmp; tmp = tmp->next, ++i)
3147                 mono_array_set (res, gpointer, i, tmp->data);
3148         g_slist_free (l);
3149         return res;
3150 }
3151
3152 static MonoReflectionType *
3153 ves_icall_Type_GetNestedType (MonoReflectionType *type, MonoString *name, guint32 bflags)
3154 {
3155         MonoDomain *domain; 
3156         MonoClass *startklass, *klass;
3157         MonoClass *nested;
3158         GList *tmpn;
3159         char *str;
3160         
3161         MONO_ARCH_SAVE_REGS;
3162
3163         domain = ((MonoObject *)type)->vtable->domain;
3164         klass = startklass = mono_class_from_mono_type (type->type);
3165         str = mono_string_to_utf8 (name);
3166
3167  handle_parent:
3168         for (tmpn = klass->nested_classes; tmpn; tmpn = tmpn->next) {
3169                 int match = 0;
3170                 nested = tmpn->data;
3171                 if ((nested->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
3172                         if (bflags & BFLAGS_Public)
3173                                 match++;
3174                 } else {
3175                         if (bflags & BFLAGS_NonPublic)
3176                                 match++;
3177                 }
3178                 if (!match)
3179                         continue;
3180                 if (strcmp (nested->name, str) == 0){
3181                         g_free (str);
3182                         return mono_type_get_object (domain, &nested->byval_arg);
3183                 }
3184         }
3185         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3186                 goto handle_parent;
3187         g_free (str);
3188         return NULL;
3189 }
3190
3191 static MonoArray*
3192 ves_icall_Type_GetNestedTypes (MonoReflectionType *type, guint32 bflags)
3193 {
3194         MonoDomain *domain; 
3195         GSList *l = NULL, *tmp;
3196         GList *tmpn;
3197         MonoClass *startklass, *klass;
3198         MonoArray *res;
3199         MonoObject *member;
3200         int i, len, match;
3201         MonoClass *nested;
3202
3203         MONO_ARCH_SAVE_REGS;
3204
3205         domain = ((MonoObject *)type)->vtable->domain;
3206         klass = startklass = mono_class_from_mono_type (type->type);
3207
3208         for (tmpn = klass->nested_classes; tmpn; tmpn = tmpn->next) {
3209                 match = 0;
3210                 nested = tmpn->data;
3211                 if ((nested->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
3212                         if (bflags & BFLAGS_Public)
3213                                 match++;
3214                 } else {
3215                         if (bflags & BFLAGS_NonPublic)
3216                                 match++;
3217                 }
3218                 if (!match)
3219                         continue;
3220                 member = (MonoObject*)mono_type_get_object (domain, &nested->byval_arg);
3221                 l = g_slist_prepend (l, member);
3222         }
3223         len = g_slist_length (l);
3224         res = mono_array_new (domain, mono_defaults.monotype_class, len);
3225         i = 0;
3226         tmp = l = g_slist_reverse (l);
3227         for (; tmp; tmp = tmp->next, ++i)
3228                 mono_array_set (res, gpointer, i, tmp->data);
3229         g_slist_free (l);
3230         return res;
3231 }
3232
3233 static MonoReflectionType*
3234 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssembly *assembly, MonoReflectionModule *module, MonoString *name, MonoBoolean throwOnError, MonoBoolean ignoreCase)
3235 {
3236         gchar *str;
3237         MonoType *type = NULL;
3238         MonoTypeNameParse info;
3239         gboolean type_resolve = FALSE;
3240
3241         MONO_ARCH_SAVE_REGS;
3242
3243         str = mono_string_to_utf8 (name);
3244         /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
3245         if (!mono_reflection_parse_type (str, &info)) {
3246                 g_free (str);
3247                 g_list_free (info.modifiers);
3248                 g_list_free (info.nested);
3249                 if (throwOnError) /* uhm: this is a parse error, though... */
3250                         mono_raise_exception (mono_get_exception_type_load (name));
3251                 /*g_print ("failed parse\n");*/
3252                 return NULL;
3253         }
3254
3255         if (module != NULL) {
3256                 if (module->image)
3257                         type = mono_reflection_get_type (module->image, &info, ignoreCase, &type_resolve);
3258                 else
3259                         type = NULL;
3260         }
3261         else
3262                 if (assembly->assembly->dynamic) {
3263                         /* Enumerate all modules */
3264                         MonoReflectionAssemblyBuilder *abuilder = (MonoReflectionAssemblyBuilder*)assembly;
3265                         int i;
3266
3267                         type = NULL;
3268                         if (abuilder->modules) {
3269                                 for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
3270                                         MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
3271                                         type = mono_reflection_get_type (&mb->dynamic_image->image, &info, ignoreCase, &type_resolve);
3272                                         if (type)
3273                                                 break;
3274                                 }
3275                         }
3276
3277                         if (!type && abuilder->loaded_modules) {
3278                                 for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
3279                                         MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
3280                                         type = mono_reflection_get_type (mod->image, &info, ignoreCase, &type_resolve);
3281                                         if (type)
3282                                                 break;
3283                                 }
3284                         }
3285                 }
3286                 else
3287                         type = mono_reflection_get_type (assembly->assembly->image, &info, ignoreCase, &type_resolve);
3288         g_free (str);
3289         g_list_free (info.modifiers);
3290         g_list_free (info.nested);
3291         if (!type) {
3292                 if (throwOnError)
3293                         mono_raise_exception (mono_get_exception_type_load (name));
3294                 /* g_print ("failed find\n"); */
3295                 return NULL;
3296         }
3297         /* g_print ("got it\n"); */
3298         return mono_type_get_object (mono_object_domain (assembly), type);
3299
3300 }
3301
3302 static MonoString *
3303 ves_icall_System_Reflection_Assembly_get_code_base (MonoReflectionAssembly *assembly)
3304 {
3305         MonoDomain *domain = mono_object_domain (assembly); 
3306         MonoAssembly *mass = assembly->assembly;
3307         MonoString *res;
3308         gchar *uri;
3309         gchar *absolute;
3310         
3311         MONO_ARCH_SAVE_REGS;
3312
3313         absolute = g_build_filename (mass->basedir, mass->image->module_name, NULL);
3314         uri = g_filename_to_uri (absolute, NULL, NULL);
3315         res = mono_string_new (domain, uri);
3316         g_free (uri);
3317         g_free (absolute);
3318         return res;
3319 }
3320
3321 static MonoBoolean
3322 ves_icall_System_Reflection_Assembly_get_global_assembly_cache (MonoReflectionAssembly *assembly)
3323 {
3324         MonoAssembly *mass = assembly->assembly;
3325
3326         MONO_ARCH_SAVE_REGS;
3327
3328         return mass->in_gac;
3329 }
3330
3331 static MonoReflectionAssembly*
3332 ves_icall_System_Reflection_Assembly_load_with_partial_name (MonoString *mname, MonoObject *evidence)
3333 {
3334         gchar *name;
3335         MonoAssembly *res;
3336         MonoImageOpenStatus status;
3337         
3338         MONO_ARCH_SAVE_REGS;
3339
3340         name = mono_string_to_utf8 (mname);
3341         res = mono_assembly_load_with_partial_name (name, &status);
3342
3343         g_free (name);
3344
3345         if (res == NULL)
3346                 return NULL;
3347         return mono_assembly_get_object (mono_domain_get (), res);
3348 }
3349
3350 static MonoString *
3351 ves_icall_System_Reflection_Assembly_get_location (MonoReflectionAssembly *assembly)
3352 {
3353         MonoDomain *domain = mono_object_domain (assembly); 
3354         MonoString *res;
3355
3356         MONO_ARCH_SAVE_REGS;
3357
3358         res = mono_string_new (domain, mono_image_get_filename (assembly->assembly->image));
3359
3360         return res;
3361 }
3362
3363 static MonoString *
3364 ves_icall_System_Reflection_Assembly_InternalImageRuntimeVersion (MonoReflectionAssembly *assembly)
3365 {
3366         MonoDomain *domain = mono_object_domain (assembly); 
3367
3368         MONO_ARCH_SAVE_REGS;
3369
3370         return mono_string_new (domain, assembly->assembly->image->version);
3371 }
3372
3373 static MonoReflectionMethod*
3374 ves_icall_System_Reflection_Assembly_get_EntryPoint (MonoReflectionAssembly *assembly) 
3375 {
3376         guint32 token = mono_image_get_entry_point (assembly->assembly->image);
3377
3378         MONO_ARCH_SAVE_REGS;
3379
3380         if (!token)
3381                 return NULL;
3382         return mono_method_get_object (mono_object_domain (assembly), mono_get_method (assembly->assembly->image, token, NULL), NULL);
3383 }
3384
3385 static MonoReflectionModule*
3386 ves_icall_System_Reflection_Assembly_get_ManifestModule (MonoReflectionAssembly *assembly) 
3387 {
3388         return mono_module_get_object (mono_object_domain (assembly), assembly->assembly->image);
3389 }
3390
3391 static MonoArray*
3392 ves_icall_System_Reflection_Assembly_GetManifestResourceNames (MonoReflectionAssembly *assembly) 
3393 {
3394         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
3395         MonoArray *result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, table->rows);
3396         int i;
3397         const char *val;
3398
3399         MONO_ARCH_SAVE_REGS;
3400
3401         for (i = 0; i < table->rows; ++i) {
3402                 val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
3403                 mono_array_set (result, gpointer, i, mono_string_new (mono_object_domain (assembly), val));
3404         }
3405         return result;
3406 }
3407
3408 static MonoArray*
3409 ves_icall_System_Reflection_Assembly_GetReferencedAssemblies (MonoReflectionAssembly *assembly) 
3410 {
3411         static MonoClass *System_Reflection_AssemblyName;
3412         MonoArray *result;
3413         MonoDomain *domain = mono_object_domain (assembly);
3414         int i, count = 0;
3415         static MonoMethod *create_culture = NULL;
3416         MonoTableInfo *t;
3417
3418         MONO_ARCH_SAVE_REGS;
3419
3420         if (!System_Reflection_AssemblyName)
3421                 System_Reflection_AssemblyName = mono_class_from_name (
3422                         mono_defaults.corlib, "System.Reflection", "AssemblyName");
3423
3424         t = &assembly->assembly->image->tables [MONO_TABLE_ASSEMBLYREF];
3425         count = t->rows;
3426
3427         result = mono_array_new (domain, System_Reflection_AssemblyName, count);
3428
3429         if (count > 0) {
3430                 MonoMethodDesc *desc = mono_method_desc_new (
3431                         "System.Globalization.CultureInfo:CreateSpecificCulture(string)", TRUE);
3432                 create_culture = mono_method_desc_search_in_image (desc, mono_defaults.corlib);
3433                 g_assert (create_culture);
3434                 mono_method_desc_free (desc);
3435         }
3436
3437         for (i = 0; i < count; i++) {
3438                 MonoAssembly *assem;
3439                 MonoReflectionAssemblyName *aname;
3440                 char *codebase, *absolute;
3441
3442                 /* FIXME: There is no need to load the assemblies themselves */
3443                 mono_assembly_load_reference (assembly->assembly->image, i);
3444
3445                 assem = assembly->assembly->image->references [i];
3446                 if (assem == (gpointer)-1) {
3447                         char *msg = g_strdup_printf ("Assembly %d referenced from assembly %s not found ", i, assembly->assembly->image->name);
3448                         MonoException *ex = mono_get_exception_file_not_found2 (msg, NULL);
3449                         g_free (msg);
3450                         mono_raise_exception (ex);
3451                 }
3452
3453                 aname = (MonoReflectionAssemblyName *) mono_object_new (
3454                         domain, System_Reflection_AssemblyName);
3455
3456                 aname->name = mono_string_new (domain, assem->aname.name);
3457
3458                 aname->major = assem->aname.major;
3459                 aname->minor = assem->aname.minor;
3460                 aname->build = assem->aname.build;
3461                 aname->revision = assem->aname.revision;
3462                 aname->revision = assem->aname.revision;
3463                 aname->hashalg = assem->aname.hash_alg;
3464                 aname->flags = assem->aname.flags;
3465
3466                 if (create_culture) {
3467                         gpointer args [1];
3468                         args [0] = mono_string_new (domain, assem->aname.culture);
3469                         aname->cultureInfo = mono_runtime_invoke (create_culture, NULL, args, NULL);
3470                 }
3471
3472                 if (assem->aname.public_key) {
3473                         guint32 pkey_len;
3474                         const char *pkey_ptr = assem->aname.public_key;
3475                         pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
3476
3477                         aname->publicKey = mono_array_new (domain, mono_defaults.byte_class, pkey_len);
3478                         memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
3479                 }
3480
3481                 /* public key token isn't copied - the class library will 
3482                    automatically generate it from the public key if required */
3483
3484                 absolute = g_build_filename (assem->basedir, assem->image->module_name, NULL);
3485                 codebase = g_filename_to_uri (absolute, NULL, NULL);
3486                 aname->codebase = mono_string_new (domain, codebase);
3487                 g_free (codebase);
3488                 g_free (absolute);
3489                 mono_array_set (result, gpointer, i, aname);
3490         }
3491         return result;
3492 }
3493
3494 typedef struct {
3495         MonoArray *res;
3496         int idx;
3497 } NameSpaceInfo;
3498
3499 static void
3500 foreach_namespace (const char* key, gconstpointer val, NameSpaceInfo *info)
3501 {
3502         MonoString *name = mono_string_new (mono_object_domain (info->res), key);
3503
3504         mono_array_set (info->res, gpointer, info->idx, name);
3505         info->idx++;
3506 }
3507
3508 static MonoArray*
3509 ves_icall_System_Reflection_Assembly_GetNamespaces (MonoReflectionAssembly *assembly) 
3510 {
3511         MonoImage *img = assembly->assembly->image;
3512         MonoArray *res;
3513         NameSpaceInfo info;
3514
3515         MONO_ARCH_SAVE_REGS;
3516         
3517         res = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, g_hash_table_size (img->name_cache));
3518         info.res = res;
3519         info.idx = 0;
3520         g_hash_table_foreach (img->name_cache, (GHFunc)foreach_namespace, &info);
3521
3522         return res;
3523 }
3524
3525 /* move this in some file in mono/util/ */
3526 static char *
3527 g_concat_dir_and_file (const char *dir, const char *file)
3528 {
3529         g_return_val_if_fail (dir != NULL, NULL);
3530         g_return_val_if_fail (file != NULL, NULL);
3531
3532         /*
3533          * If the directory name doesn't have a / on the end, we need
3534          * to add one so we get a proper path to the file
3535          */
3536         if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
3537                 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
3538         else
3539                 return g_strconcat (dir, file, NULL);
3540 }
3541
3542 static void *
3543 ves_icall_System_Reflection_Assembly_GetManifestResourceInternal (MonoReflectionAssembly *assembly, MonoString *name, gint32 *size, MonoReflectionModule **ref_module) 
3544 {
3545         char *n = mono_string_to_utf8 (name);
3546         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
3547         guint32 i;
3548         guint32 cols [MONO_MANIFEST_SIZE];
3549         guint32 impl, file_idx;
3550         const char *val;
3551         MonoImage *module;
3552
3553         MONO_ARCH_SAVE_REGS;
3554
3555         for (i = 0; i < table->rows; ++i) {
3556                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
3557                 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
3558                 if (strcmp (val, n) == 0)
3559                         break;
3560         }
3561         g_free (n);
3562         if (i == table->rows)
3563                 return NULL;
3564         /* FIXME */
3565         impl = cols [MONO_MANIFEST_IMPLEMENTATION];
3566         if (impl) {
3567                 /*
3568                  * this code should only be called after obtaining the 
3569                  * ResourceInfo and handling the other cases.
3570                  */
3571                 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
3572                 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
3573
3574                 module = mono_image_load_file_for_image (assembly->assembly->image, file_idx);
3575                 if (!module)
3576                         return NULL;
3577         }
3578         else
3579                 module = assembly->assembly->image;
3580
3581         *ref_module = mono_module_get_object (mono_domain_get (), module);
3582
3583         return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], size);
3584 }
3585
3586 static gboolean
3587 ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoManifestResourceInfo *info)
3588 {
3589         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
3590         int i;
3591         guint32 cols [MONO_MANIFEST_SIZE];
3592         guint32 file_cols [MONO_FILE_SIZE];
3593         const char *val;
3594         char *n;
3595
3596         MONO_ARCH_SAVE_REGS;
3597
3598         n = mono_string_to_utf8 (name);
3599         for (i = 0; i < table->rows; ++i) {
3600                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
3601                 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
3602                 if (strcmp (val, n) == 0)
3603                         break;
3604         }
3605         g_free (n);
3606         if (i == table->rows)
3607                 return FALSE;
3608
3609         if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
3610                 info->location = RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST;
3611         }
3612         else {
3613                 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
3614                 case MONO_IMPLEMENTATION_FILE:
3615                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
3616                         table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
3617                         mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
3618                         val = mono_metadata_string_heap (assembly->assembly->image, file_cols [MONO_FILE_NAME]);
3619                         info->filename = mono_string_new (mono_object_domain (assembly), val);
3620                         if (file_cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA)
3621                                 info->location = 0;
3622                         else
3623                                 info->location = RESOURCE_LOCATION_EMBEDDED;
3624                         break;
3625
3626                 case MONO_IMPLEMENTATION_ASSEMBLYREF:
3627                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
3628                         mono_assembly_load_reference (assembly->assembly->image, i - 1);
3629                         if (assembly->assembly->image->references [i - 1] == (gpointer)-1) {
3630                                 char *msg = g_strdup_printf ("Assembly %d referenced from assembly %s not found ", i - 1, assembly->assembly->image->name);
3631                                 MonoException *ex = mono_get_exception_file_not_found2 (msg, NULL);
3632                                 g_free (msg);
3633                                 mono_raise_exception (ex);
3634                         }
3635                         info->assembly = mono_assembly_get_object (mono_domain_get (), assembly->assembly->image->references [i - 1]);
3636
3637                         /* Obtain info recursively */
3638                         ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (info->assembly, name, info);
3639                         info->location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
3640                         break;
3641
3642                 case MONO_IMPLEMENTATION_EXP_TYPE:
3643                         g_assert_not_reached ();
3644                         break;
3645                 }
3646         }
3647
3648         return TRUE;
3649 }
3650
3651 static MonoObject*
3652 ves_icall_System_Reflection_Assembly_GetFilesInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoBoolean resource_modules) 
3653 {
3654         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
3655         MonoArray *result = NULL;
3656         int i, count;
3657         const char *val;
3658         char *n;
3659
3660         MONO_ARCH_SAVE_REGS;
3661
3662         /* check hash if needed */
3663         if (name) {
3664                 n = mono_string_to_utf8 (name);
3665                 for (i = 0; i < table->rows; ++i) {
3666                         val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
3667                         if (strcmp (val, n) == 0) {
3668                                 MonoString *fn;
3669                                 g_free (n);
3670                                 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
3671                                 fn = mono_string_new (mono_object_domain (assembly), n);
3672                                 g_free (n);
3673                                 return (MonoObject*)fn;
3674                         }
3675                 }
3676                 g_free (n);
3677                 return NULL;
3678         }
3679
3680         count = 0;
3681         for (i = 0; i < table->rows; ++i) {
3682                 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA))
3683                         count ++;
3684         }
3685
3686         result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, count);
3687
3688         count = 0;
3689         for (i = 0; i < table->rows; ++i) {
3690                 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
3691                         val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
3692                         n = g_concat_dir_and_file (assembly->assembly->basedir, val);
3693                         mono_array_set (result, gpointer, count, mono_string_new (mono_object_domain (assembly), n));
3694                         g_free (n);
3695                         count ++;
3696                 }
3697         }
3698         return (MonoObject*)result;
3699 }
3700
3701 static MonoArray*
3702 ves_icall_System_Reflection_Assembly_GetModulesInternal (MonoReflectionAssembly *assembly)
3703 {
3704         MonoDomain *domain = mono_domain_get();
3705         MonoArray *res;
3706         MonoClass *klass;
3707         int i, j, file_count = 0;
3708         MonoImage **modules;
3709         guint32 module_count, real_module_count;
3710         MonoTableInfo *table;
3711
3712         g_assert (assembly->assembly->image != NULL);
3713
3714         if (assembly->assembly->dynamic) {
3715                 MonoReflectionAssemblyBuilder *assemblyb = (MonoReflectionAssemblyBuilder*)assembly;
3716
3717                 if (assemblyb->modules)
3718                         module_count = mono_array_length (assemblyb->modules);
3719                 else
3720                         module_count = 0;
3721                 real_module_count = module_count;
3722
3723                 modules = g_new0 (MonoImage*, module_count);
3724                 for (i = 0; i < mono_array_length (assemblyb->modules); ++i) {
3725                         modules [i] = 
3726                                 mono_array_get (assemblyb->modules, MonoReflectionModuleBuilder*, i)->module.image;
3727                 }
3728         }
3729         else {
3730                 table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
3731                 file_count = table->rows;
3732
3733                 modules = assembly->assembly->image->modules;
3734                 module_count = assembly->assembly->image->module_count;
3735
3736                 real_module_count = 0;
3737                 for (i = 0; i < module_count; ++i)
3738                         if (modules [i])
3739                                 real_module_count ++;
3740         }
3741
3742         klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
3743         res = mono_array_new (domain, klass, 1 + real_module_count + file_count);
3744
3745         mono_array_set (res, gpointer, 0, mono_module_get_object (domain, assembly->assembly->image));
3746         j = 1;
3747         for (i = 0; i < module_count; ++i)
3748                 if (modules [i]) {
3749                         mono_array_set (res, gpointer, j, mono_module_get_object (domain, modules[i]));
3750                         ++j;
3751                 }
3752
3753         for (i = 0; i < file_count; ++i, ++j)
3754                 mono_array_set (res, gpointer, j, mono_module_file_get_object (domain, assembly->assembly->image, i));
3755
3756         if (assembly->assembly->dynamic)
3757                 g_free (modules);
3758
3759         return res;
3760 }
3761
3762 static MonoReflectionMethod*
3763 ves_icall_GetCurrentMethod (void) 
3764 {
3765         MonoMethod *m = mono_method_get_last_managed ();
3766
3767         MONO_ARCH_SAVE_REGS;
3768
3769         return mono_method_get_object (mono_domain_get (), m, NULL);
3770 }
3771
3772 static MonoReflectionMethod*
3773 ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternal (MonoMethod *method)
3774 {
3775         return mono_method_get_object (mono_domain_get (), method, NULL);
3776 }
3777
3778 static MonoReflectionMethodBody*
3779 ves_icall_System_Reflection_MethodBase_GetMethodBodyInternal (MonoMethod *method)
3780 {
3781         return mono_method_body_get_object (mono_domain_get (), method);
3782 }
3783
3784 static MonoReflectionAssembly*
3785 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (void)
3786 {
3787         MonoMethod *m = mono_method_get_last_managed ();
3788
3789         MONO_ARCH_SAVE_REGS;
3790
3791         return mono_assembly_get_object (mono_domain_get (), m->klass->image->assembly);
3792 }
3793
3794
3795 static gboolean
3796 get_caller (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
3797 {
3798         MonoMethod **dest = data;
3799
3800         /* skip unmanaged frames */
3801         if (!managed)
3802                 return FALSE;
3803
3804         if (m == *dest) {
3805                 *dest = NULL;
3806                 return FALSE;
3807         }
3808         if (!(*dest)) {
3809                 *dest = m;
3810                 return TRUE;
3811         }
3812         return FALSE;
3813 }
3814
3815 static MonoReflectionAssembly*
3816 ves_icall_System_Reflection_Assembly_GetEntryAssembly (void)
3817 {
3818         MonoDomain* domain = mono_domain_get ();
3819
3820         MONO_ARCH_SAVE_REGS;
3821
3822         if (!domain->entry_assembly)
3823                 return NULL;
3824
3825         return mono_assembly_get_object (domain, domain->entry_assembly);
3826 }
3827
3828
3829 static MonoReflectionAssembly*
3830 ves_icall_System_Reflection_Assembly_GetCallingAssembly (void)
3831 {
3832         MonoMethod *m = mono_method_get_last_managed ();
3833         MonoMethod *dest = m;
3834
3835         MONO_ARCH_SAVE_REGS;
3836
3837         mono_stack_walk_no_il (get_caller, &dest);
3838         if (!dest)
3839                 dest = m;
3840         return mono_assembly_get_object (mono_domain_get (), dest->klass->image->assembly);
3841 }
3842
3843 static MonoString *
3844 ves_icall_System_MonoType_getFullName (MonoReflectionType *object, gboolean full_name)
3845 {
3846         MonoDomain *domain = mono_object_domain (object); 
3847         MonoString *res;
3848         gchar *name;
3849
3850         MONO_ARCH_SAVE_REGS;
3851
3852         if (full_name)
3853                 name = mono_type_get_full_name (object->type);
3854         else
3855                 name = mono_type_get_name (object->type);
3856         res = mono_string_new (domain, name);
3857         g_free (name);
3858
3859         return res;
3860 }
3861
3862 static void
3863 fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *aname, MonoAssemblyName *name, const char *absolute)
3864 {
3865         static MonoMethod *create_culture = NULL;
3866         gpointer args [1];
3867         guint32 pkey_len;
3868         const char *pkey_ptr;
3869         gchar *codebase;
3870
3871         MONO_ARCH_SAVE_REGS;
3872
3873         aname->name = mono_string_new (domain, name->name);
3874         aname->major = name->major;
3875         aname->minor = name->minor;
3876         aname->build = name->build;
3877         aname->revision = name->revision;
3878         aname->hashalg = name->hash_alg;
3879
3880         codebase = g_filename_to_uri (absolute, NULL, NULL);
3881         if (codebase) {
3882                 aname->codebase = mono_string_new (domain, codebase);
3883                 g_free (codebase);
3884         }
3885
3886         if (!create_culture) {
3887                 MonoMethodDesc *desc = mono_method_desc_new ("System.Globalization.CultureInfo:CreateSpecificCulture(string)", TRUE);
3888                 create_culture = mono_method_desc_search_in_image (desc, mono_defaults.corlib);
3889                 g_assert (create_culture);
3890                 mono_method_desc_free (desc);
3891         }
3892
3893         args [0] = mono_string_new (domain, name->culture);
3894         aname->cultureInfo = 
3895                 mono_runtime_invoke (create_culture, NULL, args, NULL);
3896
3897         if (name->public_key) {
3898                 pkey_ptr = name->public_key;
3899                 pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
3900
3901                 aname->publicKey = mono_array_new (domain, mono_defaults.byte_class, pkey_len);
3902                 memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
3903         }
3904
3905         /* MonoAssemblyName keeps the public key token as an hexadecimal string */
3906         if (name->public_key_token [0]) {
3907                 int i, j;
3908                 char *p;
3909
3910                 aname->keyToken = mono_array_new (domain, mono_defaults.byte_class, 8);
3911                 p = mono_array_addr (aname->keyToken, char, 0);
3912
3913                 for (i = 0, j = 0; i < 8; i++) {
3914                         *p = g_ascii_xdigit_value (name->public_key_token [j++]) << 4;
3915                         *p |= g_ascii_xdigit_value (name->public_key_token [j++]);
3916                         p++;
3917                 }
3918         }
3919 }
3920
3921 static void
3922 ves_icall_System_Reflection_Assembly_FillName (MonoReflectionAssembly *assembly, MonoReflectionAssemblyName *aname)
3923 {
3924         gchar *absolute;
3925
3926         MONO_ARCH_SAVE_REGS;
3927
3928         absolute = g_build_filename (assembly->assembly->basedir, assembly->assembly->image->module_name, NULL);
3929
3930         fill_reflection_assembly_name (mono_object_domain (assembly), aname, 
3931                                                                    &assembly->assembly->aname, absolute);
3932
3933         g_free (absolute);
3934 }
3935
3936 static void
3937 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoString *fname, MonoReflectionAssemblyName *aname)
3938 {
3939         char *filename;
3940         MonoImageOpenStatus status = MONO_IMAGE_OK;
3941         gboolean res;
3942         MonoImage *image;
3943         MonoAssemblyName name;
3944
3945         MONO_ARCH_SAVE_REGS;
3946
3947         filename = mono_string_to_utf8 (fname);
3948
3949         image = mono_image_open (filename, &status);
3950         
3951         if (!image){
3952                 MonoException *exc;
3953
3954                 g_free (filename);
3955                 exc = mono_get_exception_file_not_found (fname);
3956                 mono_raise_exception (exc);
3957         }
3958
3959         res = mono_assembly_fill_assembly_name (image, &name);
3960         if (!res) {
3961                 mono_image_close (image);
3962                 g_free (filename);
3963                 mono_raise_exception (mono_get_exception_argument ("assemblyFile", "The file does not contain a manifest"));
3964         }
3965
3966         fill_reflection_assembly_name (mono_domain_get (), aname, &name, filename);
3967
3968         g_free (filename);
3969         mono_image_close (image);
3970 }
3971
3972 static MonoBoolean
3973 ves_icall_System_Reflection_Assembly_LoadPermissions (MonoReflectionAssembly *assembly,
3974         char **minimum, guint32 *minLength, char **optional, guint32 *optLength, char **refused, guint32 *refLength)
3975 {
3976         MonoBoolean result = FALSE;
3977         MonoDeclSecurityEntry entry;
3978
3979         /* SecurityAction.RequestMinimum */
3980         if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQMIN, &entry)) {
3981                 *minimum = entry.blob;
3982                 *minLength = entry.size;
3983                 result = TRUE;
3984         }
3985         /* SecurityAction.RequestOptional */
3986         if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQOPT, &entry)) {
3987                 *optional = entry.blob;
3988                 *optLength = entry.size;
3989                 result = TRUE;
3990         }
3991         /* SecurityAction.RequestRefuse */
3992         if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQREFUSE, &entry)) {
3993                 *refused = entry.blob;
3994                 *refLength = entry.size;
3995                 result = TRUE;
3996         }
3997
3998         return result;  
3999 }
4000
4001 static MonoArray*
4002 mono_module_get_types (MonoDomain *domain, MonoImage *image, 
4003                                            MonoBoolean exportedOnly)
4004 {
4005         MonoArray *res;
4006         MonoClass *klass;
4007         MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
4008         int i, count;
4009         guint32 attrs, visibility;
4010
4011         /* we start the count from 1 because we skip the special type <Module> */
4012         if (exportedOnly) {
4013                 count = 0;
4014                 for (i = 1; i < tdef->rows; ++i) {
4015                         attrs = mono_metadata_decode_row_col (tdef, i, MONO_TYPEDEF_FLAGS);
4016                         visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
4017                         if (visibility == TYPE_ATTRIBUTE_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_PUBLIC)
4018                                 count++;
4019                 }
4020         } else {
4021                 count = tdef->rows - 1;
4022         }
4023         res = mono_array_new (domain, mono_defaults.monotype_class, count);
4024         count = 0;
4025         for (i = 1; i < tdef->rows; ++i) {
4026                 attrs = mono_metadata_decode_row_col (tdef, i, MONO_TYPEDEF_FLAGS);
4027                 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
4028                 if (!exportedOnly || (visibility == TYPE_ATTRIBUTE_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_PUBLIC)) {
4029                         klass = mono_class_get (image, (i + 1) | MONO_TOKEN_TYPE_DEF);
4030                         mono_array_set (res, gpointer, count, mono_type_get_object (domain, &klass->byval_arg));
4031                         count++;
4032                 }
4033         }
4034         
4035         return res;
4036 }
4037
4038 static MonoArray*
4039 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssembly *assembly, MonoBoolean exportedOnly)
4040 {
4041         MonoArray *res = NULL;
4042         MonoImage *image = NULL;
4043         MonoTableInfo *table = NULL;
4044         MonoDomain *domain;
4045         int i;
4046
4047         MONO_ARCH_SAVE_REGS;
4048
4049         domain = mono_object_domain (assembly);
4050
4051         if (assembly->assembly->dynamic) {
4052                 MonoReflectionAssemblyBuilder *abuilder = (MonoReflectionAssemblyBuilder*)assembly;
4053                 if (abuilder->modules) {
4054                         for (i = 0; i < mono_array_length(abuilder->modules); i++) {
4055                                 MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
4056                                 if (res == NULL)
4057                                         res = mb->types;
4058                                 else {
4059                                         MonoArray *append = mb->types;
4060                                         if (mono_array_length (append) > 0) {
4061                                                 guint32 len1, len2;
4062                                                 MonoArray *new;
4063                                                 len1 = mono_array_length (res);
4064                                                 len2 = mono_array_length (append);
4065                                                 new = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
4066                                                 memcpy (mono_array_addr (new, MonoReflectionType*, 0),
4067                                                         mono_array_addr (res, MonoReflectionType*, 0),
4068                                                         len1 * sizeof (MonoReflectionType*));
4069                                                 memcpy (mono_array_addr (new, MonoReflectionType*, len1),
4070                                                         mono_array_addr (append, MonoReflectionType*, 0),
4071                                                         len2 * sizeof (MonoReflectionType*));
4072                                                 res = new;
4073                                         }
4074                                 }
4075                         }
4076
4077                         /* 
4078                          * Replace TypeBuilders with the created types to be compatible
4079                          * with MS.NET.
4080                          */
4081                         if (res) {
4082                                 for (i = 0; i < mono_array_length (res); ++i) {
4083                                         MonoReflectionTypeBuilder *tb = mono_array_get (res, MonoReflectionTypeBuilder*, i);
4084                                         if (tb->created)
4085                                                 mono_array_set (res, MonoReflectionType*, i, tb->created);
4086                                 }
4087                         }
4088                 }
4089
4090                 if (abuilder->loaded_modules)
4091                         for (i = 0; i < mono_array_length(abuilder->loaded_modules); i++) {
4092                                 MonoReflectionModule *rm = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
4093                                 if (res == NULL)
4094                                         res = mono_module_get_types (domain, rm->image, exportedOnly);
4095                                 else {
4096                                         MonoArray *append = mono_module_get_types (domain, rm->image, exportedOnly);
4097                                         if (mono_array_length (append) > 0) {
4098                                                 guint32 len1, len2;
4099                                                 MonoArray *new;
4100                                                 len1 = mono_array_length (res);
4101                                                 len2 = mono_array_length (append);
4102                                                 new = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
4103                                                 memcpy (mono_array_addr (new, MonoReflectionType*, 0),
4104                                                         mono_array_addr (res, MonoReflectionType*, 0),
4105                                                         len1 * sizeof (MonoReflectionType*));
4106                                                 memcpy (mono_array_addr (new, MonoReflectionType*, len1),
4107                                                         mono_array_addr (append, MonoReflectionType*, 0),
4108                                                         len2 * sizeof (MonoReflectionType*));
4109                                                 res = new;
4110                                         }
4111                                 }
4112                         }
4113                 return res;
4114         }
4115         image = assembly->assembly->image;
4116         table = &image->tables [MONO_TABLE_FILE];
4117         res = mono_module_get_types (domain, image, exportedOnly);
4118
4119         /* Append data from all modules in the assembly */
4120         for (i = 0; i < table->rows; ++i) {
4121                 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
4122                         MonoImage *loaded_image = mono_assembly_load_module (image->assembly, i + 1);
4123                         if (loaded_image) {
4124                                 MonoArray *res2 = mono_module_get_types (domain, loaded_image, exportedOnly);
4125                                 /* Append the new types to the end of the array */
4126                                 if (mono_array_length (res2) > 0) {
4127                                         guint32 len1, len2;
4128                                         MonoArray *res3;
4129
4130                                         len1 = mono_array_length (res);
4131                                         len2 = mono_array_length (res2);
4132                                         res3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
4133                                         memcpy (mono_array_addr (res3, MonoReflectionType*, 0),
4134                                                         mono_array_addr (res, MonoReflectionType*, 0),
4135                                                         len1 * sizeof (MonoReflectionType*));
4136                                         memcpy (mono_array_addr (res3, MonoReflectionType*, len1),
4137                                                         mono_array_addr (res2, MonoReflectionType*, 0),
4138                                                         len2 * sizeof (MonoReflectionType*));
4139                                         res = res3;
4140                                 }
4141                         }
4142                 }
4143         }               
4144         return res;
4145 }
4146
4147 static MonoReflectionType*
4148 ves_icall_System_Reflection_Module_GetGlobalType (MonoReflectionModule *module)
4149 {
4150         MonoDomain *domain = mono_object_domain (module); 
4151         MonoClass *klass;
4152
4153         MONO_ARCH_SAVE_REGS;
4154
4155         g_assert (module->image);
4156
4157         if (module->image->dynamic && ((MonoDynamicImage*)(module->image))->initial_image)
4158                 /* These images do not have a global type */
4159                 return NULL;
4160
4161         klass = mono_class_get (module->image, 1 | MONO_TOKEN_TYPE_DEF);
4162         return mono_type_get_object (domain, &klass->byval_arg);
4163 }
4164
4165 static void
4166 ves_icall_System_Reflection_Module_Close (MonoReflectionModule *module)
4167 {
4168         /*if (module->image)
4169                 mono_image_close (module->image);*/
4170 }
4171
4172 static MonoString*
4173 ves_icall_System_Reflection_Module_GetGuidInternal (MonoReflectionModule *module)
4174 {
4175         MonoDomain *domain = mono_object_domain (module); 
4176
4177         MONO_ARCH_SAVE_REGS;
4178
4179         g_assert (module->image);
4180         return mono_string_new (domain, module->image->guid);
4181 }
4182
4183 static void
4184 ves_icall_System_Reflection_Module_GetPEKind (MonoImage *image, gint32 *pe_kind, gint32 *machine)
4185 {
4186         if (image->dynamic) {
4187                 MonoDynamicImage *dyn = (MonoDynamicImage*)image;
4188                 *pe_kind = dyn->pe_kind;
4189                 *machine = dyn->machine;
4190         }
4191         else {
4192                 *pe_kind = ((MonoCLIImageInfo*)(image->image_info))->cli_cli_header.ch_flags & 0x3;
4193                 *machine = ((MonoCLIImageInfo*)(image->image_info))->cli_header.coff.coff_machine;
4194         }
4195 }
4196
4197 static MonoArray*
4198 ves_icall_System_Reflection_Module_InternalGetTypes (MonoReflectionModule *module)
4199 {
4200         MONO_ARCH_SAVE_REGS;
4201
4202         if (!module->image)
4203                 return mono_array_new (mono_object_domain (module), mono_defaults.monotype_class, 0);
4204         else
4205                 return mono_module_get_types (mono_object_domain (module), module->image, FALSE);
4206 }
4207
4208 static gboolean
4209 mono_metadata_memberref_is_method (MonoImage *image, guint32 token)
4210 {
4211         guint32 cols [MONO_MEMBERREF_SIZE];
4212         const char *sig;
4213         mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
4214         sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
4215         mono_metadata_decode_blob_size (sig, &sig);
4216         return (*sig != 0x6);
4217 }
4218
4219 static MonoType*
4220 ves_icall_System_Reflection_Module_ResolveTypeToken (MonoImage *image, guint32 token, MonoResolveTokenError *error)
4221 {
4222         MonoClass *klass;
4223         int table = mono_metadata_token_table (token);
4224         int index = mono_metadata_token_index (token);
4225
4226         *error = ResolveTokenError_Other;
4227
4228         /* Validate token */
4229         if ((table != MONO_TABLE_TYPEDEF) && (table != MONO_TABLE_TYPEREF) && 
4230                 (table != MONO_TABLE_TYPESPEC)) {
4231                 *error = ResolveTokenError_BadTable;
4232                 return NULL;
4233         }
4234
4235         if (image->dynamic)
4236                 return mono_lookup_dynamic_token (image, token);
4237
4238         if ((index <= 0) || (index > image->tables [table].rows)) {
4239                 *error = ResolveTokenError_OutOfRange;
4240                 return NULL;
4241         }
4242
4243         klass = mono_class_get (image, token);
4244         if (klass)
4245                 return &klass->byval_arg;
4246         else
4247                 return NULL;
4248 }
4249
4250 static MonoMethod*
4251 ves_icall_System_Reflection_Module_ResolveMethodToken (MonoImage *image, guint32 token, MonoResolveTokenError *error)
4252 {
4253         int table = mono_metadata_token_table (token);
4254         int index = mono_metadata_token_index (token);
4255
4256         *error = ResolveTokenError_Other;
4257
4258         /* Validate token */
4259         if ((table != MONO_TABLE_METHOD) && (table != MONO_TABLE_METHODSPEC) && 
4260                 (table != MONO_TABLE_MEMBERREF)) {
4261                 *error = ResolveTokenError_BadTable;
4262                 return NULL;
4263         }
4264
4265         if (image->dynamic)
4266                 /* FIXME: validate memberref token type */
4267                 return mono_lookup_dynamic_token (image, token);
4268
4269         if ((index <= 0) || (index > image->tables [table].rows)) {
4270                 *error = ResolveTokenError_OutOfRange;
4271                 return NULL;
4272         }
4273         if ((table == MONO_TABLE_MEMBERREF) && (!mono_metadata_memberref_is_method (image, token))) {
4274                 *error = ResolveTokenError_BadTable;
4275                 return NULL;
4276         }
4277
4278         return mono_get_method (image, token, NULL);
4279 }
4280
4281 static MonoString*
4282 ves_icall_System_Reflection_Module_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *error)
4283 {
4284         int index = mono_metadata_token_index (token);
4285
4286         *error = ResolveTokenError_Other;
4287
4288         /* Validate token */
4289         if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
4290                 *error = ResolveTokenError_BadTable;
4291                 return NULL;
4292         }
4293
4294         if (image->dynamic)
4295                 return mono_lookup_dynamic_token (image, token);
4296
4297         if ((index <= 0) || (index >= image->heap_us.size)) {
4298                 *error = ResolveTokenError_OutOfRange;
4299                 return NULL;
4300         }
4301
4302         /* FIXME: What to do if the index points into the middle of a string ? */
4303
4304         return mono_ldstr (mono_domain_get (), image, index);
4305 }
4306
4307 static MonoClassField*
4308 ves_icall_System_Reflection_Module_ResolveFieldToken (MonoImage *image, guint32 token, MonoResolveTokenError *error)
4309 {
4310         MonoClass *klass;
4311         int table = mono_metadata_token_table (token);
4312         int index = mono_metadata_token_index (token);
4313
4314         *error = ResolveTokenError_Other;
4315
4316         /* Validate token */
4317         if ((table != MONO_TABLE_FIELD) && (table != MONO_TABLE_MEMBERREF)) {
4318                 *error = ResolveTokenError_BadTable;
4319                 return NULL;
4320         }
4321
4322         if (image->dynamic)
4323                 /* FIXME: validate memberref token type */
4324                 return mono_lookup_dynamic_token (image, token);
4325
4326         if ((index <= 0) || (index > image->tables [table].rows)) {
4327                 *error = ResolveTokenError_OutOfRange;
4328                 return NULL;
4329         }
4330         if ((table == MONO_TABLE_MEMBERREF) && (mono_metadata_memberref_is_method (image, token))) {
4331                 *error = ResolveTokenError_BadTable;
4332                 return NULL;
4333         }
4334
4335         return mono_field_from_token (image, token, &klass, NULL);
4336 }
4337
4338
4339 static MonoObject*
4340 ves_icall_System_Reflection_Module_ResolveMemberToken (MonoImage *image, guint32 token, MonoResolveTokenError *error)
4341 {
4342         int table = mono_metadata_token_table (token);
4343
4344         *error = ResolveTokenError_Other;
4345
4346         switch (table) {
4347         case MONO_TABLE_TYPEDEF:
4348         case MONO_TABLE_TYPEREF:
4349         case MONO_TABLE_TYPESPEC: {
4350                 MonoType *t = ves_icall_System_Reflection_Module_ResolveTypeToken (image, token, error);
4351                 if (t)
4352                         return (MonoObject*)mono_type_get_object (mono_domain_get (), t);
4353                 else
4354                         return NULL;
4355         }
4356         case MONO_TABLE_METHOD:
4357         case MONO_TABLE_METHODSPEC: {
4358                 MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, error);
4359                 if (m)
4360                         return (MonoObject*)mono_method_get_object (mono_domain_get (), m, m->klass);
4361                 else
4362                         return NULL;
4363         }               
4364         case MONO_TABLE_FIELD: {
4365                 MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, error);
4366                 if (f)
4367                         return (MonoObject*)mono_field_get_object (mono_domain_get (), f->parent, f);
4368                 else
4369                         return NULL;
4370         }
4371         case MONO_TABLE_MEMBERREF:
4372                 if (mono_metadata_memberref_is_method (image, token)) {
4373                         MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, error);
4374                         if (m)
4375                                 return (MonoObject*)mono_method_get_object (mono_domain_get (), m, m->klass);
4376                         else
4377                                 return NULL;
4378                 }
4379                 else {
4380                         MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, error);
4381                         if (f)
4382                                 return (MonoObject*)mono_field_get_object (mono_domain_get (), f->parent, f);
4383                         else
4384                                 return NULL;
4385                 }
4386                 break;
4387
4388         default:
4389                 *error = ResolveTokenError_BadTable;
4390         }
4391
4392         return NULL;
4393 }
4394
4395 static MonoReflectionType*
4396 ves_icall_ModuleBuilder_create_modified_type (MonoReflectionTypeBuilder *tb, MonoString *smodifiers)
4397 {
4398         MonoClass *klass;
4399         int isbyref = 0, rank;
4400         char *str = mono_string_to_utf8 (smodifiers);
4401         char *p;
4402
4403         MONO_ARCH_SAVE_REGS;
4404
4405         klass = mono_class_from_mono_type (tb->type.type);
4406         p = str;
4407         /* logic taken from mono_reflection_parse_type(): keep in sync */
4408         while (*p) {
4409                 switch (*p) {
4410                 case '&':
4411                         if (isbyref) { /* only one level allowed by the spec */
4412                                 g_free (str);
4413                                 return NULL;
4414                         }
4415                         isbyref = 1;
4416                         p++;
4417                         g_free (str);
4418                         return mono_type_get_object (mono_object_domain (tb), &klass->this_arg);
4419                         break;
4420                 case '*':
4421                         klass = mono_ptr_class_get (&klass->byval_arg);
4422                         mono_class_init (klass);
4423                         p++;
4424                         break;
4425                 case '[':
4426                         rank = 1;
4427                         p++;
4428                         while (*p) {
4429                                 if (*p == ']')
4430                                         break;
4431                                 if (*p == ',')
4432                                         rank++;
4433                                 else if (*p != '*') { /* '*' means unknown lower bound */
4434                                         g_free (str);
4435                                         return NULL;
4436                                 }
4437                                 ++p;
4438                         }
4439                         if (*p != ']') {
4440                                 g_free (str);
4441                                 return NULL;
4442                         }
4443                         p++;
4444                         klass = mono_array_class_get (klass, rank);
4445                         mono_class_init (klass);
4446                         break;
4447                 default:
4448                         break;
4449                 }
4450         }
4451         g_free (str);
4452         return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
4453 }
4454
4455 static MonoBoolean
4456 ves_icall_Type_IsArrayImpl (MonoReflectionType *t)
4457 {
4458         MonoType *type;
4459         MonoBoolean res;
4460
4461         MONO_ARCH_SAVE_REGS;
4462
4463         type = t->type;
4464         res = !type->byref && (type->type == MONO_TYPE_ARRAY || type->type == MONO_TYPE_SZARRAY);
4465
4466         return res;
4467 }
4468
4469 static MonoReflectionType *
4470 ves_icall_Type_make_array_type (MonoReflectionType *type, int rank)
4471 {
4472         MonoClass *klass, *aklass;
4473
4474         MONO_ARCH_SAVE_REGS;
4475
4476         klass = mono_class_from_mono_type (type->type);
4477         aklass = mono_array_class_get (klass, rank);
4478
4479         return mono_type_get_object (mono_object_domain (type), &aklass->byval_arg);
4480 }
4481
4482 static MonoReflectionType *
4483 ves_icall_Type_make_byref_type (MonoReflectionType *type)
4484 {
4485         MonoClass *klass;
4486
4487         MONO_ARCH_SAVE_REGS;
4488
4489         klass = mono_class_from_mono_type (type->type);
4490
4491         return mono_type_get_object (mono_object_domain (type), &klass->this_arg);
4492 }
4493
4494 static MonoReflectionType *
4495 ves_icall_Type_MakePointerType (MonoReflectionType *type)
4496 {
4497         MonoClass *pklass;
4498
4499         MONO_ARCH_SAVE_REGS;
4500
4501         pklass = mono_ptr_class_get (type->type);
4502
4503         return mono_type_get_object (mono_object_domain (type), &pklass->byval_arg);
4504 }
4505
4506 static MonoObject *
4507 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionType *type, MonoObject *target,
4508                                                    MonoReflectionMethod *info)
4509 {
4510         MonoClass *delegate_class = mono_class_from_mono_type (type->type);
4511         MonoObject *delegate;
4512         gpointer func;
4513
4514         MONO_ARCH_SAVE_REGS;
4515
4516         mono_assert (delegate_class->parent == mono_defaults.multicastdelegate_class);
4517
4518         delegate = mono_object_new (mono_object_domain (type), delegate_class);
4519
4520         func = mono_compile_method (info->method);
4521
4522         mono_delegate_ctor (delegate, target, func);
4523
4524         return delegate;
4525 }
4526
4527 static void
4528 ves_icall_System_Delegate_FreeTrampoline (MonoDelegate *this)
4529 {
4530         mono_delegate_free_ftnptr (this);
4531 }
4532
4533 /*
4534  * Magic number to convert a time which is relative to
4535  * Jan 1, 1970 into a value which is relative to Jan 1, 0001.
4536  */
4537 #define EPOCH_ADJUST    ((guint64)62135596800LL)
4538
4539 /*
4540  * Magic number to convert FILETIME base Jan 1, 1601 to DateTime - base Jan, 1, 0001
4541  */
4542 #define FILETIME_ADJUST ((guint64)504911232000000000LL)
4543
4544 /*
4545  * This returns Now in UTC
4546  */
4547 static gint64
4548 ves_icall_System_DateTime_GetNow (void)
4549 {
4550 #ifdef PLATFORM_WIN32
4551         SYSTEMTIME st;
4552         FILETIME ft;
4553         
4554         GetSystemTime (&st);
4555         SystemTimeToFileTime (&st, &ft);
4556         return (gint64) FILETIME_ADJUST + ((((gint64)ft.dwHighDateTime)<<32) | ft.dwLowDateTime);
4557 #else
4558         /* FIXME: put this in io-layer and call it GetLocalTime */
4559         struct timeval tv;
4560         gint64 res;
4561
4562         MONO_ARCH_SAVE_REGS;
4563
4564         if (gettimeofday (&tv, NULL) == 0) {
4565                 res = (((gint64)tv.tv_sec + EPOCH_ADJUST)* 1000000 + tv.tv_usec)*10;
4566                 return res;
4567         }
4568         /* fixme: raise exception */
4569         return 0;
4570 #endif
4571 }
4572
4573 #ifdef PLATFORM_WIN32
4574 /* convert a SYSTEMTIME which is of the form "last thursday in october" to a real date */
4575 static void
4576 convert_to_absolute_date(SYSTEMTIME *date)
4577 {
4578 #define IS_LEAP(y) ((y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0))
4579         static int days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
4580         static int leap_days_in_month[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
4581         /* from the calendar FAQ */
4582         int a = (14 - date->wMonth) / 12;
4583         int y = date->wYear - a;
4584         int m = date->wMonth + 12 * a - 2;
4585         int d = (1 + y + y/4 - y/100 + y/400 + (31*m)/12) % 7;
4586
4587         /* d is now the day of the week for the first of the month (0 == Sunday) */
4588
4589         int day_of_week = date->wDayOfWeek;
4590
4591         /* set day_in_month to the first day in the month which falls on day_of_week */    
4592         int day_in_month = 1 + (day_of_week - d);
4593         if (day_in_month <= 0)
4594                 day_in_month += 7;
4595
4596         /* wDay is 1 for first weekday in month, 2 for 2nd ... 5 means last - so work that out allowing for days in the month */
4597         date->wDay = day_in_month + (date->wDay - 1) * 7;
4598         if (date->wDay > (IS_LEAP(date->wYear) ? leap_days_in_month[date->wMonth - 1] : days_in_month[date->wMonth - 1]))
4599                 date->wDay -= 7;
4600 }
4601 #endif
4602
4603 #ifndef PLATFORM_WIN32
4604 /*
4605  * Return's the offset from GMT of a local time.
4606  * 
4607  *  tm is a local time
4608  *  t  is the same local time as seconds.
4609  */
4610 static int 
4611 gmt_offset(struct tm *tm, time_t t)
4612 {
4613 #if defined (HAVE_TM_GMTOFF)
4614         return tm->tm_gmtoff;
4615 #else
4616         struct tm g;
4617         time_t t2;
4618         g = *gmtime(&t);
4619         g.tm_isdst = tm->tm_isdst;
4620         t2 = mktime(&g);
4621         return (int)difftime(t, t2);
4622 #endif
4623 }
4624 #endif
4625 /*
4626  * This is heavily based on zdump.c from glibc 2.2.
4627  *
4628  *  * data[0]:  start of daylight saving time (in DateTime ticks).
4629  *  * data[1]:  end of daylight saving time (in DateTime ticks).
4630  *  * data[2]:  utcoffset (in TimeSpan ticks).
4631  *  * data[3]:  additional offset when daylight saving (in TimeSpan ticks).
4632  *  * name[0]:  name of this timezone when not daylight saving.
4633  *  * name[1]:  name of this timezone when daylight saving.
4634  *
4635  *  FIXME: This only works with "standard" Unix dates (years between 1900 and 2100) while
4636  *         the class library allows years between 1 and 9999.
4637  *
4638  *  Returns true on success and zero on failure.
4639  */
4640 static guint32
4641 ves_icall_System_CurrentTimeZone_GetTimeZoneData (guint32 year, MonoArray **data, MonoArray **names)
4642 {
4643 #ifndef PLATFORM_WIN32
4644         MonoDomain *domain = mono_domain_get ();
4645         struct tm start, tt;
4646         time_t t;
4647
4648         long int gmtoff;
4649         int is_daylight = 0, day;
4650         char tzone [64];
4651
4652         MONO_ARCH_SAVE_REGS;
4653
4654         MONO_CHECK_ARG_NULL (data);
4655         MONO_CHECK_ARG_NULL (names);
4656
4657         (*data) = mono_array_new (domain, mono_defaults.int64_class, 4);
4658         (*names) = mono_array_new (domain, mono_defaults.string_class, 2);
4659
4660         /* 
4661          * no info is better than crashing: we'll need our own tz data
4662          * to make this work properly, anyway. The range is probably
4663          * reduced to 1970 .. 2037 because that is what mktime is
4664          * guaranteed to support (we get into an infinite loop
4665          * otherwise).
4666          */
4667
4668         memset (&start, 0, sizeof (start));
4669
4670         start.tm_mday = 1;
4671         start.tm_year = year-1900;
4672
4673         t = mktime (&start);
4674
4675         if ((year < 1970) || (year > 2037) || (t == -1)) {
4676                 t = time (NULL);
4677                 tt = *localtime (&t);
4678                 strftime (tzone, sizeof (tzone), "%Z", &tt);
4679                 mono_array_set ((*names), gpointer, 0, mono_string_new (domain, tzone));
4680                 mono_array_set ((*names), gpointer, 1, mono_string_new (domain, tzone));
4681                 return 1;
4682         }
4683
4684         gmtoff = gmt_offset (&start, t);
4685
4686         /* For each day of the year, calculate the tm_gmtoff. */
4687         for (day = 0; day < 365; day++) {
4688
4689                 t += 3600*24;
4690                 tt = *localtime (&t);
4691
4692                 /* Daylight saving starts or ends here. */
4693                 if (gmt_offset (&tt, t) != gmtoff) {
4694                         struct tm tt1;
4695                         time_t t1;
4696
4697                         /* Try to find the exact hour when daylight saving starts/ends. */
4698                         t1 = t;
4699                         do {
4700                                 t1 -= 3600;
4701                                 tt1 = *localtime (&t1);
4702                         } while (gmt_offset (&tt1, t1) != gmtoff);
4703
4704                         /* Try to find the exact minute when daylight saving starts/ends. */
4705                         do {
4706                                 t1 += 60;
4707                                 tt1 = *localtime (&t1);
4708                         } while (gmt_offset (&tt1, t1) == gmtoff);
4709                         t1+=gmtoff;
4710                         strftime (tzone, sizeof (tzone), "%Z", &tt);
4711                         
4712                         /* Write data, if we're already in daylight saving, we're done. */
4713                         if (is_daylight) {
4714                                 mono_array_set ((*names), gpointer, 0, mono_string_new (domain, tzone));
4715                                 mono_array_set ((*data), gint64, 1, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
4716                                 return 1;
4717                         } else {
4718                                 mono_array_set ((*names), gpointer, 1, mono_string_new (domain, tzone));
4719                                 mono_array_set ((*data), gint64, 0, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
4720                                 is_daylight = 1;
4721                         }
4722
4723                         /* This is only set once when we enter daylight saving. */
4724                         mono_array_set ((*data), gint64, 2, (gint64)gmtoff * 10000000L);
4725                         mono_array_set ((*data), gint64, 3, (gint64)(gmt_offset (&tt, t) - gmtoff) * 10000000L);
4726
4727                         gmtoff = gmt_offset (&tt, t);
4728                 }
4729         }
4730
4731         if (!is_daylight) {
4732                 strftime (tzone, sizeof (tzone), "%Z", &tt);
4733                 mono_array_set ((*names), gpointer, 0, mono_string_new (domain, tzone));
4734                 mono_array_set ((*names), gpointer, 1, mono_string_new (domain, tzone));
4735                 mono_array_set ((*data), gint64, 0, 0);
4736                 mono_array_set ((*data), gint64, 1, 0);
4737                 mono_array_set ((*data), gint64, 2, (gint64) gmtoff * 10000000L);
4738                 mono_array_set ((*data), gint64, 3, 0);
4739         }
4740
4741         return 1;
4742 #else
4743         MonoDomain *domain = mono_domain_get ();
4744         TIME_ZONE_INFORMATION tz_info;
4745         FILETIME ft;
4746         int i;
4747         int err, tz_id;
4748
4749         tz_id = GetTimeZoneInformation (&tz_info);
4750         if (tz_id == TIME_ZONE_ID_INVALID)
4751                 return 0;
4752
4753         MONO_CHECK_ARG_NULL (data);
4754         MONO_CHECK_ARG_NULL (names);
4755
4756         (*data) = mono_array_new (domain, mono_defaults.int64_class, 4);
4757         (*names) = mono_array_new (domain, mono_defaults.string_class, 2);
4758
4759         for (i = 0; i < 32; ++i)
4760                 if (!tz_info.DaylightName [i])
4761                         break;
4762         mono_array_set ((*names), gpointer, 1, mono_string_new_utf16 (domain, tz_info.DaylightName, i));
4763         for (i = 0; i < 32; ++i)
4764                 if (!tz_info.StandardName [i])
4765                         break;
4766         mono_array_set ((*names), gpointer, 0, mono_string_new_utf16 (domain, tz_info.StandardName, i));
4767
4768         if ((year <= 1601) || (year > 30827)) {
4769                 /*
4770                  * According to MSDN, the MS time functions can't handle dates outside
4771                  * this interval.
4772                  */
4773                 return 1;
4774         }
4775
4776         /* even if the timezone has no daylight savings it may have Bias (e.g. GMT+13 it seems) */
4777         if (tz_id != TIME_ZONE_ID_UNKNOWN) {
4778                 tz_info.StandardDate.wYear = year;
4779                 convert_to_absolute_date(&tz_info.StandardDate);
4780                 err = SystemTimeToFileTime (&tz_info.StandardDate, &ft);
4781                 g_assert(err);
4782                 mono_array_set ((*data), gint64, 1, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
4783                 tz_info.DaylightDate.wYear = year;
4784                 convert_to_absolute_date(&tz_info.DaylightDate);
4785                 err = SystemTimeToFileTime (&tz_info.DaylightDate, &ft);
4786                 g_assert(err);
4787                 mono_array_set ((*data), gint64, 0, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
4788         }
4789         mono_array_set ((*data), gint64, 2, (tz_info.Bias + tz_info.StandardBias) * -600000000LL);
4790         mono_array_set ((*data), gint64, 3, (tz_info.DaylightBias - tz_info.StandardBias) * -600000000LL);
4791
4792         return 1;
4793 #endif
4794 }
4795
4796 static gpointer
4797 ves_icall_System_Object_obj_address (MonoObject *this) 
4798 {
4799         MONO_ARCH_SAVE_REGS;
4800
4801         return this;
4802 }
4803
4804 /* System.Buffer */
4805
4806 static inline gint32 
4807 mono_array_get_byte_length (MonoArray *array)
4808 {
4809         MonoClass *klass;
4810         int length;
4811         int i;
4812
4813         klass = array->obj.vtable->klass;
4814
4815         if (array->bounds == NULL)
4816                 length = array->max_length;
4817         else {
4818                 length = 1;
4819                 for (i = 0; i < klass->rank; ++ i)
4820                         length *= array->bounds [i].length;
4821         }
4822
4823         switch (klass->element_class->byval_arg.type) {
4824         case MONO_TYPE_I1:
4825         case MONO_TYPE_U1:
4826         case MONO_TYPE_BOOLEAN:
4827                 return length;
4828         case MONO_TYPE_I2:
4829         case MONO_TYPE_U2:
4830         case MONO_TYPE_CHAR:
4831                 return length << 1;
4832         case MONO_TYPE_I4:
4833         case MONO_TYPE_U4:
4834         case MONO_TYPE_R4:
4835                 return length << 2;
4836         case MONO_TYPE_I:
4837         case MONO_TYPE_U:
4838                 return length * sizeof (gpointer);
4839         case MONO_TYPE_I8:
4840         case MONO_TYPE_U8:
4841         case MONO_TYPE_R8:
4842                 return length << 3;
4843         default:
4844                 return -1;
4845         }
4846 }
4847
4848 static gint32 
4849 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array) 
4850 {
4851         MONO_ARCH_SAVE_REGS;
4852
4853         return mono_array_get_byte_length (array);
4854 }
4855
4856 static gint8 
4857 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx) 
4858 {
4859         MONO_ARCH_SAVE_REGS;
4860
4861         return mono_array_get (array, gint8, idx);
4862 }
4863
4864 static void 
4865 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value) 
4866 {
4867         MONO_ARCH_SAVE_REGS;
4868
4869         mono_array_set (array, gint8, idx, value);
4870 }
4871
4872 static MonoBoolean
4873 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count) 
4874 {
4875         char *src_buf, *dest_buf;
4876
4877         MONO_ARCH_SAVE_REGS;
4878
4879         /* watch out for integer overflow */
4880         if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
4881                 return FALSE;
4882
4883         src_buf = (gint8 *)src->vector + src_offset;
4884         dest_buf = (gint8 *)dest->vector + dest_offset;
4885
4886         if (src != dest)
4887                 memcpy (dest_buf, src_buf, count);
4888         else
4889                 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
4890
4891         return TRUE;
4892 }
4893
4894 static MonoObject *
4895 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObject *this, MonoString *class_name)
4896 {
4897         MonoDomain *domain = mono_object_domain (this); 
4898         MonoObject *res;
4899         MonoRealProxy *rp = ((MonoRealProxy *)this);
4900         MonoTransparentProxy *tp;
4901         MonoType *type;
4902         MonoClass *klass;
4903
4904         MONO_ARCH_SAVE_REGS;
4905
4906         res = mono_object_new (domain, mono_defaults.transparent_proxy_class);
4907         tp = (MonoTransparentProxy*) res;
4908         
4909         tp->rp = rp;
4910         type = ((MonoReflectionType *)rp->class_to_proxy)->type;
4911         klass = mono_class_from_mono_type (type);
4912
4913         tp->custom_type_info = (mono_object_isinst (this, mono_defaults.iremotingtypeinfo_class) != NULL);
4914         tp->remote_class = mono_remote_class (domain, class_name, klass);
4915
4916         res->vtable = mono_remote_class_vtable (domain, tp->remote_class, rp);
4917         return res;
4918 }
4919
4920 static MonoReflectionType *
4921 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
4922 {
4923         return mono_type_get_object (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg);
4924 }
4925
4926 /* System.Environment */
4927
4928 static MonoString *
4929 ves_icall_System_Environment_get_MachineName (void)
4930 {
4931 #if defined (PLATFORM_WIN32)
4932         gunichar2 *buf;
4933         guint32 len;
4934         MonoString *result;
4935
4936         len = MAX_COMPUTERNAME_LENGTH + 1;
4937         buf = g_new (gunichar2, len);
4938
4939         result = NULL;
4940         if (GetComputerName (buf, (PDWORD) &len))
4941                 result = mono_string_new_utf16 (mono_domain_get (), buf, len);
4942
4943         g_free (buf);
4944         return result;
4945 #else
4946         gchar *buf;
4947         int len;
4948         MonoString *result;
4949
4950         MONO_ARCH_SAVE_REGS;
4951
4952         len = 256;
4953         buf = g_new (gchar, len);
4954
4955         result = NULL;
4956         if (gethostname (buf, len) == 0)
4957                 result = mono_string_new (mono_domain_get (), buf);
4958         
4959         g_free (buf);
4960         return result;
4961 #endif
4962 }
4963
4964 static int
4965 ves_icall_System_Environment_get_Platform (void)
4966 {
4967         MONO_ARCH_SAVE_REGS;
4968
4969 #if defined (PLATFORM_WIN32)
4970         /* Win32NT */
4971         return 2;
4972 #else
4973         /* Unix */
4974         return 128;
4975 #endif
4976 }
4977
4978 static MonoString *
4979 ves_icall_System_Environment_get_NewLine (void)
4980 {
4981         MONO_ARCH_SAVE_REGS;
4982
4983 #if defined (PLATFORM_WIN32)
4984         return mono_string_new (mono_domain_get (), "\r\n");
4985 #else
4986         return mono_string_new (mono_domain_get (), "\n");
4987 #endif
4988 }
4989
4990 static MonoString *
4991 ves_icall_System_Environment_GetEnvironmentVariable (MonoString *name)
4992 {
4993         const gchar *value;
4994         gchar *utf8_name;
4995
4996         MONO_ARCH_SAVE_REGS;
4997
4998         if (name == NULL)
4999                 return NULL;
5000
5001         utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
5002         value = g_getenv (utf8_name);
5003         g_free (utf8_name);
5004
5005         if (value == 0)
5006                 return NULL;
5007         
5008         return mono_string_new (mono_domain_get (), value);
5009 }
5010
5011 /*
5012  * There is no standard way to get at environ.
5013  */
5014 #ifndef _MSC_VER
5015 extern
5016 #endif
5017 char **environ;
5018
5019 static MonoArray *
5020 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
5021 {
5022         MonoArray *names;
5023         MonoDomain *domain;
5024         MonoString *str;
5025         gchar **e, **parts;
5026         int n;
5027
5028         MONO_ARCH_SAVE_REGS;
5029
5030         n = 0;
5031         for (e = environ; *e != 0; ++ e)
5032                 ++ n;
5033
5034         domain = mono_domain_get ();
5035         names = mono_array_new (domain, mono_defaults.string_class, n);
5036
5037         n = 0;
5038         for (e = environ; *e != 0; ++ e) {
5039                 parts = g_strsplit (*e, "=", 2);
5040                 if (*parts != 0) {
5041                         str = mono_string_new (domain, *parts);
5042                         mono_array_set (names, MonoString *, n, str);
5043                 }
5044
5045                 g_strfreev (parts);
5046
5047                 ++ n;
5048         }
5049
5050         return names;
5051 }
5052
5053 /*
5054  * Returns: the number of milliseconds elapsed since the system started.
5055  */
5056 static gint32
5057 ves_icall_System_Environment_get_TickCount (void)
5058 {
5059         return GetTickCount ();
5060 }
5061
5062
5063 static void
5064 ves_icall_System_Environment_Exit (int result)
5065 {
5066         MONO_ARCH_SAVE_REGS;
5067
5068         /* Suspend all managed threads since the runtime is going away */
5069         mono_thread_suspend_all_other_threads ();
5070
5071         mono_runtime_quit ();
5072
5073         /* we may need to do some cleanup here... */
5074         exit (result);
5075 }
5076
5077 static MonoString*
5078 ves_icall_System_Environment_GetGacPath (void)
5079 {
5080         return mono_string_new (mono_domain_get (), mono_assembly_getrootdir ());
5081 }
5082
5083 static MonoString*
5084 ves_icall_System_Environment_GetWindowsFolderPath (int folder)
5085 {
5086 #if defined (PLATFORM_WIN32)
5087         #ifndef CSIDL_FLAG_CREATE
5088                 #define CSIDL_FLAG_CREATE       0x8000
5089         #endif
5090
5091         WCHAR path [MAX_PATH];
5092         /* Create directory if no existing */
5093         if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
5094                 int len = 0;
5095                 while (path [len])
5096                         ++ len;
5097                 return mono_string_new_utf16 (mono_domain_get (), path, len);
5098         }
5099 #else
5100         g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
5101 #endif
5102         return mono_string_new (mono_domain_get (), "");
5103 }
5104
5105 static MonoArray *
5106 ves_icall_System_Environment_GetLogicalDrives (void)
5107 {
5108         gunichar2 buf [128], *ptr, *dname;
5109         gchar *u8;
5110         gint initial_size = 127, size = 128;
5111         gint ndrives;
5112         MonoArray *result;
5113         MonoString *drivestr;
5114         MonoDomain *domain = mono_domain_get ();
5115
5116         MONO_ARCH_SAVE_REGS;
5117
5118         buf [0] = '\0';
5119         ptr = buf;
5120
5121         while (size > initial_size) {
5122                 size = GetLogicalDriveStrings (initial_size, ptr);
5123                 if (size > initial_size) {
5124                         if (ptr != buf)
5125                                 g_free (ptr);
5126                         ptr = g_malloc0 ((size + 1) * sizeof (gunichar2));
5127                         initial_size = size;
5128                         size++;
5129                 }
5130         }
5131
5132         /* Count strings */
5133         dname = ptr;
5134         ndrives = 0;
5135         do {
5136                 while (*dname++);
5137                 ndrives++;
5138         } while (*dname);
5139
5140         dname = ptr;
5141         result = mono_array_new (domain, mono_defaults.string_class, ndrives);
5142         ndrives = 0;
5143         do {
5144                 u8 = g_utf16_to_utf8 (dname, -1, NULL, NULL, NULL);
5145                 drivestr = mono_string_new (domain, u8);
5146                 g_free (u8);
5147                 mono_array_set (result, gpointer, ndrives++, drivestr);
5148                 while (*dname++);
5149         } while (*dname);
5150
5151         if (ptr != buf)
5152                 g_free (ptr);
5153
5154         return result;
5155 }
5156
5157 static MonoString *
5158 ves_icall_System_Environment_InternalGetHome (void)
5159 {
5160         MONO_ARCH_SAVE_REGS;
5161
5162         return mono_string_new (mono_domain_get (), g_get_home_dir ());
5163 }
5164
5165 static const char *encodings [] = {
5166         (char *) 1,
5167                 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
5168                 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
5169                 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
5170         (char *) 2,
5171                 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
5172                 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
5173                 "x_unicode_2_0_utf_7",
5174         (char *) 3,
5175                 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
5176                 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
5177         (char *) 4,
5178                 "utf_16", "UTF_16LE", "ucs_2", "unicode",
5179                 "iso_10646_ucs2",
5180         (char *) 5,
5181                 "unicodefffe", "utf_16be",
5182         (char *) 6,
5183                 "iso_8859_1",
5184         (char *) 0
5185 };
5186
5187 /*
5188  * Returns the internal codepage, if the value of "int_code_page" is
5189  * 1 at entry, and we can not compute a suitable code page number,
5190  * returns the code page as a string
5191  */
5192 static MonoString*
5193 ves_icall_System_Text_Encoding_InternalCodePage (gint32 *int_code_page) 
5194 {
5195         const char *cset;
5196         const char *p;
5197         char *c;
5198         char *codepage = NULL;
5199         int code;
5200         int want_name = *int_code_page;
5201         int i;
5202         
5203         *int_code_page = -1;
5204         MONO_ARCH_SAVE_REGS;
5205
5206         g_get_charset (&cset);
5207         c = codepage = strdup (cset);
5208         for (c = codepage; *c; c++){
5209                 if (isascii (*c) && isalpha (*c))
5210                         *c = tolower (*c);
5211                 if (*c == '-')
5212                         *c = '_';
5213         }
5214         /* g_print ("charset: %s\n", cset); */
5215         
5216         /* handle some common aliases */
5217         p = encodings [0];
5218         code = 0;
5219         for (i = 0; p != 0; ){
5220                 if ((gssize) p < 7){
5221                         code = (gssize) p;
5222                         p = encodings [++i];
5223                         continue;
5224                 }
5225                 if (strcmp (p, codepage) == 0){
5226                         *int_code_page = code;
5227                         break;
5228                 }
5229                 p = encodings [++i];
5230         }
5231         
5232         if (strstr (codepage, "utf_8") != NULL)
5233                 *int_code_page |= 0x10000000;
5234         free (codepage);
5235         
5236         if (want_name && *int_code_page == -1)
5237                 return mono_string_new (mono_domain_get (), cset);
5238         else
5239                 return NULL;
5240 }
5241
5242 static MonoBoolean
5243 ves_icall_System_Environment_get_HasShutdownStarted (void)
5244 {
5245         if (mono_runtime_is_shutting_down ())
5246                 return TRUE;
5247
5248         if (mono_domain_is_unloading (mono_domain_get ()))
5249                 return TRUE;
5250
5251         return FALSE;
5252 }
5253
5254 static void
5255 ves_icall_MonoMethodMessage_InitMessage (MonoMethodMessage *this, 
5256                                          MonoReflectionMethod *method,
5257                                          MonoArray *out_args)
5258 {
5259         MONO_ARCH_SAVE_REGS;
5260
5261         mono_message_init (mono_object_domain (this), this, method, out_args);
5262 }
5263
5264 static MonoBoolean
5265 ves_icall_IsTransparentProxy (MonoObject *proxy)
5266 {
5267         MONO_ARCH_SAVE_REGS;
5268
5269         if (!proxy)
5270                 return 0;
5271
5272         if (proxy->vtable->klass == mono_defaults.transparent_proxy_class)
5273                 return 1;
5274
5275         return 0;
5276 }
5277
5278 static void
5279 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
5280 {
5281         MonoClass *klass;
5282         MonoVTable* vtable;
5283
5284         MONO_ARCH_SAVE_REGS;
5285
5286         klass = mono_class_from_mono_type (type->type);
5287         vtable = mono_class_vtable (mono_domain_get (), klass);
5288
5289         if (enable) vtable->remote = 1;
5290         else vtable->remote = 0;
5291 }
5292
5293 static MonoObject *
5294 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionType *type)
5295 {
5296         MonoClass *klass;
5297         MonoDomain *domain;
5298         
5299         MONO_ARCH_SAVE_REGS;
5300
5301         domain = mono_object_domain (type);
5302         klass = mono_class_from_mono_type (type->type);
5303
5304         if (klass->rank >= 1) {
5305                 g_assert (klass->rank == 1);
5306                 return (MonoObject *) mono_array_new (domain, klass->element_class, 0);
5307         } else {
5308                 /* Bypass remoting object creation check */
5309                 return mono_object_new_alloc_specific (mono_class_vtable (domain, klass));
5310         }
5311 }
5312
5313 static MonoString *
5314 ves_icall_System_IO_get_temp_path (void)
5315 {
5316         MONO_ARCH_SAVE_REGS;
5317
5318         return mono_string_new (mono_domain_get (), g_get_tmp_dir ());
5319 }
5320
5321 static gpointer
5322 ves_icall_RuntimeMethod_GetFunctionPointer (MonoMethod *method)
5323 {
5324         MONO_ARCH_SAVE_REGS;
5325
5326         return mono_compile_method (method);
5327 }
5328
5329 static MonoString *
5330 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
5331 {
5332         MonoString *mcpath;
5333         gchar *path;
5334
5335         MONO_ARCH_SAVE_REGS;
5336
5337         path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_framework_version (), "machine.config", NULL);
5338
5339 #if defined (PLATFORM_WIN32)
5340         /* Avoid mixing '/' and '\\' */
5341         {
5342                 gint i;
5343                 for (i = strlen (path) - 1; i >= 0; i--)
5344                         if (path [i] == '/')
5345                                 path [i] = '\\';
5346         }
5347 #endif
5348         mcpath = mono_string_new (mono_domain_get (), path);
5349         g_free (path);
5350
5351         return mcpath;
5352 }
5353
5354 static MonoString *
5355 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
5356 {
5357         MonoString *ipath;
5358         gchar *path;
5359
5360         MONO_ARCH_SAVE_REGS;
5361
5362         path = g_path_get_dirname (mono_get_config_dir ());
5363
5364 #if defined (PLATFORM_WIN32)
5365         /* Avoid mixing '/' and '\\' */
5366         {
5367                 gint i;
5368                 for (i = strlen (path) - 1; i >= 0; i--)
5369                         if (path [i] == '/')
5370                                 path [i] = '\\';
5371         }
5372 #endif
5373         ipath = mono_string_new (mono_domain_get (), path);
5374         g_free (path);
5375
5376         return ipath;
5377 }
5378
5379 static void
5380 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
5381 {
5382 #if defined (PLATFORM_WIN32)
5383         static void (*output_debug) (gchar *);
5384         static gboolean tried_loading = FALSE;
5385
5386         MONO_ARCH_SAVE_REGS;
5387
5388         if (!tried_loading && output_debug == NULL) {
5389                 GModule *k32;
5390
5391                 tried_loading = TRUE;
5392                 k32 = g_module_open ("kernel32", G_MODULE_BIND_LAZY);
5393                 if (!k32) {
5394                         gchar *error = g_strdup (g_module_error ());
5395                         g_warning ("Failed to load kernel32.dll: %s\n", error);
5396                         g_free (error);
5397                         return;
5398                 }
5399
5400                 g_module_symbol (k32, "OutputDebugStringW", (gpointer *) &output_debug);
5401                 if (!output_debug) {
5402                         gchar *error = g_strdup (g_module_error ());
5403                         g_warning ("Failed to load OutputDebugStringW: %s\n", error);
5404                         g_free (error);
5405                         return;
5406                 }
5407         }
5408
5409         if (output_debug == NULL)
5410                 return;
5411         
5412         output_debug (mono_string_chars (message));
5413 #else
5414         g_warning ("WriteWindowsDebugString called and PLATFORM_WIN32 not defined!\n");
5415 #endif
5416 }
5417
5418 /* Only used for value types */
5419 static MonoObject *
5420 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionType *type)
5421 {
5422         MonoClass *klass;
5423         MonoDomain *domain;
5424         
5425         MONO_ARCH_SAVE_REGS;
5426
5427         domain = mono_object_domain (type);
5428         klass = mono_class_from_mono_type (type->type);
5429
5430         return mono_object_new (domain, klass);
5431 }
5432
5433 static MonoReflectionMethod *
5434 ves_icall_MonoMethod_get_base_definition (MonoReflectionMethod *m)
5435 {
5436         MonoClass *klass;
5437         MonoMethod *method = m->method;
5438         MonoMethod *result = NULL;
5439
5440         MONO_ARCH_SAVE_REGS;
5441
5442         if (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
5443             MONO_CLASS_IS_INTERFACE (method->klass) ||
5444             method->flags & METHOD_ATTRIBUTE_NEW_SLOT)
5445                 return m;
5446
5447         if (method->klass == NULL || (klass = method->klass->parent) == NULL)
5448                 return m;
5449
5450         if (klass->generic_class)
5451                 klass = klass->generic_class->container_class;
5452
5453         mono_class_setup_vtable (klass);
5454         mono_class_setup_vtable (method->klass);
5455         while (result == NULL && klass != NULL && (klass->vtable_size > method->slot))
5456         {
5457                 mono_class_setup_vtable (klass);
5458
5459                 result = klass->vtable [method->slot];
5460                 if (result == NULL) {
5461                         MonoMethod* m;
5462                         gpointer iter = NULL;
5463                         /* It is an abstract method */
5464                         while ((m = mono_class_get_methods (klass, &iter))) {
5465                                 if (m->slot == method->slot) {
5466                                         result = m;
5467                                         break;
5468                                 }
5469                         }
5470                 }
5471                 klass = klass->parent;
5472         }
5473
5474         if (result == NULL)
5475                 return m;
5476
5477         return mono_method_get_object (mono_domain_get (), result, NULL);
5478 }
5479
5480 static void
5481 mono_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
5482 {
5483         MONO_ARCH_SAVE_REGS;
5484
5485         iter->sig = *(MonoMethodSignature**)argsp;
5486         
5487         g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
5488         g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
5489
5490         iter->next_arg = 0;
5491         /* FIXME: it's not documented what start is exactly... */
5492         if (start) {
5493                 iter->args = start;
5494         } else {
5495                 int i, align, arg_size;
5496                 iter->args = argsp + sizeof (gpointer);
5497 #ifndef MONO_ARCH_REGPARMS
5498                 for (i = 0; i < iter->sig->sentinelpos; ++i) {
5499                         arg_size = mono_type_stack_size (iter->sig->params [i], &align);
5500                         iter->args = (char*)iter->args + arg_size;
5501                 }
5502 #endif
5503         }
5504         iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
5505
5506         /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
5507 }
5508
5509 static MonoTypedRef
5510 mono_ArgIterator_IntGetNextArg (MonoArgIterator *iter)
5511 {
5512         gint i, align, arg_size;
5513         MonoTypedRef res;
5514         MONO_ARCH_SAVE_REGS;
5515
5516         i = iter->sig->sentinelpos + iter->next_arg;
5517
5518         g_assert (i < iter->sig->param_count);
5519
5520         res.type = iter->sig->params [i];
5521         res.klass = mono_class_from_mono_type (res.type);
5522         /* FIXME: endianess issue... */
5523         res.value = iter->args;
5524         arg_size = mono_type_stack_size (res.type, &align);
5525         iter->args = (char*)iter->args + arg_size;
5526         iter->next_arg++;
5527
5528         /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
5529
5530         return res;
5531 }
5532
5533 static MonoTypedRef
5534 mono_ArgIterator_IntGetNextArgT (MonoArgIterator *iter, MonoType *type)
5535 {
5536         gint i, align, arg_size;
5537         MonoTypedRef res;
5538         MONO_ARCH_SAVE_REGS;
5539
5540         i = iter->sig->sentinelpos + iter->next_arg;
5541
5542         g_assert (i < iter->sig->param_count);
5543
5544         while (i < iter->sig->param_count) {
5545                 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
5546                         continue;
5547                 res.type = iter->sig->params [i];
5548                 res.klass = mono_class_from_mono_type (res.type);
5549                 /* FIXME: endianess issue... */
5550                 res.value = iter->args;
5551                 arg_size = mono_type_stack_size (res.type, &align);
5552                 iter->args = (char*)iter->args + arg_size;
5553                 iter->next_arg++;
5554                 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
5555                 return res;
5556         }
5557         /* g_print ("arg type 0x%02x not found\n", res.type->type); */
5558
5559         res.type = NULL;
5560         res.value = NULL;
5561         res.klass = NULL;
5562         return res;
5563 }
5564
5565 static MonoType*
5566 mono_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
5567 {
5568         gint i;
5569         MONO_ARCH_SAVE_REGS;
5570         
5571         i = iter->sig->sentinelpos + iter->next_arg;
5572
5573         g_assert (i < iter->sig->param_count);
5574
5575         return iter->sig->params [i];
5576 }
5577
5578 static MonoObject*
5579 mono_TypedReference_ToObject (MonoTypedRef tref)
5580 {
5581         MONO_ARCH_SAVE_REGS;
5582
5583         if (MONO_TYPE_IS_REFERENCE (tref.type)) {
5584                 MonoObject** objp = tref.value;
5585                 return *objp;
5586         }
5587
5588         return mono_value_box (mono_domain_get (), tref.klass, tref.value);
5589 }
5590
5591 static MonoObject*
5592 mono_TypedReference_ToObjectInternal (MonoType *type, gpointer value, MonoClass *klass)
5593 {
5594         MONO_ARCH_SAVE_REGS;
5595
5596         if (MONO_TYPE_IS_REFERENCE (type)) {
5597                 MonoObject** objp = value;
5598                 return *objp;
5599         }
5600
5601         return mono_value_box (mono_domain_get (), klass, value);
5602 }
5603
5604 static void
5605 prelink_method (MonoMethod *method)
5606 {
5607         const char *exc_class, *exc_arg;
5608         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5609                 return;
5610         mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
5611         if (exc_class) {
5612                 mono_raise_exception( 
5613                         mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg ) );
5614         }
5615         /* create the wrapper, too? */
5616 }
5617
5618 static void
5619 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethod *method)
5620 {
5621         MONO_ARCH_SAVE_REGS;
5622         prelink_method (method->method);
5623 }
5624
5625 static void
5626 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionType *type)
5627 {
5628         MonoClass *klass = mono_class_from_mono_type (type->type);
5629         MonoMethod* m;
5630         gpointer iter = NULL;
5631         MONO_ARCH_SAVE_REGS;
5632
5633         while ((m = mono_class_get_methods (klass, &iter)))
5634                 prelink_method (m);
5635 }
5636
5637 /* These parameters are "readonly" in corlib/System/Char.cs */
5638 static void
5639 ves_icall_System_Char_GetDataTablePointers (guint8 const **category_data,
5640                                             guint8 const **numeric_data,
5641                                             gdouble const **numeric_data_values,
5642                                             guint16 const **to_lower_data_low,
5643                                             guint16 const **to_lower_data_high,
5644                                             guint16 const **to_upper_data_low,
5645                                             guint16 const **to_upper_data_high)
5646 {
5647         *category_data = CategoryData;
5648         *numeric_data = NumericData;
5649         *numeric_data_values = NumericDataValues;
5650         *to_lower_data_low = ToLowerDataLow;
5651         *to_lower_data_high = ToLowerDataHigh;
5652         *to_upper_data_low = ToUpperDataLow;
5653         *to_upper_data_high = ToUpperDataHigh;
5654 }
5655
5656 static MonoString *
5657 ves_icall_MonoDebugger_check_runtime_version (MonoString *fname)
5658 {
5659         gchar *filename, *error = NULL;
5660
5661         MONO_ARCH_SAVE_REGS;
5662
5663         filename = mono_string_to_utf8 (fname);
5664         error = mono_debugger_check_runtime_version (filename);
5665         g_free (filename);
5666
5667         if (error)
5668                 return mono_string_new (mono_domain_get (), error);
5669         else
5670                 return NULL;
5671 }
5672
5673 static MonoBoolean
5674 custom_attrs_defined_internal (MonoObject *obj, MonoReflectionType *attr_type)
5675 {
5676         MonoCustomAttrInfo *cinfo;
5677         gboolean found;
5678
5679         cinfo = mono_reflection_get_custom_attrs_info (obj);
5680         if (!cinfo)
5681                 return FALSE;
5682         found = mono_custom_attrs_has_attr (cinfo, mono_class_from_mono_type (attr_type->type));
5683         if (!cinfo->cached)
5684                 mono_custom_attrs_free (cinfo);
5685         return found;
5686 }
5687
5688 /* icall map */
5689 typedef struct {
5690         const char *method;
5691         gconstpointer func;
5692 } IcallEntry;
5693
5694 typedef struct {
5695         const char *klass;
5696         const IcallEntry *icalls;
5697         const int size;
5698 } IcallMap;
5699
5700 static const IcallEntry activator_icalls [] = {
5701         {"CreateInstanceInternal", ves_icall_System_Activator_CreateInstanceInternal}
5702 };
5703 static const IcallEntry appdomain_icalls [] = {
5704         {"ExecuteAssembly", ves_icall_System_AppDomain_ExecuteAssembly},
5705         {"GetAssemblies", ves_icall_System_AppDomain_GetAssemblies},
5706         {"GetData", ves_icall_System_AppDomain_GetData},
5707         {"InternalGetContext", ves_icall_System_AppDomain_InternalGetContext},
5708         {"InternalGetDefaultContext", ves_icall_System_AppDomain_InternalGetDefaultContext},
5709         {"InternalGetProcessGuid", ves_icall_System_AppDomain_InternalGetProcessGuid},
5710         {"InternalIsFinalizingForUnload", ves_icall_System_AppDomain_InternalIsFinalizingForUnload},
5711         {"InternalPopDomainRef", ves_icall_System_AppDomain_InternalPopDomainRef},
5712         {"InternalPushDomainRef", ves_icall_System_AppDomain_InternalPushDomainRef},
5713         {"InternalPushDomainRefByID", ves_icall_System_AppDomain_InternalPushDomainRefByID},
5714         {"InternalSetContext", ves_icall_System_AppDomain_InternalSetContext},
5715         {"InternalSetDomain", ves_icall_System_AppDomain_InternalSetDomain},
5716         {"InternalSetDomainByID", ves_icall_System_AppDomain_InternalSetDomainByID},
5717         {"InternalUnload", ves_icall_System_AppDomain_InternalUnload},
5718         {"LoadAssembly", ves_icall_System_AppDomain_LoadAssembly},
5719         {"LoadAssemblyRaw", ves_icall_System_AppDomain_LoadAssemblyRaw},
5720         {"SetData", ves_icall_System_AppDomain_SetData},
5721         {"createDomain", ves_icall_System_AppDomain_createDomain},
5722         {"getCurDomain", ves_icall_System_AppDomain_getCurDomain},
5723         {"getFriendlyName", ves_icall_System_AppDomain_getFriendlyName},
5724         {"getRootDomain", ves_icall_System_AppDomain_getRootDomain},
5725         {"getSetup", ves_icall_System_AppDomain_getSetup}
5726 };
5727
5728 static const IcallEntry argiterator_icalls [] = {
5729         {"IntGetNextArg()",                  mono_ArgIterator_IntGetNextArg},
5730         {"IntGetNextArg(intptr)", mono_ArgIterator_IntGetNextArgT},
5731         {"IntGetNextArgType",                mono_ArgIterator_IntGetNextArgType},
5732         {"Setup",                            mono_ArgIterator_Setup}
5733 };
5734
5735 static const IcallEntry array_icalls [] = {
5736         {"ClearInternal",    ves_icall_System_Array_ClearInternal},
5737         {"Clone",            mono_array_clone},
5738         {"CreateInstanceImpl",   ves_icall_System_Array_CreateInstanceImpl},
5739         {"FastCopy",         ves_icall_System_Array_FastCopy},
5740         {"GetLength",        ves_icall_System_Array_GetLength},
5741         {"GetLowerBound",    ves_icall_System_Array_GetLowerBound},
5742         {"GetRank",          ves_icall_System_Array_GetRank},
5743         {"GetValue",         ves_icall_System_Array_GetValue},
5744         {"GetValueImpl",     ves_icall_System_Array_GetValueImpl},
5745         {"SetValue",         ves_icall_System_Array_SetValue},
5746         {"SetValueImpl",     ves_icall_System_Array_SetValueImpl}
5747 };
5748
5749 static const IcallEntry buffer_icalls [] = {
5750         {"BlockCopyInternal", ves_icall_System_Buffer_BlockCopyInternal},
5751         {"ByteLengthInternal", ves_icall_System_Buffer_ByteLengthInternal},
5752         {"GetByteInternal", ves_icall_System_Buffer_GetByteInternal},
5753         {"SetByteInternal", ves_icall_System_Buffer_SetByteInternal}
5754 };
5755
5756 static const IcallEntry char_icalls [] = {
5757         {"GetDataTablePointers", ves_icall_System_Char_GetDataTablePointers},
5758         {"InternalToLower(char,System.Globalization.CultureInfo)", ves_icall_System_Char_InternalToLower_Comp},
5759         {"InternalToUpper(char,System.Globalization.CultureInfo)", ves_icall_System_Char_InternalToUpper_Comp}
5760 };
5761
5762 static const IcallEntry defaultconf_icalls [] = {
5763         {"get_machine_config_path", ves_icall_System_Configuration_DefaultConfig_get_machine_config_path}
5764 };
5765
5766 static const IcallEntry consoledriver_icalls [] = {
5767         {"InternalKeyAvailable", ves_icall_System_ConsoleDriver_InternalKeyAvailable },
5768         {"Isatty", ves_icall_System_ConsoleDriver_Isatty },
5769         {"SetBreak", ves_icall_System_ConsoleDriver_SetBreak },
5770         {"SetEcho", ves_icall_System_ConsoleDriver_SetEcho },
5771         {"TtySetup", ves_icall_System_ConsoleDriver_TtySetup },
5772 };
5773
5774 static const IcallEntry timezone_icalls [] = {
5775         {"GetTimeZoneData", ves_icall_System_CurrentTimeZone_GetTimeZoneData}
5776 };
5777
5778 static const IcallEntry datetime_icalls [] = {
5779         {"GetNow", ves_icall_System_DateTime_GetNow}
5780 };
5781
5782 #ifndef DISABLE_DECIMAL
5783 static const IcallEntry decimal_icalls [] = {
5784         {"decimal2Int64", mono_decimal2Int64},
5785         {"decimal2UInt64", mono_decimal2UInt64},
5786         {"decimal2double", mono_decimal2double},
5787         {"decimal2string", mono_decimal2string},
5788         {"decimalCompare", mono_decimalCompare},
5789         {"decimalDiv", mono_decimalDiv},
5790         {"decimalFloorAndTrunc", mono_decimalFloorAndTrunc},
5791         {"decimalIncr", mono_decimalIncr},
5792         {"decimalIntDiv", mono_decimalIntDiv},
5793         {"decimalMult", mono_decimalMult},
5794         {"decimalRound", mono_decimalRound},
5795         {"decimalSetExponent", mono_decimalSetExponent},
5796         {"double2decimal", mono_double2decimal}, /* FIXME: wrong signature. */
5797         {"string2decimal", mono_string2decimal}
5798 };
5799 #endif
5800
5801 static const IcallEntry delegate_icalls [] = {
5802         {"CreateDelegate_internal", ves_icall_System_Delegate_CreateDelegate_internal},
5803         {"FreeTrampoline", ves_icall_System_Delegate_FreeTrampoline}
5804 };
5805
5806 static const IcallEntry tracelist_icalls [] = {
5807         {"WriteWindowsDebugString", ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString}
5808 };
5809
5810 static const IcallEntry fileversion_icalls [] = {
5811         {"GetVersionInfo_internal(string)", ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal}
5812 };
5813
5814 static const IcallEntry process_icalls [] = {
5815         {"ExitCode_internal(intptr)", ves_icall_System_Diagnostics_Process_ExitCode_internal},
5816         {"ExitTime_internal(intptr)", ves_icall_System_Diagnostics_Process_ExitTime_internal},
5817         {"GetModules_internal()", ves_icall_System_Diagnostics_Process_GetModules_internal},
5818         {"GetPid_internal()", ves_icall_System_Diagnostics_Process_GetPid_internal},
5819         {"GetProcess_internal(int)", ves_icall_System_Diagnostics_Process_GetProcess_internal},
5820         {"GetProcesses_internal()", ves_icall_System_Diagnostics_Process_GetProcesses_internal},
5821         {"GetWorkingSet_internal(intptr,int&,int&)", ves_icall_System_Diagnostics_Process_GetWorkingSet_internal},
5822         {"Kill_internal", ves_icall_System_Diagnostics_Process_Kill_internal},
5823         {"ProcessName_internal(intptr)", ves_icall_System_Diagnostics_Process_ProcessName_internal},
5824         {"Process_free_internal(intptr)", ves_icall_System_Diagnostics_Process_Process_free_internal},
5825         {"SetWorkingSet_internal(intptr,int,int,bool)", ves_icall_System_Diagnostics_Process_SetWorkingSet_internal},
5826         {"StartTime_internal(intptr)", ves_icall_System_Diagnostics_Process_StartTime_internal},
5827         {"Start_internal(string,string,string,intptr,intptr,intptr,System.Diagnostics.Process/ProcInfo&)", ves_icall_System_Diagnostics_Process_Start_internal},
5828         {"WaitForExit_internal(intptr,int)", ves_icall_System_Diagnostics_Process_WaitForExit_internal}
5829 };
5830
5831 static const IcallEntry double_icalls [] = {
5832         {"AssertEndianity", ves_icall_System_Double_AssertEndianity},
5833         {"ParseImpl",    mono_double_ParseImpl}
5834 };
5835
5836 static const IcallEntry enum_icalls [] = {
5837         {"ToObject", ves_icall_System_Enum_ToObject},
5838         {"get_value", ves_icall_System_Enum_get_value}
5839 };
5840
5841 static const IcallEntry environment_icalls [] = {
5842         {"Exit", ves_icall_System_Environment_Exit},
5843         {"GetCommandLineArgs", mono_runtime_get_main_args},
5844         {"GetEnvironmentVariableNames", ves_icall_System_Environment_GetEnvironmentVariableNames},
5845         {"GetLogicalDrivesInternal", ves_icall_System_Environment_GetLogicalDrives },
5846         {"GetMachineConfigPath", ves_icall_System_Configuration_DefaultConfig_get_machine_config_path},
5847         {"GetOSVersionString", ves_icall_System_Environment_GetOSVersionString},
5848         {"GetWindowsFolderPath", ves_icall_System_Environment_GetWindowsFolderPath},
5849         {"get_ExitCode", mono_environment_exitcode_get},
5850         {"get_HasShutdownStarted", ves_icall_System_Environment_get_HasShutdownStarted},
5851         {"get_MachineName", ves_icall_System_Environment_get_MachineName},
5852         {"get_NewLine", ves_icall_System_Environment_get_NewLine},
5853         {"get_Platform", ves_icall_System_Environment_get_Platform},
5854         {"get_TickCount", ves_icall_System_Environment_get_TickCount},
5855         {"get_UserName", ves_icall_System_Environment_get_UserName},
5856         {"internalGetEnvironmentVariable", ves_icall_System_Environment_GetEnvironmentVariable},
5857         {"internalGetGacPath", ves_icall_System_Environment_GetGacPath},
5858         {"internalGetHome", ves_icall_System_Environment_InternalGetHome},
5859         {"set_ExitCode", mono_environment_exitcode_set}
5860 };
5861
5862 static const IcallEntry cultureinfo_icalls [] = {
5863         {"construct_compareinfo(object,string)", ves_icall_System_Globalization_CompareInfo_construct_compareinfo},
5864         {"construct_datetime_format", ves_icall_System_Globalization_CultureInfo_construct_datetime_format},
5865         {"construct_internal_locale(string)", ves_icall_System_Globalization_CultureInfo_construct_internal_locale},
5866         {"construct_internal_locale_from_current_locale", ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_current_locale},
5867         {"construct_internal_locale_from_lcid", ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_lcid},
5868         {"construct_internal_locale_from_name", ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_name},
5869         {"construct_internal_locale_from_specific_name", ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_specific_name},
5870         {"construct_number_format", ves_icall_System_Globalization_CultureInfo_construct_number_format},
5871         {"internal_get_cultures", ves_icall_System_Globalization_CultureInfo_internal_get_cultures},
5872         {"internal_is_lcid_neutral", ves_icall_System_Globalization_CultureInfo_internal_is_lcid_neutral}
5873 };
5874
5875 static const IcallEntry compareinfo_icalls [] = {
5876         {"assign_sortkey(object,string,System.Globalization.CompareOptions)", ves_icall_System_Globalization_CompareInfo_assign_sortkey},
5877         {"construct_compareinfo(string)", ves_icall_System_Globalization_CompareInfo_construct_compareinfo},
5878         {"free_internal_collator()", ves_icall_System_Globalization_CompareInfo_free_internal_collator},
5879         {"internal_compare(string,int,int,string,int,int,System.Globalization.CompareOptions)", ves_icall_System_Globalization_CompareInfo_internal_compare},
5880         {"internal_index(string,int,int,char,System.Globalization.CompareOptions,bool)", ves_icall_System_Globalization_CompareInfo_internal_index_char},
5881         {"internal_index(string,int,int,string,System.Globalization.CompareOptions,bool)", ves_icall_System_Globalization_CompareInfo_internal_index}
5882 };
5883
5884 static const IcallEntry gc_icalls [] = {
5885         {"GetTotalMemory", ves_icall_System_GC_GetTotalMemory},
5886         {"InternalCollect", ves_icall_System_GC_InternalCollect},
5887         {"KeepAlive", ves_icall_System_GC_KeepAlive},
5888         {"ReRegisterForFinalize", ves_icall_System_GC_ReRegisterForFinalize},
5889         {"SuppressFinalize", ves_icall_System_GC_SuppressFinalize},
5890         {"WaitForPendingFinalizers", ves_icall_System_GC_WaitForPendingFinalizers}
5891 };
5892
5893 static const IcallEntry famwatcher_icalls [] = {
5894         {"InternalFAMNextEvent", ves_icall_System_IO_FAMW_InternalFAMNextEvent}
5895 };
5896
5897 static const IcallEntry filewatcher_icalls [] = {
5898         {"InternalCloseDirectory", ves_icall_System_IO_FSW_CloseDirectory},
5899         {"InternalOpenDirectory", ves_icall_System_IO_FSW_OpenDirectory},
5900         {"InternalReadDirectoryChanges", ves_icall_System_IO_FSW_ReadDirectoryChanges},
5901         {"InternalSupportsFSW", ves_icall_System_IO_FSW_SupportsFSW}
5902 };
5903
5904 static const IcallEntry path_icalls [] = {
5905         {"get_temp_path", ves_icall_System_IO_get_temp_path}
5906 };
5907
5908 static const IcallEntry monoio_icalls [] = {
5909         {"BeginRead", ves_icall_System_IO_MonoIO_BeginRead },
5910         {"BeginWrite", ves_icall_System_IO_MonoIO_BeginWrite },
5911         {"Close(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Close},
5912         {"CopyFile(string,string,bool,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_CopyFile},
5913         {"CreateDirectory(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_CreateDirectory},
5914         {"CreatePipe(intptr&,intptr&)", ves_icall_System_IO_MonoIO_CreatePipe},
5915         {"DeleteFile(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_DeleteFile},
5916         {"FindClose(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_FindClose},
5917         {"FindFirstFile(string,System.IO.MonoIOStat&,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_FindFirstFile},
5918         {"FindNextFile(intptr,System.IO.MonoIOStat&,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_FindNextFile},
5919         {"Flush(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Flush},
5920         {"GetCurrentDirectory(System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetCurrentDirectory},
5921         {"GetFileAttributes(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetFileAttributes},
5922         {"GetFileStat(string,System.IO.MonoIOStat&,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetFileStat},
5923         {"GetFileType(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetFileType},
5924         {"GetLength(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetLength},
5925         {"GetSupportsAsync", ves_icall_System_IO_MonoIO_GetSupportsAsync},
5926         {"GetTempPath(string&)", ves_icall_System_IO_MonoIO_GetTempPath},
5927         {"Lock(intptr,long,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Lock},
5928         {"MoveFile(string,string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_MoveFile},
5929         {"Open(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,bool,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Open},
5930         {"Read(intptr,byte[],int,int,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Read},
5931         {"RemoveDirectory(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_RemoveDirectory},
5932         {"Seek(intptr,long,System.IO.SeekOrigin,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Seek},
5933         {"SetCurrentDirectory(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetCurrentDirectory},
5934         {"SetFileAttributes(string,System.IO.FileAttributes,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetFileAttributes},
5935         {"SetFileTime(intptr,long,long,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetFileTime},
5936         {"SetLength(intptr,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetLength},
5937         {"Unlock(intptr,long,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Unlock},
5938         {"Write(intptr,byte[],int,int,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Write},
5939         {"get_AltDirectorySeparatorChar", ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar},
5940         {"get_ConsoleError", ves_icall_System_IO_MonoIO_get_ConsoleError},
5941         {"get_ConsoleInput", ves_icall_System_IO_MonoIO_get_ConsoleInput},
5942         {"get_ConsoleOutput", ves_icall_System_IO_MonoIO_get_ConsoleOutput},
5943         {"get_DirectorySeparatorChar", ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar},
5944         {"get_InvalidPathChars", ves_icall_System_IO_MonoIO_get_InvalidPathChars},
5945         {"get_PathSeparator", ves_icall_System_IO_MonoIO_get_PathSeparator},
5946         {"get_VolumeSeparatorChar", ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar}
5947 };
5948
5949 static const IcallEntry math_icalls [] = {
5950         {"Acos", ves_icall_System_Math_Acos},
5951         {"Asin", ves_icall_System_Math_Asin},
5952         {"Atan", ves_icall_System_Math_Atan},
5953         {"Atan2", ves_icall_System_Math_Atan2},
5954         {"Cos", ves_icall_System_Math_Cos},
5955         {"Cosh", ves_icall_System_Math_Cosh},
5956         {"Exp", ves_icall_System_Math_Exp},
5957         {"Floor", ves_icall_System_Math_Floor},
5958         {"Log", ves_icall_System_Math_Log},
5959         {"Log10", ves_icall_System_Math_Log10},
5960         {"Pow", ves_icall_System_Math_Pow},
5961         {"Round", ves_icall_System_Math_Round},
5962         {"Round2", ves_icall_System_Math_Round2},
5963         {"Sin", ves_icall_System_Math_Sin},
5964         {"Sinh", ves_icall_System_Math_Sinh},
5965         {"Sqrt", ves_icall_System_Math_Sqrt},
5966         {"Tan", ves_icall_System_Math_Tan},
5967         {"Tanh", ves_icall_System_Math_Tanh}
5968 };
5969
5970 static const IcallEntry customattrs_icalls [] = {
5971         {"GetCustomAttributesInternal", mono_reflection_get_custom_attrs},
5972         {"IsDefinedInternal", custom_attrs_defined_internal}
5973 };
5974
5975 static const IcallEntry enuminfo_icalls [] = {
5976         {"get_enum_info", ves_icall_get_enum_info}
5977 };
5978
5979 static const IcallEntry fieldinfo_icalls [] = {
5980         {"GetUnmanagedMarshal", ves_icall_System_Reflection_FieldInfo_GetUnmanagedMarshal},
5981         {"internal_from_handle", ves_icall_System_Reflection_FieldInfo_internal_from_handle}
5982 };
5983
5984 static const IcallEntry memberinfo_icalls [] = {
5985         {"get_MetadataToken", mono_reflection_get_token}
5986 };
5987
5988 static const IcallEntry monotype_icalls [] = {
5989         {"GetArrayRank", ves_icall_MonoType_GetArrayRank},
5990         {"GetConstructors", ves_icall_Type_GetConstructors_internal},
5991         {"GetConstructors_internal", ves_icall_Type_GetConstructors_internal},
5992         {"GetElementType", ves_icall_MonoType_GetElementType},
5993         {"GetEvents_internal", ves_icall_Type_GetEvents_internal},
5994         {"GetField", ves_icall_Type_GetField},
5995         {"GetFields_internal", ves_icall_Type_GetFields_internal},
5996         {"GetGenericArguments", ves_icall_MonoType_GetGenericArguments},
5997         {"GetInterfaces", ves_icall_Type_GetInterfaces},
5998         {"GetMethodsByName", ves_icall_Type_GetMethodsByName},
5999         {"GetNestedType", ves_icall_Type_GetNestedType},
6000         {"GetNestedTypes", ves_icall_Type_GetNestedTypes},
6001         {"GetPropertiesByName", ves_icall_Type_GetPropertiesByName},
6002         {"InternalGetEvent", ves_icall_MonoType_GetEvent},
6003         {"IsByRefImpl", ves_icall_type_isbyref},
6004         {"IsPointerImpl", ves_icall_type_ispointer},
6005         {"IsPrimitiveImpl", ves_icall_type_isprimitive},
6006         {"getFullName", ves_icall_System_MonoType_getFullName},
6007         {"get_Assembly", ves_icall_MonoType_get_Assembly},
6008         {"get_BaseType", ves_icall_get_type_parent},
6009         {"get_DeclaringMethod", ves_icall_MonoType_get_DeclaringMethod},
6010         {"get_DeclaringType", ves_icall_MonoType_get_DeclaringType},
6011         {"get_HasGenericArguments", ves_icall_MonoType_get_HasGenericArguments},
6012         {"get_IsGenericParameter", ves_icall_MonoType_get_IsGenericParameter},
6013         {"get_Module", ves_icall_MonoType_get_Module},
6014         {"get_Name", ves_icall_MonoType_get_Name},
6015         {"get_Namespace", ves_icall_MonoType_get_Namespace},
6016         {"get_UnderlyingSystemType", ves_icall_MonoType_get_UnderlyingSystemType},
6017         {"get_attributes", ves_icall_get_attributes},
6018         {"type_from_obj", mono_type_type_from_obj}
6019 };
6020
6021 static const IcallEntry assembly_icalls [] = {
6022         {"FillName", ves_icall_System_Reflection_Assembly_FillName},
6023         {"GetCallingAssembly", ves_icall_System_Reflection_Assembly_GetCallingAssembly},
6024         {"GetEntryAssembly", ves_icall_System_Reflection_Assembly_GetEntryAssembly},
6025         {"GetExecutingAssembly", ves_icall_System_Reflection_Assembly_GetExecutingAssembly},
6026         {"GetFilesInternal", ves_icall_System_Reflection_Assembly_GetFilesInternal},
6027         {"GetManifestResourceInfoInternal", ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal},
6028         {"GetManifestResourceInternal", ves_icall_System_Reflection_Assembly_GetManifestResourceInternal},
6029         {"GetManifestResourceNames", ves_icall_System_Reflection_Assembly_GetManifestResourceNames},
6030         {"GetModulesInternal", ves_icall_System_Reflection_Assembly_GetModulesInternal},
6031         {"GetNamespaces", ves_icall_System_Reflection_Assembly_GetNamespaces},
6032         {"GetReferencedAssemblies", ves_icall_System_Reflection_Assembly_GetReferencedAssemblies},
6033         {"GetTypes", ves_icall_System_Reflection_Assembly_GetTypes},
6034         {"InternalGetAssemblyName", ves_icall_System_Reflection_Assembly_InternalGetAssemblyName},
6035         {"InternalGetType", ves_icall_System_Reflection_Assembly_InternalGetType},
6036         {"InternalImageRuntimeVersion", ves_icall_System_Reflection_Assembly_InternalImageRuntimeVersion},
6037         {"LoadFrom", ves_icall_System_Reflection_Assembly_LoadFrom},
6038         {"LoadPermissions", ves_icall_System_Reflection_Assembly_LoadPermissions},
6039         /*
6040          * Private icalls for the Mono Debugger
6041          */
6042         {"MonoDebugger_CheckRuntimeVersion", ves_icall_MonoDebugger_check_runtime_version},
6043         {"MonoDebugger_GetLocalTypeFromSignature", ves_icall_MonoDebugger_GetLocalTypeFromSignature},
6044         {"MonoDebugger_GetMethod", ves_icall_MonoDebugger_GetMethod},
6045         {"MonoDebugger_GetMethodToken", ves_icall_MonoDebugger_GetMethodToken},
6046         {"MonoDebugger_GetType", ves_icall_MonoDebugger_GetType},
6047
6048         /* normal icalls again */
6049         {"get_EntryPoint", ves_icall_System_Reflection_Assembly_get_EntryPoint},
6050         {"get_ManifestModule", ves_icall_System_Reflection_Assembly_get_ManifestModule},
6051         {"get_MetadataToken", mono_reflection_get_token},
6052         {"get_code_base", ves_icall_System_Reflection_Assembly_get_code_base},
6053         {"get_global_assembly_cache", ves_icall_System_Reflection_Assembly_get_global_assembly_cache},
6054         {"get_location", ves_icall_System_Reflection_Assembly_get_location},
6055         {"load_with_partial_name", ves_icall_System_Reflection_Assembly_load_with_partial_name}
6056 };
6057
6058 static const IcallEntry methodbase_icalls [] = {
6059         {"GetCurrentMethod", ves_icall_GetCurrentMethod},
6060         {"GetMethodBodyInternal", ves_icall_System_Reflection_MethodBase_GetMethodBodyInternal},
6061         {"GetMethodFromHandleInternal", ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternal}
6062 };
6063
6064 static const IcallEntry module_icalls [] = {
6065         {"Close", ves_icall_System_Reflection_Module_Close},
6066         {"GetGlobalType", ves_icall_System_Reflection_Module_GetGlobalType},
6067         {"GetGuidInternal", ves_icall_System_Reflection_Module_GetGuidInternal},
6068         {"GetPEKind", ves_icall_System_Reflection_Module_GetPEKind},
6069         {"InternalGetTypes", ves_icall_System_Reflection_Module_InternalGetTypes},
6070         {"ResolveFieldToken", ves_icall_System_Reflection_Module_ResolveFieldToken},
6071         {"ResolveMemberToken", ves_icall_System_Reflection_Module_ResolveMemberToken},
6072         {"ResolveMethodToken", ves_icall_System_Reflection_Module_ResolveMethodToken},
6073         {"ResolveStringToken", ves_icall_System_Reflection_Module_ResolveStringToken},
6074         {"ResolveTypeToken", ves_icall_System_Reflection_Module_ResolveTypeToken},
6075         {"get_MetadataToken", mono_reflection_get_token}
6076 };
6077
6078 static const IcallEntry monocmethod_icalls [] = {
6079         {"GetGenericMethodDefinition_impl", ves_icall_MonoMethod_GetGenericMethodDefinition},
6080         {"InternalInvoke", ves_icall_InternalInvoke},
6081         {"get_Mono_IsInflatedMethod", ves_icall_MonoMethod_get_Mono_IsInflatedMethod}
6082 };
6083
6084 static const IcallEntry monoeventinfo_icalls [] = {
6085         {"get_event_info", ves_icall_get_event_info}
6086 };
6087
6088 static const IcallEntry monofield_icalls [] = {
6089         {"GetFieldOffset", ves_icall_MonoField_GetFieldOffset},
6090         {"GetParentType", ves_icall_MonoField_GetParentType},
6091         {"GetValueInternal", ves_icall_MonoField_GetValueInternal},
6092         {"Mono_GetGenericFieldDefinition", ves_icall_MonoField_Mono_GetGenericFieldDefinition},
6093         {"SetValueInternal", ves_icall_FieldInfo_SetValueInternal}
6094 };
6095
6096 static const IcallEntry monogenericclass_icalls [] = {
6097         {"GetConstructors_internal", ves_icall_MonoGenericClass_GetConstructors},
6098         {"GetEvents_internal", ves_icall_MonoGenericClass_GetEvents},
6099         {"GetFields_internal", ves_icall_MonoGenericClass_GetFields},
6100         {"GetInterfaces_internal", ves_icall_MonoGenericClass_GetInterfaces},
6101         {"GetMethods_internal", ves_icall_MonoGenericClass_GetMethods},
6102         {"GetParentType", ves_icall_MonoGenericClass_GetParentType},
6103         {"GetProperties_internal", ves_icall_MonoGenericClass_GetProperties},
6104         {"initialize", mono_reflection_generic_class_initialize}
6105 };
6106
6107 static const IcallEntry monogenericmethod_icalls [] = {
6108         {"get_ReflectedType", ves_icall_MonoGenericMethod_get_ReflectedType}
6109 };
6110
6111 static const IcallEntry generictypeparambuilder_icalls [] = {
6112         {"initialize", mono_reflection_initialize_generic_parameter}
6113 };
6114
6115 static const IcallEntry monomethod_icalls [] = {
6116         {"BindGenericParameters", mono_reflection_bind_generic_method_parameters},
6117         {"GetDllImportAttribute", ves_icall_MonoMethod_GetDllImportAttribute},
6118         {"GetGenericArguments", ves_icall_MonoMethod_GetGenericArguments},
6119         {"GetGenericMethodDefinition_impl", ves_icall_MonoMethod_GetGenericMethodDefinition},
6120         {"InternalInvoke", ves_icall_InternalInvoke},
6121         {"get_HasGenericParameters", ves_icall_MonoMethod_get_HasGenericParameters},
6122         {"get_IsGenericMethodDefinition", ves_icall_MonoMethod_get_IsGenericMethodDefinition},
6123         {"get_Mono_IsInflatedMethod", ves_icall_MonoMethod_get_Mono_IsInflatedMethod},
6124         {"get_base_definition", ves_icall_MonoMethod_get_base_definition}
6125 };
6126
6127 static const IcallEntry monomethodinfo_icalls [] = {
6128         {"get_method_info", ves_icall_get_method_info},
6129         {"get_parameter_info", ves_icall_get_parameter_info}
6130 };
6131
6132 static const IcallEntry monopropertyinfo_icalls [] = {
6133         {"get_property_info", ves_icall_get_property_info}
6134 };
6135
6136 static const IcallEntry parameterinfo_icalls [] = {
6137         {"get_MetadataToken", mono_reflection_get_token}
6138 };
6139
6140 static const IcallEntry dns_icalls [] = {
6141         {"GetHostByAddr_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByAddr_internal},
6142         {"GetHostByName_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByName_internal},
6143         {"GetHostName_internal(string&)", ves_icall_System_Net_Dns_GetHostName_internal}
6144 };
6145
6146 static const IcallEntry socket_icalls [] = {
6147         {"Accept_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Accept_internal},
6148         {"AsyncReceiveInternal", ves_icall_System_Net_Sockets_Socket_AsyncReceive},
6149         {"AsyncSendInternal", ves_icall_System_Net_Sockets_Socket_AsyncSend},
6150         {"Available_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Available_internal},
6151         {"Bind_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Bind_internal},
6152         {"Blocking_internal(intptr,bool,int&)", ves_icall_System_Net_Sockets_Socket_Blocking_internal},
6153         {"Close_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Close_internal},
6154         {"Connect_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Connect_internal},
6155         {"GetSocketOption_arr_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,byte[]&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal},
6156         {"GetSocketOption_obj_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal},
6157         {"GetSupportsAsync", ves_icall_System_IO_MonoIO_GetSupportsAsync},
6158         {"Listen_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_Listen_internal},
6159         {"LocalEndPoint_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal},
6160         {"Poll_internal", ves_icall_System_Net_Sockets_Socket_Poll_internal},
6161         {"Receive_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Receive_internal},
6162         {"RecvFrom_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress&,int&)", ves_icall_System_Net_Sockets_Socket_RecvFrom_internal},
6163         {"RemoteEndPoint_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal},
6164         {"Select_internal(System.Net.Sockets.Socket[]&,System.Net.Sockets.Socket[]&,System.Net.Sockets.Socket[]&,int,int&)", ves_icall_System_Net_Sockets_Socket_Select_internal},
6165         {"SendTo_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_SendTo_internal},
6166         {"Send_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Send_internal},
6167         {"SetSocketOption_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object,byte[],int,int&)", ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal},
6168         {"Shutdown_internal(intptr,System.Net.Sockets.SocketShutdown,int&)", ves_icall_System_Net_Sockets_Socket_Shutdown_internal},
6169         {"Socket_internal(System.Net.Sockets.AddressFamily,System.Net.Sockets.SocketType,System.Net.Sockets.ProtocolType,int&)", ves_icall_System_Net_Sockets_Socket_Socket_internal},
6170         {"WSAIoctl(intptr,int,byte[],byte[],int&)", ves_icall_System_Net_Sockets_Socket_WSAIoctl}
6171 };
6172
6173 static const IcallEntry socketex_icalls [] = {
6174         {"WSAGetLastError_internal", ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal}
6175 };
6176
6177 static const IcallEntry object_icalls [] = {
6178         {"GetType", ves_icall_System_Object_GetType},
6179         {"InternalGetHashCode", ves_icall_System_Object_GetHashCode},
6180         {"MemberwiseClone", ves_icall_System_Object_MemberwiseClone},
6181         {"obj_address", ves_icall_System_Object_obj_address}
6182 };
6183
6184 static const IcallEntry assemblybuilder_icalls[] = {
6185         {"InternalAddModule", mono_image_load_module},
6186         {"basic_init", mono_image_basic_init}
6187 };
6188
6189 static const IcallEntry customattrbuilder_icalls [] = {
6190         {"GetBlob", mono_reflection_get_custom_attrs_blob}
6191 };
6192
6193 static const IcallEntry dynamicmethod_icalls [] = {
6194         {"create_dynamic_method", mono_reflection_create_dynamic_method}
6195 };
6196
6197 static const IcallEntry methodbuilder_icalls [] = {
6198         {"BindGenericParameters", mono_reflection_bind_generic_method_parameters}
6199 };
6200
6201 static const IcallEntry modulebuilder_icalls [] = {
6202         {"WriteToFile", ves_icall_ModuleBuilder_WriteToFile},
6203         {"basic_init", mono_image_module_basic_init},
6204         {"build_metadata", ves_icall_ModuleBuilder_build_metadata},
6205         {"create_modified_type", ves_icall_ModuleBuilder_create_modified_type},
6206         {"getMethodToken", ves_icall_ModuleBuilder_getMethodToken},
6207         {"getToken", ves_icall_ModuleBuilder_getToken},
6208         {"getUSIndex", mono_image_insert_string}
6209 };
6210
6211 static const IcallEntry signaturehelper_icalls [] = {
6212         {"get_signature_field", mono_reflection_sighelper_get_signature_field},
6213         {"get_signature_local", mono_reflection_sighelper_get_signature_local}
6214 };
6215
6216 static const IcallEntry typebuilder_icalls [] = {
6217         {"create_generic_class", mono_reflection_create_generic_class},
6218         {"create_internal_class", mono_reflection_create_internal_class},
6219         {"create_runtime_class", mono_reflection_create_runtime_class},
6220         {"get_IsGenericParameter", ves_icall_TypeBuilder_get_IsGenericParameter},
6221         {"get_event_info", mono_reflection_event_builder_get_event_info},
6222         {"setup_generic_class", mono_reflection_setup_generic_class},
6223         {"setup_internal_class", mono_reflection_setup_internal_class}
6224 };
6225
6226 static const IcallEntry enumbuilder_icalls [] = {
6227         {"setup_enum_type", ves_icall_EnumBuilder_setup_enum_type}
6228 };
6229
6230 static const IcallEntry runtimehelpers_icalls [] = {
6231         {"GetObjectValue", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue},
6232          /* REMOVEME: no longer needed, just so we dont break things when not needed */
6233         {"GetOffsetToStringData", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData},
6234         {"InitializeArray", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray},
6235         {"RunClassConstructor", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor},
6236         {"get_OffsetToStringData", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData}
6237 };
6238
6239 static const IcallEntry gchandle_icalls [] = {
6240         {"FreeHandle", ves_icall_System_GCHandle_FreeHandle},
6241         {"GetAddrOfPinnedObject", ves_icall_System_GCHandle_GetAddrOfPinnedObject},
6242         {"GetTarget", ves_icall_System_GCHandle_GetTarget},
6243         {"GetTargetHandle", ves_icall_System_GCHandle_GetTargetHandle}
6244 };
6245
6246 static const IcallEntry marshal_icalls [] = {
6247         {"AllocCoTaskMem", ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem},
6248         {"AllocHGlobal", ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal},
6249         {"DestroyStructure", ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure},
6250         {"FreeCoTaskMem", ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem},
6251         {"FreeHGlobal", ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal},
6252         {"GetDelegateForFunctionPointerInternal", ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal},
6253         {"GetFunctionPointerForDelegateInternal", mono_delegate_to_ftnptr},
6254         {"GetLastWin32Error", ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error},
6255         {"OffsetOf", ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf},
6256         {"Prelink", ves_icall_System_Runtime_InteropServices_Marshal_Prelink},
6257         {"PrelinkAll", ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll},
6258         {"PtrToStringAnsi(intptr)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi},
6259         {"PtrToStringAnsi(intptr,int)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len},
6260         {"PtrToStringAuto(intptr)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi},
6261         {"PtrToStringAuto(intptr,int)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len},
6262         {"PtrToStringBSTR", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringBSTR},
6263         {"PtrToStringUni(intptr)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni},
6264         {"PtrToStringUni(intptr,int)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len},
6265         {"PtrToStructure(intptr,System.Type)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type},
6266         {"PtrToStructure(intptr,object)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure},
6267         {"ReAllocHGlobal", mono_marshal_realloc},
6268         {"ReadByte", ves_icall_System_Runtime_InteropServices_Marshal_ReadByte},
6269         {"ReadInt16", ves_icall_System_Runtime_InteropServices_Marshal_ReadInt16},
6270         {"ReadInt32", ves_icall_System_Runtime_InteropServices_Marshal_ReadInt32},
6271         {"ReadInt64", ves_icall_System_Runtime_InteropServices_Marshal_ReadInt64},
6272         {"ReadIntPtr", ves_icall_System_Runtime_InteropServices_Marshal_ReadIntPtr},
6273         {"SizeOf", ves_icall_System_Runtime_InteropServices_Marshal_SizeOf},
6274         {"StringToHGlobalAnsi", ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi},
6275         {"StringToHGlobalAuto", ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi},
6276         {"StringToHGlobalUni", ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni},
6277         {"StructureToPtr", ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr},
6278         {"UnsafeAddrOfPinnedArrayElement", ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement},
6279         {"WriteByte", ves_icall_System_Runtime_InteropServices_Marshal_WriteByte},
6280         {"WriteInt16", ves_icall_System_Runtime_InteropServices_Marshal_WriteInt16},
6281         {"WriteInt32", ves_icall_System_Runtime_InteropServices_Marshal_WriteInt32},
6282         {"WriteInt64", ves_icall_System_Runtime_InteropServices_Marshal_WriteInt64},
6283         {"WriteIntPtr", ves_icall_System_Runtime_InteropServices_Marshal_WriteIntPtr},
6284         {"copy_from_unmanaged", ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged},
6285         {"copy_to_unmanaged", ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged}
6286 };
6287
6288 static const IcallEntry activationservices_icalls [] = {
6289         {"AllocateUninitializedClassInstance", ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance},
6290         {"EnableProxyActivation", ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation}
6291 };
6292
6293 static const IcallEntry monomethodmessage_icalls [] = {
6294         {"InitMessage", ves_icall_MonoMethodMessage_InitMessage}
6295 };
6296         
6297 static const IcallEntry realproxy_icalls [] = {
6298         {"InternalGetProxyType", ves_icall_Remoting_RealProxy_InternalGetProxyType},
6299         {"InternalGetTransparentProxy", ves_icall_Remoting_RealProxy_GetTransparentProxy}
6300 };
6301
6302 static const IcallEntry remotingservices_icalls [] = {
6303         {"InternalExecute", ves_icall_InternalExecute},
6304         {"IsTransparentProxy", ves_icall_IsTransparentProxy}
6305 };
6306
6307 static const IcallEntry rng_icalls [] = {
6308         {"RngClose", ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngClose},
6309         {"RngGetBytes", ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngGetBytes},
6310         {"RngInitialize", ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngInitialize}
6311 };
6312
6313 static const IcallEntry methodhandle_icalls [] = {
6314         {"GetFunctionPointer", ves_icall_RuntimeMethod_GetFunctionPointer}
6315 };
6316
6317 static const IcallEntry string_icalls [] = {
6318         {".ctor(char*)", ves_icall_System_String_ctor_charp},
6319         {".ctor(char*,int,int)", ves_icall_System_String_ctor_charp_int_int},
6320         {".ctor(char,int)", ves_icall_System_String_ctor_char_int},
6321         {".ctor(char[])", ves_icall_System_String_ctor_chara},
6322         {".ctor(char[],int,int)", ves_icall_System_String_ctor_chara_int_int},
6323         {".ctor(sbyte*)", ves_icall_System_String_ctor_sbytep},
6324         {".ctor(sbyte*,int,int)", ves_icall_System_String_ctor_sbytep_int_int},
6325         {".ctor(sbyte*,int,int,System.Text.Encoding)", ves_icall_System_String_ctor_encoding},
6326         {"GetHashCode", ves_icall_System_String_GetHashCode},
6327         {"InternalAllocateStr", ves_icall_System_String_InternalAllocateStr},
6328         {"InternalCharCopy", ves_icall_System_String_InternalCharCopy},
6329         {"InternalCopyTo", ves_icall_System_String_InternalCopyTo},
6330         {"InternalIndexOfAny", ves_icall_System_String_InternalIndexOfAny},
6331         {"InternalInsert", ves_icall_System_String_InternalInsert},
6332         {"InternalIntern", ves_icall_System_String_InternalIntern},
6333         {"InternalIsInterned", ves_icall_System_String_InternalIsInterned},
6334         {"InternalJoin", ves_icall_System_String_InternalJoin},
6335         {"InternalLastIndexOfAny", ves_icall_System_String_InternalLastIndexOfAny},
6336         {"InternalPad", ves_icall_System_String_InternalPad},
6337         {"InternalRemove", ves_icall_System_String_InternalRemove},
6338         {"InternalReplace(char,char)", ves_icall_System_String_InternalReplace_Char},
6339         {"InternalReplace(string,string,System.Globalization.CompareInfo)", ves_icall_System_String_InternalReplace_Str_Comp},
6340         {"InternalSplit", ves_icall_System_String_InternalSplit},
6341         {"InternalStrcpy(string,int,char[])", ves_icall_System_String_InternalStrcpy_Chars},
6342         {"InternalStrcpy(string,int,char[],int,int)", ves_icall_System_String_InternalStrcpy_CharsN},
6343         {"InternalStrcpy(string,int,string)", ves_icall_System_String_InternalStrcpy_Str},
6344         {"InternalStrcpy(string,int,string,int,int)", ves_icall_System_String_InternalStrcpy_StrN},
6345         {"InternalToLower(System.Globalization.CultureInfo)", ves_icall_System_String_InternalToLower_Comp},
6346         {"InternalToUpper(System.Globalization.CultureInfo)", ves_icall_System_String_InternalToUpper_Comp},
6347         {"InternalTrim", ves_icall_System_String_InternalTrim},
6348         {"get_Chars", ves_icall_System_String_get_Chars}
6349 };
6350
6351 static const IcallEntry encoding_icalls [] = {
6352         {"InternalCodePage", ves_icall_System_Text_Encoding_InternalCodePage}
6353 };
6354
6355 static const IcallEntry monitor_icalls [] = {
6356         {"Monitor_exit", ves_icall_System_Threading_Monitor_Monitor_exit},
6357         {"Monitor_pulse", ves_icall_System_Threading_Monitor_Monitor_pulse},
6358         {"Monitor_pulse_all", ves_icall_System_Threading_Monitor_Monitor_pulse_all},
6359         {"Monitor_test_owner", ves_icall_System_Threading_Monitor_Monitor_test_owner},
6360         {"Monitor_test_synchronised", ves_icall_System_Threading_Monitor_Monitor_test_synchronised},
6361         {"Monitor_try_enter", ves_icall_System_Threading_Monitor_Monitor_try_enter},
6362         {"Monitor_wait", ves_icall_System_Threading_Monitor_Monitor_wait}
6363 };
6364
6365 static const IcallEntry interlocked_icalls [] = {
6366         {"CompareExchange(int&,int,int)", ves_icall_System_Threading_Interlocked_CompareExchange_Int},
6367         {"CompareExchange(object&,object,object)", ves_icall_System_Threading_Interlocked_CompareExchange_Object},
6368         {"CompareExchange(single&,single,single)", ves_icall_System_Threading_Interlocked_CompareExchange_Single},
6369         {"Decrement(int&)", ves_icall_System_Threading_Interlocked_Decrement_Int},
6370         {"Decrement(long&)", ves_icall_System_Threading_Interlocked_Decrement_Long},
6371         {"Exchange(int&,int)", ves_icall_System_Threading_Interlocked_Exchange_Int},
6372         {"Exchange(object&,object)", ves_icall_System_Threading_Interlocked_Exchange_Object},
6373         {"Exchange(single&,single)", ves_icall_System_Threading_Interlocked_Exchange_Single},
6374         {"Increment(int&)", ves_icall_System_Threading_Interlocked_Increment_Int},
6375         {"Increment(long&)", ves_icall_System_Threading_Interlocked_Increment_Long}
6376 };
6377
6378 static const IcallEntry mutex_icalls [] = {
6379         {"CreateMutex_internal(bool,string,bool&)", ves_icall_System_Threading_Mutex_CreateMutex_internal},
6380         {"ReleaseMutex_internal(intptr)", ves_icall_System_Threading_Mutex_ReleaseMutex_internal}
6381 };
6382
6383 static const IcallEntry nativeevents_icalls [] = {
6384         {"CloseEvent_internal", ves_icall_System_Threading_Events_CloseEvent_internal},
6385         {"CreateEvent_internal", ves_icall_System_Threading_Events_CreateEvent_internal},
6386         {"ResetEvent_internal",  ves_icall_System_Threading_Events_ResetEvent_internal},
6387         {"SetEvent_internal",    ves_icall_System_Threading_Events_SetEvent_internal}
6388 };
6389
6390 static const IcallEntry thread_icalls [] = {
6391         {"Abort_internal(object)", ves_icall_System_Threading_Thread_Abort},
6392         {"CurrentThread_internal", mono_thread_current},
6393         {"GetCachedCurrentCulture", ves_icall_System_Threading_Thread_GetCachedCurrentCulture},
6394         {"GetCachedCurrentUICulture", ves_icall_System_Threading_Thread_GetCachedCurrentUICulture},
6395         {"GetDomainID", ves_icall_System_Threading_Thread_GetDomainID},
6396         {"GetName_internal", ves_icall_System_Threading_Thread_GetName_internal},
6397         {"GetSerializedCurrentCulture", ves_icall_System_Threading_Thread_GetSerializedCurrentCulture},
6398         {"GetSerializedCurrentUICulture", ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture},
6399         {"Join_internal", ves_icall_System_Threading_Thread_Join_internal},
6400         {"ResetAbort_internal()", ves_icall_System_Threading_Thread_ResetAbort},
6401         {"Resume_internal()", ves_icall_System_Threading_Thread_Resume},
6402         {"SetCachedCurrentCulture", ves_icall_System_Threading_Thread_SetCachedCurrentCulture},
6403         {"SetCachedCurrentUICulture", ves_icall_System_Threading_Thread_SetCachedCurrentUICulture},
6404         {"SetName_internal", ves_icall_System_Threading_Thread_SetName_internal},
6405         {"SetSerializedCurrentCulture", ves_icall_System_Threading_Thread_SetSerializedCurrentCulture},
6406         {"SetSerializedCurrentUICulture", ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture},
6407         {"Sleep_internal", ves_icall_System_Threading_Thread_Sleep_internal},
6408         {"SlotHash_lookup", ves_icall_System_Threading_Thread_SlotHash_lookup},
6409         {"SlotHash_store", ves_icall_System_Threading_Thread_SlotHash_store},
6410         {"Start_internal", ves_icall_System_Threading_Thread_Start_internal},
6411         {"Suspend_internal", ves_icall_System_Threading_Thread_Suspend},
6412         {"Thread_free_internal", ves_icall_System_Threading_Thread_Thread_free_internal},
6413         {"Thread_internal", ves_icall_System_Threading_Thread_Thread_internal},
6414         {"VolatileRead(byte&)", ves_icall_System_Threading_Thread_VolatileRead1},
6415         {"VolatileRead(double&)", ves_icall_System_Threading_Thread_VolatileRead8},
6416         {"VolatileRead(int&)", ves_icall_System_Threading_Thread_VolatileRead4},
6417         {"VolatileRead(int16&)", ves_icall_System_Threading_Thread_VolatileRead2},
6418         {"VolatileRead(intptr&)", ves_icall_System_Threading_Thread_VolatileReadIntPtr},
6419         {"VolatileRead(long&)", ves_icall_System_Threading_Thread_VolatileRead8},
6420         {"VolatileRead(object&)", ves_icall_System_Threading_Thread_VolatileReadIntPtr},
6421         {"VolatileRead(sbyte&)", ves_icall_System_Threading_Thread_VolatileRead1},
6422         {"VolatileRead(single&)", ves_icall_System_Threading_Thread_VolatileRead4},
6423         {"VolatileRead(uint&)", ves_icall_System_Threading_Thread_VolatileRead2},
6424         {"VolatileRead(uint16&)", ves_icall_System_Threading_Thread_VolatileRead2},
6425         {"VolatileRead(uintptr&)", ves_icall_System_Threading_Thread_VolatileReadIntPtr},
6426         {"VolatileRead(ulong&)", ves_icall_System_Threading_Thread_VolatileRead8},
6427         {"VolatileWrite(byte&,byte)", ves_icall_System_Threading_Thread_VolatileWrite1},
6428         {"VolatileWrite(double&,double)", ves_icall_System_Threading_Thread_VolatileWrite8},
6429         {"VolatileWrite(int&,int)", ves_icall_System_Threading_Thread_VolatileWrite4},
6430         {"VolatileWrite(int16&,int16)", ves_icall_System_Threading_Thread_VolatileWrite2},
6431         {"VolatileWrite(intptr&,intptr)", ves_icall_System_Threading_Thread_VolatileWriteIntPtr},
6432         {"VolatileWrite(long&,long)", ves_icall_System_Threading_Thread_VolatileWrite8},
6433         {"VolatileWrite(object&,object)", ves_icall_System_Threading_Thread_VolatileWriteIntPtr},
6434         {"VolatileWrite(sbyte&,sbyte)", ves_icall_System_Threading_Thread_VolatileWrite1},
6435         {"VolatileWrite(single&,single)", ves_icall_System_Threading_Thread_VolatileWrite4},
6436         {"VolatileWrite(uint&,uint)", ves_icall_System_Threading_Thread_VolatileWrite2},
6437         {"VolatileWrite(uint16&,uint16)", ves_icall_System_Threading_Thread_VolatileWrite2},
6438         {"VolatileWrite(uintptr&,uintptr)", ves_icall_System_Threading_Thread_VolatileWriteIntPtr},
6439         {"VolatileWrite(ulong&,ulong)", ves_icall_System_Threading_Thread_VolatileWrite8},
6440         {"current_lcid()", ves_icall_System_Threading_Thread_current_lcid}
6441 };
6442
6443 static const IcallEntry threadpool_icalls [] = {
6444         {"BindHandleInternal", ves_icall_System_Threading_ThreadPool_BindHandle},
6445         {"GetAvailableThreads", ves_icall_System_Threading_ThreadPool_GetAvailableThreads},
6446         {"GetMaxThreads", ves_icall_System_Threading_ThreadPool_GetMaxThreads},
6447         {"GetMinThreads", ves_icall_System_Threading_ThreadPool_GetMinThreads},
6448         {"SetMinThreads", ves_icall_System_Threading_ThreadPool_SetMinThreads}
6449 };
6450
6451 static const IcallEntry waithandle_icalls [] = {
6452         {"WaitAll_internal", ves_icall_System_Threading_WaitHandle_WaitAll_internal},
6453         {"WaitAny_internal", ves_icall_System_Threading_WaitHandle_WaitAny_internal},
6454         {"WaitOne_internal", ves_icall_System_Threading_WaitHandle_WaitOne_internal}
6455 };
6456
6457 static const IcallEntry type_icalls [] = {
6458         {"BindGenericParameters", ves_icall_Type_BindGenericParameters},
6459         {"Equals", ves_icall_type_Equals},
6460         {"GetGenericParameterAttributes", ves_icall_Type_GetGenericParameterAttributes},
6461         {"GetGenericParameterConstraints_impl", ves_icall_Type_GetGenericParameterConstraints},
6462         {"GetGenericParameterPosition", ves_icall_Type_GetGenericParameterPosition},
6463         {"GetGenericTypeDefinition_impl", ves_icall_Type_GetGenericTypeDefinition_impl},
6464         {"GetInterfaceMapData", ves_icall_Type_GetInterfaceMapData},
6465         {"GetPacking", ves_icall_Type_GetPacking},
6466         {"GetTypeCode", ves_icall_type_GetTypeCode},
6467         {"IsArrayImpl", ves_icall_Type_IsArrayImpl},
6468         {"IsInstanceOfType", ves_icall_type_IsInstanceOfType},
6469         {"MakePointerType", ves_icall_Type_MakePointerType},
6470         {"get_IsGenericInstance", ves_icall_Type_get_IsGenericInstance},
6471         {"get_IsGenericTypeDefinition", ves_icall_Type_get_IsGenericTypeDefinition},
6472         {"internal_from_handle", ves_icall_type_from_handle},
6473         {"internal_from_name", ves_icall_type_from_name},
6474         {"make_array_type", ves_icall_Type_make_array_type},
6475         {"make_byref_type", ves_icall_Type_make_byref_type},
6476         {"type_is_assignable_from", ves_icall_type_is_assignable_from},
6477         {"type_is_subtype_of", ves_icall_type_is_subtype_of}
6478 };
6479
6480 static const IcallEntry typedref_icalls [] = {
6481         {"ToObject",    mono_TypedReference_ToObject},
6482         {"ToObjectInternal",    mono_TypedReference_ToObjectInternal}
6483 };
6484
6485 static const IcallEntry valuetype_icalls [] = {
6486         {"InternalEquals", ves_icall_System_ValueType_Equals},
6487         {"InternalGetHashCode", ves_icall_System_ValueType_InternalGetHashCode}
6488 };
6489
6490 static const IcallEntry web_icalls [] = {
6491         {"GetMachineConfigPath", ves_icall_System_Configuration_DefaultConfig_get_machine_config_path},
6492         {"GetMachineInstallDirectory", ves_icall_System_Web_Util_ICalls_get_machine_install_dir}
6493 };
6494
6495 static const IcallEntry identity_icalls [] = {
6496         {"GetCurrentToken", ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken},
6497         {"GetTokenName", ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName},
6498         {"GetUserToken", ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken},
6499         {"_GetRoles", ves_icall_System_Security_Principal_WindowsIdentity_GetRoles}
6500 };
6501
6502 static const IcallEntry impersonation_icalls [] = {
6503         {"CloseToken", ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken},
6504         {"DuplicateToken", ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken},
6505         {"RevertToSelf", ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf},
6506         {"SetCurrentToken", ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken}
6507 };
6508
6509 static const IcallEntry principal_icalls [] = {
6510         {"IsMemberOfGroupId", ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId},
6511         {"IsMemberOfGroupName", ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName}
6512 };
6513
6514 static const IcallEntry keypair_icalls [] = {
6515         {"_CanSecure", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure},
6516         {"_IsMachineProtected", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected},
6517         {"_IsUserProtected", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected},
6518         {"_ProtectMachine", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine},
6519         {"_ProtectUser", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser}
6520 };
6521
6522 static const IcallEntry evidence_icalls [] = {
6523         {"IsAuthenticodePresent", ves_icall_System_Security_Policy_Evidence_IsAuthenticodePresent}
6524 };
6525
6526 static const IcallEntry securitymanager_icalls [] = {
6527         {"get_CheckExecutionRights", ves_icall_System_Security_SecurityManager_get_CheckExecutionRights},
6528         {"get_SecurityEnabled", ves_icall_System_Security_SecurityManager_get_SecurityEnabled},
6529         {"set_CheckExecutionRights", ves_icall_System_Security_SecurityManager_set_CheckExecutionRights},
6530         {"set_SecurityEnabled", ves_icall_System_Security_SecurityManager_set_SecurityEnabled}
6531 };
6532
6533 /* proto
6534 static const IcallEntry array_icalls [] = {
6535 };
6536
6537 */
6538
6539 /* keep the entries all sorted */
6540 static const IcallMap icall_entries [] = {
6541         {"Mono.Security.Cryptography.KeyPairPersistence", keypair_icalls, G_N_ELEMENTS (keypair_icalls)},
6542         {"System.Activator", activator_icalls, G_N_ELEMENTS (activator_icalls)},
6543         {"System.AppDomain", appdomain_icalls, G_N_ELEMENTS (appdomain_icalls)},
6544         {"System.ArgIterator", argiterator_icalls, G_N_ELEMENTS (argiterator_icalls)},
6545         {"System.Array", array_icalls, G_N_ELEMENTS (array_icalls)},
6546         {"System.Buffer", buffer_icalls, G_N_ELEMENTS (buffer_icalls)},
6547         {"System.Char", char_icalls, G_N_ELEMENTS (char_icalls)},
6548         {"System.Configuration.DefaultConfig", defaultconf_icalls, G_N_ELEMENTS (defaultconf_icalls)},
6549         {"System.ConsoleDriver", consoledriver_icalls, G_N_ELEMENTS (consoledriver_icalls)},
6550         {"System.CurrentTimeZone", timezone_icalls, G_N_ELEMENTS (timezone_icalls)},
6551         {"System.DateTime", datetime_icalls, G_N_ELEMENTS (datetime_icalls)},
6552 #ifndef DISABLE_DECIMAL
6553         {"System.Decimal", decimal_icalls, G_N_ELEMENTS (decimal_icalls)},
6554 #endif  
6555         {"System.Delegate", delegate_icalls, G_N_ELEMENTS (delegate_icalls)},
6556         {"System.Diagnostics.DefaultTraceListener", tracelist_icalls, G_N_ELEMENTS (tracelist_icalls)},
6557         {"System.Diagnostics.FileVersionInfo", fileversion_icalls, G_N_ELEMENTS (fileversion_icalls)},
6558         {"System.Diagnostics.Process", process_icalls, G_N_ELEMENTS (process_icalls)},
6559         {"System.Double", double_icalls, G_N_ELEMENTS (double_icalls)},
6560         {"System.Enum", enum_icalls, G_N_ELEMENTS (enum_icalls)},
6561         {"System.Environment", environment_icalls, G_N_ELEMENTS (environment_icalls)},
6562         {"System.GC", gc_icalls, G_N_ELEMENTS (gc_icalls)},
6563         {"System.Globalization.CompareInfo", compareinfo_icalls, G_N_ELEMENTS (compareinfo_icalls)},
6564         {"System.Globalization.CultureInfo", cultureinfo_icalls, G_N_ELEMENTS (cultureinfo_icalls)},
6565         {"System.IO.FAMWatcher", famwatcher_icalls, G_N_ELEMENTS (famwatcher_icalls)},
6566         {"System.IO.FileSystemWatcher", filewatcher_icalls, G_N_ELEMENTS (filewatcher_icalls)},
6567         {"System.IO.MonoIO", monoio_icalls, G_N_ELEMENTS (monoio_icalls)},
6568         {"System.IO.Path", path_icalls, G_N_ELEMENTS (path_icalls)},
6569         {"System.Math", math_icalls, G_N_ELEMENTS (math_icalls)},
6570         {"System.MonoCustomAttrs", customattrs_icalls, G_N_ELEMENTS (customattrs_icalls)},
6571         {"System.MonoEnumInfo", enuminfo_icalls, G_N_ELEMENTS (enuminfo_icalls)},
6572         {"System.MonoType", monotype_icalls, G_N_ELEMENTS (monotype_icalls)},
6573         {"System.Net.Dns", dns_icalls, G_N_ELEMENTS (dns_icalls)},
6574         {"System.Net.Sockets.Socket", socket_icalls, G_N_ELEMENTS (socket_icalls)},
6575         {"System.Net.Sockets.SocketException", socketex_icalls, G_N_ELEMENTS (socketex_icalls)},
6576         {"System.Object", object_icalls, G_N_ELEMENTS (object_icalls)},
6577         {"System.Reflection.Assembly", assembly_icalls, G_N_ELEMENTS (assembly_icalls)},
6578         {"System.Reflection.Emit.AssemblyBuilder", assemblybuilder_icalls, G_N_ELEMENTS (assemblybuilder_icalls)},
6579         {"System.Reflection.Emit.CustomAttributeBuilder", customattrbuilder_icalls, G_N_ELEMENTS (customattrbuilder_icalls)},
6580         {"System.Reflection.Emit.DynamicMethod", dynamicmethod_icalls, G_N_ELEMENTS (dynamicmethod_icalls)},
6581         {"System.Reflection.Emit.EnumBuilder", enumbuilder_icalls, G_N_ELEMENTS (enumbuilder_icalls)},
6582         {"System.Reflection.Emit.GenericTypeParameterBuilder", generictypeparambuilder_icalls, G_N_ELEMENTS (generictypeparambuilder_icalls)},
6583         {"System.Reflection.Emit.MethodBuilder", methodbuilder_icalls, G_N_ELEMENTS (methodbuilder_icalls)},
6584         {"System.Reflection.Emit.ModuleBuilder", modulebuilder_icalls, G_N_ELEMENTS (modulebuilder_icalls)},
6585         {"System.Reflection.Emit.SignatureHelper", signaturehelper_icalls, G_N_ELEMENTS (signaturehelper_icalls)},
6586         {"System.Reflection.Emit.TypeBuilder", typebuilder_icalls, G_N_ELEMENTS (typebuilder_icalls)},
6587         {"System.Reflection.FieldInfo", fieldinfo_icalls, G_N_ELEMENTS (fieldinfo_icalls)},
6588         {"System.Reflection.MemberInfo", memberinfo_icalls, G_N_ELEMENTS (memberinfo_icalls)},
6589         {"System.Reflection.MethodBase", methodbase_icalls, G_N_ELEMENTS (methodbase_icalls)},
6590         {"System.Reflection.Module", module_icalls, G_N_ELEMENTS (module_icalls)},
6591         {"System.Reflection.MonoCMethod", monocmethod_icalls, G_N_ELEMENTS (monocmethod_icalls)},
6592         {"System.Reflection.MonoEventInfo", monoeventinfo_icalls, G_N_ELEMENTS (monoeventinfo_icalls)},
6593         {"System.Reflection.MonoField", monofield_icalls, G_N_ELEMENTS (monofield_icalls)},
6594         {"System.Reflection.MonoGenericCMethod", monogenericmethod_icalls, G_N_ELEMENTS (monogenericmethod_icalls)},
6595         {"System.Reflection.MonoGenericClass", monogenericclass_icalls, G_N_ELEMENTS (monogenericclass_icalls)},
6596         {"System.Reflection.MonoGenericMethod", monogenericmethod_icalls, G_N_ELEMENTS (monogenericmethod_icalls)},
6597         {"System.Reflection.MonoMethod", monomethod_icalls, G_N_ELEMENTS (monomethod_icalls)},
6598         {"System.Reflection.MonoMethodInfo", monomethodinfo_icalls, G_N_ELEMENTS (monomethodinfo_icalls)},
6599         {"System.Reflection.MonoPropertyInfo", monopropertyinfo_icalls, G_N_ELEMENTS (monopropertyinfo_icalls)},
6600         {"System.Reflection.ParameterInfo", parameterinfo_icalls, G_N_ELEMENTS (parameterinfo_icalls)},
6601         {"System.Runtime.CompilerServices.RuntimeHelpers", runtimehelpers_icalls, G_N_ELEMENTS (runtimehelpers_icalls)},
6602         {"System.Runtime.InteropServices.GCHandle", gchandle_icalls, G_N_ELEMENTS (gchandle_icalls)},
6603         {"System.Runtime.InteropServices.Marshal", marshal_icalls, G_N_ELEMENTS (marshal_icalls)},
6604         {"System.Runtime.Remoting.Activation.ActivationServices", activationservices_icalls, G_N_ELEMENTS (activationservices_icalls)},
6605         {"System.Runtime.Remoting.Messaging.MonoMethodMessage", monomethodmessage_icalls, G_N_ELEMENTS (monomethodmessage_icalls)},
6606         {"System.Runtime.Remoting.Proxies.RealProxy", realproxy_icalls, G_N_ELEMENTS (realproxy_icalls)},
6607         {"System.Runtime.Remoting.RemotingServices", remotingservices_icalls, G_N_ELEMENTS (remotingservices_icalls)},
6608         {"System.RuntimeMethodHandle", methodhandle_icalls, G_N_ELEMENTS (methodhandle_icalls)},
6609         {"System.Security.Cryptography.RNGCryptoServiceProvider", rng_icalls, G_N_ELEMENTS (rng_icalls)},
6610         {"System.Security.Policy.Evidence", evidence_icalls, G_N_ELEMENTS (evidence_icalls)},
6611         {"System.Security.Principal.WindowsIdentity", identity_icalls, G_N_ELEMENTS (identity_icalls)},
6612         {"System.Security.Principal.WindowsImpersonationContext", impersonation_icalls, G_N_ELEMENTS (impersonation_icalls)},
6613         {"System.Security.Principal.WindowsPrincipal", principal_icalls, G_N_ELEMENTS (principal_icalls)},
6614         {"System.Security.SecurityManager", securitymanager_icalls, G_N_ELEMENTS (securitymanager_icalls)},
6615         {"System.String", string_icalls, G_N_ELEMENTS (string_icalls)},
6616         {"System.Text.Encoding", encoding_icalls, G_N_ELEMENTS (encoding_icalls)},
6617         {"System.Threading.Interlocked", interlocked_icalls, G_N_ELEMENTS (interlocked_icalls)},
6618         {"System.Threading.Monitor", monitor_icalls, G_N_ELEMENTS (monitor_icalls)},
6619         {"System.Threading.Mutex", mutex_icalls, G_N_ELEMENTS (mutex_icalls)},
6620         {"System.Threading.NativeEventCalls", nativeevents_icalls, G_N_ELEMENTS (nativeevents_icalls)},
6621         {"System.Threading.Thread", thread_icalls, G_N_ELEMENTS (thread_icalls)},
6622         {"System.Threading.ThreadPool", threadpool_icalls, G_N_ELEMENTS (threadpool_icalls)},
6623         {"System.Threading.WaitHandle", waithandle_icalls, G_N_ELEMENTS (waithandle_icalls)},
6624         {"System.Type", type_icalls, G_N_ELEMENTS (type_icalls)},
6625         {"System.TypedReference", typedref_icalls, G_N_ELEMENTS (typedref_icalls)},
6626         {"System.ValueType", valuetype_icalls, G_N_ELEMENTS (valuetype_icalls)},
6627         {"System.Web.Util.ICalls", web_icalls, G_N_ELEMENTS (web_icalls)}
6628 };
6629
6630 static GHashTable *icall_hash = NULL;
6631 static GHashTable *jit_icall_hash_name = NULL;
6632 static GHashTable *jit_icall_hash_addr = NULL;
6633
6634 void
6635 mono_icall_init (void)
6636 {
6637         int i = 0;
6638
6639         /* check that tables are sorted: disable in release */
6640         if (TRUE) {
6641                 int j;
6642                 const IcallMap *imap;
6643                 const IcallEntry *ientry;
6644                 const char *prev_class = NULL;
6645                 const char *prev_method;
6646                 
6647                 for (i = 0; i < G_N_ELEMENTS (icall_entries); ++i) {
6648                         imap = &icall_entries [i];
6649                         prev_method = NULL;
6650                         if (prev_class && strcmp (prev_class, imap->klass) >= 0)
6651                                 g_print ("class %s should come before class %s\n", imap->klass, prev_class);
6652                         prev_class = imap->klass;
6653                         for (j = 0; j < imap->size; ++j) {
6654                                 ientry = &imap->icalls [j];
6655                                 if (prev_method && strcmp (prev_method, ientry->method) >= 0)
6656                                         g_print ("method %s should come before method %s\n", ientry->method, prev_method);
6657                                 prev_method = ientry->method;
6658                         }
6659                 }
6660         }
6661
6662         icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6663 }
6664
6665 void
6666 mono_icall_cleanup (void)
6667 {
6668         g_hash_table_destroy (icall_hash);
6669         g_hash_table_destroy (jit_icall_hash_name);
6670         g_hash_table_destroy (jit_icall_hash_addr);
6671 }
6672
6673 void
6674 mono_add_internal_call (const char *name, gconstpointer method)
6675 {
6676         mono_loader_lock ();
6677
6678         g_hash_table_insert (icall_hash, g_strdup (name), (gpointer) method);
6679
6680         mono_loader_unlock ();
6681 }
6682
6683 static int
6684 compare_class_imap (const void *key, const void *elem)
6685 {
6686         const IcallMap* imap = (const IcallMap*)elem;
6687         return strcmp (key, imap->klass);
6688 }
6689
6690 static const IcallMap*
6691 find_class_icalls (const char *name)
6692 {
6693         return (const IcallMap*) bsearch (name, icall_entries, G_N_ELEMENTS (icall_entries), sizeof (IcallMap), compare_class_imap);
6694 }
6695
6696 static int
6697 compare_method_imap (const void *key, const void *elem)
6698 {
6699         const IcallEntry* ientry = (const IcallEntry*)elem;
6700         return strcmp (key, ientry->method);
6701 }
6702
6703 static void*
6704 find_method_icall (const IcallMap *imap, const char *name)
6705 {
6706         const IcallEntry *ientry = (const IcallEntry*) bsearch (name, imap->icalls, imap->size, sizeof (IcallEntry), compare_method_imap);
6707         if (ientry)
6708                 return (void*)ientry->func;
6709         return NULL;
6710 }
6711
6712 /* 
6713  * we should probably export this as an helper (handle nested types).
6714  * Returns the number of chars written in buf.
6715  */
6716 static int
6717 concat_class_name (char *buf, int bufsize, MonoClass *klass)
6718 {
6719         int nspacelen, cnamelen;
6720         nspacelen = strlen (klass->name_space);
6721         cnamelen = strlen (klass->name);
6722         if (nspacelen + cnamelen + 2 > bufsize)
6723                 return 0;
6724         if (nspacelen) {
6725                 memcpy (buf, klass->name_space, nspacelen);
6726                 buf [nspacelen ++] = '.';
6727         }
6728         memcpy (buf + nspacelen, klass->name, cnamelen);
6729         buf [nspacelen + cnamelen] = 0;
6730         return nspacelen + cnamelen;
6731 }
6732
6733 gpointer
6734 mono_lookup_internal_call (MonoMethod *method)
6735 {
6736         char *sigstart;
6737         char *tmpsig;
6738         char mname [2048];
6739         int typelen = 0, mlen, siglen;
6740         gpointer res;
6741         const IcallMap *imap;
6742
6743         g_assert (method != NULL);
6744
6745         typelen = concat_class_name (mname, sizeof (mname), method->klass);
6746         if (!typelen)
6747                 return NULL;
6748
6749         imap = find_class_icalls (mname);
6750
6751         mname [typelen] = ':';
6752         mname [typelen + 1] = ':';
6753
6754         mlen = strlen (method->name);
6755         memcpy (mname + typelen + 2, method->name, mlen);
6756         sigstart = mname + typelen + 2 + mlen;
6757         *sigstart = 0;
6758
6759         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6760         siglen = strlen (tmpsig);
6761         if (typelen + mlen + siglen + 6 > sizeof (mname))
6762                 return NULL;
6763         sigstart [0] = '(';
6764         memcpy (sigstart + 1, tmpsig, siglen);
6765         sigstart [siglen + 1] = ')';
6766         sigstart [siglen + 2] = 0;
6767         g_free (tmpsig);
6768         
6769         mono_loader_lock ();
6770
6771         res = g_hash_table_lookup (icall_hash, mname);
6772         if (res) {
6773                 mono_loader_unlock ();
6774                 return res;
6775         }
6776         /* try without signature */
6777         *sigstart = 0;
6778         res = g_hash_table_lookup (icall_hash, mname);
6779         if (res) {
6780                 mono_loader_unlock ();
6781                 return res;
6782         }
6783
6784         /* it wasn't found in the static call tables */
6785         if (!imap) {
6786                 mono_loader_unlock ();
6787                 return NULL;
6788         }
6789         res = find_method_icall (imap, sigstart - mlen);
6790         if (res) {
6791                 mono_loader_unlock ();
6792                 return res;
6793         }
6794         /* try _with_ signature */
6795         *sigstart = '(';
6796         res = find_method_icall (imap, sigstart - mlen);
6797         if (res) {
6798                 mono_loader_unlock ();
6799                 return res;
6800         }
6801         
6802         g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
6803         g_print ("\nYour mono runtime and class libraries are out of sync.\n");
6804         g_print ("The out of sync library is: %s\n", method->klass->image->name);
6805         g_print ("\nWhen you update one from cvs you need to update, compile and install\nthe other too.\n");
6806         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");
6807         g_print ("If you see other errors or faults after this message they are probably related\n");
6808         g_print ("and you need to fix your mono install first.\n");
6809
6810         mono_loader_unlock ();
6811
6812         return NULL;
6813 }
6814
6815 static MonoType*
6816 type_from_typename (char *typename)
6817 {
6818         MonoClass *klass = NULL;        /* assignment to shut GCC warning up */
6819
6820         if (!strcmp (typename, "int"))
6821                 klass = mono_defaults.int_class;
6822         else if (!strcmp (typename, "ptr"))
6823                 klass = mono_defaults.int_class;
6824         else if (!strcmp (typename, "void"))
6825                 klass = mono_defaults.void_class;
6826         else if (!strcmp (typename, "int32"))
6827                 klass = mono_defaults.int32_class;
6828         else if (!strcmp (typename, "uint32"))
6829                 klass = mono_defaults.uint32_class;
6830         else if (!strcmp (typename, "long"))
6831                 klass = mono_defaults.int64_class;
6832         else if (!strcmp (typename, "ulong"))
6833                 klass = mono_defaults.uint64_class;
6834         else if (!strcmp (typename, "float"))
6835                 klass = mono_defaults.single_class;
6836         else if (!strcmp (typename, "double"))
6837                 klass = mono_defaults.double_class;
6838         else if (!strcmp (typename, "object"))
6839                 klass = mono_defaults.object_class;
6840         else if (!strcmp (typename, "obj"))
6841                 klass = mono_defaults.object_class;
6842         else {
6843                 g_error (typename);
6844                 g_assert_not_reached ();
6845         }
6846         return &klass->byval_arg;
6847 }
6848
6849 MonoMethodSignature*
6850 mono_create_icall_signature (const char *sigstr)
6851 {
6852         gchar **parts;
6853         int i, len;
6854         gchar **tmp;
6855         MonoMethodSignature *res;
6856
6857         mono_loader_lock ();
6858         res = g_hash_table_lookup (mono_defaults.corlib->helper_signatures, sigstr);
6859         if (res) {
6860                 mono_loader_unlock ();
6861                 return res;
6862         }
6863
6864         parts = g_strsplit (sigstr, " ", 256);
6865
6866         tmp = parts;
6867         len = 0;
6868         while (*tmp) {
6869                 len ++;
6870                 tmp ++;
6871         }
6872
6873         res = mono_metadata_signature_alloc (mono_defaults.corlib, len - 1);
6874         res->pinvoke = 1;
6875
6876 #ifdef PLATFORM_WIN32
6877         /* 
6878          * Under windows, the default pinvoke calling convention is STDCALL but
6879          * we need CDECL.
6880          */
6881         res->call_convention = MONO_CALL_C;
6882 #endif
6883
6884         res->ret = type_from_typename (parts [0]);
6885         for (i = 1; i < len; ++i) {
6886                 res->params [i - 1] = type_from_typename (parts [i]);
6887         }
6888
6889         g_strfreev (parts);
6890
6891         g_hash_table_insert (mono_defaults.corlib->helper_signatures, (gpointer)sigstr, res);
6892
6893         mono_loader_unlock ();
6894
6895         return res;
6896 }
6897
6898 MonoJitICallInfo *
6899 mono_find_jit_icall_by_name (const char *name)
6900 {
6901         MonoJitICallInfo *info;
6902         g_assert (jit_icall_hash_name);
6903
6904         mono_loader_lock ();
6905         info = g_hash_table_lookup (jit_icall_hash_name, name);
6906         mono_loader_unlock ();
6907         return info;
6908 }
6909
6910 MonoJitICallInfo *
6911 mono_find_jit_icall_by_addr (gconstpointer addr)
6912 {
6913         MonoJitICallInfo *info;
6914         g_assert (jit_icall_hash_addr);
6915
6916         mono_loader_lock ();
6917         info = g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
6918         mono_loader_unlock ();
6919
6920         return info;
6921 }
6922
6923 void
6924 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
6925 {
6926         mono_loader_lock ();
6927         g_hash_table_insert (jit_icall_hash_addr, (gpointer)info->wrapper, info);       
6928         mono_loader_unlock ();
6929 }
6930
6931 MonoJitICallInfo *
6932 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
6933 {
6934         MonoJitICallInfo *info;
6935         
6936         g_assert (func);
6937         g_assert (name);
6938
6939         mono_loader_lock ();
6940
6941         if (!jit_icall_hash_name) {
6942                 jit_icall_hash_name = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
6943                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
6944         }
6945
6946         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
6947                 g_warning ("jit icall already defined \"%s\"\n", name);
6948                 g_assert_not_reached ();
6949         }
6950
6951         info = g_new (MonoJitICallInfo, 1);
6952         
6953         info->name = name;
6954         info->func = func;
6955         info->sig = sig;
6956
6957         if (is_save) {
6958                 info->wrapper = func;
6959         } else {
6960                 info->wrapper = NULL;
6961         }
6962
6963         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
6964         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
6965
6966         mono_loader_unlock ();
6967         return info;
6968 }