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