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