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