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