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