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