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