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