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