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