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