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