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