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