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