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