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