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