Some docs.
[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         MonoAssembly **ptr;
3216         MonoDomain *domain = mono_object_domain (assembly);
3217         int i, count = 0;
3218         static MonoMethod *create_culture = NULL;
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         for (ptr = assembly->assembly->image->references; ptr && *ptr; ptr++)
3227                 count++;
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 = assembly->assembly->image->references [i];
3241                 MonoReflectionAssemblyName *aname;
3242                 char *codebase, *absolute;
3243
3244                 aname = (MonoReflectionAssemblyName *) mono_object_new (
3245                         domain, System_Reflection_AssemblyName);
3246
3247                 aname->name = mono_string_new (domain, assem->aname.name);
3248
3249                 aname->major = assem->aname.major;
3250                 aname->minor = assem->aname.minor;
3251                 aname->build = assem->aname.build;
3252                 aname->revision = assem->aname.revision;
3253                 aname->revision = assem->aname.revision;
3254                 aname->hashalg = assem->aname.hash_alg;
3255                 aname->flags = assem->aname.flags;
3256
3257                 if (create_culture) {
3258                         gpointer args [1];
3259                         args [0] = mono_string_new (domain, assem->aname.culture);
3260                         aname->cultureInfo = mono_runtime_invoke (create_culture, NULL, args, NULL);
3261                 }
3262
3263                 if (assem->aname.public_key) {
3264                         guint32 pkey_len;
3265                         const char *pkey_ptr = assem->aname.public_key;
3266                         pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
3267
3268                         aname->publicKey = mono_array_new (domain, mono_defaults.byte_class, pkey_len);
3269                         memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
3270                 }
3271
3272                 /* public key token isn't copied - the class library will 
3273                    automatically generate it from the public key if required */
3274
3275                 absolute = g_build_filename (assem->basedir, assem->image->module_name, NULL);
3276                 codebase = g_filename_to_uri (absolute, NULL, NULL);
3277                 aname->codebase = mono_string_new (domain, codebase);
3278                 g_free (codebase);
3279                 g_free (absolute);
3280                 mono_array_set (result, gpointer, i, aname);
3281         }
3282         return result;
3283 }
3284
3285 typedef struct {
3286         MonoArray *res;
3287         int idx;
3288 } NameSpaceInfo;
3289
3290 static void
3291 foreach_namespace (const char* key, gconstpointer val, NameSpaceInfo *info)
3292 {
3293         MonoString *name = mono_string_new (mono_object_domain (info->res), key);
3294
3295         mono_array_set (info->res, gpointer, info->idx, name);
3296         info->idx++;
3297 }
3298
3299 static MonoArray*
3300 ves_icall_System_Reflection_Assembly_GetNamespaces (MonoReflectionAssembly *assembly) 
3301 {
3302         MonoImage *img = assembly->assembly->image;
3303         int n;
3304         MonoArray *res;
3305         NameSpaceInfo info;
3306         MonoTableInfo  *t = &img->tables [MONO_TABLE_EXPORTEDTYPE];
3307         int i;
3308
3309         MONO_ARCH_SAVE_REGS;
3310
3311         n = g_hash_table_size (img->name_cache);
3312         res = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, n);
3313         info.res = res;
3314         info.idx = 0;
3315         g_hash_table_foreach (img->name_cache, (GHFunc)foreach_namespace, &info);
3316
3317         /* Add namespaces from the EXPORTEDTYPES table as well */
3318         if (t->rows) {
3319                 MonoArray *res2;
3320                 GPtrArray *nspaces = g_ptr_array_new ();
3321                 for (i = 0; i < t->rows; ++i) {
3322                         const char *nspace = mono_metadata_string_heap (img, mono_metadata_decode_row_col (t, i, MONO_EXP_TYPE_NAMESPACE));
3323                         if (!g_hash_table_lookup (img->name_cache, nspace)) {
3324                                 g_ptr_array_add (nspaces, (char*)nspace);
3325                         }
3326                 }
3327                 if (nspaces->len > 0) {
3328                         res2 = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, n + nspaces->len);
3329                         memcpy (mono_array_addr (res2, MonoString*, 0),
3330                                         mono_array_addr (res, MonoString*, 0),
3331                                         n * sizeof (MonoString*));
3332                         for (i = 0; i < nspaces->len; ++i)
3333                                 mono_array_set (res2, MonoString*, n + i, 
3334                                                                 mono_string_new (mono_object_domain (assembly),
3335                                                                                                  g_ptr_array_index (nspaces, i)));
3336                         res = res2;
3337                 }
3338                 g_ptr_array_free (nspaces, TRUE);
3339         }
3340
3341         return res;
3342 }
3343
3344 /* move this in some file in mono/util/ */
3345 static char *
3346 g_concat_dir_and_file (const char *dir, const char *file)
3347 {
3348         g_return_val_if_fail (dir != NULL, NULL);
3349         g_return_val_if_fail (file != NULL, NULL);
3350
3351         /*
3352          * If the directory name doesn't have a / on the end, we need
3353          * to add one so we get a proper path to the file
3354          */
3355         if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
3356                 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
3357         else
3358                 return g_strconcat (dir, file, NULL);
3359 }
3360
3361 static void *
3362 ves_icall_System_Reflection_Assembly_GetManifestResourceInternal (MonoReflectionAssembly *assembly, MonoString *name, gint32 *size, MonoReflectionModule **ref_module) 
3363 {
3364         char *n = mono_string_to_utf8 (name);
3365         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
3366         guint32 i;
3367         guint32 cols [MONO_MANIFEST_SIZE];
3368         guint32 impl, file_idx;
3369         const char *val;
3370         MonoImage *module;
3371
3372         MONO_ARCH_SAVE_REGS;
3373
3374         for (i = 0; i < table->rows; ++i) {
3375                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
3376                 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
3377                 if (strcmp (val, n) == 0)
3378                         break;
3379         }
3380         g_free (n);
3381         if (i == table->rows)
3382                 return NULL;
3383         /* FIXME */
3384         impl = cols [MONO_MANIFEST_IMPLEMENTATION];
3385         if (impl) {
3386                 /*
3387                  * this code should only be called after obtaining the 
3388                  * ResourceInfo and handling the other cases.
3389                  */
3390                 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
3391                 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
3392
3393                 module = mono_image_load_file_for_image (assembly->assembly->image, file_idx);
3394                 if (!module)
3395                         return NULL;
3396         }
3397         else
3398                 module = assembly->assembly->image;
3399
3400         *ref_module = mono_module_get_object (mono_domain_get (), module);
3401
3402         return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], size);
3403 }
3404
3405 static gboolean
3406 ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoManifestResourceInfo *info)
3407 {
3408         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
3409         int i;
3410         guint32 cols [MONO_MANIFEST_SIZE];
3411         guint32 file_cols [MONO_FILE_SIZE];
3412         const char *val;
3413         char *n;
3414
3415         MONO_ARCH_SAVE_REGS;
3416
3417         n = mono_string_to_utf8 (name);
3418         for (i = 0; i < table->rows; ++i) {
3419                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
3420                 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
3421                 if (strcmp (val, n) == 0)
3422                         break;
3423         }
3424         g_free (n);
3425         if (i == table->rows)
3426                 return FALSE;
3427
3428         if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
3429                 info->location = RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST;
3430         }
3431         else {
3432                 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
3433                 case MONO_IMPLEMENTATION_FILE:
3434                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
3435                         table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
3436                         mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
3437                         val = mono_metadata_string_heap (assembly->assembly->image, file_cols [MONO_FILE_NAME]);
3438                         info->filename = mono_string_new (mono_object_domain (assembly), val);
3439                         if (file_cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA)
3440                                 info->location = 0;
3441                         else
3442                                 info->location = RESOURCE_LOCATION_EMBEDDED;
3443                         break;
3444
3445                 case MONO_IMPLEMENTATION_ASSEMBLYREF:
3446                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
3447                         info->assembly = mono_assembly_get_object (mono_domain_get (), assembly->assembly->image->references [i - 1]);
3448
3449                         /* Obtain info recursively */
3450                         ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (info->assembly, name, info);
3451                         info->location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
3452                         break;
3453
3454                 case MONO_IMPLEMENTATION_EXP_TYPE:
3455                         g_assert_not_reached ();
3456                         break;
3457                 }
3458         }
3459
3460         return TRUE;
3461 }
3462
3463 static MonoObject*
3464 ves_icall_System_Reflection_Assembly_GetFilesInternal (MonoReflectionAssembly *assembly, MonoString *name) 
3465 {
3466         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
3467         MonoArray *result = NULL;
3468         int i;
3469         const char *val;
3470         char *n;
3471
3472         MONO_ARCH_SAVE_REGS;
3473
3474         /* check hash if needed */
3475         if (name) {
3476                 n = mono_string_to_utf8 (name);
3477                 for (i = 0; i < table->rows; ++i) {
3478                         val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
3479                         if (strcmp (val, n) == 0) {
3480                                 MonoString *fn;
3481                                 g_free (n);
3482                                 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
3483                                 fn = mono_string_new (mono_object_domain (assembly), n);
3484                                 g_free (n);
3485                                 return (MonoObject*)fn;
3486                         }
3487                 }
3488                 g_free (n);
3489                 return NULL;
3490         }
3491
3492         for (i = 0; i < table->rows; ++i) {
3493                 result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, table->rows);
3494                 val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
3495                 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
3496                 mono_array_set (result, gpointer, i, mono_string_new (mono_object_domain (assembly), n));
3497                 g_free (n);
3498         }
3499         return (MonoObject*)result;
3500 }
3501
3502 static MonoArray*
3503 ves_icall_System_Reflection_Assembly_GetModulesInternal (MonoReflectionAssembly *assembly)
3504 {
3505         MonoDomain *domain = mono_domain_get();
3506         MonoArray *res;
3507         MonoClass *klass;
3508         int i, module_count = 0, file_count = 0;
3509         MonoImage **modules = assembly->assembly->image->modules;
3510         MonoTableInfo *table;
3511
3512         if (modules) {
3513                 while (modules[module_count])
3514                         ++module_count;
3515         }
3516
3517         table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
3518         file_count = table->rows;
3519
3520         g_assert( assembly->assembly->image != NULL);
3521         ++module_count;
3522
3523         klass = mono_class_from_name ( mono_defaults.corlib, "System.Reflection", "Module");
3524         res = mono_array_new (domain, klass, module_count + file_count);
3525
3526         mono_array_set (res, gpointer, 0, mono_module_get_object (domain, assembly->assembly->image));
3527         for ( i = 1; i < module_count; ++i )
3528                 mono_array_set (res, gpointer, i, mono_module_get_object (domain, modules[i]));
3529
3530         for (i = 0; i < table->rows; ++i)
3531                 mono_array_set (res, gpointer, module_count + i, mono_module_file_get_object (domain, assembly->assembly->image, i));
3532
3533         return res;
3534 }
3535
3536 static MonoReflectionMethod*
3537 ves_icall_GetCurrentMethod (void) 
3538 {
3539         MonoMethod *m = mono_method_get_last_managed ();
3540
3541         MONO_ARCH_SAVE_REGS;
3542
3543         return mono_method_get_object (mono_domain_get (), m, NULL);
3544 }
3545
3546 static MonoReflectionMethod*
3547 ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternal (MonoMethod *method)
3548 {
3549         return mono_method_get_object (mono_domain_get (), method, NULL);
3550 }
3551
3552 static MonoReflectionAssembly*
3553 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (void)
3554 {
3555         MonoMethod *m = mono_method_get_last_managed ();
3556
3557         MONO_ARCH_SAVE_REGS;
3558
3559         return mono_assembly_get_object (mono_domain_get (), m->klass->image->assembly);
3560 }
3561
3562
3563 static gboolean
3564 get_caller (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
3565 {
3566         MonoMethod **dest = data;
3567
3568         /* skip unmanaged frames */
3569         if (!managed)
3570                 return FALSE;
3571
3572         if (m == *dest) {
3573                 *dest = NULL;
3574                 return FALSE;
3575         }
3576         if (!(*dest)) {
3577                 *dest = m;
3578                 return TRUE;
3579         }
3580         return FALSE;
3581 }
3582
3583 static MonoReflectionAssembly*
3584 ves_icall_System_Reflection_Assembly_GetEntryAssembly (void)
3585 {
3586         MonoDomain* domain = mono_domain_get ();
3587
3588         MONO_ARCH_SAVE_REGS;
3589
3590         if (!domain->entry_assembly)
3591                 domain = mono_get_root_domain ();
3592
3593         return mono_assembly_get_object (domain, domain->entry_assembly);
3594 }
3595
3596
3597 static MonoReflectionAssembly*
3598 ves_icall_System_Reflection_Assembly_GetCallingAssembly (void)
3599 {
3600         MonoMethod *m = mono_method_get_last_managed ();
3601         MonoMethod *dest = m;
3602
3603         MONO_ARCH_SAVE_REGS;
3604
3605         mono_stack_walk (get_caller, &dest);
3606         if (!dest)
3607                 dest = m;
3608         return mono_assembly_get_object (mono_domain_get (), dest->klass->image->assembly);
3609 }
3610
3611 static MonoString *
3612 ves_icall_System_MonoType_getFullName (MonoReflectionType *object, gboolean full_name)
3613 {
3614         MonoDomain *domain = mono_object_domain (object); 
3615         MonoString *res;
3616         gchar *name;
3617
3618         MONO_ARCH_SAVE_REGS;
3619
3620         if (full_name)
3621                 name = mono_type_get_full_name (object->type);
3622         else
3623                 name = mono_type_get_name (object->type);
3624         res = mono_string_new (domain, name);
3625         g_free (name);
3626
3627         return res;
3628 }
3629
3630 static void
3631 fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *aname, MonoAssemblyName *name, const char *absolute)
3632 {
3633         static MonoMethod *create_culture = NULL;
3634     gpointer args [1];
3635         guint32 pkey_len;
3636         const char *pkey_ptr;
3637         gchar *codebase;
3638
3639         MONO_ARCH_SAVE_REGS;
3640
3641         aname->name = mono_string_new (domain, name->name);
3642         aname->major = name->major;
3643         aname->minor = name->minor;
3644         aname->build = name->build;
3645         aname->revision = name->revision;
3646         aname->hashalg = name->hash_alg;
3647
3648         codebase = g_filename_to_uri (absolute, NULL, NULL);
3649         if (codebase) {
3650                 aname->codebase = mono_string_new (domain, codebase);
3651                 g_free (codebase);
3652         }
3653
3654         if (!create_culture) {
3655                 MonoMethodDesc *desc = mono_method_desc_new ("System.Globalization.CultureInfo:CreateSpecificCulture(string)", TRUE);
3656                 create_culture = mono_method_desc_search_in_image (desc, mono_defaults.corlib);
3657                 g_assert (create_culture);
3658                 mono_method_desc_free (desc);
3659         }
3660
3661         args [0] = mono_string_new (domain, name->culture);
3662         aname->cultureInfo = 
3663                 mono_runtime_invoke (create_culture, NULL, args, NULL);
3664
3665         if (name->public_key) {
3666                 pkey_ptr = name->public_key;
3667                 pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
3668
3669                 aname->publicKey = mono_array_new (domain, mono_defaults.byte_class, pkey_len);
3670                 memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
3671         }
3672 }
3673
3674 static void
3675 ves_icall_System_Reflection_Assembly_FillName (MonoReflectionAssembly *assembly, MonoReflectionAssemblyName *aname)
3676 {
3677         gchar *absolute;
3678
3679         MONO_ARCH_SAVE_REGS;
3680
3681         absolute = g_build_filename (assembly->assembly->basedir, assembly->assembly->image->module_name, NULL);
3682
3683         fill_reflection_assembly_name (mono_object_domain (assembly), aname, 
3684                                                                    &assembly->assembly->aname, absolute);
3685
3686         g_free (absolute);
3687 }
3688
3689 static void
3690 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoString *fname, MonoReflectionAssemblyName *aname)
3691 {
3692         char *filename;
3693         MonoImageOpenStatus status = MONO_IMAGE_OK;
3694         gboolean res;
3695         MonoImage *image;
3696         MonoAssemblyName name;
3697
3698         MONO_ARCH_SAVE_REGS;
3699
3700         filename = mono_string_to_utf8 (fname);
3701
3702         image = mono_image_open (filename, &status);
3703         
3704         if (!image){
3705                 MonoException *exc;
3706
3707                 g_free (filename);
3708                 exc = mono_get_exception_file_not_found (fname);
3709                 mono_raise_exception (exc);
3710         }
3711
3712         res = mono_assembly_fill_assembly_name (image, &name);
3713         if (!res) {
3714                 mono_image_close (image);
3715                 g_free (filename);
3716                 mono_raise_exception (mono_get_exception_argument ("assemblyFile", "The file does not contain a manifest"));
3717         }
3718
3719         fill_reflection_assembly_name (mono_domain_get (), aname, &name, filename);
3720
3721         g_free (filename);
3722         mono_image_close (image);
3723 }
3724
3725 static MonoArray*
3726 mono_module_get_types (MonoDomain *domain, MonoImage *image, 
3727                                            MonoBoolean exportedOnly)
3728 {
3729         MonoArray *res;
3730         MonoClass *klass;
3731         MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
3732         int i, count;
3733         guint32 attrs, visibility;
3734
3735         /* we start the count from 1 because we skip the special type <Module> */
3736         if (exportedOnly) {
3737                 count = 0;
3738                 for (i = 1; i < tdef->rows; ++i) {
3739                         attrs = mono_metadata_decode_row_col (tdef, i, MONO_TYPEDEF_FLAGS);
3740                         visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
3741                         if (visibility == TYPE_ATTRIBUTE_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_PUBLIC)
3742                                 count++;
3743                 }
3744         } else {
3745                 count = tdef->rows - 1;
3746         }
3747         res = mono_array_new (domain, mono_defaults.monotype_class, count);
3748         count = 0;
3749         for (i = 1; i < tdef->rows; ++i) {
3750                 attrs = mono_metadata_decode_row_col (tdef, i, MONO_TYPEDEF_FLAGS);
3751                 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
3752                 if (!exportedOnly || (visibility == TYPE_ATTRIBUTE_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_PUBLIC)) {
3753                         klass = mono_class_get (image, (i + 1) | MONO_TOKEN_TYPE_DEF);
3754                         mono_array_set (res, gpointer, count, mono_type_get_object (domain, &klass->byval_arg));
3755                         count++;
3756                 }
3757         }
3758         
3759         return res;
3760 }
3761
3762 static MonoArray*
3763 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssembly *assembly, MonoBoolean exportedOnly)
3764 {
3765         MonoArray *res = NULL;
3766         MonoImage *image = NULL;
3767         MonoTableInfo *table = NULL;
3768         MonoDomain *domain;
3769         int i;
3770
3771         MONO_ARCH_SAVE_REGS;
3772
3773         domain = mono_object_domain (assembly);
3774
3775         if (assembly->assembly->dynamic) {
3776                 MonoReflectionAssemblyBuilder *abuilder = (MonoReflectionAssemblyBuilder*)assembly;
3777                 if (abuilder->modules)
3778                         for (i = 0; i < mono_array_length(abuilder->modules); i++) {
3779                                 MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
3780                                 if (res == NULL)
3781                                         res = mb->types;
3782                                 else {
3783                                         MonoArray *append = mb->types;
3784                                         if (mono_array_length (append) > 0) {
3785                                                 guint32 len1, len2;
3786                                                 MonoArray *new;
3787                                                 len1 = mono_array_length (res);
3788                                                 len2 = mono_array_length (append);
3789                                                 new = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
3790                                                 memcpy (mono_array_addr (new, MonoReflectionType*, 0),
3791                                                         mono_array_addr (res, MonoReflectionType*, 0),
3792                                                         len1 * sizeof (MonoReflectionType*));
3793                                                 memcpy (mono_array_addr (new, MonoReflectionType*, len1),
3794                                                         mono_array_addr (append, MonoReflectionType*, 0),
3795                                                         len2 * sizeof (MonoReflectionType*));
3796                                                 res = new;
3797                                         }
3798                                 }
3799                         }
3800                 if (abuilder->loaded_modules)
3801                         for (i = 0; i < mono_array_length(abuilder->loaded_modules); i++) {
3802                                 MonoReflectionModule *rm = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
3803                                 if (res == NULL)
3804                                         res = mono_module_get_types (domain, rm->image, exportedOnly);
3805                                 else {
3806                                         MonoArray *append = mono_module_get_types (domain, rm->image, exportedOnly);
3807                                         if (mono_array_length (append) > 0) {
3808                                                 guint32 len1, len2;
3809                                                 MonoArray *new;
3810                                                 len1 = mono_array_length (res);
3811                                                 len2 = mono_array_length (append);
3812                                                 new = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
3813                                                 memcpy (mono_array_addr (new, MonoReflectionType*, 0),
3814                                                         mono_array_addr (res, MonoReflectionType*, 0),
3815                                                         len1 * sizeof (MonoReflectionType*));
3816                                                 memcpy (mono_array_addr (new, MonoReflectionType*, len1),
3817                                                         mono_array_addr (append, MonoReflectionType*, 0),
3818                                                         len2 * sizeof (MonoReflectionType*));
3819                                                 res = new;
3820                                         }
3821                                 }
3822                         }
3823                 return res;
3824         }
3825         image = assembly->assembly->image;
3826         table = &image->tables [MONO_TABLE_FILE];
3827         res = mono_module_get_types (domain, image, exportedOnly);
3828
3829         /* Append data from all modules in the assembly */
3830         for (i = 0; i < table->rows; ++i) {
3831                 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
3832                         MonoImage *loaded_image = mono_assembly_load_module (image->assembly, i + 1);
3833                         if (loaded_image) {
3834                                 MonoArray *res2 = mono_module_get_types (domain, loaded_image, exportedOnly);
3835                                 /* Append the new types to the end of the array */
3836                                 if (mono_array_length (res2) > 0) {
3837                                         guint32 len1, len2;
3838                                         MonoArray *res3;
3839
3840                                         len1 = mono_array_length (res);
3841                                         len2 = mono_array_length (res2);
3842                                         res3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
3843                                         memcpy (mono_array_addr (res3, MonoReflectionType*, 0),
3844                                                         mono_array_addr (res, MonoReflectionType*, 0),
3845                                                         len1 * sizeof (MonoReflectionType*));
3846                                         memcpy (mono_array_addr (res3, MonoReflectionType*, len1),
3847                                                         mono_array_addr (res2, MonoReflectionType*, 0),
3848                                                         len2 * sizeof (MonoReflectionType*));
3849                                         res = res3;
3850                                 }
3851                         }
3852                 }
3853         }               
3854         return res;
3855 }
3856
3857 static MonoReflectionType*
3858 ves_icall_System_Reflection_Module_GetGlobalType (MonoReflectionModule *module)
3859 {
3860         MonoDomain *domain = mono_object_domain (module); 
3861         MonoClass *klass;
3862
3863         MONO_ARCH_SAVE_REGS;
3864
3865         g_assert (module->image);
3866         klass = mono_class_get (module->image, 1 | MONO_TOKEN_TYPE_DEF);
3867         return mono_type_get_object (domain, &klass->byval_arg);
3868 }
3869
3870 static void
3871 ves_icall_System_Reflection_Module_Close (MonoReflectionModule *module)
3872 {
3873         if (module->image)
3874                 mono_image_close (module->image);
3875 }
3876
3877 static MonoString*
3878 ves_icall_System_Reflection_Module_GetGuidInternal (MonoReflectionModule *module)
3879 {
3880         MonoDomain *domain = mono_object_domain (module); 
3881
3882         MONO_ARCH_SAVE_REGS;
3883
3884         g_assert (module->image);
3885         return mono_string_new (domain, module->image->guid);
3886 }
3887
3888 static MonoArray*
3889 ves_icall_System_Reflection_Module_InternalGetTypes (MonoReflectionModule *module)
3890 {
3891         MONO_ARCH_SAVE_REGS;
3892
3893         if (!module->image)
3894                 return mono_array_new (mono_object_domain (module), mono_defaults.monotype_class, 0);
3895         else
3896                 return mono_module_get_types (mono_object_domain (module), module->image, FALSE);
3897 }
3898
3899 static MonoReflectionType*
3900 ves_icall_ModuleBuilder_create_modified_type (MonoReflectionTypeBuilder *tb, MonoString *smodifiers)
3901 {
3902         MonoClass *klass;
3903         int isbyref = 0, rank;
3904         char *str = mono_string_to_utf8 (smodifiers);
3905         char *p;
3906
3907         MONO_ARCH_SAVE_REGS;
3908
3909         klass = mono_class_from_mono_type (tb->type.type);
3910         p = str;
3911         /* logic taken from mono_reflection_parse_type(): keep in sync */
3912         while (*p) {
3913                 switch (*p) {
3914                 case '&':
3915                         if (isbyref) { /* only one level allowed by the spec */
3916                                 g_free (str);
3917                                 return NULL;
3918                         }
3919                         isbyref = 1;
3920                         p++;
3921                         g_free (str);
3922                         return mono_type_get_object (mono_object_domain (tb), &klass->this_arg);
3923                         break;
3924                 case '*':
3925                         klass = mono_ptr_class_get (&klass->byval_arg);
3926                         mono_class_init (klass);
3927                         p++;
3928                         break;
3929                 case '[':
3930                         rank = 1;
3931                         p++;
3932                         while (*p) {
3933                                 if (*p == ']')
3934                                         break;
3935                                 if (*p == ',')
3936                                         rank++;
3937                                 else if (*p != '*') { /* '*' means unknown lower bound */
3938                                         g_free (str);
3939                                         return NULL;
3940                                 }
3941                                 ++p;
3942                         }
3943                         if (*p != ']') {
3944                                 g_free (str);
3945                                 return NULL;
3946                         }
3947                         p++;
3948                         klass = mono_array_class_get (klass, rank);
3949                         mono_class_init (klass);
3950                         break;
3951                 default:
3952                         break;
3953                 }
3954         }
3955         g_free (str);
3956         return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
3957 }
3958
3959 static MonoBoolean
3960 ves_icall_Type_IsArrayImpl (MonoReflectionType *t)
3961 {
3962         MonoType *type;
3963         MonoBoolean res;
3964
3965         MONO_ARCH_SAVE_REGS;
3966
3967         type = t->type;
3968         res = !type->byref && (type->type == MONO_TYPE_ARRAY || type->type == MONO_TYPE_SZARRAY);
3969
3970         return res;
3971 }
3972
3973 static MonoReflectionType *
3974 ves_icall_Type_make_array_type (MonoReflectionType *type, int rank)
3975 {
3976         MonoClass *klass, *aklass;
3977
3978         MONO_ARCH_SAVE_REGS;
3979
3980         klass = mono_class_from_mono_type (type->type);
3981         aklass = mono_array_class_get (klass, rank);
3982
3983         return mono_type_get_object (mono_object_domain (type), &aklass->byval_arg);
3984 }
3985
3986 static MonoReflectionType *
3987 ves_icall_Type_make_byref_type (MonoReflectionType *type)
3988 {
3989         MonoClass *klass;
3990
3991         MONO_ARCH_SAVE_REGS;
3992
3993         klass = mono_class_from_mono_type (type->type);
3994
3995         return mono_type_get_object (mono_object_domain (type), &klass->this_arg);
3996 }
3997
3998 static MonoObject *
3999 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionType *type, MonoObject *target,
4000                                                    MonoReflectionMethod *info)
4001 {
4002         MonoClass *delegate_class = mono_class_from_mono_type (type->type);
4003         MonoObject *delegate;
4004         gpointer func;
4005
4006         MONO_ARCH_SAVE_REGS;
4007
4008         mono_assert (delegate_class->parent == mono_defaults.multicastdelegate_class);
4009
4010         delegate = mono_object_new (mono_object_domain (type), delegate_class);
4011
4012         func = mono_compile_method (info->method);
4013
4014         mono_delegate_ctor (delegate, target, func);
4015
4016         return delegate;
4017 }
4018
4019 static void
4020 ves_icall_System_Delegate_FreeTrampoline (MonoDelegate *this)
4021 {
4022         mono_delegate_free_ftnptr (this);
4023 }
4024
4025 /*
4026  * Magic number to convert a time which is relative to
4027  * Jan 1, 1970 into a value which is relative to Jan 1, 0001.
4028  */
4029 #define EPOCH_ADJUST    ((guint64)62135596800LL)
4030
4031 /*
4032  * Magic number to convert FILETIME base Jan 1, 1601 to DateTime - base Jan, 1, 0001
4033  */
4034 #define FILETIME_ADJUST ((guint64)504911232000000000LL)
4035
4036 /*
4037  * This returns Now in UTC
4038  */
4039 static gint64
4040 ves_icall_System_DateTime_GetNow (void)
4041 {
4042 #ifdef PLATFORM_WIN32
4043         SYSTEMTIME st;
4044         FILETIME ft;
4045         
4046         GetSystemTime (&st);
4047         SystemTimeToFileTime (&st, &ft);
4048         return (gint64) FILETIME_ADJUST + ((((gint64)ft.dwHighDateTime)<<32) | ft.dwLowDateTime);
4049 #else
4050         /* FIXME: put this in io-layer and call it GetLocalTime */
4051         struct timeval tv;
4052         gint64 res;
4053
4054         MONO_ARCH_SAVE_REGS;
4055
4056         if (gettimeofday (&tv, NULL) == 0) {
4057                 res = (((gint64)tv.tv_sec + EPOCH_ADJUST)* 1000000 + tv.tv_usec)*10;
4058                 return res;
4059         }
4060         /* fixme: raise exception */
4061         return 0;
4062 #endif
4063 }
4064
4065 #ifdef PLATFORM_WIN32
4066 /* convert a SYSTEMTIME which is of the form "last thursday in october" to a real date */
4067 static void
4068 convert_to_absolute_date(SYSTEMTIME *date)
4069 {
4070 #define IS_LEAP(y) ((y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0))
4071         static int days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
4072         static int leap_days_in_month[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
4073         /* from the calendar FAQ */
4074         int a = (14 - date->wMonth) / 12;
4075         int y = date->wYear - a;
4076         int m = date->wMonth + 12 * a - 2;
4077         int d = (1 + y + y/4 - y/100 + y/400 + (31*m)/12) % 7;
4078
4079         /* d is now the day of the week for the first of the month (0 == Sunday) */
4080
4081         int day_of_week = date->wDayOfWeek;
4082
4083         /* set day_in_month to the first day in the month which falls on day_of_week */    
4084         int day_in_month = 1 + (day_of_week - d);
4085         if (day_in_month <= 0)
4086                 day_in_month += 7;
4087
4088         /* wDay is 1 for first weekday in month, 2 for 2nd ... 5 means last - so work that out allowing for days in the month */
4089         date->wDay = day_in_month + (date->wDay - 1) * 7;
4090         if (date->wDay > (IS_LEAP(date->wYear) ? leap_days_in_month[date->wMonth - 1] : days_in_month[date->wMonth - 1]))
4091                 date->wDay -= 7;
4092 }
4093 #endif
4094
4095 #ifndef PLATFORM_WIN32
4096 /*
4097  * Return's the offset from GMT of a local time.
4098  * 
4099  *  tm is a local time
4100  *  t  is the same local time as seconds.
4101  */
4102 static int 
4103 gmt_offset(struct tm *tm, time_t t)
4104 {
4105 #if defined (HAVE_TM_GMTOFF)
4106         return tm->tm_gmtoff;
4107 #else
4108         struct tm g;
4109         time_t t2;
4110         g = *gmtime(&t);
4111         g.tm_isdst = tm->tm_isdst;
4112         t2 = mktime(&g);
4113         return (int)difftime(t, t2);
4114 #endif
4115 }
4116 #endif
4117 /*
4118  * This is heavily based on zdump.c from glibc 2.2.
4119  *
4120  *  * data[0]:  start of daylight saving time (in DateTime ticks).
4121  *  * data[1]:  end of daylight saving time (in DateTime ticks).
4122  *  * data[2]:  utcoffset (in TimeSpan ticks).
4123  *  * data[3]:  additional offset when daylight saving (in TimeSpan ticks).
4124  *  * name[0]:  name of this timezone when not daylight saving.
4125  *  * name[1]:  name of this timezone when daylight saving.
4126  *
4127  *  FIXME: This only works with "standard" Unix dates (years between 1900 and 2100) while
4128  *         the class library allows years between 1 and 9999.
4129  *
4130  *  Returns true on success and zero on failure.
4131  */
4132 static guint32
4133 ves_icall_System_CurrentTimeZone_GetTimeZoneData (guint32 year, MonoArray **data, MonoArray **names)
4134 {
4135 #ifndef PLATFORM_WIN32
4136         MonoDomain *domain = mono_domain_get ();
4137         struct tm start, tt;
4138         time_t t;
4139
4140         long int gmtoff;
4141         int is_daylight = 0, day;
4142         char tzone [64];
4143
4144         MONO_ARCH_SAVE_REGS;
4145
4146         MONO_CHECK_ARG_NULL (data);
4147         MONO_CHECK_ARG_NULL (names);
4148
4149         (*data) = mono_array_new (domain, mono_defaults.int64_class, 4);
4150         (*names) = mono_array_new (domain, mono_defaults.string_class, 2);
4151
4152         /* 
4153          * no info is better than crashing: we'll need our own tz data to make 
4154          * this work properly, anyway. The range is reduced to 1970 .. 2037 because
4155          * that is what mktime is guaranteed to support (we get into an infinite loop 
4156          * otherwise).
4157          */
4158         if ((year < 1970) || (year > 2037)) {
4159                 t = time (NULL);
4160                 tt = *localtime (&t);
4161                 strftime (tzone, sizeof (tzone), "%Z", &tt);
4162                 mono_array_set ((*names), gpointer, 0, mono_string_new (domain, tzone));
4163                 mono_array_set ((*names), gpointer, 1, mono_string_new (domain, tzone));
4164                 return 1;
4165         }
4166
4167         memset (&start, 0, sizeof (start));
4168
4169         start.tm_mday = 1;
4170         start.tm_year = year-1900;
4171
4172         t = mktime (&start);
4173         gmtoff = gmt_offset (&start, t);
4174
4175         /* For each day of the year, calculate the tm_gmtoff. */
4176         for (day = 0; day < 365; day++) {
4177
4178                 t += 3600*24;
4179                 tt = *localtime (&t);
4180
4181                 /* Daylight saving starts or ends here. */
4182                 if (gmt_offset (&tt, t) != gmtoff) {
4183                         struct tm tt1;
4184                         time_t t1;
4185
4186                         /* Try to find the exact hour when daylight saving starts/ends. */
4187                         t1 = t;
4188                         do {
4189                                 t1 -= 3600;
4190                                 tt1 = *localtime (&t1);
4191                         } while (gmt_offset (&tt1, t1) != gmtoff);
4192
4193                         /* Try to find the exact minute when daylight saving starts/ends. */
4194                         do {
4195                                 t1 += 60;
4196                                 tt1 = *localtime (&t1);
4197                         } while (gmt_offset (&tt1, t1) == gmtoff);
4198                         t1+=gmtoff;
4199                         strftime (tzone, sizeof (tzone), "%Z", &tt);
4200                         
4201                         /* Write data, if we're already in daylight saving, we're done. */
4202                         if (is_daylight) {
4203                                 mono_array_set ((*names), gpointer, 0, mono_string_new (domain, tzone));
4204                                 mono_array_set ((*data), gint64, 1, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
4205                                 return 1;
4206                         } else {
4207                                 mono_array_set ((*names), gpointer, 1, mono_string_new (domain, tzone));
4208                                 mono_array_set ((*data), gint64, 0, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
4209                                 is_daylight = 1;
4210                         }
4211
4212                         /* This is only set once when we enter daylight saving. */
4213                         mono_array_set ((*data), gint64, 2, (gint64)gmtoff * 10000000L);
4214                         mono_array_set ((*data), gint64, 3, (gint64)(gmt_offset (&tt, t) - gmtoff) * 10000000L);
4215
4216                         gmtoff = gmt_offset (&tt, t);
4217                 }
4218         }
4219
4220         if (!is_daylight) {
4221                 strftime (tzone, sizeof (tzone), "%Z", &tt);
4222                 mono_array_set ((*names), gpointer, 0, mono_string_new (domain, tzone));
4223                 mono_array_set ((*names), gpointer, 1, mono_string_new (domain, tzone));
4224                 mono_array_set ((*data), gint64, 0, 0);
4225                 mono_array_set ((*data), gint64, 1, 0);
4226                 mono_array_set ((*data), gint64, 2, (gint64) gmtoff * 10000000L);
4227                 mono_array_set ((*data), gint64, 3, 0);
4228         }
4229
4230         return 1;
4231 #else
4232         MonoDomain *domain = mono_domain_get ();
4233         TIME_ZONE_INFORMATION tz_info;
4234         FILETIME ft;
4235         int i;
4236         int err, tz_id;
4237
4238         tz_id = GetTimeZoneInformation (&tz_info);
4239         if (tz_id == TIME_ZONE_ID_INVALID)
4240                 return 0;
4241
4242         MONO_CHECK_ARG_NULL (data);
4243         MONO_CHECK_ARG_NULL (names);
4244
4245         (*data) = mono_array_new (domain, mono_defaults.int64_class, 4);
4246         (*names) = mono_array_new (domain, mono_defaults.string_class, 2);
4247
4248         for (i = 0; i < 32; ++i)
4249                 if (!tz_info.DaylightName [i])
4250                         break;
4251         mono_array_set ((*names), gpointer, 1, mono_string_new_utf16 (domain, tz_info.DaylightName, i));
4252         for (i = 0; i < 32; ++i)
4253                 if (!tz_info.StandardName [i])
4254                         break;
4255         mono_array_set ((*names), gpointer, 0, mono_string_new_utf16 (domain, tz_info.StandardName, i));
4256
4257         if ((year <= 1601) || (year > 30827)) {
4258                 /*
4259                  * According to MSDN, the MS time functions can't handle dates outside
4260                  * this interval.
4261                  */
4262                 return 1;
4263         }
4264
4265         /* even if the timezone has no daylight savings it may have Bias (e.g. GMT+13 it seems) */
4266         if (tz_id != TIME_ZONE_ID_UNKNOWN) {
4267                 tz_info.StandardDate.wYear = year;
4268                 convert_to_absolute_date(&tz_info.StandardDate);
4269                 err = SystemTimeToFileTime (&tz_info.StandardDate, &ft);
4270                 g_assert(err);
4271                 mono_array_set ((*data), gint64, 1, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
4272                 tz_info.DaylightDate.wYear = year;
4273                 convert_to_absolute_date(&tz_info.DaylightDate);
4274                 err = SystemTimeToFileTime (&tz_info.DaylightDate, &ft);
4275                 g_assert(err);
4276                 mono_array_set ((*data), gint64, 0, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
4277         }
4278         mono_array_set ((*data), gint64, 2, (tz_info.Bias + tz_info.StandardBias) * -600000000LL);
4279         mono_array_set ((*data), gint64, 3, (tz_info.DaylightBias - tz_info.StandardBias) * -600000000LL);
4280
4281         return 1;
4282 #endif
4283 }
4284
4285 static gpointer
4286 ves_icall_System_Object_obj_address (MonoObject *this) 
4287 {
4288         MONO_ARCH_SAVE_REGS;
4289
4290         return this;
4291 }
4292
4293 /* System.Buffer */
4294
4295 static inline gint32 
4296 mono_array_get_byte_length (MonoArray *array)
4297 {
4298         MonoClass *klass;
4299         int length;
4300         int i;
4301
4302         klass = array->obj.vtable->klass;
4303
4304         if (array->bounds == NULL)
4305                 length = array->max_length;
4306         else {
4307                 length = 1;
4308                 for (i = 0; i < klass->rank; ++ i)
4309                         length *= array->bounds [i].length;
4310         }
4311
4312         switch (klass->element_class->byval_arg.type) {
4313         case MONO_TYPE_I1:
4314         case MONO_TYPE_U1:
4315         case MONO_TYPE_BOOLEAN:
4316                 return length;
4317         case MONO_TYPE_I2:
4318         case MONO_TYPE_U2:
4319         case MONO_TYPE_CHAR:
4320                 return length << 1;
4321         case MONO_TYPE_I4:
4322         case MONO_TYPE_U4:
4323         case MONO_TYPE_R4:
4324                 return length << 2;
4325         case MONO_TYPE_I:
4326         case MONO_TYPE_U:
4327                 return length * sizeof (gpointer);
4328         case MONO_TYPE_I8:
4329         case MONO_TYPE_U8:
4330         case MONO_TYPE_R8:
4331                 return length << 3;
4332         default:
4333                 return -1;
4334         }
4335 }
4336
4337 static gint32 
4338 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array) 
4339 {
4340         MONO_ARCH_SAVE_REGS;
4341
4342         return mono_array_get_byte_length (array);
4343 }
4344
4345 static gint8 
4346 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx) 
4347 {
4348         MONO_ARCH_SAVE_REGS;
4349
4350         return mono_array_get (array, gint8, idx);
4351 }
4352
4353 static void 
4354 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value) 
4355 {
4356         MONO_ARCH_SAVE_REGS;
4357
4358         mono_array_set (array, gint8, idx, value);
4359 }
4360
4361 static MonoBoolean
4362 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count) 
4363 {
4364         char *src_buf, *dest_buf;
4365
4366         MONO_ARCH_SAVE_REGS;
4367
4368         /* watch out for integer overflow */
4369         if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
4370                 return FALSE;
4371
4372         src_buf = (gint8 *)src->vector + src_offset;
4373         dest_buf = (gint8 *)dest->vector + dest_offset;
4374
4375         memcpy (dest_buf, src_buf, count);
4376
4377         return TRUE;
4378 }
4379
4380 static MonoObject *
4381 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObject *this, MonoString *class_name)
4382 {
4383         MonoDomain *domain = mono_object_domain (this); 
4384         MonoObject *res;
4385         MonoRealProxy *rp = ((MonoRealProxy *)this);
4386         MonoTransparentProxy *tp;
4387         MonoType *type;
4388         MonoClass *klass;
4389
4390         MONO_ARCH_SAVE_REGS;
4391
4392         res = mono_object_new (domain, mono_defaults.transparent_proxy_class);
4393         tp = (MonoTransparentProxy*) res;
4394         
4395         tp->rp = rp;
4396         type = ((MonoReflectionType *)rp->class_to_proxy)->type;
4397         klass = mono_class_from_mono_type (type);
4398
4399         tp->custom_type_info = (mono_object_isinst (this, mono_defaults.iremotingtypeinfo_class) != NULL);
4400         tp->remote_class = mono_remote_class (domain, class_name, klass);
4401         res->vtable = tp->remote_class->vtable;
4402
4403         return res;
4404 }
4405
4406 static MonoReflectionType *
4407 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
4408 {
4409         return mono_type_get_object (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg);
4410 }
4411
4412 /* System.Environment */
4413
4414 static MonoString *
4415 ves_icall_System_Environment_get_MachineName (void)
4416 {
4417 #if defined (PLATFORM_WIN32)
4418         gunichar2 *buf;
4419         guint32 len;
4420         MonoString *result;
4421
4422         len = MAX_COMPUTERNAME_LENGTH + 1;
4423         buf = g_new (gunichar2, len);
4424
4425         result = NULL;
4426         if (GetComputerName (buf, (PDWORD) &len))
4427                 result = mono_string_new_utf16 (mono_domain_get (), buf, len);
4428
4429         g_free (buf);
4430         return result;
4431 #else
4432         gchar *buf;
4433         int len;
4434         MonoString *result;
4435
4436         MONO_ARCH_SAVE_REGS;
4437
4438         len = 256;
4439         buf = g_new (gchar, len);
4440
4441         result = NULL;
4442         if (gethostname (buf, len) == 0)
4443                 result = mono_string_new (mono_domain_get (), buf);
4444         
4445         g_free (buf);
4446         return result;
4447 #endif
4448 }
4449
4450 static int
4451 ves_icall_System_Environment_get_Platform (void)
4452 {
4453         MONO_ARCH_SAVE_REGS;
4454
4455 #if defined (PLATFORM_WIN32)
4456         /* Win32NT */
4457         return 2;
4458 #else
4459         /* Unix */
4460         return 128;
4461 #endif
4462 }
4463
4464 static MonoString *
4465 ves_icall_System_Environment_get_NewLine (void)
4466 {
4467         MONO_ARCH_SAVE_REGS;
4468
4469 #if defined (PLATFORM_WIN32)
4470         return mono_string_new (mono_domain_get (), "\r\n");
4471 #else
4472         return mono_string_new (mono_domain_get (), "\n");
4473 #endif
4474 }
4475
4476 static MonoString *
4477 ves_icall_System_Environment_GetEnvironmentVariable (MonoString *name)
4478 {
4479         const gchar *value;
4480         gchar *utf8_name;
4481
4482         MONO_ARCH_SAVE_REGS;
4483
4484         if (name == NULL)
4485                 return NULL;
4486
4487         utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
4488         value = g_getenv (utf8_name);
4489         g_free (utf8_name);
4490
4491         if (value == 0)
4492                 return NULL;
4493         
4494         return mono_string_new (mono_domain_get (), value);
4495 }
4496
4497 /*
4498  * There is no standard way to get at environ.
4499  */
4500 #ifndef _MSC_VER
4501 extern
4502 #endif
4503 char **environ;
4504
4505 static MonoArray *
4506 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
4507 {
4508         MonoArray *names;
4509         MonoDomain *domain;
4510         MonoString *str;
4511         gchar **e, **parts;
4512         int n;
4513
4514         MONO_ARCH_SAVE_REGS;
4515
4516         n = 0;
4517         for (e = environ; *e != 0; ++ e)
4518                 ++ n;
4519
4520         domain = mono_domain_get ();
4521         names = mono_array_new (domain, mono_defaults.string_class, n);
4522
4523         n = 0;
4524         for (e = environ; *e != 0; ++ e) {
4525                 parts = g_strsplit (*e, "=", 2);
4526                 if (*parts != 0) {
4527                         str = mono_string_new (domain, *parts);
4528                         mono_array_set (names, MonoString *, n, str);
4529                 }
4530
4531                 g_strfreev (parts);
4532
4533                 ++ n;
4534         }
4535
4536         return names;
4537 }
4538
4539 /*
4540  * Returns the number of milliseconds elapsed since the system started.
4541  */
4542 static gint32
4543 ves_icall_System_Environment_get_TickCount (void)
4544 {
4545 #if defined (PLATFORM_WIN32)
4546         return GetTickCount();
4547 #else
4548         struct timeval tv;
4549         struct timezone tz;
4550         gint32 res;
4551
4552         MONO_ARCH_SAVE_REGS;
4553
4554         res = (gint32) gettimeofday (&tv, &tz);
4555
4556         if (res != -1)
4557                 res = (gint32) ((tv.tv_sec & 0xFFFFF) * 1000 + (tv.tv_usec / 1000));
4558         return res;
4559 #endif
4560 }
4561
4562
4563 static void
4564 ves_icall_System_Environment_Exit (int result)
4565 {
4566         MONO_ARCH_SAVE_REGS;
4567
4568         mono_runtime_quit ();
4569
4570         /* we may need to do some cleanup here... */
4571         exit (result);
4572 }
4573
4574 static MonoString*
4575 ves_icall_System_Environment_GetGacPath (void)
4576 {
4577         return mono_string_new (mono_domain_get (), mono_assembly_getrootdir ());
4578 }
4579
4580 static MonoString*
4581 ves_icall_System_Environment_GetWindowsFolderPath (int folder)
4582 {
4583 #if defined (PLATFORM_WIN32)
4584         #ifndef CSIDL_FLAG_CREATE
4585                 #define CSIDL_FLAG_CREATE       0x8000
4586         #endif
4587
4588         WCHAR path [MAX_PATH];
4589         /* Create directory if no existing */
4590         if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
4591                 int len = 0;
4592                 while (path [len])
4593                         ++ len;
4594                 return mono_string_new_utf16 (mono_domain_get (), path, len);
4595         }
4596 #else
4597         g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
4598 #endif
4599         return mono_string_new (mono_domain_get (), "");
4600 }
4601
4602 static MonoArray *
4603 ves_icall_System_Environment_GetLogicalDrives (void)
4604 {
4605         gunichar2 buf [128], *ptr, *dname;
4606         gchar *u8;
4607         gint initial_size = 127, size = 128;
4608         gint ndrives;
4609         MonoArray *result;
4610         MonoString *drivestr;
4611         MonoDomain *domain = mono_domain_get ();
4612
4613         MONO_ARCH_SAVE_REGS;
4614
4615         buf [0] = '\0';
4616         ptr = buf;
4617
4618         while (size > initial_size) {
4619                 size = GetLogicalDriveStrings (initial_size, ptr);
4620                 if (size > initial_size) {
4621                         if (ptr != buf)
4622                                 g_free (ptr);
4623                         ptr = g_malloc0 ((size + 1) * sizeof (gunichar2));
4624                         initial_size = size;
4625                         size++;
4626                 }
4627         }
4628
4629         /* Count strings */
4630         dname = ptr;
4631         ndrives = 0;
4632         do {
4633                 while (*dname++);
4634                 ndrives++;
4635         } while (*dname);
4636
4637         dname = ptr;
4638         result = mono_array_new (domain, mono_defaults.string_class, ndrives);
4639         ndrives = 0;
4640         do {
4641                 u8 = g_utf16_to_utf8 (dname, -1, NULL, NULL, NULL);
4642                 drivestr = mono_string_new (domain, u8);
4643                 g_free (u8);
4644                 mono_array_set (result, gpointer, ndrives++, drivestr);
4645                 while (*dname++);
4646         } while (*dname);
4647
4648         if (ptr != buf)
4649                 g_free (ptr);
4650
4651         return result;
4652 }
4653
4654 static MonoString *
4655 ves_icall_System_Environment_InternalGetHome (void)
4656 {
4657         MONO_ARCH_SAVE_REGS;
4658
4659         return mono_string_new (mono_domain_get (), g_get_home_dir ());
4660 }
4661
4662 static const char *encodings [] = {
4663         (char *) 1,
4664                 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
4665                 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
4666                 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
4667         (char *) 2,
4668                 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
4669                 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
4670                 "x_unicode_2_0_utf_7",
4671         (char *) 3,
4672                 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
4673                 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
4674         (char *) 4,
4675                 "utf_16", "UTF_16LE", "ucs_2", "unicode",
4676                 "iso_10646_ucs2",
4677         (char *) 5,
4678                 "unicodefffe", "utf_16be",
4679         (char *) 6,
4680                 "iso_8859_1",
4681         (char *) 0
4682 };
4683
4684 /*
4685  * Returns the internal codepage, if the value of "int_code_page" is
4686  * 1 at entry, and we can not compute a suitable code page number,
4687  * returns the code page as a string
4688  */
4689 static MonoString*
4690 ves_icall_System_Text_Encoding_InternalCodePage (gint32 *int_code_page) 
4691 {
4692         const char *cset;
4693         const char *p;
4694         char *c;
4695         char *codepage = NULL;
4696         int code;
4697         int want_name = *int_code_page;
4698         int i;
4699         
4700         *int_code_page = -1;
4701         MONO_ARCH_SAVE_REGS;
4702
4703         g_get_charset (&cset);
4704         c = codepage = strdup (cset);
4705         for (c = codepage; *c; c++){
4706                 if (isascii (*c) && isalpha (*c))
4707                         *c = tolower (*c);
4708                 if (*c == '-')
4709                         *c = '_';
4710         }
4711         /* g_print ("charset: %s\n", cset); */
4712         
4713         /* handle some common aliases */
4714         p = encodings [0];
4715         code = 0;
4716         for (i = 0; p != 0; ){
4717                 if ((int) p < 7){
4718                         code = (int) p;
4719                         p = encodings [++i];
4720                         continue;
4721                 }
4722                 if (strcmp (p, codepage) == 0){
4723                         *int_code_page = code;
4724                         break;
4725                 }
4726                 p = encodings [++i];
4727         }
4728         
4729         if (strstr (codepage, "utf_8") != NULL)
4730                 *int_code_page |= 0x10000000;
4731         free (codepage);
4732         
4733         if (want_name && *int_code_page == -1)
4734                 return mono_string_new (mono_domain_get (), cset);
4735         else
4736                 return NULL;
4737 }
4738
4739 static MonoBoolean
4740 ves_icall_System_Environment_get_HasShutdownStarted (void)
4741 {
4742         if (mono_runtime_is_shutting_down ())
4743                 return TRUE;
4744
4745         if (mono_domain_is_unloading (mono_domain_get ()))
4746                 return TRUE;
4747
4748         return FALSE;
4749 }
4750
4751 static void
4752 ves_icall_MonoMethodMessage_InitMessage (MonoMethodMessage *this, 
4753                                          MonoReflectionMethod *method,
4754                                          MonoArray *out_args)
4755 {
4756         MONO_ARCH_SAVE_REGS;
4757
4758         mono_message_init (mono_object_domain (this), this, method, out_args);
4759 }
4760
4761 static MonoBoolean
4762 ves_icall_IsTransparentProxy (MonoObject *proxy)
4763 {
4764         MONO_ARCH_SAVE_REGS;
4765
4766         if (!proxy)
4767                 return 0;
4768
4769         if (proxy->vtable->klass == mono_defaults.transparent_proxy_class)
4770                 return 1;
4771
4772         return 0;
4773 }
4774
4775 static void
4776 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
4777 {
4778         MonoClass *klass;
4779         MonoVTable* vtable;
4780
4781         MONO_ARCH_SAVE_REGS;
4782
4783         klass = mono_class_from_mono_type (type->type);
4784         vtable = mono_class_vtable (mono_domain_get (), klass);
4785
4786         if (enable) vtable->remote = 1;
4787         else vtable->remote = 0;
4788 }
4789
4790 static MonoObject *
4791 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionType *type)
4792 {
4793         MonoClass *klass;
4794         MonoDomain *domain;
4795         
4796         MONO_ARCH_SAVE_REGS;
4797
4798         domain = mono_object_domain (type);
4799         klass = mono_class_from_mono_type (type->type);
4800
4801         if (klass->rank >= 1) {
4802                 g_assert (klass->rank == 1);
4803                 return (MonoObject *) mono_array_new (domain, klass->element_class, 0);
4804         } else {
4805                 /* Bypass remoting object creation check */
4806                 return mono_object_new_alloc_specific (mono_class_vtable (domain, klass));
4807         }
4808 }
4809
4810 static MonoString *
4811 ves_icall_System_IO_get_temp_path (void)
4812 {
4813         MONO_ARCH_SAVE_REGS;
4814
4815         return mono_string_new (mono_domain_get (), g_get_tmp_dir ());
4816 }
4817
4818 static gpointer
4819 ves_icall_RuntimeMethod_GetFunctionPointer (MonoMethod *method)
4820 {
4821         MONO_ARCH_SAVE_REGS;
4822
4823         return mono_compile_method (method);
4824 }
4825
4826 static MonoString *
4827 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
4828 {
4829         MonoString *mcpath;
4830         gchar *path;
4831
4832         MONO_ARCH_SAVE_REGS;
4833
4834         path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_framework_version (), "machine.config", NULL);
4835
4836 #if defined (PLATFORM_WIN32)
4837         /* Avoid mixing '/' and '\\' */
4838         {
4839                 gint i;
4840                 for (i = strlen (path) - 1; i >= 0; i--)
4841                         if (path [i] == '/')
4842                                 path [i] = '\\';
4843         }
4844 #endif
4845         mcpath = mono_string_new (mono_domain_get (), path);
4846         g_free (path);
4847
4848         return mcpath;
4849 }
4850
4851 static MonoString *
4852 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
4853 {
4854         MonoString *ipath;
4855         gchar *path;
4856
4857         MONO_ARCH_SAVE_REGS;
4858
4859         path = g_path_get_dirname (mono_get_config_dir ());
4860
4861 #if defined (PLATFORM_WIN32)
4862         /* Avoid mixing '/' and '\\' */
4863         {
4864                 gint i;
4865                 for (i = strlen (path) - 1; i >= 0; i--)
4866                         if (path [i] == '/')
4867                                 path [i] = '\\';
4868         }
4869 #endif
4870         ipath = mono_string_new (mono_domain_get (), path);
4871         g_free (path);
4872
4873         return ipath;
4874 }
4875
4876 static void
4877 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
4878 {
4879 #if defined (PLATFORM_WIN32)
4880         static void (*output_debug) (gchar *);
4881         static gboolean tried_loading = FALSE;
4882
4883         MONO_ARCH_SAVE_REGS;
4884
4885         if (!tried_loading && output_debug == NULL) {
4886                 GModule *k32;
4887
4888                 tried_loading = TRUE;
4889                 k32 = g_module_open ("kernel32", G_MODULE_BIND_LAZY);
4890                 if (!k32) {
4891                         gchar *error = g_strdup (g_module_error ());
4892                         g_warning ("Failed to load kernel32.dll: %s\n", error);
4893                         g_free (error);
4894                         return;
4895                 }
4896
4897                 g_module_symbol (k32, "OutputDebugStringW", (gpointer *) &output_debug);
4898                 if (!output_debug) {
4899                         gchar *error = g_strdup (g_module_error ());
4900                         g_warning ("Failed to load OutputDebugStringW: %s\n", error);
4901                         g_free (error);
4902                         return;
4903                 }
4904         }
4905
4906         if (output_debug == NULL)
4907                 return;
4908         
4909         output_debug (mono_string_chars (message));
4910 #else
4911         g_warning ("WriteWindowsDebugString called and PLATFORM_WIN32 not defined!\n");
4912 #endif
4913 }
4914
4915 /* Only used for value types */
4916 static MonoObject *
4917 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionType *type)
4918 {
4919         MonoClass *klass;
4920         MonoDomain *domain;
4921         
4922         MONO_ARCH_SAVE_REGS;
4923
4924         domain = mono_object_domain (type);
4925         klass = mono_class_from_mono_type (type->type);
4926
4927         return mono_object_new (domain, klass);
4928 }
4929
4930 static MonoReflectionMethod *
4931 ves_icall_MonoMethod_get_base_definition (MonoReflectionMethod *m)
4932 {
4933         MonoClass *klass;
4934         MonoMethod *method = m->method;
4935         MonoMethod *result = NULL;
4936
4937         MONO_ARCH_SAVE_REGS;
4938
4939         if (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
4940             MONO_CLASS_IS_INTERFACE (method->klass) ||
4941             method->flags & METHOD_ATTRIBUTE_NEW_SLOT)
4942                 return m;
4943
4944         if (method->klass == NULL || (klass = method->klass->parent) == NULL)
4945                 return m;
4946
4947         if (klass->generic_inst)
4948                 klass = mono_class_from_mono_type (klass->generic_inst->generic_type);
4949
4950         while (result == NULL && klass != NULL && (klass->vtable_size > method->slot))
4951         {
4952                 result = klass->vtable [method->slot];
4953                 if (result == NULL) {
4954                         /* It is an abstract method */
4955                         int i;
4956                         for (i=0; i<klass->method.count; i++) {
4957                                 if (klass->methods [i]->slot == method->slot) {
4958                                         result = klass->methods [i];
4959                                         break;
4960                                 }
4961                         }
4962                 }
4963                 klass = klass->parent;
4964         }
4965
4966         if (result == NULL)
4967                 return m;
4968
4969         return mono_method_get_object (mono_domain_get (), result, NULL);
4970 }
4971
4972 static void
4973 mono_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
4974 {
4975         MONO_ARCH_SAVE_REGS;
4976
4977         iter->sig = *(MonoMethodSignature**)argsp;
4978         
4979         g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
4980         g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
4981
4982         iter->next_arg = 0;
4983         /* FIXME: it's not documented what start is exactly... */
4984         if (start) {
4985                 iter->args = start;
4986         } else {
4987                 int i, align, arg_size;
4988                 iter->args = argsp + sizeof (gpointer);
4989                 for (i = 0; i < iter->sig->sentinelpos; ++i) {
4990                         arg_size = mono_type_stack_size (iter->sig->params [i], &align);
4991                         iter->args = (char*)iter->args + arg_size;
4992                 }
4993         }
4994         iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
4995
4996         /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
4997 }
4998
4999 static MonoTypedRef
5000 mono_ArgIterator_IntGetNextArg (MonoArgIterator *iter)
5001 {
5002         gint i, align, arg_size;
5003         MonoTypedRef res;
5004         MONO_ARCH_SAVE_REGS;
5005
5006         i = iter->sig->sentinelpos + iter->next_arg;
5007
5008         g_assert (i < iter->sig->param_count);
5009
5010         res.type = iter->sig->params [i];
5011         res.klass = mono_class_from_mono_type (res.type);
5012         /* FIXME: endianess issue... */
5013         res.value = iter->args;
5014         arg_size = mono_type_stack_size (res.type, &align);
5015         iter->args = (char*)iter->args + arg_size;
5016         iter->next_arg++;
5017
5018         /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
5019
5020         return res;
5021 }
5022
5023 static MonoTypedRef
5024 mono_ArgIterator_IntGetNextArgT (MonoArgIterator *iter, MonoType *type)
5025 {
5026         gint i, align, arg_size;
5027         MonoTypedRef res;
5028         MONO_ARCH_SAVE_REGS;
5029
5030         i = iter->sig->sentinelpos + iter->next_arg;
5031
5032         g_assert (i < iter->sig->param_count);
5033
5034         while (i < iter->sig->param_count) {
5035                 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
5036                         continue;
5037                 res.type = iter->sig->params [i];
5038                 res.klass = mono_class_from_mono_type (res.type);
5039                 /* FIXME: endianess issue... */
5040                 res.value = iter->args;
5041                 arg_size = mono_type_stack_size (res.type, &align);
5042                 iter->args = (char*)iter->args + arg_size;
5043                 iter->next_arg++;
5044                 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
5045                 return res;
5046         }
5047         /* g_print ("arg type 0x%02x not found\n", res.type->type); */
5048
5049         res.type = NULL;
5050         res.value = NULL;
5051         res.klass = NULL;
5052         return res;
5053 }
5054
5055 static MonoType*
5056 mono_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
5057 {
5058         gint i;
5059         MONO_ARCH_SAVE_REGS;
5060         
5061         i = iter->sig->sentinelpos + iter->next_arg;
5062
5063         g_assert (i < iter->sig->param_count);
5064
5065         return iter->sig->params [i];
5066 }
5067
5068 static MonoObject*
5069 mono_TypedReference_ToObject (MonoTypedRef tref)
5070 {
5071         MONO_ARCH_SAVE_REGS;
5072
5073         if (MONO_TYPE_IS_REFERENCE (tref.type)) {
5074                 MonoObject** objp = tref.value;
5075                 return *objp;
5076         }
5077
5078         return mono_value_box (mono_domain_get (), tref.klass, tref.value);
5079 }
5080
5081 static void
5082 prelink_method (MonoMethod *method)
5083 {
5084         const char *exc_class, *exc_arg;
5085         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5086                 return;
5087         mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
5088         if (exc_class) {
5089                 mono_raise_exception( 
5090                         mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg ) );
5091         }
5092         /* create the wrapper, too? */
5093 }
5094
5095 static void
5096 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethod *method)
5097 {
5098         MONO_ARCH_SAVE_REGS;
5099         prelink_method (method->method);
5100 }
5101
5102 static void
5103 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionType *type)
5104 {
5105         MonoClass *klass = mono_class_from_mono_type (type->type);
5106         int i;
5107         MONO_ARCH_SAVE_REGS;
5108
5109         mono_class_init (klass);
5110         for (i = 0; i < klass->method.count; ++i)
5111                 prelink_method (klass->methods [i]);
5112 }
5113
5114 /* These parameters are "readonly" in corlib/System/Char.cs */
5115 static void
5116 ves_icall_System_Char_GetDataTablePointers (guint8 const **category_data,
5117                                             guint8 const **numeric_data,
5118                                             gdouble const **numeric_data_values,
5119                                             guint16 const **to_lower_data_low,
5120                                             guint16 const **to_lower_data_high,
5121                                             guint16 const **to_upper_data_low,
5122                                             guint16 const **to_upper_data_high)
5123 {
5124         *category_data = CategoryData;
5125         *numeric_data = NumericData;
5126         *numeric_data_values = NumericDataValues;
5127         *to_lower_data_low = ToLowerDataLow;
5128         *to_lower_data_high = ToLowerDataHigh;
5129         *to_upper_data_low = ToUpperDataLow;
5130         *to_upper_data_high = ToUpperDataHigh;
5131 }
5132
5133 /* icall map */
5134 typedef struct {
5135         const char *method;
5136         gconstpointer func;
5137 } IcallEntry;
5138
5139 typedef struct {
5140         const char *klass;
5141         const IcallEntry *icalls;
5142         const int size;
5143 } IcallMap;
5144
5145 static const IcallEntry activator_icalls [] = {
5146         {"CreateInstanceInternal", ves_icall_System_Activator_CreateInstanceInternal}
5147 };
5148 static const IcallEntry appdomain_icalls [] = {
5149         {"ExecuteAssembly", ves_icall_System_AppDomain_ExecuteAssembly},
5150         {"GetAssemblies", ves_icall_System_AppDomain_GetAssemblies},
5151         {"GetData", ves_icall_System_AppDomain_GetData},
5152         {"InternalGetContext", ves_icall_System_AppDomain_InternalGetContext},
5153         {"InternalGetDefaultContext", ves_icall_System_AppDomain_InternalGetDefaultContext},
5154         {"InternalGetProcessGuid", ves_icall_System_AppDomain_InternalGetProcessGuid},
5155         {"InternalIsFinalizingForUnload", ves_icall_System_AppDomain_InternalIsFinalizingForUnload},
5156         {"InternalPopDomainRef", ves_icall_System_AppDomain_InternalPopDomainRef},
5157         {"InternalPushDomainRef", ves_icall_System_AppDomain_InternalPushDomainRef},
5158         {"InternalPushDomainRefByID", ves_icall_System_AppDomain_InternalPushDomainRefByID},
5159         {"InternalSetContext", ves_icall_System_AppDomain_InternalSetContext},
5160         {"InternalSetDomain", ves_icall_System_AppDomain_InternalSetDomain},
5161         {"InternalSetDomainByID", ves_icall_System_AppDomain_InternalSetDomainByID},
5162         {"InternalUnload", ves_icall_System_AppDomain_InternalUnload},
5163         {"LoadAssembly", ves_icall_System_AppDomain_LoadAssembly},
5164         {"LoadAssemblyRaw", ves_icall_System_AppDomain_LoadAssemblyRaw},
5165         {"SetData", ves_icall_System_AppDomain_SetData},
5166         {"createDomain", ves_icall_System_AppDomain_createDomain},
5167         {"getCurDomain", ves_icall_System_AppDomain_getCurDomain},
5168         {"getDomainByID", ves_icall_System_AppDomain_getDomainByID},
5169         {"getFriendlyName", ves_icall_System_AppDomain_getFriendlyName},
5170         {"getSetup", ves_icall_System_AppDomain_getSetup}
5171 };
5172
5173 static const IcallEntry argiterator_icalls [] = {
5174         {"IntGetNextArg()",                  mono_ArgIterator_IntGetNextArg},
5175         {"IntGetNextArg(intptr)", mono_ArgIterator_IntGetNextArgT},
5176         {"IntGetNextArgType",                mono_ArgIterator_IntGetNextArgType},
5177         {"Setup",                            mono_ArgIterator_Setup}
5178 };
5179
5180 static const IcallEntry array_icalls [] = {
5181         {"ClearInternal",    ves_icall_System_Array_ClearInternal},
5182         {"Clone",            mono_array_clone},
5183         {"CreateInstanceImpl",   ves_icall_System_Array_CreateInstanceImpl},
5184         {"FastCopy",         ves_icall_System_Array_FastCopy},
5185         {"GetLength",        ves_icall_System_Array_GetLength},
5186         {"GetLowerBound",    ves_icall_System_Array_GetLowerBound},
5187         {"GetRank",          ves_icall_System_Array_GetRank},
5188         {"GetValue",         ves_icall_System_Array_GetValue},
5189         {"GetValueImpl",     ves_icall_System_Array_GetValueImpl},
5190         {"SetValue",         ves_icall_System_Array_SetValue},
5191         {"SetValueImpl",     ves_icall_System_Array_SetValueImpl}
5192 };
5193
5194 static const IcallEntry buffer_icalls [] = {
5195         {"BlockCopyInternal", ves_icall_System_Buffer_BlockCopyInternal},
5196         {"ByteLengthInternal", ves_icall_System_Buffer_ByteLengthInternal},
5197         {"GetByteInternal", ves_icall_System_Buffer_GetByteInternal},
5198         {"SetByteInternal", ves_icall_System_Buffer_SetByteInternal}
5199 };
5200
5201 static const IcallEntry char_icalls [] = {
5202         {"GetDataTablePointers", ves_icall_System_Char_GetDataTablePointers},
5203         {"InternalToLower(char,System.Globalization.CultureInfo)", ves_icall_System_Char_InternalToLower_Comp},
5204         {"InternalToUpper(char,System.Globalization.CultureInfo)", ves_icall_System_Char_InternalToUpper_Comp}
5205 };
5206
5207 static const IcallEntry defaultconf_icalls [] = {
5208         {"get_machine_config_path", ves_icall_System_Configuration_DefaultConfig_get_machine_config_path}
5209 };
5210
5211 static const IcallEntry timezone_icalls [] = {
5212         {"GetTimeZoneData", ves_icall_System_CurrentTimeZone_GetTimeZoneData}
5213 };
5214
5215 static const IcallEntry datetime_icalls [] = {
5216         {"GetNow", ves_icall_System_DateTime_GetNow}
5217 };
5218
5219 static const IcallEntry decimal_icalls [] = {
5220         {"decimal2Int64", mono_decimal2Int64},
5221         {"decimal2UInt64", mono_decimal2UInt64},
5222         {"decimal2double", mono_decimal2double},
5223         {"decimal2string", mono_decimal2string},
5224         {"decimalCompare", mono_decimalCompare},
5225         {"decimalDiv", mono_decimalDiv},
5226         {"decimalFloorAndTrunc", mono_decimalFloorAndTrunc},
5227         {"decimalIncr", mono_decimalIncr},
5228         {"decimalIntDiv", mono_decimalIntDiv},
5229         {"decimalMult", mono_decimalMult},
5230         {"decimalRound", mono_decimalRound},
5231         {"decimalSetExponent", mono_decimalSetExponent},
5232         {"double2decimal", mono_double2decimal}, /* FIXME: wrong signature. */
5233         {"string2decimal", mono_string2decimal}
5234 };
5235
5236 static const IcallEntry delegate_icalls [] = {
5237         {"CreateDelegate_internal", ves_icall_System_Delegate_CreateDelegate_internal},
5238         {"FreeTrampoline", ves_icall_System_Delegate_FreeTrampoline}
5239 };
5240
5241 static const IcallEntry tracelist_icalls [] = {
5242         {"WriteWindowsDebugString", ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString}
5243 };
5244
5245 static const IcallEntry fileversion_icalls [] = {
5246         {"GetVersionInfo_internal(string)", ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal}
5247 };
5248
5249 static const IcallEntry process_icalls [] = {
5250         {"ExitCode_internal(intptr)", ves_icall_System_Diagnostics_Process_ExitCode_internal},
5251         {"ExitTime_internal(intptr)", ves_icall_System_Diagnostics_Process_ExitTime_internal},
5252         {"GetModules_internal()", ves_icall_System_Diagnostics_Process_GetModules_internal},
5253         {"GetPid_internal()", ves_icall_System_Diagnostics_Process_GetPid_internal},
5254         {"GetProcess_internal(int)", ves_icall_System_Diagnostics_Process_GetProcess_internal},
5255         {"GetProcesses_internal()", ves_icall_System_Diagnostics_Process_GetProcesses_internal},
5256         {"GetWorkingSet_internal(intptr,int&,int&)", ves_icall_System_Diagnostics_Process_GetWorkingSet_internal},
5257         {"Kill_internal", ves_icall_System_Diagnostics_Process_Kill_internal},
5258         {"ProcessName_internal(intptr)", ves_icall_System_Diagnostics_Process_ProcessName_internal},
5259         {"Process_free_internal(intptr)", ves_icall_System_Diagnostics_Process_Process_free_internal},
5260         {"SetWorkingSet_internal(intptr,int,int,bool)", ves_icall_System_Diagnostics_Process_SetWorkingSet_internal},
5261         {"StartTime_internal(intptr)", ves_icall_System_Diagnostics_Process_StartTime_internal},
5262         {"Start_internal(string,string,string,intptr,intptr,intptr,System.Diagnostics.Process/ProcInfo&)", ves_icall_System_Diagnostics_Process_Start_internal},
5263         {"WaitForExit_internal(intptr,int)", ves_icall_System_Diagnostics_Process_WaitForExit_internal}
5264 };
5265
5266 static const IcallEntry double_icalls [] = {
5267         {"AssertEndianity", ves_icall_System_Double_AssertEndianity},
5268         {"ParseImpl",    mono_double_ParseImpl}
5269 };
5270
5271 static const IcallEntry enum_icalls [] = {
5272         {"ToObject", ves_icall_System_Enum_ToObject},
5273         {"get_value", ves_icall_System_Enum_get_value}
5274 };
5275
5276 static const IcallEntry environment_icalls [] = {
5277         {"Exit", ves_icall_System_Environment_Exit},
5278         {"GetCommandLineArgs", mono_runtime_get_main_args},
5279         {"GetEnvironmentVariable", ves_icall_System_Environment_GetEnvironmentVariable},
5280         {"GetEnvironmentVariableNames", ves_icall_System_Environment_GetEnvironmentVariableNames},
5281         {"GetLogicalDrivesInternal", ves_icall_System_Environment_GetLogicalDrives },
5282         {"GetMachineConfigPath", ves_icall_System_Configuration_DefaultConfig_get_machine_config_path},
5283         {"GetOSVersionString", ves_icall_System_Environment_GetOSVersionString},
5284         {"GetWindowsFolderPath", ves_icall_System_Environment_GetWindowsFolderPath},
5285         {"get_ExitCode", mono_environment_exitcode_get},
5286         {"get_HasShutdownStarted", ves_icall_System_Environment_get_HasShutdownStarted},
5287         {"get_MachineName", ves_icall_System_Environment_get_MachineName},
5288         {"get_NewLine", ves_icall_System_Environment_get_NewLine},
5289         {"get_Platform", ves_icall_System_Environment_get_Platform},
5290         {"get_TickCount", ves_icall_System_Environment_get_TickCount},
5291         {"get_UserName", ves_icall_System_Environment_get_UserName},
5292         {"internalGetGacPath", ves_icall_System_Environment_GetGacPath},
5293         {"internalGetHome", ves_icall_System_Environment_InternalGetHome},
5294         {"set_ExitCode", mono_environment_exitcode_set}
5295 };
5296
5297 static const IcallEntry cultureinfo_icalls [] = {
5298         {"construct_compareinfo(object,string)", ves_icall_System_Globalization_CompareInfo_construct_compareinfo},
5299         {"construct_datetime_format", ves_icall_System_Globalization_CultureInfo_construct_datetime_format},
5300         {"construct_internal_locale(string)", ves_icall_System_Globalization_CultureInfo_construct_internal_locale},
5301         {"construct_internal_locale_from_current_locale", ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_current_locale},
5302         {"construct_internal_locale_from_lcid", ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_lcid},
5303         {"construct_internal_locale_from_name", ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_name},
5304         {"construct_internal_locale_from_specific_name", ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_specific_name},
5305         {"construct_number_format", ves_icall_System_Globalization_CultureInfo_construct_number_format},
5306         {"internal_get_cultures", ves_icall_System_Globalization_CultureInfo_internal_get_cultures},
5307         {"internal_is_lcid_neutral", ves_icall_System_Globalization_CultureInfo_internal_is_lcid_neutral}
5308 };
5309
5310 static const IcallEntry compareinfo_icalls [] = {
5311         {"assign_sortkey(object,string,System.Globalization.CompareOptions)", ves_icall_System_Globalization_CompareInfo_assign_sortkey},
5312         {"construct_compareinfo(string)", ves_icall_System_Globalization_CompareInfo_construct_compareinfo},
5313         {"free_internal_collator()", ves_icall_System_Globalization_CompareInfo_free_internal_collator},
5314         {"internal_compare(string,int,int,string,int,int,System.Globalization.CompareOptions)", ves_icall_System_Globalization_CompareInfo_internal_compare},
5315         {"internal_index(string,int,int,char,System.Globalization.CompareOptions,bool)", ves_icall_System_Globalization_CompareInfo_internal_index_char},
5316         {"internal_index(string,int,int,string,System.Globalization.CompareOptions,bool)", ves_icall_System_Globalization_CompareInfo_internal_index}
5317 };
5318
5319 static const IcallEntry gc_icalls [] = {
5320         {"GetTotalMemory", ves_icall_System_GC_GetTotalMemory},
5321         {"InternalCollect", ves_icall_System_GC_InternalCollect},
5322         {"KeepAlive", ves_icall_System_GC_KeepAlive},
5323         {"ReRegisterForFinalize", ves_icall_System_GC_ReRegisterForFinalize},
5324         {"SuppressFinalize", ves_icall_System_GC_SuppressFinalize},
5325         {"WaitForPendingFinalizers", ves_icall_System_GC_WaitForPendingFinalizers}
5326 };
5327
5328 static const IcallEntry famwatcher_icalls [] = {
5329         {"InternalFAMNextEvent", ves_icall_System_IO_FAMW_InternalFAMNextEvent}
5330 };
5331
5332 static const IcallEntry filewatcher_icalls [] = {
5333         {"InternalCloseDirectory", ves_icall_System_IO_FSW_CloseDirectory},
5334         {"InternalOpenDirectory", ves_icall_System_IO_FSW_OpenDirectory},
5335         {"InternalReadDirectoryChanges", ves_icall_System_IO_FSW_ReadDirectoryChanges},
5336         {"InternalSupportsFSW", ves_icall_System_IO_FSW_SupportsFSW}
5337 };
5338
5339 static const IcallEntry path_icalls [] = {
5340         {"get_temp_path", ves_icall_System_IO_get_temp_path}
5341 };
5342
5343 static const IcallEntry monoio_icalls [] = {
5344         {"BeginRead", ves_icall_System_IO_MonoIO_BeginRead },
5345         {"BeginWrite", ves_icall_System_IO_MonoIO_BeginWrite },
5346         {"Close(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Close},
5347         {"CopyFile(string,string,bool,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_CopyFile},
5348         {"CreateDirectory(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_CreateDirectory},
5349         {"CreatePipe(intptr&,intptr&)", ves_icall_System_IO_MonoIO_CreatePipe},
5350         {"DeleteFile(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_DeleteFile},
5351         {"FindClose(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_FindClose},
5352         {"FindFirstFile(string,System.IO.MonoIOStat&,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_FindFirstFile},
5353         {"FindNextFile(intptr,System.IO.MonoIOStat&,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_FindNextFile},
5354         {"Flush(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Flush},
5355         {"GetCurrentDirectory(System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetCurrentDirectory},
5356         {"GetFileAttributes(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetFileAttributes},
5357         {"GetFileStat(string,System.IO.MonoIOStat&,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetFileStat},
5358         {"GetFileType(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetFileType},
5359         {"GetLength(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetLength},
5360         {"GetSupportsAsync", ves_icall_System_IO_MonoIO_GetSupportsAsync},
5361         {"GetTempPath(string&)", ves_icall_System_IO_MonoIO_GetTempPath},
5362         {"Lock(intptr,long,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Lock},
5363         {"MoveFile(string,string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_MoveFile},
5364         {"Open(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,bool,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Open},
5365         {"Read(intptr,byte[],int,int,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Read},
5366         {"RemoveDirectory(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_RemoveDirectory},
5367         {"Seek(intptr,long,System.IO.SeekOrigin,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Seek},
5368         {"SetCurrentDirectory(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetCurrentDirectory},
5369         {"SetFileAttributes(string,System.IO.FileAttributes,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetFileAttributes},
5370         {"SetFileTime(intptr,long,long,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetFileTime},
5371         {"SetLength(intptr,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetLength},
5372         {"Unlock(intptr,long,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Unlock},
5373         {"Write(intptr,byte[],int,int,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Write},
5374         {"get_AltDirectorySeparatorChar", ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar},
5375         {"get_ConsoleError", ves_icall_System_IO_MonoIO_get_ConsoleError},
5376         {"get_ConsoleInput", ves_icall_System_IO_MonoIO_get_ConsoleInput},
5377         {"get_ConsoleOutput", ves_icall_System_IO_MonoIO_get_ConsoleOutput},
5378         {"get_DirectorySeparatorChar", ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar},
5379         {"get_InvalidPathChars", ves_icall_System_IO_MonoIO_get_InvalidPathChars},
5380         {"get_PathSeparator", ves_icall_System_IO_MonoIO_get_PathSeparator},
5381         {"get_VolumeSeparatorChar", ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar}
5382 };
5383
5384 static const IcallEntry math_icalls [] = {
5385         {"Acos", ves_icall_System_Math_Acos},
5386         {"Asin", ves_icall_System_Math_Asin},
5387         {"Atan", ves_icall_System_Math_Atan},
5388         {"Atan2", ves_icall_System_Math_Atan2},
5389         {"Cos", ves_icall_System_Math_Cos},
5390         {"Cosh", ves_icall_System_Math_Cosh},
5391         {"Exp", ves_icall_System_Math_Exp},
5392         {"Floor", ves_icall_System_Math_Floor},
5393         {"Log", ves_icall_System_Math_Log},
5394         {"Log10", ves_icall_System_Math_Log10},
5395         {"Pow", ves_icall_System_Math_Pow},
5396         {"Round", ves_icall_System_Math_Round},
5397         {"Round2", ves_icall_System_Math_Round2},
5398         {"Sin", ves_icall_System_Math_Sin},
5399         {"Sinh", ves_icall_System_Math_Sinh},
5400         {"Sqrt", ves_icall_System_Math_Sqrt},
5401         {"Tan", ves_icall_System_Math_Tan},
5402         {"Tanh", ves_icall_System_Math_Tanh}
5403 };
5404
5405 static const IcallEntry customattrs_icalls [] = {
5406         {"GetCustomAttributes", mono_reflection_get_custom_attrs}
5407 };
5408
5409 static const IcallEntry enuminfo_icalls [] = {
5410         {"get_enum_info", ves_icall_get_enum_info}
5411 };
5412
5413 static const IcallEntry fieldinfo_icalls [] = {
5414         {"internal_from_handle", ves_icall_System_Reflection_FieldInfo_internal_from_handle}
5415 };
5416
5417 static const IcallEntry monotype_icalls [] = {
5418         {"GetArrayRank", ves_icall_MonoType_GetArrayRank},
5419         {"GetConstructors", ves_icall_Type_GetConstructors_internal},
5420         {"GetConstructors_internal", ves_icall_Type_GetConstructors_internal},
5421         {"GetElementType", ves_icall_MonoType_GetElementType},
5422         {"GetEvents_internal", ves_icall_Type_GetEvents_internal},
5423         {"GetField", ves_icall_Type_GetField},
5424         {"GetFields_internal", ves_icall_Type_GetFields_internal},
5425         {"GetGenericArguments", ves_icall_MonoType_GetGenericArguments},
5426         {"GetInterfaces", ves_icall_Type_GetInterfaces},
5427         {"GetMethodsByName", ves_icall_Type_GetMethodsByName},
5428         {"GetNestedType", ves_icall_Type_GetNestedType},
5429         {"GetNestedTypes", ves_icall_Type_GetNestedTypes},
5430         {"GetPropertiesByName", ves_icall_Type_GetPropertiesByName},
5431         {"InternalGetEvent", ves_icall_MonoType_GetEvent},
5432         {"IsByRefImpl", ves_icall_type_isbyref},
5433         {"IsPointerImpl", ves_icall_type_ispointer},
5434         {"IsPrimitiveImpl", ves_icall_type_isprimitive},
5435         {"getFullName", ves_icall_System_MonoType_getFullName},
5436         {"get_Assembly", ves_icall_MonoType_get_Assembly},
5437         {"get_BaseType", ves_icall_get_type_parent},
5438         {"get_DeclaringMethod", ves_icall_MonoType_get_DeclaringMethod},
5439         {"get_DeclaringType", ves_icall_MonoType_get_DeclaringType},
5440         {"get_HasGenericArguments", ves_icall_MonoType_get_HasGenericArguments},
5441         {"get_IsGenericParameter", ves_icall_MonoType_get_IsGenericParameter},
5442         {"get_Module", ves_icall_MonoType_get_Module},
5443         {"get_Name", ves_icall_MonoType_get_Name},
5444         {"get_Namespace", ves_icall_MonoType_get_Namespace},
5445         {"get_UnderlyingSystemType", ves_icall_MonoType_get_UnderlyingSystemType},
5446         {"get_attributes", ves_icall_get_attributes},
5447         {"type_from_obj", mono_type_type_from_obj}
5448 };
5449
5450 static const IcallEntry assembly_icalls [] = {
5451         {"FillName", ves_icall_System_Reflection_Assembly_FillName},
5452         {"GetCallingAssembly", ves_icall_System_Reflection_Assembly_GetCallingAssembly},
5453         {"GetEntryAssembly", ves_icall_System_Reflection_Assembly_GetEntryAssembly},
5454         {"GetExecutingAssembly", ves_icall_System_Reflection_Assembly_GetExecutingAssembly},
5455         {"GetFilesInternal", ves_icall_System_Reflection_Assembly_GetFilesInternal},
5456         {"GetManifestResourceInfoInternal", ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal},
5457         {"GetManifestResourceInternal", ves_icall_System_Reflection_Assembly_GetManifestResourceInternal},
5458         {"GetManifestResourceNames", ves_icall_System_Reflection_Assembly_GetManifestResourceNames},
5459         {"GetModulesInternal", ves_icall_System_Reflection_Assembly_GetModulesInternal},
5460         {"GetNamespaces", ves_icall_System_Reflection_Assembly_GetNamespaces},
5461         {"GetReferencedAssemblies", ves_icall_System_Reflection_Assembly_GetReferencedAssemblies},
5462         {"GetTypes", ves_icall_System_Reflection_Assembly_GetTypes},
5463         {"InternalGetAssemblyName", ves_icall_System_Reflection_Assembly_InternalGetAssemblyName},
5464         {"InternalGetType", ves_icall_System_Reflection_Assembly_InternalGetType},
5465         {"InternalImageRuntimeVersion", ves_icall_System_Reflection_Assembly_InternalImageRuntimeVersion},
5466         {"LoadFrom", ves_icall_System_Reflection_Assembly_LoadFrom},
5467         /*
5468          * Private icalls for the Mono Debugger
5469          */
5470         {"MonoDebugger_GetLocalTypeFromSignature", ves_icall_MonoDebugger_GetLocalTypeFromSignature},
5471         {"MonoDebugger_GetMethod", ves_icall_MonoDebugger_GetMethod},
5472         {"MonoDebugger_GetMethodToken", ves_icall_MonoDebugger_GetMethodToken},
5473         {"MonoDebugger_GetType", ves_icall_MonoDebugger_GetType},
5474         /* normal icalls again */
5475         {"get_EntryPoint", ves_icall_System_Reflection_Assembly_get_EntryPoint},
5476         {"get_code_base", ves_icall_System_Reflection_Assembly_get_code_base},
5477         {"get_global_assembly_cache", ves_icall_System_Reflection_Assembly_get_global_assembly_cache},
5478         {"get_location", ves_icall_System_Reflection_Assembly_get_location},
5479         {"load_with_partial_name", ves_icall_System_Reflection_Assembly_load_with_partial_name}
5480 };
5481
5482 static const IcallEntry methodbase_icalls [] = {
5483         {"GetCurrentMethod", ves_icall_GetCurrentMethod},
5484         {"GetMethodFromHandleInternal", ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternal}
5485 };
5486
5487 static const IcallEntry module_icalls [] = {
5488         {"Close", ves_icall_System_Reflection_Module_Close},
5489         {"GetGlobalType", ves_icall_System_Reflection_Module_GetGlobalType},
5490         {"GetGuidInternal", ves_icall_System_Reflection_Module_GetGuidInternal},
5491         {"InternalGetTypes", ves_icall_System_Reflection_Module_InternalGetTypes}
5492 };
5493
5494 static const IcallEntry monocmethod_icalls [] = {
5495         {"GetGenericMethodDefinition_impl", ves_icall_MonoMethod_GetGenericMethodDefinition},
5496         {"InternalInvoke", ves_icall_InternalInvoke},
5497         {"get_Mono_IsInflatedMethod", ves_icall_MonoMethod_get_Mono_IsInflatedMethod}
5498 };
5499
5500 static const IcallEntry monoeventinfo_icalls [] = {
5501         {"get_event_info", ves_icall_get_event_info}
5502 };
5503
5504 static const IcallEntry monofield_icalls [] = {
5505         {"GetParentType", ves_icall_MonoField_GetParentType},
5506         {"GetValueInternal", ves_icall_MonoField_GetValueInternal},
5507         {"Mono_GetGenericFieldDefinition", ves_icall_MonoField_Mono_GetGenericFieldDefinition},
5508         {"SetValueInternal", ves_icall_FieldInfo_SetValueInternal}
5509 };
5510
5511 static const IcallEntry monogenericinst_icalls [] = {
5512         {"GetConstructors_internal", ves_icall_MonoGenericInst_GetConstructors},
5513         {"GetEvents_internal", ves_icall_MonoGenericInst_GetEvents},
5514         {"GetFields_internal", ves_icall_MonoGenericInst_GetFields},
5515         {"GetInterfaces_internal", ves_icall_MonoGenericInst_GetInterfaces},
5516         {"GetMethods_internal", ves_icall_MonoGenericInst_GetMethods},
5517         {"GetParentType", ves_icall_MonoGenericInst_GetParentType},
5518         {"GetProperties_internal", ves_icall_MonoGenericInst_GetProperties},
5519         {"initialize", mono_reflection_generic_inst_initialize}
5520 };
5521
5522 static const IcallEntry generictypeparambuilder_icalls [] = {
5523         {"initialize", mono_reflection_initialize_generic_parameter}
5524 };
5525
5526 static const IcallEntry monomethod_icalls [] = {
5527         {"BindGenericParameters", mono_reflection_bind_generic_method_parameters},
5528         {"GetGenericArguments", ves_icall_MonoMethod_GetGenericArguments},
5529         {"GetGenericMethodDefinition_impl", ves_icall_MonoMethod_GetGenericMethodDefinition},
5530         {"InternalInvoke", ves_icall_InternalInvoke},
5531         {"get_HasGenericParameters", ves_icall_MonoMethod_get_HasGenericParameters},
5532         {"get_IsGenericMethodDefinition", ves_icall_MonoMethod_get_IsGenericMethodDefinition},
5533         {"get_Mono_IsInflatedMethod", ves_icall_MonoMethod_get_Mono_IsInflatedMethod},
5534         {"get_base_definition", ves_icall_MonoMethod_get_base_definition}
5535 };
5536
5537 static const IcallEntry monomethodinfo_icalls [] = {
5538         {"get_method_info", ves_icall_get_method_info},
5539         {"get_parameter_info", ves_icall_get_parameter_info}
5540 };
5541
5542 static const IcallEntry monopropertyinfo_icalls [] = {
5543         {"get_property_info", ves_icall_get_property_info}
5544 };
5545
5546 static const IcallEntry dns_icalls [] = {
5547         {"GetHostByAddr_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByAddr_internal},
5548         {"GetHostByName_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByName_internal},
5549         {"GetHostName_internal(string&)", ves_icall_System_Net_Dns_GetHostName_internal}
5550 };
5551
5552 static const IcallEntry socket_icalls [] = {
5553         {"Accept_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Accept_internal},
5554         {"AsyncReceiveInternal", ves_icall_System_Net_Sockets_Socket_AsyncReceive},
5555         {"AsyncSendInternal", ves_icall_System_Net_Sockets_Socket_AsyncSend},
5556         {"Available_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Available_internal},
5557         {"Bind_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Bind_internal},
5558         {"Blocking_internal(intptr,bool,int&)", ves_icall_System_Net_Sockets_Socket_Blocking_internal},
5559         {"Close_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Close_internal},
5560         {"Connect_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Connect_internal},
5561         {"GetSocketOption_arr_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,byte[]&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal},
5562         {"GetSocketOption_obj_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal},
5563         {"GetSupportsAsync", ves_icall_System_IO_MonoIO_GetSupportsAsync},
5564         {"Listen_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_Listen_internal},
5565         {"LocalEndPoint_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal},
5566         {"Poll_internal", ves_icall_System_Net_Sockets_Socket_Poll_internal},
5567         {"Receive_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Receive_internal},
5568         {"RecvFrom_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress&,int&)", ves_icall_System_Net_Sockets_Socket_RecvFrom_internal},
5569         {"RemoteEndPoint_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal},
5570         {"Select_internal(System.Net.Sockets.Socket[]&,System.Net.Sockets.Socket[]&,System.Net.Sockets.Socket[]&,int,int&)", ves_icall_System_Net_Sockets_Socket_Select_internal},
5571         {"SendTo_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_SendTo_internal},
5572         {"Send_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Send_internal},
5573         {"SetSocketOption_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object,byte[],int,int&)", ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal},
5574         {"Shutdown_internal(intptr,System.Net.Sockets.SocketShutdown,int&)", ves_icall_System_Net_Sockets_Socket_Shutdown_internal},
5575         {"Socket_internal(System.Net.Sockets.AddressFamily,System.Net.Sockets.SocketType,System.Net.Sockets.ProtocolType,int&)", ves_icall_System_Net_Sockets_Socket_Socket_internal},
5576         {"WSAIoctl(intptr,int,byte[],byte[],int&)", ves_icall_System_Net_Sockets_Socket_WSAIoctl}
5577 };
5578
5579 static const IcallEntry socketex_icalls [] = {
5580         {"WSAGetLastError_internal", ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal}
5581 };
5582
5583 static const IcallEntry object_icalls [] = {
5584         {"GetType", ves_icall_System_Object_GetType},
5585         {"InternalGetHashCode", ves_icall_System_Object_GetHashCode},
5586         {"MemberwiseClone", ves_icall_System_Object_MemberwiseClone},
5587         {"obj_address", ves_icall_System_Object_obj_address}
5588 };
5589
5590 static const IcallEntry assemblybuilder_icalls[] = {
5591         {"InternalAddModule", mono_image_load_module},
5592         {"basic_init", mono_image_basic_init}
5593 };
5594
5595 static const IcallEntry customattrbuilder_icalls [] = {
5596         {"GetBlob", mono_reflection_get_custom_attrs_blob}
5597 };
5598
5599 static const IcallEntry dynamicmethod_icalls [] = {
5600         {"create_dynamic_method", mono_reflection_create_dynamic_method}
5601 };
5602
5603 static const IcallEntry methodbuilder_icalls [] = {
5604         {"BindGenericParameters", mono_reflection_bind_generic_method_parameters}
5605 };
5606
5607 static const IcallEntry modulebuilder_icalls [] = {
5608         {"basic_init", mono_image_module_basic_init},
5609         {"build_metadata", ves_icall_ModuleBuilder_build_metadata},
5610         {"create_modified_type", ves_icall_ModuleBuilder_create_modified_type},
5611         {"getDataChunk", ves_icall_ModuleBuilder_getDataChunk},
5612         {"getMethodToken", ves_icall_ModuleBuilder_getMethodToken},
5613         {"getToken", ves_icall_ModuleBuilder_getToken},
5614         {"getUSIndex", mono_image_insert_string}
5615 };
5616
5617 static const IcallEntry signaturehelper_icalls [] = {
5618         {"get_signature_field", mono_reflection_sighelper_get_signature_field},
5619         {"get_signature_local", mono_reflection_sighelper_get_signature_local}
5620 };
5621
5622 static const IcallEntry typebuilder_icalls [] = {
5623         {"create_internal_class", mono_reflection_create_internal_class},
5624         {"create_runtime_class", mono_reflection_create_runtime_class},
5625         {"get_IsGenericParameter", ves_icall_TypeBuilder_get_IsGenericParameter},
5626         {"get_event_info", mono_reflection_event_builder_get_event_info},
5627         {"setup_generic_class", mono_reflection_setup_generic_class},
5628         {"setup_internal_class", mono_reflection_setup_internal_class}
5629 };
5630
5631 static const IcallEntry enumbuilder_icalls [] = {
5632         {"setup_enum_type", ves_icall_EnumBuilder_setup_enum_type}
5633 };
5634
5635 static const IcallEntry runtimehelpers_icalls [] = {
5636         {"GetObjectValue", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue},
5637          /* REMOVEME: no longer needed, just so we dont break things when not needed */
5638         {"GetOffsetToStringData", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData},
5639         {"InitializeArray", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray},
5640         {"RunClassConstructor", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor},
5641         {"get_OffsetToStringData", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData}
5642 };
5643
5644 static const IcallEntry gchandle_icalls [] = {
5645         {"FreeHandle", ves_icall_System_GCHandle_FreeHandle},
5646         {"GetAddrOfPinnedObject", ves_icall_System_GCHandle_GetAddrOfPinnedObject},
5647         {"GetTarget", ves_icall_System_GCHandle_GetTarget},
5648         {"GetTargetHandle", ves_icall_System_GCHandle_GetTargetHandle}
5649 };
5650
5651 static const IcallEntry marshal_icalls [] = {
5652         {"AllocCoTaskMem", ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem},
5653         {"AllocHGlobal", mono_marshal_alloc},
5654         {"DestroyStructure", ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure},
5655         {"FreeCoTaskMem", ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem},
5656         {"FreeHGlobal", mono_marshal_free},
5657         {"GetLastWin32Error", ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error},
5658         {"OffsetOf", ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf},
5659         {"Prelink", ves_icall_System_Runtime_InteropServices_Marshal_Prelink},
5660         {"PrelinkAll", ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll},
5661         {"PtrToStringAnsi(intptr)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi},
5662         {"PtrToStringAnsi(intptr,int)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len},
5663         {"PtrToStringAuto(intptr)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi},
5664         {"PtrToStringAuto(intptr,int)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len},
5665         {"PtrToStringBSTR", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringBSTR},
5666         {"PtrToStringUni(intptr)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni},
5667         {"PtrToStringUni(intptr,int)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len},
5668         {"PtrToStructure(intptr,System.Type)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type},
5669         {"PtrToStructure(intptr,object)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure},
5670         {"ReAllocHGlobal", mono_marshal_realloc},
5671         {"ReadByte", ves_icall_System_Runtime_InteropServices_Marshal_ReadByte},
5672         {"ReadInt16", ves_icall_System_Runtime_InteropServices_Marshal_ReadInt16},
5673         {"ReadInt32", ves_icall_System_Runtime_InteropServices_Marshal_ReadInt32},
5674         {"ReadInt64", ves_icall_System_Runtime_InteropServices_Marshal_ReadInt64},
5675         {"ReadIntPtr", ves_icall_System_Runtime_InteropServices_Marshal_ReadIntPtr},
5676         {"SizeOf", ves_icall_System_Runtime_InteropServices_Marshal_SizeOf},
5677         {"StringToHGlobalAnsi", ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi},
5678         {"StringToHGlobalAuto", ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi},
5679         {"StringToHGlobalUni", ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni},
5680         {"StructureToPtr", ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr},
5681         {"UnsafeAddrOfPinnedArrayElement", ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement},
5682         {"WriteByte", ves_icall_System_Runtime_InteropServices_Marshal_WriteByte},
5683         {"WriteInt16", ves_icall_System_Runtime_InteropServices_Marshal_WriteInt16},
5684         {"WriteInt32", ves_icall_System_Runtime_InteropServices_Marshal_WriteInt32},
5685         {"WriteInt64", ves_icall_System_Runtime_InteropServices_Marshal_WriteInt64},
5686         {"WriteIntPtr", ves_icall_System_Runtime_InteropServices_Marshal_WriteIntPtr},
5687         {"copy_from_unmanaged", ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged},
5688         {"copy_to_unmanaged", ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged}
5689 };
5690
5691 static const IcallEntry activationservices_icalls [] = {
5692         {"AllocateUninitializedClassInstance", ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance},
5693         {"EnableProxyActivation", ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation}
5694 };
5695
5696 static const IcallEntry monomethodmessage_icalls [] = {
5697         {"InitMessage", ves_icall_MonoMethodMessage_InitMessage}
5698 };
5699         
5700 static const IcallEntry realproxy_icalls [] = {
5701         {"InternalGetProxyType", ves_icall_Remoting_RealProxy_InternalGetProxyType},
5702         {"InternalGetTransparentProxy", ves_icall_Remoting_RealProxy_GetTransparentProxy}
5703 };
5704
5705 static const IcallEntry remotingservices_icalls [] = {
5706         {"InternalExecute", ves_icall_InternalExecute},
5707         {"IsTransparentProxy", ves_icall_IsTransparentProxy}
5708 };
5709
5710 static const IcallEntry rng_icalls [] = {
5711         {"RngClose", ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngClose},
5712         {"RngGetBytes", ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngGetBytes},
5713         {"RngInitialize", ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngInitialize}
5714 };
5715
5716 static const IcallEntry methodhandle_icalls [] = {
5717         {"GetFunctionPointer", ves_icall_RuntimeMethod_GetFunctionPointer}
5718 };
5719
5720 static const IcallEntry string_icalls [] = {
5721         {".ctor(char*)", ves_icall_System_String_ctor_charp},
5722         {".ctor(char*,int,int)", ves_icall_System_String_ctor_charp_int_int},
5723         {".ctor(char,int)", ves_icall_System_String_ctor_char_int},
5724         {".ctor(char[])", ves_icall_System_String_ctor_chara},
5725         {".ctor(char[],int,int)", ves_icall_System_String_ctor_chara_int_int},
5726         {".ctor(sbyte*)", ves_icall_System_String_ctor_sbytep},
5727         {".ctor(sbyte*,int,int)", ves_icall_System_String_ctor_sbytep_int_int},
5728         {".ctor(sbyte*,int,int,System.Text.Encoding)", ves_icall_System_String_ctor_encoding},
5729         {"GetHashCode", ves_icall_System_String_GetHashCode},
5730         {"InternalAllocateStr", ves_icall_System_String_InternalAllocateStr},
5731         {"InternalCharCopy", ves_icall_System_String_InternalCharCopy},
5732         {"InternalCopyTo", ves_icall_System_String_InternalCopyTo},
5733         {"InternalIndexOfAny", ves_icall_System_String_InternalIndexOfAny},
5734         {"InternalInsert", ves_icall_System_String_InternalInsert},
5735         {"InternalIntern", ves_icall_System_String_InternalIntern},
5736         {"InternalIsInterned", ves_icall_System_String_InternalIsInterned},
5737         {"InternalJoin", ves_icall_System_String_InternalJoin},
5738         {"InternalLastIndexOfAny", ves_icall_System_String_InternalLastIndexOfAny},
5739         {"InternalPad", ves_icall_System_String_InternalPad},
5740         {"InternalRemove", ves_icall_System_String_InternalRemove},
5741         {"InternalReplace(char,char)", ves_icall_System_String_InternalReplace_Char},
5742         {"InternalReplace(string,string,System.Globalization.CompareInfo)", ves_icall_System_String_InternalReplace_Str_Comp},
5743         {"InternalSplit", ves_icall_System_String_InternalSplit},
5744         {"InternalStrcpy(string,int,char[])", ves_icall_System_String_InternalStrcpy_Chars},
5745         {"InternalStrcpy(string,int,char[],int,int)", ves_icall_System_String_InternalStrcpy_CharsN},
5746         {"InternalStrcpy(string,int,string)", ves_icall_System_String_InternalStrcpy_Str},
5747         {"InternalStrcpy(string,int,string,int,int)", ves_icall_System_String_InternalStrcpy_StrN},
5748         {"InternalToLower(System.Globalization.CultureInfo)", ves_icall_System_String_InternalToLower_Comp},
5749         {"InternalToUpper(System.Globalization.CultureInfo)", ves_icall_System_String_InternalToUpper_Comp},
5750         {"InternalTrim", ves_icall_System_String_InternalTrim},
5751         {"get_Chars", ves_icall_System_String_get_Chars}
5752 };
5753
5754 static const IcallEntry encoding_icalls [] = {
5755         {"InternalCodePage", ves_icall_System_Text_Encoding_InternalCodePage}
5756 };
5757
5758 static const IcallEntry monitor_icalls [] = {
5759         {"Monitor_exit", ves_icall_System_Threading_Monitor_Monitor_exit},
5760         {"Monitor_pulse", ves_icall_System_Threading_Monitor_Monitor_pulse},
5761         {"Monitor_pulse_all", ves_icall_System_Threading_Monitor_Monitor_pulse_all},
5762         {"Monitor_test_owner", ves_icall_System_Threading_Monitor_Monitor_test_owner},
5763         {"Monitor_test_synchronised", ves_icall_System_Threading_Monitor_Monitor_test_synchronised},
5764         {"Monitor_try_enter", ves_icall_System_Threading_Monitor_Monitor_try_enter},
5765         {"Monitor_wait", ves_icall_System_Threading_Monitor_Monitor_wait}
5766 };
5767
5768 static const IcallEntry interlocked_icalls [] = {
5769         {"CompareExchange(int&,int,int)", ves_icall_System_Threading_Interlocked_CompareExchange_Int},
5770         {"CompareExchange(object&,object,object)", ves_icall_System_Threading_Interlocked_CompareExchange_Object},
5771         {"CompareExchange(single&,single,single)", ves_icall_System_Threading_Interlocked_CompareExchange_Single},
5772         {"Decrement(int&)", ves_icall_System_Threading_Interlocked_Decrement_Int},
5773         {"Decrement(long&)", ves_icall_System_Threading_Interlocked_Decrement_Long},
5774         {"Exchange(int&,int)", ves_icall_System_Threading_Interlocked_Exchange_Int},
5775         {"Exchange(object&,object)", ves_icall_System_Threading_Interlocked_Exchange_Object},
5776         {"Exchange(single&,single)", ves_icall_System_Threading_Interlocked_Exchange_Single},
5777         {"Increment(int&)", ves_icall_System_Threading_Interlocked_Increment_Int},
5778         {"Increment(long&)", ves_icall_System_Threading_Interlocked_Increment_Long}
5779 };
5780
5781 static const IcallEntry mutex_icalls [] = {
5782         {"CreateMutex_internal(bool,string,bool&)", ves_icall_System_Threading_Mutex_CreateMutex_internal},
5783         {"ReleaseMutex_internal(intptr)", ves_icall_System_Threading_Mutex_ReleaseMutex_internal}
5784 };
5785
5786 static const IcallEntry nativeevents_icalls [] = {
5787         {"CloseEvent_internal", ves_icall_System_Threading_Events_CloseEvent_internal},
5788         {"CreateEvent_internal", ves_icall_System_Threading_Events_CreateEvent_internal},
5789         {"ResetEvent_internal",  ves_icall_System_Threading_Events_ResetEvent_internal},
5790         {"SetEvent_internal",    ves_icall_System_Threading_Events_SetEvent_internal}
5791 };
5792
5793 static const IcallEntry thread_icalls [] = {
5794         {"Abort_internal(object)", ves_icall_System_Threading_Thread_Abort},
5795         {"CurrentThread_internal", mono_thread_current},
5796         {"GetDomainID", ves_icall_System_Threading_Thread_GetDomainID},
5797         {"GetName_internal", ves_icall_System_Threading_Thread_GetName_internal},
5798         {"Join_internal", ves_icall_System_Threading_Thread_Join_internal},
5799         {"ResetAbort_internal()", ves_icall_System_Threading_Thread_ResetAbort},
5800         {"Resume_internal()", ves_icall_System_Threading_Thread_Resume},
5801         {"SetName_internal", ves_icall_System_Threading_Thread_SetName_internal},
5802         {"Sleep_internal", ves_icall_System_Threading_Thread_Sleep_internal},
5803         {"SlotHash_lookup", ves_icall_System_Threading_Thread_SlotHash_lookup},
5804         {"SlotHash_store", ves_icall_System_Threading_Thread_SlotHash_store},
5805         {"Start_internal", ves_icall_System_Threading_Thread_Start_internal},
5806         {"Suspend_internal", ves_icall_System_Threading_Thread_Suspend},
5807         {"Thread_free_internal", ves_icall_System_Threading_Thread_Thread_free_internal},
5808         {"Thread_internal", ves_icall_System_Threading_Thread_Thread_internal},
5809         {"VolatileRead(byte&)", ves_icall_System_Threading_Thread_VolatileRead1},
5810         {"VolatileRead(double&)", ves_icall_System_Threading_Thread_VolatileRead8},
5811         {"VolatileRead(int&)", ves_icall_System_Threading_Thread_VolatileRead4},
5812         {"VolatileRead(int16&)", ves_icall_System_Threading_Thread_VolatileRead2},
5813         {"VolatileRead(intptr&)", ves_icall_System_Threading_Thread_VolatileReadIntPtr},
5814         {"VolatileRead(long&)", ves_icall_System_Threading_Thread_VolatileRead8},
5815         {"VolatileRead(object&)", ves_icall_System_Threading_Thread_VolatileReadIntPtr},
5816         {"VolatileRead(sbyte&)", ves_icall_System_Threading_Thread_VolatileRead1},
5817         {"VolatileRead(single&)", ves_icall_System_Threading_Thread_VolatileRead4},
5818         {"VolatileRead(uint&)", ves_icall_System_Threading_Thread_VolatileRead2},
5819         {"VolatileRead(uint16&)", ves_icall_System_Threading_Thread_VolatileRead2},
5820         {"VolatileRead(uintptr&)", ves_icall_System_Threading_Thread_VolatileReadIntPtr},
5821         {"VolatileRead(ulong&)", ves_icall_System_Threading_Thread_VolatileRead8},
5822         {"VolatileWrite(byte&,byte)", ves_icall_System_Threading_Thread_VolatileWrite1},
5823         {"VolatileWrite(double&,double)", ves_icall_System_Threading_Thread_VolatileWrite8},
5824         {"VolatileWrite(int&,int)", ves_icall_System_Threading_Thread_VolatileWrite4},
5825         {"VolatileWrite(int16&,int16)", ves_icall_System_Threading_Thread_VolatileWrite2},
5826         {"VolatileWrite(intptr&,intptr)", ves_icall_System_Threading_Thread_VolatileWriteIntPtr},
5827         {"VolatileWrite(long&,long)", ves_icall_System_Threading_Thread_VolatileWrite8},
5828         {"VolatileWrite(object&,object)", ves_icall_System_Threading_Thread_VolatileWriteIntPtr},
5829         {"VolatileWrite(sbyte&,sbyte)", ves_icall_System_Threading_Thread_VolatileWrite1},
5830         {"VolatileWrite(single&,single)", ves_icall_System_Threading_Thread_VolatileWrite4},
5831         {"VolatileWrite(uint&,uint)", ves_icall_System_Threading_Thread_VolatileWrite2},
5832         {"VolatileWrite(uint16&,uint16)", ves_icall_System_Threading_Thread_VolatileWrite2},
5833         {"VolatileWrite(uintptr&,uintptr)", ves_icall_System_Threading_Thread_VolatileWriteIntPtr},
5834         {"VolatileWrite(ulong&,ulong)", ves_icall_System_Threading_Thread_VolatileWrite8},
5835         {"current_lcid()", ves_icall_System_Threading_Thread_current_lcid}
5836 };
5837
5838 static const IcallEntry threadpool_icalls [] = {
5839         {"BindHandleInternal", ves_icall_System_Threading_ThreadPool_BindHandle},
5840         {"GetAvailableThreads", ves_icall_System_Threading_ThreadPool_GetAvailableThreads},
5841         {"GetMaxThreads", ves_icall_System_Threading_ThreadPool_GetMaxThreads},
5842         {"GetMinThreads", ves_icall_System_Threading_ThreadPool_GetMinThreads},
5843         {"SetMinThreads", ves_icall_System_Threading_ThreadPool_SetMinThreads}
5844 };
5845
5846 static const IcallEntry waithandle_icalls [] = {
5847         {"WaitAll_internal", ves_icall_System_Threading_WaitHandle_WaitAll_internal},
5848         {"WaitAny_internal", ves_icall_System_Threading_WaitHandle_WaitAny_internal},
5849         {"WaitOne_internal", ves_icall_System_Threading_WaitHandle_WaitOne_internal}
5850 };
5851
5852 static const IcallEntry type_icalls [] = {
5853         {"BindGenericParameters", ves_icall_Type_BindGenericParameters},
5854         {"Equals", ves_icall_type_Equals},
5855         {"GetGenericParameterPosition", ves_icall_Type_GetGenericParameterPosition},
5856         {"GetGenericTypeDefinition_impl", ves_icall_Type_GetGenericTypeDefinition_impl},
5857         {"GetInterfaceMapData", ves_icall_Type_GetInterfaceMapData},
5858         {"GetTypeCode", ves_icall_type_GetTypeCode},
5859         {"IsArrayImpl", ves_icall_Type_IsArrayImpl},
5860         {"IsInstanceOfType", ves_icall_type_IsInstanceOfType},
5861         {"get_IsGenericInstance", ves_icall_Type_get_IsGenericInstance},
5862         {"get_IsGenericTypeDefinition", ves_icall_Type_get_IsGenericTypeDefinition},
5863         {"internal_from_handle", ves_icall_type_from_handle},
5864         {"internal_from_name", ves_icall_type_from_name},
5865         {"make_array_type", ves_icall_Type_make_array_type},
5866         {"make_byref_type", ves_icall_Type_make_byref_type},
5867         {"type_is_assignable_from", ves_icall_type_is_assignable_from},
5868         {"type_is_subtype_of", ves_icall_type_is_subtype_of}
5869 };
5870
5871 static const IcallEntry typedref_icalls [] = {
5872         {"ToObject",    mono_TypedReference_ToObject}
5873 };
5874
5875 static const IcallEntry valuetype_icalls [] = {
5876         {"InternalEquals", ves_icall_System_ValueType_Equals},
5877         {"InternalGetHashCode", ves_icall_System_ValueType_InternalGetHashCode}
5878 };
5879
5880 static const IcallEntry web_icalls [] = {
5881         {"GetMachineConfigPath", ves_icall_System_Configuration_DefaultConfig_get_machine_config_path},
5882         {"GetMachineInstallDirectory", ves_icall_System_Web_Util_ICalls_get_machine_install_dir}
5883 };
5884
5885 static const IcallEntry identity_icalls [] = {
5886         {"GetCurrentToken", ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken},
5887         {"GetTokenName", ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName},
5888         {"GetUserToken", ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken},
5889         {"_GetRoles", ves_icall_System_Security_Principal_WindowsIdentity_GetRoles}
5890 };
5891
5892 static const IcallEntry impersonation_icalls [] = {
5893         {"CloseToken", ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken},
5894         {"DuplicateToken", ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken},
5895         {"RevertToSelf", ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf},
5896         {"SetCurrentToken", ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken}
5897 };
5898
5899 static const IcallEntry principal_icalls [] = {
5900         {"IsMemberOfGroupId", ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId},
5901         {"IsMemberOfGroupName", ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName}
5902 };
5903
5904 static const IcallEntry keypair_icalls [] = {
5905         {"_CanSecure", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure},
5906         {"_IsMachineProtected", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected},
5907         {"_IsUserProtected", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected},
5908         {"_ProtectMachine", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine},
5909         {"_ProtectUser", ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser}
5910 };
5911
5912 /* proto
5913 static const IcallEntry array_icalls [] = {
5914 };
5915
5916 */
5917
5918 /* keep the entries all sorted */
5919 static const IcallMap icall_entries [] = {
5920         {"Mono.Security.Cryptography.KeyPairPersistence", keypair_icalls, G_N_ELEMENTS (keypair_icalls)},
5921         {"System.Activator", activator_icalls, G_N_ELEMENTS (activator_icalls)},
5922         {"System.AppDomain", appdomain_icalls, G_N_ELEMENTS (appdomain_icalls)},
5923         {"System.ArgIterator", argiterator_icalls, G_N_ELEMENTS (argiterator_icalls)},
5924         {"System.Array", array_icalls, G_N_ELEMENTS (array_icalls)},
5925         {"System.Buffer", buffer_icalls, G_N_ELEMENTS (buffer_icalls)},
5926         {"System.Char", char_icalls, G_N_ELEMENTS (char_icalls)},
5927         {"System.Configuration.DefaultConfig", defaultconf_icalls, G_N_ELEMENTS (defaultconf_icalls)},
5928         {"System.CurrentTimeZone", timezone_icalls, G_N_ELEMENTS (timezone_icalls)},
5929         {"System.DateTime", datetime_icalls, G_N_ELEMENTS (datetime_icalls)},
5930         {"System.Decimal", decimal_icalls, G_N_ELEMENTS (decimal_icalls)},
5931         {"System.Delegate", delegate_icalls, G_N_ELEMENTS (delegate_icalls)},
5932         {"System.Diagnostics.DefaultTraceListener", tracelist_icalls, G_N_ELEMENTS (tracelist_icalls)},
5933         {"System.Diagnostics.FileVersionInfo", fileversion_icalls, G_N_ELEMENTS (fileversion_icalls)},
5934         {"System.Diagnostics.Process", process_icalls, G_N_ELEMENTS (process_icalls)},
5935         {"System.Double", double_icalls, G_N_ELEMENTS (double_icalls)},
5936         {"System.Enum", enum_icalls, G_N_ELEMENTS (enum_icalls)},
5937         {"System.Environment", environment_icalls, G_N_ELEMENTS (environment_icalls)},
5938         {"System.GC", gc_icalls, G_N_ELEMENTS (gc_icalls)},
5939         {"System.Globalization.CompareInfo", compareinfo_icalls, G_N_ELEMENTS (compareinfo_icalls)},
5940         {"System.Globalization.CultureInfo", cultureinfo_icalls, G_N_ELEMENTS (cultureinfo_icalls)},
5941         {"System.IO.FAMWatcher", famwatcher_icalls, G_N_ELEMENTS (famwatcher_icalls)},
5942         {"System.IO.FileSystemWatcher", filewatcher_icalls, G_N_ELEMENTS (filewatcher_icalls)},
5943         {"System.IO.MonoIO", monoio_icalls, G_N_ELEMENTS (monoio_icalls)},
5944         {"System.IO.Path", path_icalls, G_N_ELEMENTS (path_icalls)},
5945         {"System.Math", math_icalls, G_N_ELEMENTS (math_icalls)},
5946         {"System.MonoCustomAttrs", customattrs_icalls, G_N_ELEMENTS (customattrs_icalls)},
5947         {"System.MonoEnumInfo", enuminfo_icalls, G_N_ELEMENTS (enuminfo_icalls)},
5948         {"System.MonoType", monotype_icalls, G_N_ELEMENTS (monotype_icalls)},
5949         {"System.Net.Dns", dns_icalls, G_N_ELEMENTS (dns_icalls)},
5950         {"System.Net.Sockets.Socket", socket_icalls, G_N_ELEMENTS (socket_icalls)},
5951         {"System.Net.Sockets.SocketException", socketex_icalls, G_N_ELEMENTS (socketex_icalls)},
5952         {"System.Object", object_icalls, G_N_ELEMENTS (object_icalls)},
5953         {"System.Reflection.Assembly", assembly_icalls, G_N_ELEMENTS (assembly_icalls)},
5954         {"System.Reflection.Emit.AssemblyBuilder", assemblybuilder_icalls, G_N_ELEMENTS (assemblybuilder_icalls)},
5955         {"System.Reflection.Emit.CustomAttributeBuilder", customattrbuilder_icalls, G_N_ELEMENTS (customattrbuilder_icalls)},
5956         {"System.Reflection.Emit.DynamicMethod", dynamicmethod_icalls, G_N_ELEMENTS (dynamicmethod_icalls)},
5957         {"System.Reflection.Emit.EnumBuilder", enumbuilder_icalls, G_N_ELEMENTS (enumbuilder_icalls)},
5958         {"System.Reflection.Emit.GenericTypeParameterBuilder", generictypeparambuilder_icalls, G_N_ELEMENTS (generictypeparambuilder_icalls)},
5959         {"System.Reflection.Emit.MethodBuilder", methodbuilder_icalls, G_N_ELEMENTS (methodbuilder_icalls)},
5960         {"System.Reflection.Emit.ModuleBuilder", modulebuilder_icalls, G_N_ELEMENTS (modulebuilder_icalls)},
5961         {"System.Reflection.Emit.SignatureHelper", signaturehelper_icalls, G_N_ELEMENTS (signaturehelper_icalls)},
5962         {"System.Reflection.Emit.TypeBuilder", typebuilder_icalls, G_N_ELEMENTS (typebuilder_icalls)},
5963         {"System.Reflection.FieldInfo", fieldinfo_icalls, G_N_ELEMENTS (fieldinfo_icalls)},
5964         {"System.Reflection.MethodBase", methodbase_icalls, G_N_ELEMENTS (methodbase_icalls)},
5965         {"System.Reflection.Module", module_icalls, G_N_ELEMENTS (module_icalls)},
5966         {"System.Reflection.MonoCMethod", monocmethod_icalls, G_N_ELEMENTS (monocmethod_icalls)},
5967         {"System.Reflection.MonoEventInfo", monoeventinfo_icalls, G_N_ELEMENTS (monoeventinfo_icalls)},
5968         {"System.Reflection.MonoField", monofield_icalls, G_N_ELEMENTS (monofield_icalls)},
5969         {"System.Reflection.MonoGenericInst", monogenericinst_icalls, G_N_ELEMENTS (monogenericinst_icalls)},
5970         {"System.Reflection.MonoMethod", monomethod_icalls, G_N_ELEMENTS (monomethod_icalls)},
5971         {"System.Reflection.MonoMethodInfo", monomethodinfo_icalls, G_N_ELEMENTS (monomethodinfo_icalls)},
5972         {"System.Reflection.MonoPropertyInfo", monopropertyinfo_icalls, G_N_ELEMENTS (monopropertyinfo_icalls)},
5973         {"System.Runtime.CompilerServices.RuntimeHelpers", runtimehelpers_icalls, G_N_ELEMENTS (runtimehelpers_icalls)},
5974         {"System.Runtime.InteropServices.GCHandle", gchandle_icalls, G_N_ELEMENTS (gchandle_icalls)},
5975         {"System.Runtime.InteropServices.Marshal", marshal_icalls, G_N_ELEMENTS (marshal_icalls)},
5976         {"System.Runtime.Remoting.Activation.ActivationServices", activationservices_icalls, G_N_ELEMENTS (activationservices_icalls)},
5977         {"System.Runtime.Remoting.Messaging.MonoMethodMessage", monomethodmessage_icalls, G_N_ELEMENTS (monomethodmessage_icalls)},
5978         {"System.Runtime.Remoting.Proxies.RealProxy", realproxy_icalls, G_N_ELEMENTS (realproxy_icalls)},
5979         {"System.Runtime.Remoting.RemotingServices", remotingservices_icalls, G_N_ELEMENTS (remotingservices_icalls)},
5980         {"System.RuntimeMethodHandle", methodhandle_icalls, G_N_ELEMENTS (methodhandle_icalls)},
5981         {"System.Security.Cryptography.RNGCryptoServiceProvider", rng_icalls, G_N_ELEMENTS (rng_icalls)},
5982         {"System.Security.Principal.WindowsIdentity", identity_icalls, G_N_ELEMENTS (identity_icalls)},
5983         {"System.Security.Principal.WindowsImpersonationContext", impersonation_icalls, G_N_ELEMENTS (impersonation_icalls)},
5984         {"System.Security.Principal.WindowsPrincipal", principal_icalls, G_N_ELEMENTS (principal_icalls)},
5985         {"System.String", string_icalls, G_N_ELEMENTS (string_icalls)},
5986         {"System.Text.Encoding", encoding_icalls, G_N_ELEMENTS (encoding_icalls)},
5987         {"System.Threading.Interlocked", interlocked_icalls, G_N_ELEMENTS (interlocked_icalls)},
5988         {"System.Threading.Monitor", monitor_icalls, G_N_ELEMENTS (monitor_icalls)},
5989         {"System.Threading.Mutex", mutex_icalls, G_N_ELEMENTS (mutex_icalls)},
5990         {"System.Threading.NativeEventCalls", nativeevents_icalls, G_N_ELEMENTS (nativeevents_icalls)},
5991         {"System.Threading.Thread", thread_icalls, G_N_ELEMENTS (thread_icalls)},
5992         {"System.Threading.ThreadPool", threadpool_icalls, G_N_ELEMENTS (threadpool_icalls)},
5993         {"System.Threading.WaitHandle", waithandle_icalls, G_N_ELEMENTS (waithandle_icalls)},
5994         {"System.Type", type_icalls, G_N_ELEMENTS (type_icalls)},
5995         {"System.TypedReference", typedref_icalls, G_N_ELEMENTS (typedref_icalls)},
5996         {"System.ValueType", valuetype_icalls, G_N_ELEMENTS (valuetype_icalls)},
5997         {"System.Web.Util.ICalls", web_icalls, G_N_ELEMENTS (web_icalls)}
5998 };
5999
6000 static GHashTable *icall_hash = NULL;
6001 static GHashTable *jit_icall_hash_name = NULL;
6002 static GHashTable *jit_icall_hash_addr = NULL;
6003
6004 void
6005 mono_init_icall (void)
6006 {
6007         int i = 0;
6008
6009         /* check that tables are sorted: disable in release */
6010         if (TRUE) {
6011                 int j;
6012                 const IcallMap *imap;
6013                 const IcallEntry *ientry;
6014                 const char *prev_class = NULL;
6015                 const char *prev_method;
6016                 
6017                 for (i = 0; i < G_N_ELEMENTS (icall_entries); ++i) {
6018                         imap = &icall_entries [i];
6019                         prev_method = NULL;
6020                         if (prev_class && strcmp (prev_class, imap->klass) >= 0)
6021                                 g_print ("class %s should come before class %s\n", imap->klass, prev_class);
6022                         prev_class = imap->klass;
6023                         for (j = 0; j < imap->size; ++j) {
6024                                 ientry = &imap->icalls [j];
6025                                 if (prev_method && strcmp (prev_method, ientry->method) >= 0)
6026                                         g_print ("method %s should come before method %s\n", ientry->method, prev_method);
6027                                 prev_method = ientry->method;
6028                         }
6029                 }
6030         }
6031
6032         icall_hash = g_hash_table_new (g_str_hash , g_str_equal);
6033 }
6034
6035 void
6036 mono_add_internal_call (const char *name, gconstpointer method)
6037 {
6038         mono_loader_lock ();
6039
6040         g_hash_table_insert (icall_hash, g_strdup (name), (gpointer) method);
6041
6042         mono_loader_unlock ();
6043 }
6044
6045 static int
6046 compare_class_imap (const void *key, const void *elem)
6047 {
6048         const IcallMap* imap = (const IcallMap*)elem;
6049         return strcmp (key, imap->klass);
6050 }
6051
6052 static const IcallMap*
6053 find_class_icalls (const char *name)
6054 {
6055         return (const IcallMap*) bsearch (name, icall_entries, G_N_ELEMENTS (icall_entries), sizeof (IcallMap), compare_class_imap);
6056 }
6057
6058 static int
6059 compare_method_imap (const void *key, const void *elem)
6060 {
6061         const IcallEntry* ientry = (const IcallEntry*)elem;
6062         return strcmp (key, ientry->method);
6063 }
6064
6065 static void*
6066 find_method_icall (const IcallMap *imap, const char *name)
6067 {
6068         const IcallEntry *ientry = (const IcallEntry*) bsearch (name, imap->icalls, imap->size, sizeof (IcallEntry), compare_method_imap);
6069         if (ientry)
6070                 return (void*)ientry->func;
6071         return NULL;
6072 }
6073
6074 /* 
6075  * we should probably export this as an helper (handle nested types).
6076  * Returns the number of chars written in buf.
6077  */
6078 static int
6079 concat_class_name (char *buf, int bufsize, MonoClass *klass)
6080 {
6081         int nspacelen, cnamelen;
6082         nspacelen = strlen (klass->name_space);
6083         cnamelen = strlen (klass->name);
6084         if (nspacelen + cnamelen + 2 > bufsize)
6085                 return 0;
6086         if (nspacelen) {
6087                 memcpy (buf, klass->name_space, nspacelen);
6088                 buf [nspacelen ++] = '.';
6089         }
6090         memcpy (buf + nspacelen, klass->name, cnamelen);
6091         buf [nspacelen + cnamelen] = 0;
6092         return nspacelen + cnamelen;
6093 }
6094
6095 gpointer
6096 mono_lookup_internal_call (MonoMethod *method)
6097 {
6098         char *sigstart;
6099         char *tmpsig;
6100         char mname [2048];
6101         int typelen = 0, mlen, siglen;
6102         gpointer res;
6103         const IcallMap *imap;
6104
6105         g_assert (method != NULL);
6106
6107         typelen = concat_class_name (mname, sizeof (mname), method->klass);
6108         if (!typelen)
6109                 return NULL;
6110
6111         imap = find_class_icalls (mname);
6112
6113         mname [typelen] = ':';
6114         mname [typelen + 1] = ':';
6115
6116         mlen = strlen (method->name);
6117         memcpy (mname + typelen + 2, method->name, mlen);
6118         sigstart = mname + typelen + 2 + mlen;
6119         *sigstart = 0;
6120
6121         tmpsig = mono_signature_get_desc (method->signature, TRUE);
6122         siglen = strlen (tmpsig);
6123         if (typelen + mlen + siglen + 6 > sizeof (mname))
6124                 return NULL;
6125         sigstart [0] = '(';
6126         memcpy (sigstart + 1, tmpsig, siglen);
6127         sigstart [siglen + 1] = ')';
6128         sigstart [siglen + 2] = 0;
6129         g_free (tmpsig);
6130         
6131         mono_loader_lock ();
6132
6133         res = g_hash_table_lookup (icall_hash, mname);
6134         if (res) {
6135                 mono_loader_unlock ();
6136                 return res;
6137         }
6138         /* try without signature */
6139         *sigstart = 0;
6140         res = g_hash_table_lookup (icall_hash, mname);
6141         if (res) {
6142                 mono_loader_unlock ();
6143                 return res;
6144         }
6145
6146         /* it wasn't found in the static call tables */
6147         if (!imap) {
6148                 mono_loader_unlock ();
6149                 return NULL;
6150         }
6151         res = find_method_icall (imap, sigstart - mlen);
6152         if (res) {
6153                 mono_loader_unlock ();
6154                 return res;
6155         }
6156         /* try _with_ signature */
6157         *sigstart = '(';
6158         res = find_method_icall (imap, sigstart - mlen);
6159         if (res) {
6160                 mono_loader_unlock ();
6161                 return res;
6162         }
6163         
6164         g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
6165         g_print ("\nYour mono runtime and class libraries are out of sync.\n");
6166         g_print ("The out of sync library is: %s\n", method->klass->image->name);
6167         g_print ("\nWhen you update one from cvs you need to update, compile and install\nthe other too.\n");
6168         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");
6169         g_print ("If you see other errors or faults after this message they are probably related\n");
6170         g_print ("and you need to fix your mono install first.\n");
6171
6172         mono_loader_unlock ();
6173
6174         return NULL;
6175 }
6176
6177 static MonoType*
6178 type_from_typename (char *typename)
6179 {
6180         MonoClass *klass = NULL;        /* assignment to shut GCC warning up */
6181
6182         if (!strcmp (typename, "int"))
6183                 klass = mono_defaults.int_class;
6184         else if (!strcmp (typename, "ptr"))
6185                 klass = mono_defaults.int_class;
6186         else if (!strcmp (typename, "void"))
6187                 klass = mono_defaults.void_class;
6188         else if (!strcmp (typename, "int32"))
6189                 klass = mono_defaults.int32_class;
6190         else if (!strcmp (typename, "uint32"))
6191                 klass = mono_defaults.uint32_class;
6192         else if (!strcmp (typename, "long"))
6193                 klass = mono_defaults.int64_class;
6194         else if (!strcmp (typename, "ulong"))
6195                 klass = mono_defaults.uint64_class;
6196         else if (!strcmp (typename, "float"))
6197                 klass = mono_defaults.single_class;
6198         else if (!strcmp (typename, "double"))
6199                 klass = mono_defaults.double_class;
6200         else if (!strcmp (typename, "object"))
6201                 klass = mono_defaults.object_class;
6202         else if (!strcmp (typename, "obj"))
6203                 klass = mono_defaults.object_class;
6204         else {
6205                 g_error (typename);
6206                 g_assert_not_reached ();
6207         }
6208         return &klass->byval_arg;
6209 }
6210
6211 MonoMethodSignature*
6212 mono_create_icall_signature (const char *sigstr)
6213 {
6214         gchar **parts;
6215         int i, len;
6216         gchar **tmp;
6217         MonoMethodSignature *res;
6218
6219         mono_loader_lock ();
6220         res = g_hash_table_lookup (mono_defaults.corlib->helper_signatures, sigstr);
6221         if (res) {
6222                 mono_loader_unlock ();
6223                 return res;
6224         }
6225
6226         parts = g_strsplit (sigstr, " ", 256);
6227
6228         tmp = parts;
6229         len = 0;
6230         while (*tmp) {
6231                 len ++;
6232                 tmp ++;
6233         }
6234
6235         res = mono_metadata_signature_alloc (mono_defaults.corlib, len - 1);
6236         res->pinvoke = 1;
6237
6238 #ifdef PLATFORM_WIN32
6239         /* 
6240          * Under windows, the default pinvoke calling convention is STDCALL but
6241          * we need CDECL.
6242          */
6243         res->call_convention = MONO_CALL_C;
6244 #endif
6245
6246         res->ret = type_from_typename (parts [0]);
6247         for (i = 1; i < len; ++i) {
6248                 res->params [i - 1] = type_from_typename (parts [i]);
6249         }
6250
6251         g_strfreev (parts);
6252
6253         g_hash_table_insert (mono_defaults.corlib->helper_signatures, (gpointer)sigstr, res);
6254
6255         mono_loader_unlock ();
6256
6257         return res;
6258 }
6259
6260 MonoJitICallInfo *
6261 mono_find_jit_icall_by_name (const char *name)
6262 {
6263         MonoJitICallInfo *info;
6264         g_assert (jit_icall_hash_name);
6265
6266         mono_loader_lock ();
6267         info = g_hash_table_lookup (jit_icall_hash_name, name);
6268         mono_loader_unlock ();
6269         return info;
6270 }
6271
6272 MonoJitICallInfo *
6273 mono_find_jit_icall_by_addr (gconstpointer addr)
6274 {
6275         MonoJitICallInfo *info;
6276         g_assert (jit_icall_hash_addr);
6277
6278         mono_loader_lock ();
6279         info = g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
6280         mono_loader_unlock ();
6281
6282         return info;
6283 }
6284
6285 void
6286 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
6287 {
6288         mono_loader_lock ();
6289         g_hash_table_insert (jit_icall_hash_addr, (gpointer)info->wrapper, info);       
6290         mono_loader_unlock ();
6291 }
6292
6293 MonoJitICallInfo *
6294 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
6295 {
6296         MonoJitICallInfo *info;
6297         
6298         g_assert (func);
6299         g_assert (name);
6300
6301         mono_loader_lock ();
6302
6303         if (!jit_icall_hash_name) {
6304                 jit_icall_hash_name = g_hash_table_new (g_str_hash, g_str_equal);
6305                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
6306         }
6307
6308         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
6309                 g_warning ("jit icall already defined \"%s\"\n", name);
6310                 g_assert_not_reached ();
6311         }
6312
6313         info = g_new (MonoJitICallInfo, 1);
6314         
6315         info->name = name;
6316         info->func = func;
6317         info->sig = sig;
6318
6319         if (is_save) {
6320                 info->wrapper = func;
6321         } else {
6322                 info->wrapper = NULL;
6323         }
6324
6325         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
6326         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
6327
6328         mono_loader_unlock ();
6329         return info;
6330 }