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