2002-11-04 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mono / metadata / icall.c
1 /*
2  * icall.c:
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Paolo Molaro (lupus@ximian.com)
7  *       Patrik Torstensson (patrik.torstensson@labs2.com)
8  *
9  * (C) 2001 Ximian, Inc.
10  */
11
12 #include <config.h>
13 #include <glib.h>
14 #include <stdarg.h>
15 #include <string.h>
16 #include <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/reflection.h>
25 #include <mono/metadata/assembly.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/file-io.h>
29 #include <mono/metadata/socket-io.h>
30 #include <mono/metadata/mono-endian.h>
31 #include <mono/metadata/tokentype.h>
32 #include <mono/metadata/unicode.h>
33 #include <mono/metadata/appdomain.h>
34 #include <mono/metadata/marshal.h>
35 #include <mono/metadata/gc.h>
36 #include <mono/metadata/rand.h>
37 #include <mono/metadata/sysmath.h>
38 #include <mono/metadata/string-icalls.h>
39 #include <mono/metadata/debug-mono-symfile.h>
40 #include <mono/metadata/process.h>
41 #include <mono/io-layer/io-layer.h>
42 #include <mono/utils/strtod.h>
43
44 #if defined (PLATFORM_WIN32)
45 #include <windows.h>
46 #endif
47 #include "decimal.h"
48
49 static MonoString *
50 mono_double_ToStringImpl (double value)
51 {
52         /* FIXME: Handle formats, etc. */
53         MonoString *s;
54         gchar *retVal;
55         retVal = g_strdup_printf ("%.15g", value);
56         s = mono_string_new (mono_domain_get (), retVal);
57         g_free (retVal);
58         return s;
59 }
60
61 /*
62  * We expect a pointer to a char, not a string
63  */
64 static double
65 mono_double_ParseImpl (char *ptr)
66 {
67         return bsd_strtod (ptr, NULL);
68 }
69
70 static MonoString *
71 mono_float_ToStringImpl (float value)
72 {
73         return mono_double_ToStringImpl (value);
74 }
75
76 static MonoObject *
77 ves_icall_System_Array_GetValueImpl (MonoObject *this, guint32 pos)
78 {
79         MonoClass *ac;
80         MonoArray *ao;
81         gint32 esize;
82         gpointer *ea;
83
84         ao = (MonoArray *)this;
85         ac = (MonoClass *)ao->obj.vtable->klass;
86
87         esize = mono_array_element_size (ac);
88         ea = (gpointer*)((char*)ao->vector + (pos * esize));
89
90         if (ac->element_class->valuetype)
91                 return mono_value_box (this->vtable->domain, ac->element_class, ea);
92         else
93                 return *ea;
94 }
95
96 static MonoObject *
97 ves_icall_System_Array_GetValue (MonoObject *this, MonoObject *idxs)
98 {
99         MonoClass *ac, *ic;
100         MonoArray *ao, *io;
101         gint32 i, pos, *ind;
102
103         MONO_CHECK_ARG_NULL (idxs);
104
105         io = (MonoArray *)idxs;
106         ic = (MonoClass *)io->obj.vtable->klass;
107         
108         ao = (MonoArray *)this;
109         ac = (MonoClass *)ao->obj.vtable->klass;
110
111         g_assert (ic->rank == 1);
112         if (io->bounds != NULL || io->max_length !=  ac->rank)
113                 mono_raise_exception (mono_get_exception_argument (NULL, NULL));
114
115         ind = (guint32 *)io->vector;
116
117         if (ao->bounds == NULL) {
118                 if (*ind < 0 || *ind >= ao->max_length)
119                         mono_raise_exception (mono_get_exception_index_out_of_range ());
120
121                 return ves_icall_System_Array_GetValueImpl (this, *ind);
122         }
123         
124         for (i = 0; i < ac->rank; i++)
125                 if ((ind [i] < ao->bounds [i].lower_bound) ||
126                     (ind [i] >= ao->bounds [i].length + ao->bounds [i].lower_bound))
127                         mono_raise_exception (mono_get_exception_index_out_of_range ());
128
129         pos = ind [0] - ao->bounds [0].lower_bound;
130         for (i = 1; i < ac->rank; i++)
131                 pos = pos*ao->bounds [i].length + ind [i] - 
132                         ao->bounds [i].lower_bound;
133
134         return ves_icall_System_Array_GetValueImpl (this, pos);
135 }
136
137 static void
138 ves_icall_System_Array_SetValueImpl (MonoArray *this, MonoObject *value, guint32 pos)
139 {
140         MonoClass *ac, *vc, *ec;
141         gint32 esize, vsize;
142         gpointer *ea, *va;
143
144         guint64 u64;
145         gint64 i64;
146         gdouble r64;
147
148         if (value)
149                 vc = value->vtable->klass;
150         else
151                 vc = NULL;
152
153         ac = this->obj.vtable->klass;
154         ec = ac->element_class;
155
156         esize = mono_array_element_size (ac);
157         ea = (gpointer*)((char*)this->vector + (pos * esize));
158         va = (gpointer*)((char*)value + sizeof (MonoObject));
159
160         if (!value) {
161                 memset (ea, 0,  esize);
162                 return;
163         }
164
165 #define NO_WIDENING_CONVERSION G_STMT_START{\
166         mono_raise_exception (mono_get_exception_argument ( \
167                 "value", "not a widening conversion")); \
168 }G_STMT_END
169
170 #define CHECK_WIDENING_CONVERSION(extra) G_STMT_START{\
171         if (esize < vsize + (extra)) \
172                 mono_raise_exception (mono_get_exception_argument ( \
173                         "value", "not a widening conversion")); \
174 }G_STMT_END
175
176 #define INVALID_CAST G_STMT_START{\
177         mono_raise_exception (mono_get_exception_invalid_cast ()); \
178 }G_STMT_END
179
180         /* Check element (destination) type. */
181         switch (ec->byval_arg.type) {
182         case MONO_TYPE_STRING:
183                 switch (vc->byval_arg.type) {
184                 case MONO_TYPE_STRING:
185                         break;
186                 default:
187                         INVALID_CAST;
188                 }
189                 break;
190         case MONO_TYPE_BOOLEAN:
191                 switch (vc->byval_arg.type) {
192                 case MONO_TYPE_BOOLEAN:
193                         break;
194                 case MONO_TYPE_CHAR:
195                 case MONO_TYPE_U1:
196                 case MONO_TYPE_U2:
197                 case MONO_TYPE_U4:
198                 case MONO_TYPE_U8:
199                 case MONO_TYPE_I1:
200                 case MONO_TYPE_I2:
201                 case MONO_TYPE_I4:
202                 case MONO_TYPE_I8:
203                 case MONO_TYPE_R4:
204                 case MONO_TYPE_R8:
205                         NO_WIDENING_CONVERSION;
206                 default:
207                         INVALID_CAST;
208                 }
209                 break;
210         }
211
212         if (!ec->valuetype) {
213                 *ea = (gpointer)value;
214                 return;
215         }
216
217         if (mono_object_isinst (value, ec)) {
218                 memcpy (ea, (char *)value + sizeof (MonoObject), esize);
219                 return;
220         }
221
222         if (!vc->valuetype)
223                 INVALID_CAST;
224
225         vsize = mono_class_instance_size (vc) - sizeof (MonoObject);
226
227 #if 0
228         g_message (G_STRLOC ": %d (%d) <= %d (%d)",
229                    ec->byval_arg.type, esize,
230                    vc->byval_arg.type, vsize);
231 #endif
232
233 #define ASSIGN_UNSIGNED(etype) G_STMT_START{\
234         switch (vc->byval_arg.type) { \
235         case MONO_TYPE_U1: \
236         case MONO_TYPE_U2: \
237         case MONO_TYPE_U4: \
238         case MONO_TYPE_U8: \
239         case MONO_TYPE_CHAR: \
240                 CHECK_WIDENING_CONVERSION(0); \
241                 *(etype *) ea = (etype) u64; \
242                 return; \
243         /* You can't assign a signed value to an unsigned array. */ \
244         case MONO_TYPE_I1: \
245         case MONO_TYPE_I2: \
246         case MONO_TYPE_I4: \
247         case MONO_TYPE_I8: \
248         /* You can't assign a floating point number to an integer array. */ \
249         case MONO_TYPE_R4: \
250         case MONO_TYPE_R8: \
251                 NO_WIDENING_CONVERSION; \
252         } \
253 }G_STMT_END
254
255 #define ASSIGN_SIGNED(etype) G_STMT_START{\
256         switch (vc->byval_arg.type) { \
257         case MONO_TYPE_I1: \
258         case MONO_TYPE_I2: \
259         case MONO_TYPE_I4: \
260         case MONO_TYPE_I8: \
261                 CHECK_WIDENING_CONVERSION(0); \
262                 *(etype *) ea = (etype) i64; \
263                 return; \
264         /* You can assign an unsigned value to a signed array if the array's */ \
265         /* element size is larger than the value size. */ \
266         case MONO_TYPE_U1: \
267         case MONO_TYPE_U2: \
268         case MONO_TYPE_U4: \
269         case MONO_TYPE_U8: \
270         case MONO_TYPE_CHAR: \
271                 CHECK_WIDENING_CONVERSION(1); \
272                 *(etype *) ea = (etype) u64; \
273                 return; \
274         /* You can't assign a floating point number to an integer array. */ \
275         case MONO_TYPE_R4: \
276         case MONO_TYPE_R8: \
277                 NO_WIDENING_CONVERSION; \
278         } \
279 }G_STMT_END
280
281 #define ASSIGN_REAL(etype) G_STMT_START{\
282         switch (vc->byval_arg.type) { \
283         case MONO_TYPE_R4: \
284         case MONO_TYPE_R8: \
285                 CHECK_WIDENING_CONVERSION(0); \
286                 *(etype *) ea = (etype) r64; \
287                 return; \
288         /* All integer values fit into a floating point array, so we don't */ \
289         /* need to CHECK_WIDENING_CONVERSION here. */ \
290         case MONO_TYPE_I1: \
291         case MONO_TYPE_I2: \
292         case MONO_TYPE_I4: \
293         case MONO_TYPE_I8: \
294                 *(etype *) ea = (etype) i64; \
295                 return; \
296         case MONO_TYPE_U1: \
297         case MONO_TYPE_U2: \
298         case MONO_TYPE_U4: \
299         case MONO_TYPE_U8: \
300         case MONO_TYPE_CHAR: \
301                 *(etype *) ea = (etype) u64; \
302                 return; \
303         } \
304 }G_STMT_END
305
306         switch (vc->byval_arg.type) {
307         case MONO_TYPE_U1:
308                 u64 = *(guint8 *) va;
309                 break;
310         case MONO_TYPE_U2:
311                 u64 = *(guint16 *) va;
312                 break;
313         case MONO_TYPE_U4:
314                 u64 = *(guint32 *) va;
315                 break;
316         case MONO_TYPE_U8:
317                 u64 = *(guint64 *) va;
318                 break;
319         case MONO_TYPE_I1:
320                 i64 = *(gint8 *) va;
321                 break;
322         case MONO_TYPE_I2:
323                 i64 = *(gint16 *) va;
324                 break;
325         case MONO_TYPE_I4:
326                 i64 = *(gint32 *) va;
327                 break;
328         case MONO_TYPE_I8:
329                 i64 = *(gint64 *) va;
330                 break;
331         case MONO_TYPE_R4:
332                 r64 = *(gfloat *) va;
333                 break;
334         case MONO_TYPE_R8:
335                 r64 = *(gdouble *) va;
336                 break;
337         case MONO_TYPE_CHAR:
338                 u64 = *(guint16 *) va;
339                 break;
340         case MONO_TYPE_BOOLEAN:
341                 /* Boolean is only compatible with itself. */
342                 switch (ec->byval_arg.type) {
343                 case MONO_TYPE_CHAR:
344                 case MONO_TYPE_U1:
345                 case MONO_TYPE_U2:
346                 case MONO_TYPE_U4:
347                 case MONO_TYPE_U8:
348                 case MONO_TYPE_I1:
349                 case MONO_TYPE_I2:
350                 case MONO_TYPE_I4:
351                 case MONO_TYPE_I8:
352                 case MONO_TYPE_R4:
353                 case MONO_TYPE_R8:
354                         NO_WIDENING_CONVERSION;
355                 default:
356                         INVALID_CAST;
357                 }
358                 break;
359         }
360
361         /* If we can't do a direct copy, let's try a widening conversion. */
362         switch (ec->byval_arg.type) {
363         case MONO_TYPE_CHAR:
364                 ASSIGN_UNSIGNED (guint16);
365         case MONO_TYPE_U1:
366                 ASSIGN_UNSIGNED (guint8);
367         case MONO_TYPE_U2:
368                 ASSIGN_UNSIGNED (guint16);
369         case MONO_TYPE_U4:
370                 ASSIGN_UNSIGNED (guint32);
371         case MONO_TYPE_U8:
372                 ASSIGN_UNSIGNED (guint64);
373         case MONO_TYPE_I1:
374                 ASSIGN_SIGNED (gint8);
375         case MONO_TYPE_I2:
376                 ASSIGN_SIGNED (gint16);
377         case MONO_TYPE_I4:
378                 ASSIGN_SIGNED (gint32);
379         case MONO_TYPE_I8:
380                 ASSIGN_SIGNED (gint64);
381         case MONO_TYPE_R4:
382                 ASSIGN_REAL (gfloat);
383         case MONO_TYPE_R8:
384                 ASSIGN_REAL (gdouble);
385         }
386
387         INVALID_CAST;
388         /* Not reached, INVALID_CAST does not return. Just to avoid a compiler warning ... */
389         return;
390
391 #undef INVALID_CAST
392 #undef NO_WIDENING_CONVERSION
393 #undef CHECK_WIDENING_CONVERSION
394 #undef ASSIGN_UNSIGNED
395 #undef ASSIGN_SIGNED
396 #undef ASSIGN_REAL
397 }
398
399 static void 
400 ves_icall_System_Array_SetValue (MonoArray *this, MonoObject *value,
401                                  MonoArray *idxs)
402 {
403         MonoClass *ac, *ic;
404         gint32 i, pos, *ind;
405
406         MONO_CHECK_ARG_NULL (idxs);
407
408         ic = idxs->obj.vtable->klass;
409         ac = this->obj.vtable->klass;
410
411         g_assert (ic->rank == 1);
412         if (idxs->bounds != NULL || idxs->max_length != ac->rank)
413                 mono_raise_exception (mono_get_exception_argument (NULL, NULL));
414
415         ind = (guint32 *)idxs->vector;
416
417         if (this->bounds == NULL) {
418                 if (*ind < 0 || *ind >= this->max_length)
419                         mono_raise_exception (mono_get_exception_index_out_of_range ());
420
421                 ves_icall_System_Array_SetValueImpl (this, value, *ind);
422                 return;
423         }
424         
425         for (i = 0; i < ac->rank; i++)
426                 if ((ind [i] < this->bounds [i].lower_bound) ||
427                     (ind [i] >= this->bounds [i].length + this->bounds [i].lower_bound))
428                         mono_raise_exception (mono_get_exception_index_out_of_range ());
429
430         pos = ind [0] - this->bounds [0].lower_bound;
431         for (i = 1; i < ac->rank; i++)
432                 pos = pos * this->bounds [i].length + ind [i] - 
433                         this->bounds [i].lower_bound;
434
435         ves_icall_System_Array_SetValueImpl (this, value, pos);
436 }
437
438 static MonoArray *
439 ves_icall_System_Array_CreateInstanceImpl (MonoReflectionType *type, MonoArray *lengths, MonoArray *bounds)
440 {
441         MonoClass *aklass;
442         MonoArray *array;
443         gint32 *sizes, i;
444
445         MONO_CHECK_ARG_NULL (type);
446         MONO_CHECK_ARG_NULL (lengths);
447
448         MONO_CHECK_ARG (lengths, mono_array_length (lengths) > 0);
449         if (bounds)
450                 MONO_CHECK_ARG (bounds, mono_array_length (lengths) == mono_array_length (bounds));
451
452         for (i = 0; i < mono_array_length (lengths); i++)
453                 if (mono_array_get (lengths, gint32, i) < 0)
454                         mono_raise_exception (mono_get_exception_argument_out_of_range (NULL));
455
456         aklass = mono_array_class_get (type->type, mono_array_length (lengths));
457
458         sizes = alloca (aklass->rank * sizeof(guint32) * 2);
459         for (i = 0; i < aklass->rank; ++i) {
460                 sizes [i] = mono_array_get (lengths, gint32, i);
461                 if (bounds)
462                         sizes [i + aklass->rank] = mono_array_get (bounds, gint32, i);
463                 else
464                         sizes [i + aklass->rank] = 0;
465         }
466
467         array = mono_array_new_full (mono_object_domain (type), aklass, sizes, sizes + aklass->rank);
468
469         return array;
470 }
471
472 static gint32 
473 ves_icall_System_Array_GetRank (MonoObject *this)
474 {
475         return this->vtable->klass->rank;
476 }
477
478 static gint32
479 ves_icall_System_Array_GetLength (MonoArray *this, gint32 dimension)
480 {
481         gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
482         if ((dimension < 0) || (dimension >= rank))
483                 mono_raise_exception (mono_get_exception_index_out_of_range ());
484         
485         if (this->bounds == NULL)
486                 return this->max_length;
487         
488         return this->bounds [dimension].length;
489 }
490
491 static gint32
492 ves_icall_System_Array_GetLowerBound (MonoArray *this, gint32 dimension)
493 {
494         gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
495         if ((dimension < 0) || (dimension >= rank))
496                 mono_raise_exception (mono_get_exception_index_out_of_range ());
497         
498         if (this->bounds == NULL)
499                 return 0;
500         
501         return this->bounds [dimension].lower_bound;
502 }
503
504 static void
505 ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* dest, int dest_idx, int length)
506 {
507         int element_size = mono_array_element_size (source->obj.vtable->klass);
508         void * dest_addr = mono_array_addr_with_size (dest, element_size, dest_idx);
509         void * source_addr = mono_array_addr_with_size (source, element_size, source_idx);
510
511         g_assert (dest_idx + length <= mono_array_length (dest));
512         g_assert (source_idx + length <= mono_array_length (source));
513         memmove (dest_addr, source_addr, element_size * length);
514 }
515
516 static void
517 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArray *array, MonoClassField *field_handle)
518 {
519         MonoClass *klass = array->obj.vtable->klass;
520         guint32 size = mono_array_element_size (klass);
521         int i;
522
523         if (array->bounds == NULL)
524                 size *= array->max_length;
525         else
526                 for (i = 0; i < klass->rank; ++i) 
527                         size *= array->bounds [i].length;
528
529         memcpy (mono_array_addr (array, char, 0), field_handle->data, size);
530
531 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
532 #define SWAP(n) {\
533         gint i; \
534         guint ## n tmp; \
535         guint ## n *data = (guint ## n *) mono_array_addr (array, char, 0); \
536 \
537         for (i = 0; i < size; i += n/8, data++) { \
538                 tmp = read ## n (data); \
539                 *data = tmp; \
540         } \
541 }
542
543         /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
544
545         switch (klass->element_class->byval_arg.type) {
546         case MONO_TYPE_CHAR:
547         case MONO_TYPE_I2:
548         case MONO_TYPE_U2:
549                 SWAP (16);
550                 break;
551         case MONO_TYPE_I4:
552         case MONO_TYPE_U4:
553                 SWAP (32);
554                 break;
555         case MONO_TYPE_I8:
556         case MONO_TYPE_U8:
557                 SWAP (64);
558                 break;
559         }
560                  
561 #endif
562 }
563
564 static gint
565 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
566 {
567         return offsetof (MonoString, chars);
568 }
569
570 static MonoObject *
571 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObject *obj)
572 {
573         if ((obj == NULL) || (! (obj->vtable->klass->valuetype)))
574                 return obj;
575         else
576                 return mono_object_clone (obj);
577 }
578
579 static void
580 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle)
581 {
582         MonoClass *klass;
583
584         MONO_CHECK_ARG_NULL (handle);
585
586         klass = mono_class_from_mono_type (handle);
587         MONO_CHECK_ARG (handle, klass);
588
589         /* This will call the type constructor */
590         mono_class_vtable (mono_domain_get (), klass);
591 }
592
593 static MonoObject *
594 ves_icall_System_Object_MemberwiseClone (MonoObject *this)
595 {
596         return mono_object_clone (this);
597 }
598
599 #if HAVE_BOEHM_GC
600 #define MONO_OBJECT_ALIGNMENT_SHIFT     3
601 #else
602 #define MONO_OBJECT_ALIGNMENT_SHIFT     2
603 #endif
604
605 /*
606  * Return hashcode based on object address. This function will need to be
607  * smarter in the presence of a moving garbage collector, which will cache
608  * the address hash before relocating the object.
609  *
610  * Wang's address-based hash function:
611  *   http://www.concentric.net/~Ttwang/tech/addrhash.htm
612  */
613 static gint32
614 ves_icall_System_Object_GetHashCode (MonoObject *this)
615 {
616         register guint32 key;
617         key = (GPOINTER_TO_UINT (this) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
618
619         return key & 0x7fffffff;
620 }
621
622 /*
623  * A hash function for value types. I have no idea if this is a good hash 
624  * function (its similar to g_str_hash).
625  */
626 static gint32
627 ves_icall_System_ValueType_GetHashCode (MonoObject *this)
628 {
629         gint32 i, size;
630         const char *p;
631         guint h = 0;
632
633         MONO_CHECK_ARG_NULL (this);
634
635         size = this->vtable->klass->instance_size - sizeof (MonoObject);
636
637         p = (const char *)this + sizeof (MonoObject);
638
639         for (i = 0; i < size; i++) {
640                 h = (h << 5) - h + *p;
641                 p++;
642         }
643
644         return h;
645 }
646
647 static MonoBoolean
648 ves_icall_System_ValueType_Equals (MonoObject *this, MonoObject *that)
649 {
650         gint32 size;
651         const char *p, *s;
652
653         MONO_CHECK_ARG_NULL (that);
654
655         if (this->vtable != that->vtable)
656                 return FALSE;
657
658         size = this->vtable->klass->instance_size - sizeof (MonoObject);
659
660         p = (const char *)this + sizeof (MonoObject);
661         s = (const char *)that + sizeof (MonoObject);
662
663         return memcmp (p, s, size)? FALSE: TRUE;
664 }
665
666 static MonoReflectionType *
667 ves_icall_System_Object_GetType (MonoObject *obj)
668 {
669         return mono_type_get_object (mono_object_domain (obj), &obj->vtable->klass->byval_arg);
670 }
671
672 static void
673 mono_type_type_from_obj (MonoReflectionType *mtype, MonoObject *obj)
674 {
675         mtype->type = &obj->vtable->klass->byval_arg;
676         g_assert (mtype->type->type);
677 }
678
679 static gint32
680 ves_icall_AssemblyBuilder_getToken (MonoReflectionAssemblyBuilder *assb, MonoObject *obj)
681 {
682         return mono_image_create_token (assb->dynamic_assembly, obj);
683 }
684
685 static gint32
686 ves_icall_AssemblyBuilder_getDataChunk (MonoReflectionAssemblyBuilder *assb, MonoArray *buf, gint32 offset)
687 {
688         int count;
689         MonoDynamicAssembly *ass = assb->dynamic_assembly;
690         char *p = mono_array_addr (buf, char, 0);
691
692         mono_image_create_pefile (assb);
693
694         if (offset >= ass->pefile.index)
695                 return 0;
696         count = mono_array_length (buf);
697         count = MIN (count, ass->pefile.index - offset);
698         
699         memcpy (p, ass->pefile.data + offset, count);
700
701         return count;
702 }
703
704 static gboolean
705 get_get_type_caller (MonoMethod *m, gint32 no, gint32 ilo, gpointer data) {
706         MonoImage **dest = data;
707
708         /* skip icalls and Type::GetType () */
709         if (!m || m->wrapper_type || (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
710                         (strcmp (m->name, "GetType") == 0 && m->klass == mono_defaults.monotype_class->parent))
711                 return FALSE;
712         *dest = m->klass->image;
713         return TRUE;
714 }
715
716 static MonoReflectionType*
717 ves_icall_type_from_name (MonoString *name)
718 {
719         MonoImage *image = NULL;
720         MonoType *type;
721         gchar *str;
722
723         mono_stack_walk (get_get_type_caller, &image);
724         str = mono_string_to_utf8 (name);
725         /*g_print ("requested type %s\n", str);*/
726         type = mono_reflection_type_from_name (str, image);
727         g_free (str);
728         if (!type)
729                 return NULL;
730         /*g_print ("got it\n");*/
731         return mono_type_get_object (mono_object_domain (name), type);
732 }
733
734 static MonoReflectionType*
735 ves_icall_type_from_handle (MonoType *handle)
736 {
737         MonoDomain *domain = mono_domain_get (); 
738         MonoClass *klass = mono_class_from_mono_type (handle);
739
740         mono_class_init (klass);
741         return mono_type_get_object (domain, handle);
742 }
743
744 static guint32
745 ves_icall_type_Equals (MonoReflectionType *type, MonoReflectionType *c)
746 {
747         if (type->type && c->type)
748                 return mono_metadata_type_equal (type->type, c->type);
749         g_print ("type equals\n");
750         return 0;
751 }
752
753 /* System.TypeCode */
754 typedef enum {
755         TYPECODE_EMPTY,
756         TYPECODE_OBJECT,
757         TYPECODE_DBNULL,
758         TYPECODE_BOOLEAN,
759         TYPECODE_CHAR,
760         TYPECODE_SBYTE,
761         TYPECODE_BYTE,
762         TYPECODE_INT16,
763         TYPECODE_UINT16,
764         TYPECODE_INT32,
765         TYPECODE_UINT32,
766         TYPECODE_INT64,
767         TYPECODE_UINT64,
768         TYPECODE_SINGLE,
769         TYPECODE_DOUBLE,
770         TYPECODE_DECIMAL,
771         TYPECODE_DATETIME,
772         TYPECODE_STRING = 18
773 } TypeCode;
774
775 static guint32
776 ves_icall_type_GetTypeCode (MonoReflectionType *type)
777 {
778         int t = type->type->type;
779 handle_enum:
780         switch (t) {
781         case MONO_TYPE_VOID:
782                 return TYPECODE_OBJECT;
783         case MONO_TYPE_BOOLEAN:
784                 return TYPECODE_BOOLEAN;
785         case MONO_TYPE_U1:
786                 return TYPECODE_BYTE;
787         case MONO_TYPE_I1:
788                 return TYPECODE_SBYTE;
789         case MONO_TYPE_U2:
790                 return TYPECODE_UINT16;
791         case MONO_TYPE_I2:
792                 return TYPECODE_INT16;
793         case MONO_TYPE_CHAR:
794                 return TYPECODE_CHAR;
795         case MONO_TYPE_PTR:
796         case MONO_TYPE_U:
797         case MONO_TYPE_I:
798                 return TYPECODE_OBJECT;
799         case MONO_TYPE_U4:
800                 return TYPECODE_UINT32;
801         case MONO_TYPE_I4:
802                 return TYPECODE_INT32;
803         case MONO_TYPE_U8:
804                 return TYPECODE_UINT64;
805         case MONO_TYPE_I8:
806                 return TYPECODE_INT64;
807         case MONO_TYPE_R4:
808                 return TYPECODE_SINGLE;
809         case MONO_TYPE_R8:
810                 return TYPECODE_DOUBLE;
811         case MONO_TYPE_VALUETYPE:
812                 if (type->type->data.klass->enumtype) {
813                         t = type->type->data.klass->enum_basetype->type;
814                         goto handle_enum;
815                 } else {
816                         MonoClass *k =  type->type->data.klass;
817                         if (strcmp (k->name_space, "System") == 0) {
818                                 if (strcmp (k->name, "Decimal") == 0)
819                                         return TYPECODE_DECIMAL;
820                                 else if (strcmp (k->name, "DateTime") == 0)
821                                         return TYPECODE_DATETIME;
822                                 else if (strcmp (k->name, "DBNull") == 0)
823                                         return TYPECODE_DBNULL;
824                         }
825                 }
826                 /* handle datetime, dbnull.. */
827                 return TYPECODE_OBJECT;
828         case MONO_TYPE_STRING:
829                 return TYPECODE_STRING;
830         case MONO_TYPE_SZARRAY:
831         case MONO_TYPE_ARRAY:
832         case MONO_TYPE_OBJECT:
833                 return TYPECODE_OBJECT;
834         case MONO_TYPE_CLASS:
835                 return TYPECODE_OBJECT;
836         default:
837                 g_error ("type 0x%02x not handled in GetTypeCode()", t);
838         }
839         return 0;
840 }
841
842 static guint32
843 ves_icall_type_is_subtype_of (MonoReflectionType *type, MonoReflectionType *c, MonoBoolean check_interfaces)
844 {
845         MonoDomain *domain; 
846         MonoClass *klass;
847         MonoClass *klassc;
848
849         g_assert (type != NULL);
850         
851         domain = ((MonoObject *)type)->vtable->domain;
852
853         if (!c) /* FIXME: dont know what do do here */
854                 return 0;
855
856         klass = mono_class_from_mono_type (type->type);
857         klassc = mono_class_from_mono_type (c->type);
858
859         /* cut&paste from mono_object_isinst (): keep in sync */
860         if (check_interfaces && (klassc->flags & TYPE_ATTRIBUTE_INTERFACE) && !(klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
861                 MonoVTable *klass_vt = mono_class_vtable (domain, klass);
862                 if ((klassc->interface_id <= klass->max_interface_id) &&
863                     klass_vt->interface_offsets [klassc->interface_id])
864                         return 1;
865         } else if (check_interfaces && (klassc->flags & TYPE_ATTRIBUTE_INTERFACE) && (klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
866                 int i;
867
868                 for (i = 0; i < klass->interface_count; i ++) {
869                         MonoClass *ic =  klass->interfaces [i];
870                         if (ic == klassc)
871                                 return 1;
872                 }
873         } else {
874                 /*
875                  * klass->baseval is 0 for interfaces 
876                  */
877                 if (klass->baseval && ((klass->baseval - klassc->baseval) <= klassc->diffval))
878                         return 1;
879         }
880         return 0;
881 }
882
883 static guint32
884 ves_icall_get_attributes (MonoReflectionType *type)
885 {
886         MonoClass *klass = mono_class_from_mono_type (type->type);
887
888         return klass->flags;
889 }
890
891 static void
892 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info)
893 {
894         MonoDomain *domain = mono_domain_get ();
895
896         info->parent = mono_type_get_object (domain, &method->klass->byval_arg);
897         info->ret = mono_type_get_object (domain, method->signature->ret);
898         info->attrs = method->flags;
899         info->implattrs = method->iflags;
900 }
901
902 static MonoArray*
903 ves_icall_get_parameter_info (MonoMethod *method)
904 {
905         MonoDomain *domain = mono_domain_get (); 
906         MonoArray *res;
907         static MonoClass *System_Reflection_ParameterInfo;
908         MonoReflectionParameter** args;
909         int i;
910
911         args = mono_param_get_objects (domain, method);
912         if (!System_Reflection_ParameterInfo)
913                 System_Reflection_ParameterInfo = mono_class_from_name (
914                         mono_defaults.corlib, "System.Reflection", "ParameterInfo");
915         res = mono_array_new (domain, System_Reflection_ParameterInfo, method->signature->param_count);
916         for (i = 0; i < method->signature->param_count; ++i) {
917                 mono_array_set (res, gpointer, i, args [i]);
918         }
919         return res;
920 }
921
922 static void
923 ves_icall_get_field_info (MonoReflectionField *field, MonoFieldInfo *info)
924 {
925         MonoDomain *domain = mono_object_domain (field); 
926
927         info->parent = mono_type_get_object (domain, &field->klass->byval_arg);
928         info->type = mono_type_get_object (domain, field->field->type);
929         info->name = mono_string_new (domain, field->field->name);
930         info->attrs = field->field->type->attrs;
931 }
932
933 static MonoObject *
934 ves_icall_MonoField_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
935 {       
936         MonoObject *o;
937         MonoClassField *cf = field->field;
938         MonoClass *klass;
939         MonoVTable *vtable;
940         MonoDomain *domain = mono_object_domain (field); 
941         gchar *v;
942         gboolean is_static = FALSE;
943         gboolean is_ref = FALSE;
944
945         mono_class_init (field->klass);
946
947         switch (cf->type->type) {
948         case MONO_TYPE_STRING:
949         case MONO_TYPE_OBJECT:
950         case MONO_TYPE_CLASS:
951         case MONO_TYPE_ARRAY:
952         case MONO_TYPE_SZARRAY:
953                 is_ref = TRUE;
954                 break;
955         case MONO_TYPE_U1:
956         case MONO_TYPE_I1:
957         case MONO_TYPE_BOOLEAN:
958         case MONO_TYPE_U2:
959         case MONO_TYPE_I2:
960         case MONO_TYPE_CHAR:
961         case MONO_TYPE_U:
962         case MONO_TYPE_I:
963         case MONO_TYPE_U4:
964         case MONO_TYPE_I4:
965         case MONO_TYPE_R4:
966         case MONO_TYPE_U8:
967         case MONO_TYPE_I8:
968         case MONO_TYPE_R8:
969         case MONO_TYPE_VALUETYPE:
970                 is_ref = cf->type->byref;
971                 break;
972         default:
973                 g_error ("type 0x%x not handled in "
974                          "ves_icall_Monofield_GetValue", cf->type->type);
975                 return NULL;
976         }
977
978         if (cf->type->attrs & FIELD_ATTRIBUTE_STATIC) {
979                 is_static = TRUE;
980                 vtable = mono_class_vtable (domain, field->klass);
981         }
982         
983         if (is_ref) {
984                 if (is_static) {
985                         mono_field_static_get_value (vtable, cf, &o);
986                 } else {
987                         mono_field_get_value (obj, cf, &o);
988                 }
989                 return o;
990         }
991
992         /* boxed value type */
993         klass = mono_class_from_mono_type (cf->type);
994         o = mono_object_new (domain, klass);
995         v = ((gchar *) o) + sizeof (MonoObject);
996         if (is_static) {
997                 mono_field_static_get_value (vtable, cf, v);
998         } else {
999                 mono_field_get_value (obj, cf, v);
1000         }
1001
1002         return o;
1003 }
1004
1005 static void
1006 ves_icall_FieldInfo_SetValueInternal (MonoReflectionField *field, MonoObject *obj, MonoObject *value)
1007 {
1008         MonoClassField *cf = field->field;
1009         gchar *v;
1010
1011         v = (gchar *) value;
1012         if (!cf->type->byref) {
1013                 switch (cf->type->type) {
1014                 case MONO_TYPE_U1:
1015                 case MONO_TYPE_I1:
1016                 case MONO_TYPE_BOOLEAN:
1017                 case MONO_TYPE_U2:
1018                 case MONO_TYPE_I2:
1019                 case MONO_TYPE_CHAR:
1020                 case MONO_TYPE_U:
1021                 case MONO_TYPE_I:
1022                 case MONO_TYPE_U4:
1023                 case MONO_TYPE_I4:
1024                 case MONO_TYPE_R4:
1025                 case MONO_TYPE_U8:
1026                 case MONO_TYPE_I8:
1027                 case MONO_TYPE_R8:
1028                 case MONO_TYPE_VALUETYPE:
1029                         v += sizeof (MonoObject);
1030                         break;
1031                 case MONO_TYPE_STRING:
1032                 case MONO_TYPE_OBJECT:
1033                 case MONO_TYPE_CLASS:
1034                 case MONO_TYPE_ARRAY:
1035                 case MONO_TYPE_SZARRAY:
1036                         /* Do nothing */
1037                         break;
1038                 default:
1039                         g_error ("type 0x%x not handled in "
1040                                  "ves_icall_FieldInfo_SetValueInternal", cf->type->type);
1041                         return;
1042                 }
1043         }
1044
1045         if (cf->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1046                 MonoVTable *vtable = mono_class_vtable (mono_object_domain (field), field->klass);
1047                 mono_field_static_set_value (vtable, cf, v);
1048         } else {
1049                 mono_field_set_value (obj, cf, v);
1050         }
1051 }
1052
1053 static void
1054 ves_icall_get_property_info (MonoReflectionProperty *property, MonoPropertyInfo *info)
1055 {
1056         MonoDomain *domain = mono_object_domain (property); 
1057
1058         info->parent = mono_type_get_object (domain, &property->klass->byval_arg);
1059         info->name = mono_string_new (domain, property->property->name);
1060         info->attrs = property->property->attrs;
1061         info->get = property->property->get ? mono_method_get_object (domain, property->property->get, NULL): NULL;
1062         info->set = property->property->set ? mono_method_get_object (domain, property->property->set, NULL): NULL;
1063         /* 
1064          * There may be other methods defined for properties, though, it seems they are not exposed 
1065          * in the reflection API 
1066          */
1067 }
1068
1069 static void
1070 ves_icall_get_event_info (MonoReflectionEvent *event, MonoEventInfo *info)
1071 {
1072         MonoDomain *domain = mono_object_domain (event); 
1073
1074         info->parent = mono_type_get_object (domain, &event->klass->byval_arg);
1075         info->name = mono_string_new (domain, event->event->name);
1076         info->attrs = event->event->attrs;
1077         info->add_method = event->event->add ? mono_method_get_object (domain, event->event->add, NULL): NULL;
1078         info->remove_method = event->event->remove ? mono_method_get_object (domain, event->event->remove, NULL): NULL;
1079         info->raise_method = event->event->raise ? mono_method_get_object (domain, event->event->raise, NULL): NULL;
1080 }
1081
1082 static MonoArray*
1083 ves_icall_Type_GetInterfaces (MonoReflectionType* type)
1084 {
1085         MonoDomain *domain = mono_object_domain (type); 
1086         MonoArray *intf;
1087         int ninterf, i;
1088         MonoClass *class = mono_class_from_mono_type (type->type);
1089         MonoClass *parent;
1090
1091         ninterf = 0;
1092         for (parent = class; parent; parent = parent->parent) {
1093                 ninterf += parent->interface_count;
1094         }
1095         intf = mono_array_new (domain, mono_defaults.monotype_class, ninterf);
1096         ninterf = 0;
1097         for (parent = class; parent; parent = parent->parent) {
1098                 for (i = 0; i < parent->interface_count; ++i) {
1099                         mono_array_set (intf, gpointer, ninterf, mono_type_get_object (domain, &parent->interfaces [i]->byval_arg));
1100                         ++ninterf;
1101                 }
1102         }
1103         return intf;
1104 }
1105
1106 static MonoReflectionType*
1107 ves_icall_MonoType_GetElementType (MonoReflectionType *type)
1108 {
1109         MonoClass *class = mono_class_from_mono_type (type->type);
1110         if (class->enumtype && class->enum_basetype) /* types that are modifierd typebuilkders may not have enum_basetype set */
1111                 return mono_type_get_object (mono_object_domain (type), class->enum_basetype);
1112         else if (class->element_class)
1113                 return mono_type_get_object (mono_object_domain (type), &class->element_class->byval_arg);
1114         else
1115                 return NULL;
1116 }
1117
1118 static MonoReflectionType*
1119 ves_icall_get_type_parent (MonoReflectionType *type)
1120 {
1121         MonoClass *class = mono_class_from_mono_type (type->type);
1122         return class->parent ? mono_type_get_object (mono_object_domain (type), &class->parent->byval_arg): NULL;
1123 }
1124
1125 static MonoBoolean
1126 ves_icall_type_ispointer (MonoReflectionType *type)
1127 {
1128         return type->type->type == MONO_TYPE_PTR;
1129 }
1130
1131 static MonoBoolean
1132 ves_icall_type_isbyref (MonoReflectionType *type)
1133 {
1134         return type->type->byref;
1135 }
1136
1137 static MonoReflectionModule*
1138 ves_icall_MonoType_get_Module (MonoReflectionType *type)
1139 {
1140         MonoClass *class = mono_class_from_mono_type (type->type);
1141         return mono_module_get_object (mono_object_domain (type), class->image);
1142 }
1143
1144 static void
1145 ves_icall_get_type_info (MonoType *type, MonoTypeInfo *info)
1146 {
1147         MonoDomain *domain = mono_domain_get (); 
1148         MonoClass *class = mono_class_from_mono_type (type);
1149
1150         info->nested_in = class->nested_in ? mono_type_get_object (domain, &class->nested_in->byval_arg): NULL;
1151         info->name = mono_string_new (domain, class->name);
1152         info->name_space = mono_string_new (domain, class->name_space);
1153         info->rank = class->rank;
1154         info->assembly = mono_assembly_get_object (domain, class->image->assembly);
1155         if (class->enumtype && class->enum_basetype) /* types that are modifierd typebuilkders may not have enum_basetype set */
1156                 info->etype = mono_type_get_object (domain, class->enum_basetype);
1157         else if (class->element_class)
1158                 info->etype = mono_type_get_object (domain, &class->element_class->byval_arg);
1159         else
1160                 info->etype = NULL;
1161
1162         info->isprimitive = (type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8);
1163 }
1164
1165 static MonoObject *
1166 ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this, MonoArray *params) 
1167 {
1168         /* 
1169          * Invoke from reflection is supposed to always be a virtual call (the API
1170          * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
1171          * greater flexibility.
1172          */
1173         MonoMethod *m = method->method;
1174         if (this)
1175                 m = mono_object_get_virtual_method (this, m);
1176
1177         return mono_runtime_invoke_array (m, this, params, NULL);
1178 }
1179
1180 static MonoObject *
1181 ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this, MonoArray *params, MonoArray **outArgs) 
1182 {
1183         MonoDomain *domain = mono_object_domain (method); 
1184         MonoMethod *m = method->method;
1185         MonoMethodSignature *sig = m->signature;
1186         MonoArray *out_args;
1187         MonoObject *result;
1188         int i, j, outarg_count = 0;
1189
1190         if (m->klass == mono_defaults.object_class) {
1191
1192                 if (!strcmp (m->name, "FieldGetter")) {
1193                         MonoClass *k = this->vtable->klass;
1194                         MonoString *name = mono_array_get (params, MonoString *, 1);
1195                         char *str;
1196
1197                         str = mono_string_to_utf8 (name);
1198                 
1199                         for (i = 0; i < k->field.count; i++) {
1200                                 if (!strcmp (k->fields [i].name, str)) {
1201                                         MonoClass *field_klass =  mono_class_from_mono_type (k->fields [i].type);
1202                                         if (field_klass->valuetype)
1203                                                 result = mono_value_box (domain, field_klass,
1204                                                                          (char *)this + k->fields [i].offset);
1205                                         else 
1206                                                 result = *((gpointer *)((char *)this + k->fields [i].offset));
1207                                 
1208                                         g_assert (result);
1209                                         out_args = mono_array_new (domain, mono_defaults.object_class, 1);
1210                                         *outArgs = out_args;
1211                                         mono_array_set (out_args, gpointer, 0, result);
1212                                         g_free (str);
1213                                         return NULL;
1214                                 }
1215                         }
1216
1217                         g_free (str);
1218                         g_assert_not_reached ();
1219
1220                 } else if (!strcmp (m->name, "FieldSetter")) {
1221                         MonoClass *k = this->vtable->klass;
1222                         MonoString *name = mono_array_get (params, MonoString *, 1);
1223                         int size, align;
1224                         char *str;
1225
1226                         str = mono_string_to_utf8 (name);
1227                 
1228                         for (i = 0; i < k->field.count; i++) {
1229                                 if (!strcmp (k->fields [i].name, str)) {
1230                                         MonoClass *field_klass =  mono_class_from_mono_type (k->fields [i].type);
1231                                         MonoObject *val = mono_array_get (params, gpointer, 2);
1232
1233                                         if (field_klass->valuetype) {
1234                                                 size = mono_type_size (k->fields [i].type, &align);
1235                                                 memcpy ((char *)this + k->fields [i].offset, 
1236                                                         ((char *)val) + sizeof (MonoObject), size);
1237                                         } else 
1238                                                 *((gpointer *)this + k->fields [i].offset) = val;
1239                                 
1240                                         g_assert (result);
1241                                         g_free (str);
1242                                         return NULL;
1243                                 }
1244                         }
1245
1246                         g_free (str);
1247                         g_assert_not_reached ();
1248
1249                 }
1250         }
1251
1252         for (i = 0; i < mono_array_length (params); i++) {
1253                 if (sig->params [i]->byref) 
1254                         outarg_count++;
1255         }
1256
1257         out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
1258         
1259         for (i = 0, j = 0; i < mono_array_length (params); i++) {
1260                 if (sig->params [i]->byref) {
1261                         gpointer arg;
1262                         arg = mono_array_get (params, gpointer, i);
1263                         mono_array_set (out_args, gpointer, j, arg);
1264                         j++;
1265                 }
1266         }
1267
1268         /* fixme: handle constructors? */
1269         if (!strcmp (method->method->name, ".ctor"))
1270                 g_assert_not_reached ();
1271
1272         result = mono_runtime_invoke_array (method->method, this, params, NULL);
1273
1274         *outArgs = out_args;
1275
1276         return result;
1277 }
1278
1279 static MonoObject *
1280 ves_icall_System_Enum_ToObject (MonoReflectionType *type, MonoObject *obj)
1281 {
1282         MonoDomain *domain; 
1283         MonoClass *enumc, *objc;
1284         gint32 s1, s2;
1285         MonoObject *res;
1286         
1287         MONO_CHECK_ARG_NULL (type);
1288         MONO_CHECK_ARG_NULL (obj);
1289
1290         domain = mono_object_domain (type); 
1291         enumc = mono_class_from_mono_type (type->type);
1292         objc = obj->vtable->klass;
1293
1294         MONO_CHECK_ARG (obj, enumc->enumtype == TRUE);
1295         MONO_CHECK_ARG (obj, (objc->enumtype) || (objc->byval_arg.type >= MONO_TYPE_I1 &&
1296                                                   objc->byval_arg.type <= MONO_TYPE_U8));
1297         
1298         s1 = mono_class_value_size (enumc, NULL);
1299         s2 = mono_class_value_size (objc, NULL);
1300
1301         res = mono_object_new (domain, enumc);
1302
1303 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
1304         memcpy ((char *)res + sizeof (MonoObject), (char *)obj + sizeof (MonoObject), MIN (s1, s2));
1305 #else
1306         memcpy ((char *)res + sizeof (MonoObject) + (s1 > s2 ? s1 - s2 : 0),
1307                 (char *)obj + sizeof (MonoObject) + (s2 > s1 ? s2 - s1 : 0),
1308                 MIN (s1, s2));
1309 #endif
1310         return res;
1311 }
1312
1313 static MonoObject *
1314 ves_icall_System_Enum_get_value (MonoObject *this)
1315 {
1316         MonoObject *res;
1317         MonoClass *enumc;
1318         gpointer dst;
1319         gpointer src;
1320         int size;
1321
1322         if (!this)
1323                 return NULL;
1324
1325         g_assert (this->vtable->klass->enumtype);
1326         
1327         enumc = mono_class_from_mono_type (this->vtable->klass->enum_basetype);
1328         res = mono_object_new (mono_object_domain (this), enumc);
1329         dst = (char *)res + sizeof (MonoObject);
1330         src = (char *)this + sizeof (MonoObject);
1331         size = mono_class_value_size (enumc, NULL);
1332
1333         memcpy (dst, src, size);
1334
1335         return res;
1336 }
1337
1338 static void
1339 ves_icall_get_enum_info (MonoReflectionType *type, MonoEnumInfo *info)
1340 {
1341         MonoDomain *domain = mono_object_domain (type); 
1342         MonoClass *enumc = mono_class_from_mono_type (type->type);
1343         guint i, j, nvalues, crow;
1344         MonoClassField *field;
1345         
1346         info->utype = mono_type_get_object (domain, enumc->enum_basetype);
1347         nvalues = enumc->field.count - 1;
1348         info->names = mono_array_new (domain, mono_defaults.string_class, nvalues);
1349         info->values = mono_array_new (domain, enumc, nvalues);
1350         
1351         for (i = 0, j = 0; i < enumc->field.count; ++i) {
1352                 field = &enumc->fields [i];
1353                 if (strcmp ("value__", field->name) == 0)
1354                         continue;
1355                 mono_array_set (info->names, gpointer, j, mono_string_new (domain, field->name));
1356                 if (!field->data) {
1357                         crow = mono_metadata_get_constant_index (enumc->image, MONO_TOKEN_FIELD_DEF | (i+enumc->field.first+1));
1358                         crow = mono_metadata_decode_row_col (&enumc->image->tables [MONO_TABLE_CONSTANT], crow-1, MONO_CONSTANT_VALUE);
1359                         /* 1 is the length of the blob */
1360                         field->data = 1 + mono_metadata_blob_heap (enumc->image, crow);
1361                 }
1362                 switch (enumc->enum_basetype->type) {
1363                 case MONO_TYPE_U1:
1364                 case MONO_TYPE_I1:
1365                         mono_array_set (info->values, gchar, j, *field->data);
1366                         break;
1367                 case MONO_TYPE_CHAR:
1368                 case MONO_TYPE_U2:
1369                 case MONO_TYPE_I2:
1370                         mono_array_set (info->values, gint16, j, read16 (field->data));
1371                         break;
1372                 case MONO_TYPE_U4:
1373                 case MONO_TYPE_I4:
1374                         mono_array_set (info->values, gint32, j, read32 (field->data));
1375                         break;
1376                 case MONO_TYPE_U8:
1377                 case MONO_TYPE_I8:
1378                         mono_array_set (info->values, gint64, j, read64 (field->data));
1379                         break;
1380                 default:
1381                         g_error ("Implement type 0x%02x in get_enum_info", enumc->enum_basetype->type);
1382                 }
1383                 ++j;
1384         }
1385 }
1386
1387 enum {
1388         BFLAGS_IgnoreCase = 1,
1389         BFLAGS_DeclaredOnly = 2,
1390         BFLAGS_Instance = 4,
1391         BFLAGS_Static = 8,
1392         BFLAGS_Public = 0x10,
1393         BFLAGS_NonPublic = 0x20,
1394         BFLAGS_InvokeMethod = 0x100,
1395         BFLAGS_CreateInstance = 0x200,
1396         BFLAGS_GetField = 0x400,
1397         BFLAGS_SetField = 0x800,
1398         BFLAGS_GetProperty = 0x1000,
1399         BFLAGS_SetProperty = 0x2000,
1400         BFLAGS_ExactBinding = 0x10000,
1401         BFLAGS_SuppressChangeType = 0x20000,
1402         BFLAGS_OptionalParamBinding = 0x40000
1403 };
1404
1405 static MonoFieldInfo *
1406 ves_icall_Type_GetField (MonoReflectionType *type, MonoString *name, guint32 bflags)
1407 {
1408         MonoDomain *domain; 
1409         MonoClass *startklass, *klass;
1410         int i, match;
1411         MonoClassField *field;
1412         char *utf8_name;
1413         domain = ((MonoObject *)type)->vtable->domain;
1414         klass = startklass = mono_class_from_mono_type (type->type);
1415
1416         if (!name)
1417                 return NULL;
1418
1419 handle_parent:  
1420         for (i = 0; i < klass->field.count; ++i) {
1421                 match = 0;
1422                 field = &klass->fields [i];
1423                 if ((field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
1424                         if (bflags & BFLAGS_Public)
1425                                 match++;
1426                 } else {
1427                         if (bflags & BFLAGS_NonPublic)
1428                                 match++;
1429                 }
1430                 if (!match)
1431                         continue;
1432                 match = 0;
1433                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1434                         if (bflags & BFLAGS_Static)
1435                                 match++;
1436                 } else {
1437                         if (bflags & BFLAGS_Instance)
1438                                 match++;
1439                 }
1440
1441                 if (!match)
1442                         continue;
1443                 
1444                 utf8_name = mono_string_to_utf8 (name);
1445
1446                 if (strcmp (field->name, utf8_name)) {
1447                         g_free (utf8_name);
1448                         continue;
1449                 }
1450                 g_free (utf8_name);
1451                 
1452                 return (MonoFieldInfo *)mono_field_get_object (domain, klass, field);
1453         }
1454         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
1455                 goto handle_parent;
1456
1457         return NULL;
1458 }
1459
1460 static MonoArray*
1461 ves_icall_Type_GetFields (MonoReflectionType *type, guint32 bflags)
1462 {
1463         MonoDomain *domain; 
1464         GSList *l = NULL, *tmp;
1465         MonoClass *startklass, *klass;
1466         MonoArray *res;
1467         MonoObject *member;
1468         int i, len, match;
1469         MonoClassField *field;
1470
1471         domain = ((MonoObject *)type)->vtable->domain;
1472         klass = startklass = mono_class_from_mono_type (type->type);
1473
1474 handle_parent:  
1475         for (i = 0; i < klass->field.count; ++i) {
1476                 match = 0;
1477                 field = &klass->fields [i];
1478                 if ((field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
1479                         if (bflags & BFLAGS_Public)
1480                                 match++;
1481                 } else {
1482                         if (bflags & BFLAGS_NonPublic)
1483                                 match++;
1484                 }
1485                 if (!match)
1486                         continue;
1487                 match = 0;
1488                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
1489                         if (bflags & BFLAGS_Static)
1490                                 match++;
1491                 } else {
1492                         if (bflags & BFLAGS_Instance)
1493                                 match++;
1494                 }
1495
1496                 if (!match)
1497                         continue;
1498                 member = (MonoObject*)mono_field_get_object (domain, klass, field);
1499                 l = g_slist_prepend (l, member);
1500         }
1501         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
1502                 goto handle_parent;
1503         len = g_slist_length (l);
1504         res = mono_array_new (domain, mono_defaults.field_info_class, len);
1505         i = 0;
1506         tmp = g_slist_reverse (l);
1507         for (; tmp; tmp = tmp->next, ++i)
1508                 mono_array_set (res, gpointer, i, tmp->data);
1509         g_slist_free (l);
1510         return res;
1511 }
1512
1513 static MonoArray*
1514 ves_icall_Type_GetMethods (MonoReflectionType *type, guint32 bflags)
1515 {
1516         MonoDomain *domain; 
1517         GSList *l = NULL, *tmp;
1518         static MonoClass *System_Reflection_MethodInfo;
1519         MonoClass *startklass, *klass;
1520         MonoArray *res;
1521         MonoMethod *method;
1522         MonoObject *member;
1523         int i, len, match;
1524         GHashTable *method_slots = g_hash_table_new (NULL, NULL);
1525                 
1526         domain = ((MonoObject *)type)->vtable->domain;
1527         klass = startklass = mono_class_from_mono_type (type->type);
1528         len = 0;
1529
1530 handle_parent:
1531         for (i = 0; i < klass->method.count; ++i) {
1532                 match = 0;
1533                 method = klass->methods [i];
1534                 if (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)
1535                         continue;
1536                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
1537                         if (bflags & BFLAGS_Public)
1538                                 match++;
1539                 } else {
1540                         if (bflags & BFLAGS_NonPublic)
1541                                 match++;
1542                 }
1543                 if (!match)
1544                         continue;
1545                 match = 0;
1546                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
1547                         if (bflags & BFLAGS_Static)
1548                                 match++;
1549                 } else {
1550                         if (bflags & BFLAGS_Instance)
1551                                 match++;
1552                 }
1553
1554                 if (!match)
1555                         continue;
1556                 match = 0;
1557                 if (g_hash_table_lookup (method_slots, GUINT_TO_POINTER (method->slot)))
1558                         continue;
1559                 g_hash_table_insert (method_slots, GUINT_TO_POINTER (method->slot), method);
1560                 member = (MonoObject*)mono_method_get_object (domain, method, startklass);
1561                 
1562                 l = g_slist_prepend (l, member);
1563                 len++;
1564         }
1565         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
1566                 goto handle_parent;
1567         if (!System_Reflection_MethodInfo)
1568                 System_Reflection_MethodInfo = mono_class_from_name (
1569                         mono_defaults.corlib, "System.Reflection", "MethodInfo");
1570         res = mono_array_new (domain, System_Reflection_MethodInfo, len);
1571         i = 0;
1572         tmp = l;
1573         for (; tmp; tmp = tmp->next, ++i)
1574                 mono_array_set (res, gpointer, i, tmp->data);
1575         g_slist_free (l);
1576         g_hash_table_destroy (method_slots);
1577         return res;
1578 }
1579
1580 static MonoArray*
1581 ves_icall_Type_GetConstructors (MonoReflectionType *type, guint32 bflags)
1582 {
1583         MonoDomain *domain; 
1584         GSList *l = NULL, *tmp;
1585         static MonoClass *System_Reflection_ConstructorInfo;
1586         MonoClass *startklass, *klass;
1587         MonoArray *res;
1588         MonoMethod *method;
1589         MonoObject *member;
1590         int i, len, match;
1591
1592         domain = ((MonoObject *)type)->vtable->domain;
1593         klass = startklass = mono_class_from_mono_type (type->type);
1594
1595         for (i = 0; i < klass->method.count; ++i) {
1596                 match = 0;
1597                 method = klass->methods [i];
1598                 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
1599                         continue;
1600                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
1601                         if (bflags & BFLAGS_Public)
1602                                 match++;
1603                 } else {
1604                         if (bflags & BFLAGS_NonPublic)
1605                                 match++;
1606                 }
1607                 if (!match)
1608                         continue;
1609                 match = 0;
1610                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
1611                         if (bflags & BFLAGS_Static)
1612                                 match++;
1613                 } else {
1614                         if (bflags & BFLAGS_Instance)
1615                                 match++;
1616                 }
1617
1618                 if (!match)
1619                         continue;
1620                 member = (MonoObject*)mono_method_get_object (domain, method, startklass);
1621                         
1622                 l = g_slist_prepend (l, member);
1623         }
1624         len = g_slist_length (l);
1625         if (!System_Reflection_ConstructorInfo)
1626                 System_Reflection_ConstructorInfo = mono_class_from_name (
1627                         mono_defaults.corlib, "System.Reflection", "ConstructorInfo");
1628         res = mono_array_new (domain, System_Reflection_ConstructorInfo, len);
1629         i = 0;
1630         tmp = g_slist_reverse (l);
1631         for (; tmp; tmp = tmp->next, ++i)
1632                 mono_array_set (res, gpointer, i, tmp->data);
1633         g_slist_free (l);
1634         return res;
1635 }
1636
1637 static MonoArray*
1638 ves_icall_Type_GetProperties (MonoReflectionType *type, guint32 bflags)
1639 {
1640         MonoDomain *domain; 
1641         GSList *l = NULL, *tmp;
1642         static MonoClass *System_Reflection_PropertyInfo;
1643         MonoClass *startklass, *klass;
1644         MonoArray *res;
1645         MonoMethod *method;
1646         MonoProperty *prop;
1647         int i, match;
1648         int len = 0;
1649         GHashTable *method_slots = g_hash_table_new (NULL, NULL);
1650
1651         domain = ((MonoObject *)type)->vtable->domain;
1652         klass = startklass = mono_class_from_mono_type (type->type);
1653
1654 handle_parent:
1655         for (i = 0; i < klass->property.count; ++i) {
1656                 prop = &klass->properties [i];
1657                 match = 0;
1658                 method = prop->get;
1659                 if (!method)
1660                         method = prop->set;
1661                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
1662                         if (bflags & BFLAGS_Public)
1663                                 match++;
1664                 } else {
1665                         if (bflags & BFLAGS_NonPublic)
1666                                 match++;
1667                 }
1668                 if (!match)
1669                         continue;
1670                 match = 0;
1671                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
1672                         if (bflags & BFLAGS_Static)
1673                                 match++;
1674                 } else {
1675                         if (bflags & BFLAGS_Instance)
1676                                 match++;
1677                 }
1678
1679                 if (!match)
1680                         continue;
1681                 match = 0;
1682
1683                 if (g_hash_table_lookup (method_slots, GUINT_TO_POINTER (method->slot)))
1684                         continue;
1685                 g_hash_table_insert (method_slots, GUINT_TO_POINTER (method->slot), prop);
1686
1687                 l = g_slist_prepend (l, mono_property_get_object (domain, klass, prop));
1688                 len++;
1689         }
1690         if ((!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent)))
1691                 goto handle_parent;
1692         if (!System_Reflection_PropertyInfo)
1693                 System_Reflection_PropertyInfo = mono_class_from_name (
1694                         mono_defaults.corlib, "System.Reflection", "PropertyInfo");
1695         res = mono_array_new (domain, System_Reflection_PropertyInfo, len);
1696         i = 0;
1697         tmp = l;
1698         for (; tmp; tmp = tmp->next, ++i)
1699                 mono_array_set (res, gpointer, i, tmp->data);
1700         g_slist_free (l);
1701         g_hash_table_destroy (method_slots);
1702         return res;
1703 }
1704
1705 static MonoReflectionEvent *
1706 ves_icall_MonoType_GetEvent (MonoReflectionType *type, MonoString *name, guint32 bflags)
1707 {
1708         MonoDomain *domain;
1709         MonoClass *klass;
1710         gint i;
1711         MonoEvent *event;
1712         MonoMethod *method;
1713         gchar *event_name;
1714
1715         event_name = mono_string_to_utf8 (name);
1716         klass = mono_class_from_mono_type (type->type);
1717         domain = mono_object_domain (type);
1718
1719 handle_parent:  
1720         for (i = 0; i < klass->event.count; i++) {
1721                 event = &klass->events [i];
1722                 if (strcmp (event->name, event_name))
1723                         continue;
1724
1725                 method = event->add;
1726                 if (!method)
1727                         method = event->remove;
1728
1729                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
1730                         if (!(bflags & BFLAGS_Public))
1731                                 continue;
1732                 } else {
1733                         if (!(bflags & BFLAGS_NonPublic))
1734                                 continue;
1735                 }
1736
1737                 g_free (event_name);
1738                 return mono_event_get_object (domain, klass, event);
1739         }
1740
1741         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
1742                 goto handle_parent;
1743
1744         g_free (event_name);
1745         return NULL;
1746 }
1747
1748 static MonoArray*
1749 ves_icall_Type_GetEvents (MonoReflectionType *type, guint32 bflags)
1750 {
1751         MonoDomain *domain; 
1752         GSList *l = NULL, *tmp;
1753         static MonoClass *System_Reflection_EventInfo;
1754         MonoClass *startklass, *klass;
1755         MonoArray *res;
1756         MonoMethod *method;
1757         MonoEvent *event;
1758         int i, len, match;
1759
1760         domain = ((MonoObject *)type)->vtable->domain;
1761         klass = startklass = mono_class_from_mono_type (type->type);
1762
1763 handle_parent:  
1764         for (i = 0; i < klass->event.count; ++i) {
1765                 event = &klass->events [i];
1766                 match = 0;
1767                 method = event->add;
1768                 if (!method)
1769                         method = event->remove;
1770                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
1771                         if (bflags & BFLAGS_Public)
1772                                 match++;
1773                 } else {
1774                         if (bflags & BFLAGS_NonPublic)
1775                                 match++;
1776                 }
1777                 if (!match)
1778                         continue;
1779                 match = 0;
1780                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
1781                         if (bflags & BFLAGS_Static)
1782                                 match++;
1783                 } else {
1784                         if (bflags & BFLAGS_Instance)
1785                                 match++;
1786                 }
1787
1788                 if (!match)
1789                         continue;
1790                 match = 0;
1791                 l = g_slist_prepend (l, mono_event_get_object (domain, klass, event));
1792         }
1793         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
1794                 goto handle_parent;
1795         len = g_slist_length (l);
1796         if (!System_Reflection_EventInfo)
1797                 System_Reflection_EventInfo = mono_class_from_name (
1798                         mono_defaults.corlib, "System.Reflection", "EventInfo");
1799         res = mono_array_new (domain, System_Reflection_EventInfo, len);
1800         i = 0;
1801         tmp = l;
1802         for (; tmp; tmp = tmp->next, ++i)
1803                 mono_array_set (res, gpointer, i, tmp->data);
1804         g_slist_free (l);
1805         return res;
1806 }
1807
1808 static MonoArray*
1809 ves_icall_Type_GetNestedTypes (MonoReflectionType *type, guint32 bflags)
1810 {
1811         MonoDomain *domain; 
1812         GSList *l = NULL, *tmp;
1813         GList *tmpn;
1814         MonoClass *startklass, *klass;
1815         MonoArray *res;
1816         MonoObject *member;
1817         int i, len, match;
1818         MonoClass *nested;
1819
1820         domain = ((MonoObject *)type)->vtable->domain;
1821         klass = startklass = mono_class_from_mono_type (type->type);
1822
1823         for (tmpn = klass->nested_classes; tmpn; tmpn = tmpn->next) {
1824                 match = 0;
1825                 nested = tmpn->data;
1826                 if ((nested->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
1827                         if (bflags & BFLAGS_Public)
1828                                 match++;
1829                 } else {
1830                         if (bflags & BFLAGS_NonPublic)
1831                                 match++;
1832                 }
1833                 if (!match)
1834                         continue;
1835                 member = (MonoObject*)mono_type_get_object (domain, &nested->byval_arg);
1836                 l = g_slist_prepend (l, member);
1837         }
1838         len = g_slist_length (l);
1839         res = mono_array_new (domain, mono_defaults.monotype_class, len);
1840         i = 0;
1841         tmp = g_slist_reverse (l);
1842         for (; tmp; tmp = tmp->next, ++i)
1843                 mono_array_set (res, gpointer, i, tmp->data);
1844         g_slist_free (l);
1845         return res;
1846 }
1847
1848 static MonoReflectionType*
1849 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssembly *assembly, MonoString *name, MonoBoolean throwOnError, MonoBoolean ignoreCase)
1850 {
1851         gchar *str;
1852         MonoType *type;
1853         MonoTypeNameParse info;
1854
1855         str = mono_string_to_utf8 (name);
1856         /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
1857         if (!mono_reflection_parse_type (str, &info)) {
1858                 g_free (str);
1859                 g_list_free (info.modifiers);
1860                 g_list_free (info.nested);
1861                 if (throwOnError) /* uhm: this is a parse error, though... */
1862                         mono_raise_exception (mono_get_exception_type_load ());
1863                 /*g_print ("failed parse\n");*/
1864                 return NULL;
1865         }
1866
1867         type = mono_reflection_get_type (assembly->assembly->image, &info, ignoreCase);
1868         g_free (str);
1869         g_list_free (info.modifiers);
1870         g_list_free (info.nested);
1871         if (!type) {
1872                 if (throwOnError)
1873                         mono_raise_exception (mono_get_exception_type_load ());
1874                 /* g_print ("failed find\n"); */
1875                 return NULL;
1876         }
1877         /* g_print ("got it\n"); */
1878         return mono_type_get_object (mono_object_domain (assembly), type);
1879
1880 }
1881
1882 static MonoString *
1883 ves_icall_System_Reflection_Assembly_get_code_base (MonoReflectionAssembly *assembly)
1884 {
1885         MonoDomain *domain = mono_object_domain (assembly); 
1886         MonoString *res;
1887         char *name = g_strconcat (
1888                 "file://", assembly->assembly->image->name, NULL);
1889         
1890         res = mono_string_new (domain, name);
1891         g_free (name);
1892         return res;
1893 }
1894
1895 static MonoString *
1896 ves_icall_System_Reflection_Assembly_get_location (MonoReflectionAssembly *assembly)
1897 {
1898         MonoDomain *domain = mono_object_domain (assembly); 
1899         MonoString *res;
1900         char *name = g_strconcat (
1901                 assembly->assembly->basedir,
1902                 assembly->assembly->image->module_name, NULL);
1903
1904         res = mono_string_new (domain, name);
1905         g_free (name);
1906         return res;
1907 }
1908
1909 static MonoReflectionMethod*
1910 ves_icall_System_Reflection_Assembly_get_EntryPoint (MonoReflectionAssembly *assembly) {
1911         guint32 token = mono_image_get_entry_point (assembly->assembly->image);
1912         if (!token)
1913                 return NULL;
1914         return mono_method_get_object (mono_object_domain (assembly), mono_get_method (assembly->assembly->image, token, NULL), NULL);
1915 }
1916
1917 static MonoArray*
1918 ves_icall_System_Reflection_Assembly_GetManifestResourceNames (MonoReflectionAssembly *assembly) {
1919         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
1920         MonoArray *result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, table->rows);
1921         int i;
1922         const char *val;
1923
1924         for (i = 0; i < table->rows; ++i) {
1925                 val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
1926                 mono_array_set (result, gpointer, i, mono_string_new (mono_object_domain (assembly), val));
1927         }
1928         return result;
1929 }
1930
1931 static MonoArray*
1932 ves_icall_System_Reflection_Assembly_GetReferencedAssemblies (MonoReflectionAssembly *assembly) {
1933         static MonoClass *System_Reflection_AssemblyName;
1934         MonoArray *result;
1935         MonoAssembly **ptr;
1936         int i, count = 0;
1937
1938         if (!System_Reflection_AssemblyName)
1939                 System_Reflection_AssemblyName = mono_class_from_name (
1940                         mono_defaults.corlib, "System.Reflection", "AssemblyName");
1941
1942         for (ptr = assembly->assembly->image->references; ptr && *ptr; ptr++)
1943                 count++;
1944
1945         result = mono_array_new (mono_object_domain (assembly), System_Reflection_AssemblyName, count);
1946
1947         for (i = 0; i < count; i++) {
1948                 MonoAssembly *assem = assembly->assembly->image->references [i];
1949                 MonoReflectionAssemblyName *aname;
1950
1951                 aname = (MonoReflectionAssemblyName *) mono_object_new (
1952                         mono_object_domain (assembly), System_Reflection_AssemblyName);
1953
1954                 if (strcmp (assem->aname.name, "corlib") == 0)
1955                         aname->name = mono_string_new (mono_object_domain (assembly), "mscorlib");
1956                 else
1957                         aname->name = mono_string_new (mono_object_domain (assembly), assem->aname.name);
1958                 aname->major = assem->aname.major;
1959
1960                 mono_array_set (result, gpointer, i, aname);
1961         }
1962         return result;
1963 }
1964
1965 /* move this in some file in mono/util/ */
1966 static char *
1967 g_concat_dir_and_file (const char *dir, const char *file)
1968 {
1969         g_return_val_if_fail (dir != NULL, NULL);
1970         g_return_val_if_fail (file != NULL, NULL);
1971
1972         /*
1973          * If the directory name doesn't have a / on the end, we need
1974          * to add one so we get a proper path to the file
1975          */
1976         if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
1977                 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
1978         else
1979                 return g_strconcat (dir, file, NULL);
1980 }
1981
1982 static MonoObject*
1983 ves_icall_System_Reflection_Assembly_GetManifestResourceInternal (MonoReflectionAssembly *assembly, MonoString *name) {
1984         char *n = mono_string_to_utf8 (name);
1985         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
1986         guint32 i;
1987         guint32 cols [MONO_MANIFEST_SIZE];
1988         const char *val;
1989         MonoObject *result;
1990
1991         for (i = 0; i < table->rows; ++i) {
1992                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
1993                 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
1994                 if (strcmp (val, n) == 0)
1995                         break;
1996         }
1997         g_free (n);
1998         if (i == table->rows)
1999                 return NULL;
2000         /* FIXME */
2001         if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
2002                 guint32 size;
2003                 MonoArray *data;
2004                 val = mono_image_get_resource (assembly->assembly->image, cols [MONO_MANIFEST_OFFSET], &size);
2005                 if (!val)
2006                         return NULL;
2007                 data = mono_array_new (mono_object_domain (assembly), mono_defaults.byte_class, size);
2008                 memcpy (mono_array_addr (data, char, 0), val, size);
2009                 return (MonoObject*)data;
2010         }
2011         switch (cols [MONO_MANIFEST_IMPLEMENTATION] & IMPLEMENTATION_MASK) {
2012         case IMPLEMENTATION_FILE:
2013                 i = cols [MONO_MANIFEST_IMPLEMENTATION] >> IMPLEMENTATION_BITS;
2014                 table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
2015                 i = mono_metadata_decode_row_col (table, i - 1, MONO_FILE_NAME);
2016                 val = mono_metadata_string_heap (assembly->assembly->image, i);
2017                 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
2018                 result = (MonoObject*)mono_string_new (mono_object_domain (assembly), n);
2019                 /* check hash if needed */
2020                 g_free (n);
2021                 return result;
2022         case IMPLEMENTATION_ASSEMBLYREF:
2023         case IMPLEMENTATION_EXP_TYPE:
2024                 /* FIXME */
2025                 break;
2026         }
2027         return NULL;
2028 }
2029
2030 static MonoObject*
2031 ves_icall_System_Reflection_Assembly_GetFilesInternal (MonoReflectionAssembly *assembly, MonoString *name) {
2032         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
2033         MonoArray *result;
2034         int i;
2035         const char *val;
2036         char *n;
2037
2038         /* check hash if needed */
2039         if (name) {
2040                 n = mono_string_to_utf8 (name);
2041                 for (i = 0; i < table->rows; ++i) {
2042                         val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
2043                         if (strcmp (val, n) == 0) {
2044                                 MonoString *fn;
2045                                 g_free (n);
2046                                 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
2047                                 fn = mono_string_new (mono_object_domain (assembly), n);
2048                                 g_free (n);
2049                                 return (MonoObject*)fn;
2050                         }
2051                 }
2052                 g_free (n);
2053                 return NULL;
2054         }
2055
2056         for (i = 0; i < table->rows; ++i) {
2057                 result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, table->rows);
2058                 val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
2059                 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
2060                 mono_array_set (result, gpointer, i, mono_string_new (mono_object_domain (assembly), n));
2061                 g_free (n);
2062         }
2063         return (MonoObject*)result;
2064 }
2065
2066 static MonoReflectionMethod*
2067 ves_icall_GetCurrentMethod (void) {
2068         MonoMethod *m = mono_method_get_last_managed ();
2069         return mono_method_get_object (mono_domain_get (), m, NULL);
2070 }
2071
2072 static MonoReflectionAssembly*
2073 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (void)
2074 {
2075         MonoMethod *m = mono_method_get_last_managed ();
2076         return mono_assembly_get_object (mono_domain_get (), m->klass->image->assembly);
2077 }
2078
2079
2080 static gboolean
2081 get_caller (MonoMethod *m, gint32 no, gint32 ilo, gpointer data)
2082 {
2083         MonoMethod **dest = data;
2084         if (m == *dest) {
2085                 *dest = NULL;
2086                 return FALSE;
2087         }
2088         if (!(*dest)) {
2089                 *dest = m;
2090                 return TRUE;
2091         }
2092         return FALSE;
2093 }
2094
2095 static MonoReflectionAssembly*
2096 ves_icall_System_Reflection_Assembly_GetEntryAssembly (void)
2097 {
2098         MonoDomain* domain = mono_domain_get ();
2099         g_assert (domain->entry_assembly);
2100         return mono_assembly_get_object (domain, domain->entry_assembly);
2101 }
2102
2103
2104 static MonoReflectionAssembly*
2105 ves_icall_System_Reflection_Assembly_GetCallingAssembly (void)
2106 {
2107         MonoMethod *m = mono_method_get_last_managed ();
2108         MonoMethod *dest = m;
2109         mono_stack_walk (get_caller, &dest);
2110         if (!dest)
2111                 dest = m;
2112         return mono_assembly_get_object (mono_domain_get (), dest->klass->image->assembly);
2113 }
2114
2115 static MonoString *
2116 ves_icall_System_MonoType_getFullName (MonoReflectionType *object)
2117 {
2118         MonoDomain *domain = mono_object_domain (object); 
2119         MonoString *res;
2120         gchar *name;
2121
2122         name = mono_type_get_name (object->type);
2123         res = mono_string_new (domain, name);
2124         g_free (name);
2125
2126         return res;
2127 }
2128
2129 static void
2130 ves_icall_System_Reflection_Assembly_FillName (MonoReflectionAssembly *assembly, MonoReflectionAssemblyName *aname)
2131 {
2132         MonoAssemblyName *name = &assembly->assembly->aname;
2133
2134         if (strcmp (name->name, "corlib") == 0)
2135                 aname->name = mono_string_new (mono_object_domain (assembly), "mscorlib");
2136         else
2137                 aname->name = mono_string_new (mono_object_domain (assembly), name->name);
2138         aname->major = name->major;
2139 }
2140
2141 static MonoArray*
2142 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssembly *assembly, MonoBoolean exportedOnly)
2143 {
2144         MonoDomain *domain = mono_object_domain (assembly); 
2145         MonoArray *res;
2146         MonoClass *klass;
2147         MonoTableInfo *tdef = &assembly->assembly->image->tables [MONO_TABLE_TYPEDEF];
2148         int i, count;
2149         guint32 attrs, visibility;
2150
2151         /* we start the count from 1 because we skip the special type <Module> */
2152         if (exportedOnly) {
2153                 count = 0;
2154                 for (i = 1; i < tdef->rows; ++i) {
2155                         attrs = mono_metadata_decode_row_col (tdef, i, MONO_TYPEDEF_FLAGS);
2156                         visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
2157                         if (visibility == TYPE_ATTRIBUTE_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_PUBLIC)
2158                                 count++;
2159                 }
2160         } else {
2161                 count = tdef->rows - 1;
2162         }
2163         res = mono_array_new (domain, mono_defaults.monotype_class, count);
2164         count = 0;
2165         for (i = 1; i < tdef->rows; ++i) {
2166                 attrs = mono_metadata_decode_row_col (tdef, i, MONO_TYPEDEF_FLAGS);
2167                 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
2168                 if (!exportedOnly || (visibility == TYPE_ATTRIBUTE_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_PUBLIC)) {
2169                         klass = mono_class_get (assembly->assembly->image, (i + 1) | MONO_TOKEN_TYPE_DEF);
2170                         mono_array_set (res, gpointer, count, mono_type_get_object (domain, &klass->byval_arg));
2171                         count++;
2172                 }
2173         }
2174         
2175         return res;
2176 }
2177
2178 static MonoReflectionType*
2179 ves_icall_ModuleBuilder_create_modified_type (MonoReflectionTypeBuilder *tb, MonoString *smodifiers)
2180 {
2181         MonoClass *klass;
2182         int isbyref = 0, rank;
2183         char *str = mono_string_to_utf8 (smodifiers);
2184         char *p;
2185
2186         klass = mono_class_from_mono_type (tb->type.type);
2187         p = str;
2188         /* logic taken from mono_reflection_parse_type(): keep in sync */
2189         while (*p) {
2190                 switch (*p) {
2191                 case '&':
2192                         if (isbyref) { /* only one level allowed by the spec */
2193                                 g_free (str);
2194                                 return NULL;
2195                         }
2196                         isbyref = 1;
2197                         p++;
2198                         g_free (str);
2199                         return mono_type_get_object (mono_object_domain (tb), &klass->this_arg);
2200                         break;
2201                 case '*':
2202                         klass = mono_ptr_class_get (&klass->byval_arg);
2203                         mono_class_init (klass);
2204                         p++;
2205                         break;
2206                 case '[':
2207                         rank = 1;
2208                         p++;
2209                         while (*p) {
2210                                 if (*p == ']')
2211                                         break;
2212                                 if (*p == ',')
2213                                         rank++;
2214                                 else if (*p != '*') { /* '*' means unknown lower bound */
2215                                         g_free (str);
2216                                         return NULL;
2217                                 }
2218                                 ++p;
2219                         }
2220                         if (*p != ']') {
2221                                 g_free (str);
2222                                 return NULL;
2223                         }
2224                         p++;
2225                         klass = mono_array_class_get (&klass->byval_arg, rank);
2226                         mono_class_init (klass);
2227                         break;
2228                 default:
2229                         break;
2230                 }
2231         }
2232         g_free (str);
2233         return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
2234 }
2235
2236 static MonoObject *
2237 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionType *type, MonoObject *target,
2238                                                    MonoReflectionMethod *info)
2239 {
2240         MonoClass *delegate_class = mono_class_from_mono_type (type->type);
2241         MonoObject *delegate;
2242         gpointer func;
2243
2244         mono_assert (delegate_class->parent == mono_defaults.multicastdelegate_class);
2245
2246         delegate = mono_object_new (mono_object_domain (type), delegate_class);
2247
2248         func = mono_compile_method (info->method);
2249
2250         mono_delegate_ctor (delegate, target, func);
2251
2252         return delegate;
2253 }
2254
2255 /*
2256  * Magic number to convert a time which is relative to
2257  * Jan 1, 1970 into a value which is relative to Jan 1, 0001.
2258  */
2259 #define EPOCH_ADJUST    ((gint64)62135596800L)
2260
2261 static gint64
2262 ves_icall_System_DateTime_GetNow (void)
2263 {
2264 #ifdef PLATFORM_WIN32
2265         SYSTEMTIME st;
2266         FILETIME ft;
2267         
2268         GetLocalTime (&st);
2269         SystemTimeToFileTime (&st, &ft);
2270         return (gint64)504911232000000000L + ((((gint64)ft.dwHighDateTime)<<32) | ft.dwLowDateTime);
2271 #else
2272         /* FIXME: put this in io-layer and call it GetLocalTime */
2273         struct timeval tv;
2274         gint64 res;
2275
2276         if (gettimeofday (&tv, NULL) == 0) {
2277                 res = (((gint64)tv.tv_sec + EPOCH_ADJUST)* 1000000 + tv.tv_usec)*10;
2278                 return res;
2279         }
2280         /* fixme: raise exception */
2281         return 0;
2282 #endif
2283 }
2284
2285 /*
2286  * This is heavily based on zdump.c from glibc 2.2.
2287  *
2288  *  * data[0]:  start of daylight saving time (in DateTime ticks).
2289  *  * data[1]:  end of daylight saving time (in DateTime ticks).
2290  *  * data[2]:  utcoffset (in TimeSpan ticks).
2291  *  * data[3]:  additional offset when daylight saving (in TimeSpan ticks).
2292  *  * name[0]:  name of this timezone when not daylight saving.
2293  *  * name[1]:  name of this timezone when daylight saving.
2294  *
2295  *  FIXME: This only works with "standard" Unix dates (years between 1900 and 2100) while
2296  *         the class library allows years between 1 and 9999.
2297  *
2298  *  Returns true on success and zero on failure.
2299  */
2300 static guint32
2301 ves_icall_System_CurrentTimeZone_GetTimeZoneData (guint32 year, MonoArray **data, MonoArray **names)
2302 {
2303 #ifndef PLATFORM_WIN32
2304         MonoDomain *domain = mono_domain_get ();
2305         struct tm start, tt;
2306         time_t t;
2307
2308         long int gmtoff;
2309         int is_daylight = 0, day;
2310
2311         memset (&start, 0, sizeof (start));
2312
2313         start.tm_mday = 1;
2314         start.tm_year = year-1900;
2315
2316         t = mktime (&start);
2317 #if defined (HAVE_TIMEZONE)
2318 #define gmt_offset(x) (-1 * (((timezone / 60 / 60) - daylight) * 100))
2319 #elif defined (HAVE_TM_GMTOFF)
2320 #define gmt_offset(x) x.tm_gmtoff
2321 #else
2322 #error Neither HAVE_TIMEZONE nor HAVE_TM_GMTOFF defined. Rerun autoheader, autoconf, etc.
2323 #endif
2324         
2325         gmtoff = gmt_offset (start);
2326         
2327         MONO_CHECK_ARG_NULL (data);
2328         MONO_CHECK_ARG_NULL (names);
2329
2330         (*data) = mono_array_new (domain, mono_defaults.int64_class, 4);
2331         (*names) = mono_array_new (domain, mono_defaults.string_class, 2);
2332
2333         /* For each day of the year, calculate the tm_gmtoff. */
2334         for (day = 0; day < 365; day++) {
2335
2336                 t += 3600*24;
2337                 tt = *localtime (&t);
2338
2339                 /* Daylight saving starts or ends here. */
2340                 if (gmt_offset (tt) != gmtoff) {
2341                         char tzone[10];
2342                         struct tm tt1;
2343                         time_t t1;
2344
2345                         /* Try to find the exact hour when daylight saving starts/ends. */
2346                         t1 = t;
2347                         do {
2348                                 t1 -= 3600;
2349                                 tt1 = *localtime (&t1);
2350                         } while (gmt_offset (tt1) != gmtoff);
2351
2352                         /* Try to find the exact minute when daylight saving starts/ends. */
2353                         do {
2354                                 t1 += 60;
2355                                 tt1 = *localtime (&t1);
2356                         } while (gmt_offset (tt1) == gmtoff);
2357                         
2358                         strftime (tzone, 10, "%Z", &tt);
2359                         
2360                         /* Write data, if we're already in daylight saving, we're done. */
2361                         if (is_daylight) {
2362                                 mono_array_set ((*names), gpointer, 0, mono_string_new (domain, tzone));
2363                                 mono_array_set ((*data), gint64, 1, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
2364                                 return 1;
2365                         } else {
2366                                 mono_array_set ((*names), gpointer, 1, mono_string_new (domain, tzone));
2367                                 mono_array_set ((*data), gint64, 0, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
2368                                 is_daylight = 1;
2369                         }
2370
2371                         /* This is only set once when we enter daylight saving. */
2372                         mono_array_set ((*data), gint64, 2, (gint64)gmtoff * 10000000L);
2373                         mono_array_set ((*data), gint64, 3, (gint64)(gmt_offset (tt) - gmtoff) * 10000000L);
2374
2375                         gmtoff = gmt_offset (tt);
2376                 }
2377
2378                 gmtoff = gmt_offset (tt);
2379         }
2380         return 1;
2381 #else
2382         MonoDomain *domain = mono_domain_get ();
2383         TIME_ZONE_INFORMATION tz_info;
2384         FILETIME ft;
2385         int i;
2386
2387         GetTimeZoneInformation (&tz_info);
2388
2389         MONO_CHECK_ARG_NULL (data);
2390         MONO_CHECK_ARG_NULL (names);
2391
2392         (*data) = mono_array_new (domain, mono_defaults.int64_class, 4);
2393         (*names) = mono_array_new (domain, mono_defaults.string_class, 2);
2394
2395         for (i = 0; i < 32; ++i)
2396                 if (!tz_info.DaylightName [i])
2397                         break;
2398         mono_array_set ((*names), gpointer, 1, mono_string_new_utf16 (domain, tz_info.DaylightName, i));
2399         for (i = 0; i < 32; ++i)
2400                 if (!tz_info.StandardName [i])
2401                         break;
2402         mono_array_set ((*names), gpointer, 0, mono_string_new_utf16 (domain, tz_info.StandardName, i));
2403
2404         SystemTimeToFileTime (&tz_info.StandardDate, &ft);
2405         mono_array_set ((*data), gint64, 1, ((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime);
2406         SystemTimeToFileTime (&tz_info.DaylightDate, &ft);
2407         mono_array_set ((*data), gint64, 0, ((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime);
2408         mono_array_set ((*data), gint64, 3, tz_info.Bias + tz_info.StandardBias);
2409         mono_array_set ((*data), gint64, 2, tz_info.Bias + tz_info.DaylightBias);
2410
2411         return 1;
2412 #endif
2413 }
2414
2415 static gpointer
2416 ves_icall_System_Object_obj_address (MonoObject *this) {
2417         return this;
2418 }
2419
2420 /* System.Buffer */
2421
2422 static gint32 
2423 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array) {
2424         MonoClass *klass;
2425         MonoTypeEnum etype;
2426         int length, esize;
2427         int i;
2428
2429         klass = array->obj.vtable->klass;
2430         etype = klass->element_class->byval_arg.type;
2431         if (etype < MONO_TYPE_BOOLEAN || etype > MONO_TYPE_R8)
2432                 return -1;
2433
2434         if (array->bounds == NULL)
2435                 length = array->max_length;
2436         else {
2437                 length = 0;
2438                 for (i = 0; i < klass->rank; ++ i)
2439                         length += array->bounds [i].length;
2440         }
2441
2442         esize = mono_array_element_size (klass);
2443         return length * esize;
2444 }
2445
2446 static gint8 
2447 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx) {
2448         return mono_array_get (array, gint8, idx);
2449 }
2450
2451 static void 
2452 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value) {
2453         mono_array_set (array, gint8, idx, value);
2454 }
2455
2456 static void 
2457 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count) {
2458         char *src_buf, *dest_buf;
2459
2460         src_buf = (gint8 *)src->vector + src_offset;
2461         dest_buf = (gint8 *)dest->vector + dest_offset;
2462
2463         memcpy (dest_buf, src_buf, count);
2464 }
2465
2466 static MonoObject *
2467 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObject *this)
2468 {
2469         MonoDomain *domain = mono_object_domain (this); 
2470         MonoObject *res;
2471         MonoRealProxy *rp = ((MonoRealProxy *)this);
2472         MonoType *type;
2473         MonoClass *klass;
2474
2475         res = mono_object_new (domain, mono_defaults.transparent_proxy_class);
2476         
2477         ((MonoTransparentProxy *)res)->rp = rp;
2478         type = ((MonoReflectionType *)rp->class_to_proxy)->type;
2479         klass = mono_class_from_mono_type (type);
2480
2481         ((MonoTransparentProxy *)res)->klass = klass;
2482
2483         res->vtable = mono_class_proxy_vtable (domain, klass);
2484
2485         return res;
2486 }
2487
2488 /* System.Environment */
2489
2490 static MonoString *
2491 ves_icall_System_Environment_get_MachineName (void)
2492 {
2493 #if defined (PLATFORM_WIN32)
2494         gunichar2 *buf;
2495         guint32 len;
2496         MonoString *result;
2497
2498         len = MAX_COMPUTERNAME_LENGTH + 1;
2499         buf = g_new (gunichar2, len);
2500
2501         result = NULL;
2502         if (GetComputerName (buf, (PDWORD) &len))
2503                 result = mono_string_new_utf16 (mono_domain_get (), buf, len);
2504
2505         g_free (buf);
2506         return result;
2507 #else
2508         gchar *buf;
2509         int len;
2510         MonoString *result;
2511
2512         len = 256;
2513         buf = g_new (gchar, len);
2514
2515         result = NULL;
2516         if (gethostname (buf, len) != 0)
2517                 result = mono_string_new (mono_domain_get (), buf);
2518         
2519         g_free (buf);
2520         return result;
2521 #endif
2522 }
2523
2524 static int
2525 ves_icall_System_Environment_get_Platform (void)
2526 {
2527 #if defined (PLATFORM_WIN32)
2528         /* Win32NT */
2529         return 2;
2530 #else
2531         /* Unix */
2532         return 128;
2533 #endif
2534 }
2535
2536 static MonoString *
2537 ves_icall_System_Environment_get_NewLine (void)
2538 {
2539 #if defined (PLATFORM_WIN32)
2540         return mono_string_new (mono_domain_get (), "\r\n");
2541 #else
2542         return mono_string_new (mono_domain_get (), "\n");
2543 #endif
2544 }
2545
2546 static MonoString *
2547 ves_icall_System_Environment_GetEnvironmentVariable (MonoString *name)
2548 {
2549         const gchar *value;
2550         gchar *utf8_name;
2551
2552         if (name == NULL)
2553                 return NULL;
2554
2555         utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
2556         value = g_getenv (utf8_name);
2557         g_free (utf8_name);
2558
2559         if (value == 0)
2560                 return NULL;
2561         
2562         return mono_string_new (mono_domain_get (), value);
2563 }
2564
2565 /*
2566  * There is no standard way to get at environ.
2567  */
2568 extern char **environ;
2569
2570 static MonoArray *
2571 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
2572 {
2573         MonoArray *names;
2574         MonoDomain *domain;
2575         MonoString *str;
2576         gchar **e, **parts;
2577         int n;
2578
2579         n = 0;
2580         for (e = environ; *e != 0; ++ e)
2581                 ++ n;
2582
2583         domain = mono_domain_get ();
2584         names = mono_array_new (domain, mono_defaults.string_class, n);
2585
2586         n = 0;
2587         for (e = environ; *e != 0; ++ e) {
2588                 parts = g_strsplit (*e, "=", 2);
2589                 if (*parts != 0) {
2590                         str = mono_string_new (domain, *parts);
2591                         mono_array_set (names, MonoString *, n, str);
2592                 }
2593
2594                 g_strfreev (parts);
2595
2596                 ++ n;
2597         }
2598
2599         return names;
2600 }
2601
2602 /*
2603  * Returns the number of milliseconds elapsed since the system started.
2604  */
2605 static gint32
2606 ves_icall_System_Environment_get_TickCount (void)
2607 {
2608 #if defined (PLATFORM_WIN32)
2609         return GetTickCount();
2610 #else
2611         struct timeval tv;
2612         struct timezone tz;
2613         gint32 res;
2614
2615         res = (gint32) gettimeofday (&tv, &tz);
2616
2617         if (res != -1)
2618                 res = (gint32) ((tv.tv_sec & 0xFFFFF) * 1000 + (tv.tv_usec / 1000));
2619         return res;
2620 #endif
2621 }
2622
2623
2624 static void
2625 ves_icall_System_Environment_Exit (int result)
2626 {
2627         /* we may need to do some cleanup here... */
2628         exit (result);
2629 }
2630
2631 static MonoString*
2632 ves_icall_System_Text_Encoding_InternalCodePage (void) {
2633         const char *cset;
2634         g_get_charset (&cset);
2635         /* g_print ("charset: %s\n", cset); */
2636         /* handle some common aliases */
2637         switch (*cset) {
2638         case 'A':
2639                 if (strcmp (cset, "ANSI_X3.4-1968") == 0)
2640                         cset = "us-ascii";
2641                 break;
2642         }
2643         return mono_string_new (mono_domain_get (), cset);
2644 }
2645
2646 static void
2647 ves_icall_MonoMethodMessage_InitMessage (MonoMethodMessage *this, 
2648                                          MonoReflectionMethod *method,
2649                                          MonoArray *out_args)
2650 {
2651         mono_message_init (mono_object_domain (this), this, method, out_args);
2652 }
2653
2654 static MonoBoolean
2655 ves_icall_IsTransparentProxy (MonoObject *proxy)
2656 {
2657         if (!proxy)
2658                 return 0;
2659
2660         if (proxy->vtable->klass == mono_defaults.transparent_proxy_class)
2661                 return 1;
2662
2663         return 0;
2664 }
2665
2666 static MonoObject *
2667 ves_icall_System_Runtime_Serialization_FormatterServices_GetUninitializedObject_Internal (MonoReflectionType *type)
2668 {
2669         MonoClass *klass;
2670         MonoObject *obj;
2671         MonoDomain *domain;
2672         
2673         domain = mono_object_domain (type);
2674         klass = mono_class_from_mono_type (type->type);
2675
2676         if (klass->rank >= 1) {
2677                 g_assert (klass->rank == 1);
2678                 obj = (MonoObject *) mono_array_new (domain, klass->element_class, 0);
2679         } else {
2680                 obj = mono_object_new (domain, klass);
2681         }
2682
2683         return obj;
2684 }
2685
2686 static MonoString *
2687 ves_icall_System_IO_get_temp_path (void)
2688 {
2689         return mono_string_new (mono_domain_get (), g_get_tmp_dir ());
2690 }
2691
2692 static gpointer
2693 ves_icall_RuntimeMethod_GetFunctionPointer (MonoMethod *method)
2694 {
2695         return mono_compile_method (method);
2696 }
2697
2698 static MonoString *
2699 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
2700 {
2701         static MonoString *mcpath;
2702         gchar *path;
2703
2704         if (mcpath != NULL)
2705                 return mcpath;
2706
2707         path = g_build_path (G_DIR_SEPARATOR_S, MONO_CFG_DIR, "mono", "machine.config", NULL);
2708
2709 #if defined (PLATFORM_WIN32)
2710         /* Avoid mixing '/' and '\\' */
2711         {
2712                 gint i;
2713                 for (i = strlen (path) - 1; i >= 0; i--)
2714                         if (path [i] == '/')
2715                                 path [i] = '\\';
2716         }
2717 #endif
2718         mcpath = mono_string_new (mono_domain_get (), path);
2719         g_free (path);
2720
2721         return mcpath;
2722 }
2723
2724 /* icall map */
2725
2726 static gconstpointer icall_map [] = {
2727         /*
2728          * System.Array
2729          */
2730         "System.Array::GetValue",         ves_icall_System_Array_GetValue,
2731         "System.Array::SetValue",         ves_icall_System_Array_SetValue,
2732         "System.Array::GetValueImpl",     ves_icall_System_Array_GetValueImpl,
2733         "System.Array::SetValueImpl",     ves_icall_System_Array_SetValueImpl,
2734         "System.Array::GetRank",          ves_icall_System_Array_GetRank,
2735         "System.Array::GetLength",        ves_icall_System_Array_GetLength,
2736         "System.Array::GetLowerBound",    ves_icall_System_Array_GetLowerBound,
2737         "System.Array::CreateInstanceImpl",   ves_icall_System_Array_CreateInstanceImpl,
2738         "System.Array::FastCopy",         ves_icall_System_Array_FastCopy,
2739         "System.Array::Clone",            mono_array_clone,
2740
2741         /*
2742          * System.Object
2743          */
2744         "System.Object::MemberwiseClone", ves_icall_System_Object_MemberwiseClone,
2745         "System.Object::GetType", ves_icall_System_Object_GetType,
2746         "System.Object::GetHashCode", ves_icall_System_Object_GetHashCode,
2747         "System.Object::obj_address", ves_icall_System_Object_obj_address,
2748
2749         /*
2750          * System.ValueType
2751          */
2752         "System.ValueType::GetHashCode", ves_icall_System_ValueType_GetHashCode,
2753         "System.ValueType::Equals", ves_icall_System_ValueType_Equals,
2754
2755         /*
2756          * System.String
2757          */
2758         
2759         "System.String::.ctor(char*)", ves_icall_System_String_ctor_charp,
2760         "System.String::.ctor(char*,int,int)", ves_icall_System_String_ctor_charp_int_int,
2761         "System.String::.ctor(sbyte*)", ves_icall_System_String_ctor_sbytep,
2762         "System.String::.ctor(sbyte*,int,int)", ves_icall_System_String_ctor_sbytep_int_int,
2763         "System.String::.ctor(sbyte*,int,int,System.Text.Encoding)", ves_icall_System_String_ctor_encoding,
2764         "System.String::.ctor(char[])", ves_icall_System_String_ctor_chara,
2765         "System.String::.ctor(char[],int,int)", ves_icall_System_String_ctor_chara_int_int,
2766         "System.String::.ctor(char,int)", ves_icall_System_String_ctor_char_int,
2767         "System.String::InternalEquals", ves_icall_System_String_InternalEquals,
2768         "System.String::InternalJoin", ves_icall_System_String_InternalJoin,
2769         "System.String::InternalInsert", ves_icall_System_String_InternalInsert,
2770         "System.String::InternalReplace(char,char)", ves_icall_System_String_InternalReplace_Char,
2771         "System.String::InternalReplace(string,string)", ves_icall_System_String_InternalReplace_Str,
2772         "System.String::InternalRemove", ves_icall_System_String_InternalRemove,
2773         "System.String::InternalCopyTo", ves_icall_System_String_InternalCopyTo,
2774         "System.String::InternalSplit", ves_icall_System_String_InternalSplit,
2775         "System.String::InternalTrim", ves_icall_System_String_InternalTrim,
2776         "System.String::InternalIndexOf(char,int,int)", ves_icall_System_String_InternalIndexOf_Char,
2777         "System.String::InternalIndexOf(string,int,int)", ves_icall_System_String_InternalIndexOf_Str,
2778         "System.String::InternalIndexOfAny", ves_icall_System_String_InternalIndexOfAny,
2779         "System.String::InternalLastIndexOf(char,int,int)", ves_icall_System_String_InternalLastIndexOf_Char,
2780         "System.String::InternalLastIndexOf(string,int,int)", ves_icall_System_String_InternalLastIndexOf_Str,
2781         "System.String::InternalLastIndexOfAny", ves_icall_System_String_InternalLastIndexOfAny,
2782         "System.String::InternalPad", ves_icall_System_String_InternalPad,
2783         "System.String::InternalToLower", ves_icall_System_String_InternalToLower,
2784         "System.String::InternalToUpper", ves_icall_System_String_InternalToUpper,
2785         "System.String::InternalAllocateStr", ves_icall_System_String_InternalAllocateStr,
2786         "System.String::InternalStrcpy(string,int,string)", ves_icall_System_String_InternalStrcpy_Str,
2787         "System.String::InternalStrcpy(string,int,string,int,int)", ves_icall_System_String_InternalStrcpy_StrN,
2788         "System.String::InternalIntern", ves_icall_System_String_InternalIntern,
2789         "System.String::InternalIsInterned", ves_icall_System_String_InternalIsInterned,
2790         "System.String::InternalCompare(string,int,string,int,int,bool)", ves_icall_System_String_InternalCompareStr_N,
2791         "System.String::GetHashCode", ves_icall_System_String_GetHashCode,
2792         "System.String::get_Chars", ves_icall_System_String_get_Chars,
2793
2794         /*
2795          * System.AppDomain
2796          */
2797         "System.AppDomain::createDomain", ves_icall_System_AppDomain_createDomain,
2798         "System.AppDomain::getCurDomain", ves_icall_System_AppDomain_getCurDomain,
2799         "System.AppDomain::GetData", ves_icall_System_AppDomain_GetData,
2800         "System.AppDomain::SetData", ves_icall_System_AppDomain_SetData,
2801         "System.AppDomain::getSetup", ves_icall_System_AppDomain_getSetup,
2802         "System.AppDomain::getFriendlyName", ves_icall_System_AppDomain_getFriendlyName,
2803         "System.AppDomain::GetAssemblies", ves_icall_System_AppDomain_GetAssemblies,
2804         "System.AppDomain::LoadAssembly", ves_icall_System_AppDomain_LoadAssembly,
2805         "System.AppDomain::Unload", ves_icall_System_AppDomain_Unload,
2806         "System.AppDomain::ExecuteAssembly", ves_icall_System_AppDomain_ExecuteAssembly,
2807
2808         /*
2809          * System.AppDomainSetup
2810          */
2811         "System.AppDomainSetup::InitAppDomainSetup", ves_icall_System_AppDomainSetup_InitAppDomainSetup,
2812
2813         /*
2814          * System.Double
2815          */
2816         "System.Double::ToStringImpl", mono_double_ToStringImpl,
2817         "System.Double::ParseImpl",    mono_double_ParseImpl,
2818
2819         /*
2820          * System.Single
2821          */
2822         "System.Single::ToStringImpl", mono_float_ToStringImpl,
2823
2824         /*
2825          * System.Decimal
2826          */
2827         "System.Decimal::decimal2UInt64", mono_decimal2UInt64,
2828         "System.Decimal::decimal2Int64", mono_decimal2Int64,
2829         "System.Decimal::double2decimal", mono_double2decimal, /* FIXME: wrong signature. */
2830         "System.Decimal::decimalIncr", mono_decimalIncr,
2831         "System.Decimal::decimalSetExponent", mono_decimalSetExponent,
2832         "System.Decimal::decimal2double", mono_decimal2double,
2833         "System.Decimal::decimalFloorAndTrunc", mono_decimalFloorAndTrunc,
2834         "System.Decimal::decimalRound", mono_decimalRound,
2835         "System.Decimal::decimalMult", mono_decimalMult,
2836         "System.Decimal::decimalDiv", mono_decimalDiv,
2837         "System.Decimal::decimalIntDiv", mono_decimalIntDiv,
2838         "System.Decimal::decimalCompare", mono_decimalCompare,
2839         "System.Decimal::string2decimal", mono_string2decimal,
2840         "System.Decimal::decimal2string", mono_decimal2string,
2841
2842         /*
2843          * ModuleBuilder
2844          */
2845         "System.Reflection.Emit.ModuleBuilder::create_modified_type", ves_icall_ModuleBuilder_create_modified_type,
2846         
2847         /*
2848          * AssemblyBuilder
2849          */
2850         "System.Reflection.Emit.AssemblyBuilder::getDataChunk", ves_icall_AssemblyBuilder_getDataChunk,
2851         "System.Reflection.Emit.AssemblyBuilder::getUSIndex", mono_image_insert_string,
2852         "System.Reflection.Emit.AssemblyBuilder::getToken", ves_icall_AssemblyBuilder_getToken,
2853         "System.Reflection.Emit.AssemblyBuilder::basic_init", mono_image_basic_init,
2854
2855         /*
2856          * Reflection stuff.
2857          */
2858         "System.Reflection.MonoMethodInfo::get_method_info", ves_icall_get_method_info,
2859         "System.Reflection.MonoMethodInfo::get_parameter_info", ves_icall_get_parameter_info,
2860         "System.Reflection.MonoFieldInfo::get_field_info", ves_icall_get_field_info,
2861         "System.Reflection.MonoPropertyInfo::get_property_info", ves_icall_get_property_info,
2862         "System.Reflection.MonoEventInfo::get_event_info", ves_icall_get_event_info,
2863         "System.Reflection.MonoMethod::InternalInvoke", ves_icall_InternalInvoke,
2864         "System.Reflection.MonoCMethod::InternalInvoke", ves_icall_InternalInvoke,
2865         "System.Reflection.MethodBase::GetCurrentMethod", ves_icall_GetCurrentMethod,
2866         "System.MonoCustomAttrs::GetCustomAttributes", mono_reflection_get_custom_attrs,
2867         "System.Reflection.Emit.CustomAttributeBuilder::GetBlob", mono_reflection_get_custom_attrs_blob,
2868         "System.Reflection.MonoField::GetValueInternal", ves_icall_MonoField_GetValueInternal,
2869         "System.Reflection.MonoField::SetValueInternal", ves_icall_FieldInfo_SetValueInternal,
2870         "System.Reflection.Emit.SignatureHelper::get_signature_local", mono_reflection_sighelper_get_signature_local,
2871         "System.Reflection.Emit.SignatureHelper::get_signature_field", mono_reflection_sighelper_get_signature_field,
2872
2873         "System.RuntimeMethodHandle::GetFunctionPointer", ves_icall_RuntimeMethod_GetFunctionPointer,
2874         
2875         /* System.Enum */
2876
2877         "System.MonoEnumInfo::get_enum_info", ves_icall_get_enum_info,
2878         "System.Enum::get_value", ves_icall_System_Enum_get_value,
2879         "System.Enum::ToObject", ves_icall_System_Enum_ToObject,
2880
2881         /*
2882          * TypeBuilder
2883          */
2884         "System.Reflection.Emit.TypeBuilder::setup_internal_class", mono_reflection_setup_internal_class,
2885         "System.Reflection.Emit.TypeBuilder::create_internal_class", mono_reflection_create_internal_class,
2886         "System.Reflection.Emit.TypeBuilder::create_runtime_class", mono_reflection_create_runtime_class,
2887         
2888         /*
2889          * MethodBuilder
2890          */
2891         
2892         /*
2893          * System.Type
2894          */
2895         "System.Type::internal_from_name", ves_icall_type_from_name,
2896         "System.Type::internal_from_handle", ves_icall_type_from_handle,
2897         "System.MonoType::get_attributes", ves_icall_get_attributes,
2898         "System.Type::type_is_subtype_of", ves_icall_type_is_subtype_of,
2899         "System.Type::Equals", ves_icall_type_Equals,
2900         "System.Type::GetTypeCode", ves_icall_type_GetTypeCode,
2901
2902         /*
2903          * System.Runtime.CompilerServices.RuntimeHelpers
2904          */
2905         "System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray,
2906         "System.Runtime.CompilerServices.RuntimeHelpers::GetOffsetToStringData", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData,
2907         "System.Runtime.CompilerServices.RuntimeHelpers::GetObjectValue", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue,
2908         "System.Runtime.CompilerServices.RuntimeHelpers::RunClassConstructor", ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor,
2909         
2910         /*
2911          * System.Threading
2912          */
2913         "System.Threading.Thread::Abort(object)", ves_icall_System_Threading_Thread_Abort,
2914         "System.Threading.Thread::ResetAbort", ves_icall_System_Threading_Thread_ResetAbort,
2915         "System.Threading.Thread::Thread_internal", ves_icall_System_Threading_Thread_Thread_internal,
2916         "System.Threading.Thread::Thread_free_internal", ves_icall_System_Threading_Thread_Thread_free_internal,
2917         "System.Threading.Thread::Start_internal", ves_icall_System_Threading_Thread_Start_internal,
2918         "System.Threading.Thread::Sleep_internal", ves_icall_System_Threading_Thread_Sleep_internal,
2919         "System.Threading.Thread::CurrentThread_internal", mono_thread_current,
2920         "System.Threading.Thread::Join_internal", ves_icall_System_Threading_Thread_Join_internal,
2921         "System.Threading.Thread::SlotHash_lookup", ves_icall_System_Threading_Thread_SlotHash_lookup,
2922         "System.Threading.Thread::SlotHash_store", ves_icall_System_Threading_Thread_SlotHash_store,
2923         "System.Threading.Thread::GetDomainID", ves_icall_System_Threading_Thread_GetDomainID,
2924         "System.Threading.Monitor::Monitor_exit", ves_icall_System_Threading_Monitor_Monitor_exit,
2925         "System.Threading.Monitor::Monitor_test_owner", ves_icall_System_Threading_Monitor_Monitor_test_owner,
2926         "System.Threading.Monitor::Monitor_test_synchronised", ves_icall_System_Threading_Monitor_Monitor_test_synchronised,
2927         "System.Threading.Monitor::Monitor_pulse", ves_icall_System_Threading_Monitor_Monitor_pulse,
2928         "System.Threading.Monitor::Monitor_pulse_all", ves_icall_System_Threading_Monitor_Monitor_pulse_all,
2929         "System.Threading.Monitor::Monitor_try_enter", ves_icall_System_Threading_Monitor_Monitor_try_enter,
2930         "System.Threading.Monitor::Monitor_wait", ves_icall_System_Threading_Monitor_Monitor_wait,
2931         "System.Threading.Mutex::CreateMutex_internal", ves_icall_System_Threading_Mutex_CreateMutex_internal,
2932         "System.Threading.Mutex::ReleaseMutex_internal", ves_icall_System_Threading_Mutex_ReleaseMutex_internal,
2933         "System.Threading.NativeEventCalls::CreateEvent_internal", ves_icall_System_Threading_Events_CreateEvent_internal,
2934         "System.Threading.NativeEventCalls::SetEvent_internal",    ves_icall_System_Threading_Events_SetEvent_internal,
2935         "System.Threading.NativeEventCalls::ResetEvent_internal",  ves_icall_System_Threading_Events_ResetEvent_internal,
2936
2937         /*
2938          * System.Threading.WaitHandle
2939          */
2940         "System.Threading.WaitHandle::WaitAll_internal", ves_icall_System_Threading_WaitHandle_WaitAll_internal,
2941         "System.Threading.WaitHandle::WaitAny_internal", ves_icall_System_Threading_WaitHandle_WaitAny_internal,
2942         "System.Threading.WaitHandle::WaitOne_internal", ves_icall_System_Threading_WaitHandle_WaitOne_internal,
2943
2944         /*
2945          * System.Runtime.InteropServices.Marshal
2946          */
2947         "System.Runtime.InteropServices.Marshal::ReadIntPtr", ves_icall_System_Runtime_InteropServices_Marshal_ReadIntPtr,
2948         "System.Runtime.InteropServices.Marshal::ReadByte", ves_icall_System_Runtime_InteropServices_Marshal_ReadByte,
2949         "System.Runtime.InteropServices.Marshal::ReadInt16", ves_icall_System_Runtime_InteropServices_Marshal_ReadInt16,
2950         "System.Runtime.InteropServices.Marshal::ReadInt32", ves_icall_System_Runtime_InteropServices_Marshal_ReadInt32,
2951         "System.Runtime.InteropServices.Marshal::ReadInt64", ves_icall_System_Runtime_InteropServices_Marshal_ReadInt64,
2952         "System.Runtime.InteropServices.Marshal::WriteIntPtr", ves_icall_System_Runtime_InteropServices_Marshal_WriteIntPtr,
2953         "System.Runtime.InteropServices.Marshal::WriteByte", ves_icall_System_Runtime_InteropServices_Marshal_WriteByte,
2954         "System.Runtime.InteropServices.Marshal::WriteInt16", ves_icall_System_Runtime_InteropServices_Marshal_WriteInt16,
2955         "System.Runtime.InteropServices.Marshal::WriteInt32", ves_icall_System_Runtime_InteropServices_Marshal_WriteInt32,
2956         "System.Runtime.InteropServices.Marshal::WriteInt64", ves_icall_System_Runtime_InteropServices_Marshal_WriteInt64,
2957
2958         "System.Runtime.InteropServices.Marshal::PtrToStringAnsi(intptr)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi,
2959         "System.Runtime.InteropServices.Marshal::PtrToStringAnsi(intptr,int)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len,
2960         "System.Runtime.InteropServices.Marshal::PtrToStringAuto(intptr)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi,
2961         "System.Runtime.InteropServices.Marshal::PtrToStringAuto(intptr,int)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len,
2962         "System.Runtime.InteropServices.Marshal::PtrToStringUni(intptr)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni,
2963         "System.Runtime.InteropServices.Marshal::PtrToStringUni(intptr,int)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len,
2964         "System.Runtime.InteropServices.Marshal::PtrToStringBSTR", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringBSTR,
2965
2966         "System.Runtime.InteropServices.Marshal::GetLastWin32Error", ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error,
2967         "System.Runtime.InteropServices.Marshal::AllocHGlobal", mono_marshal_alloc,
2968         "System.Runtime.InteropServices.Marshal::FreeHGlobal", mono_marshal_free,
2969         "System.Runtime.InteropServices.Marshal::ReAllocHGlobal", mono_marshal_realloc,
2970         "System.Runtime.InteropServices.Marshal::copy_to_unmanaged", ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged,
2971         "System.Runtime.InteropServices.Marshal::copy_from_unmanaged", ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged,
2972         "System.Runtime.InteropServices.Marshal::SizeOf", ves_icall_System_Runtime_InteropServices_Marshal_SizeOf,
2973         "System.Runtime.InteropServices.Marshal::StructureToPtr", ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr,
2974         "System.Runtime.InteropServices.Marshal::PtrToStructure(intptr,object)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure,
2975         "System.Runtime.InteropServices.Marshal::PtrToStructure(intptr,System.Type)", ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type,
2976         "System.Runtime.InteropServices.Marshal::OffsetOf", ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf,
2977         "System.Runtime.InteropServices.Marshal::StringToHGlobalAnsi", ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi,
2978         "System.Runtime.InteropServices.Marshal::StringToHGlobalAuto", ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi,
2979         "System.Runtime.InteropServices.Marshal::StringToHGlobalUni", ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni,
2980         "System.Runtime.InteropServices.Marshal::DestroyStructure", ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure,
2981
2982
2983         "System.Reflection.Assembly::LoadFrom", ves_icall_System_Reflection_Assembly_LoadFrom,
2984         "System.Reflection.Assembly::InternalGetType", ves_icall_System_Reflection_Assembly_InternalGetType,
2985         "System.Reflection.Assembly::GetTypes", ves_icall_System_Reflection_Assembly_GetTypes,
2986         "System.Reflection.Assembly::FillName", ves_icall_System_Reflection_Assembly_FillName,
2987         "System.Reflection.Assembly::get_code_base", ves_icall_System_Reflection_Assembly_get_code_base,
2988         "System.Reflection.Assembly::get_location", ves_icall_System_Reflection_Assembly_get_location,
2989         "System.Reflection.Assembly::GetExecutingAssembly", ves_icall_System_Reflection_Assembly_GetExecutingAssembly,
2990         "System.Reflection.Assembly::GetEntryAssembly", ves_icall_System_Reflection_Assembly_GetEntryAssembly,
2991         "System.Reflection.Assembly::GetCallingAssembly", ves_icall_System_Reflection_Assembly_GetCallingAssembly,
2992         "System.Reflection.Assembly::get_EntryPoint", ves_icall_System_Reflection_Assembly_get_EntryPoint,
2993         "System.Reflection.Assembly::GetManifestResourceNames", ves_icall_System_Reflection_Assembly_GetManifestResourceNames,
2994         "System.Reflection.Assembly::GetManifestResourceInternal", ves_icall_System_Reflection_Assembly_GetManifestResourceInternal,
2995         "System.Reflection.Assembly::GetFilesInternal", ves_icall_System_Reflection_Assembly_GetFilesInternal,
2996         "System.Reflection.Assembly::GetReferencedAssemblies", ves_icall_System_Reflection_Assembly_GetReferencedAssemblies,
2997
2998         /*
2999          * System.MonoType.
3000          */
3001         "System.MonoType::getFullName", ves_icall_System_MonoType_getFullName,
3002         "System.MonoType::type_from_obj", mono_type_type_from_obj,
3003         "System.MonoType::GetElementType", ves_icall_MonoType_GetElementType,
3004         "System.MonoType::get_type_info", ves_icall_get_type_info,
3005         "System.MonoType::get_BaseType", ves_icall_get_type_parent,
3006         "System.MonoType::get_Module", ves_icall_MonoType_get_Module,
3007         "System.MonoType::IsPointerImpl", ves_icall_type_ispointer,
3008         "System.MonoType::IsByRefImpl", ves_icall_type_isbyref,
3009         "System.MonoType::GetField", ves_icall_Type_GetField,
3010         "System.MonoType::GetFields", ves_icall_Type_GetFields,
3011         "System.MonoType::GetMethods", ves_icall_Type_GetMethods,
3012         "System.MonoType::GetConstructors", ves_icall_Type_GetConstructors,
3013         "System.MonoType::GetProperties", ves_icall_Type_GetProperties,
3014         "System.MonoType::GetEvents", ves_icall_Type_GetEvents,
3015         "System.MonoType::InternalGetEvent", ves_icall_MonoType_GetEvent,
3016         "System.MonoType::GetInterfaces", ves_icall_Type_GetInterfaces,
3017         "System.MonoType::GetNestedTypes", ves_icall_Type_GetNestedTypes,
3018
3019         /*
3020          * System.Net.Sockets I/O Services
3021          */
3022         "System.Net.Sockets.Socket::Socket_internal", ves_icall_System_Net_Sockets_Socket_Socket_internal,
3023         "System.Net.Sockets.Socket::Close_internal", ves_icall_System_Net_Sockets_Socket_Close_internal,
3024         "System.Net.Sockets.SocketException::WSAGetLastError_internal", ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal,
3025         "System.Net.Sockets.Socket::Available_internal", ves_icall_System_Net_Sockets_Socket_Available_internal,
3026         "System.Net.Sockets.Socket::Blocking_internal", ves_icall_System_Net_Sockets_Socket_Blocking_internal,
3027         "System.Net.Sockets.Socket::Accept_internal", ves_icall_System_Net_Sockets_Socket_Accept_internal,
3028         "System.Net.Sockets.Socket::Listen_internal", ves_icall_System_Net_Sockets_Socket_Listen_internal,
3029         "System.Net.Sockets.Socket::LocalEndPoint_internal", ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal,
3030         "System.Net.Sockets.Socket::RemoteEndPoint_internal", ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal,
3031         "System.Net.Sockets.Socket::Bind_internal", ves_icall_System_Net_Sockets_Socket_Bind_internal,
3032         "System.Net.Sockets.Socket::Connect_internal", ves_icall_System_Net_Sockets_Socket_Connect_internal,
3033         "System.Net.Sockets.Socket::Receive_internal", ves_icall_System_Net_Sockets_Socket_Receive_internal,
3034         "System.Net.Sockets.Socket::RecvFrom_internal", ves_icall_System_Net_Sockets_Socket_RecvFrom_internal,
3035         "System.Net.Sockets.Socket::Send_internal", ves_icall_System_Net_Sockets_Socket_Send_internal,
3036         "System.Net.Sockets.Socket::SendTo_internal", ves_icall_System_Net_Sockets_Socket_SendTo_internal,
3037         "System.Net.Sockets.Socket::Select_internal", ves_icall_System_Net_Sockets_Socket_Select_internal,
3038         "System.Net.Sockets.Socket::Shutdown_internal", ves_icall_System_Net_Sockets_Socket_Shutdown_internal,
3039         "System.Net.Sockets.Socket::GetSocketOption_obj_internal", ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal,
3040         "System.Net.Sockets.Socket::GetSocketOption_arr_internal", ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal,
3041         "System.Net.Sockets.Socket::SetSocketOption_internal", ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal,
3042         "System.Net.Dns::GetHostByName_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByName_internal,
3043         "System.Net.Dns::GetHostByAddr_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByAddr_internal,
3044         "System.Net.Dns::GetHostName_internal(string&)", ves_icall_System_Net_Dns_GetHostName_internal,
3045
3046         /*
3047          * System.Char
3048          */
3049         "System.Char::GetNumericValue", ves_icall_System_Char_GetNumericValue,
3050         "System.Char::GetUnicodeCategory", ves_icall_System_Char_GetUnicodeCategory,
3051         "System.Char::IsControl", ves_icall_System_Char_IsControl,
3052         "System.Char::IsDigit", ves_icall_System_Char_IsDigit,
3053         "System.Char::IsLetter", ves_icall_System_Char_IsLetter,
3054         "System.Char::IsLower", ves_icall_System_Char_IsLower,
3055         "System.Char::IsUpper", ves_icall_System_Char_IsUpper,
3056         "System.Char::IsNumber", ves_icall_System_Char_IsNumber,
3057         "System.Char::IsPunctuation", ves_icall_System_Char_IsPunctuation,
3058         "System.Char::IsSeparator", ves_icall_System_Char_IsSeparator,
3059         "System.Char::IsSurrogate", ves_icall_System_Char_IsSurrogate,
3060         "System.Char::IsSymbol", ves_icall_System_Char_IsSymbol,
3061         "System.Char::IsWhiteSpace", ves_icall_System_Char_IsWhiteSpace,
3062         "System.Char::ToLower", ves_icall_System_Char_ToLower,
3063         "System.Char::ToUpper", ves_icall_System_Char_ToUpper,
3064
3065         /*
3066          * System.Text.Encoding
3067          */
3068         "System.Text.Encoding::InternalCodePage", ves_icall_System_Text_Encoding_InternalCodePage,
3069
3070         "System.DateTime::GetNow", ves_icall_System_DateTime_GetNow,
3071         "System.CurrentTimeZone::GetTimeZoneData", ves_icall_System_CurrentTimeZone_GetTimeZoneData,
3072
3073         /*
3074          * System.GC
3075          */
3076         "System.GC::InternalCollect", ves_icall_System_GC_InternalCollect,
3077         "System.GC::GetTotalMemory", ves_icall_System_GC_GetTotalMemory,
3078         "System.GC::KeepAlive", ves_icall_System_GC_KeepAlive,
3079         "System.GC::ReRegisterForFinalize", ves_icall_System_GC_ReRegisterForFinalize,
3080         "System.GC::SuppressFinalize", ves_icall_System_GC_SuppressFinalize,
3081         "System.GC::WaitForPendingFinalizers", ves_icall_System_GC_WaitForPendingFinalizers,
3082         "System.Runtime.InteropServices.GCHandle::GetTarget", ves_icall_System_GCHandle_GetTarget,
3083         "System.Runtime.InteropServices.GCHandle::GetTargetHandle", ves_icall_System_GCHandle_GetTargetHandle,
3084         "System.Runtime.InteropServices.GCHandle::FreeHandle", ves_icall_System_GCHandle_FreeHandle,
3085         "System.Runtime.InteropServices.GCHandle::GetAddrOfPinnedObject", ves_icall_System_GCHandle_GetAddrOfPinnedObject,
3086
3087         /*
3088          * System.Security.Cryptography calls
3089          */
3090
3091          "System.Security.Cryptography.RNGCryptoServiceProvider::GetBytes", ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_GetBytes,
3092          "System.Security.Cryptography.RNGCryptoServiceProvider::GetNonZeroBytes", ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_GetNonZeroBytes,
3093         
3094         /*
3095          * System.Buffer
3096          */
3097         "System.Buffer::ByteLengthInternal", ves_icall_System_Buffer_ByteLengthInternal,
3098         "System.Buffer::GetByteInternal", ves_icall_System_Buffer_GetByteInternal,
3099         "System.Buffer::SetByteInternal", ves_icall_System_Buffer_SetByteInternal,
3100         "System.Buffer::BlockCopyInternal", ves_icall_System_Buffer_BlockCopyInternal,
3101
3102         /*
3103          * System.IO.MonoIO
3104          */
3105         "System.IO.MonoIO::CreateDirectory(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_CreateDirectory,
3106         "System.IO.MonoIO::RemoveDirectory(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_RemoveDirectory,
3107         "System.IO.MonoIO::FindFirstFile(string,System.IO.MonoIOStat&,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_FindFirstFile,
3108         "System.IO.MonoIO::FindNextFile(intptr,System.IO.MonoIOStat&,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_FindNextFile,
3109         "System.IO.MonoIO::FindClose(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_FindClose,
3110         "System.IO.MonoIO::GetCurrentDirectory(System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetCurrentDirectory,
3111         "System.IO.MonoIO::SetCurrentDirectory(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetCurrentDirectory,
3112         "System.IO.MonoIO::MoveFile(string,string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_MoveFile,
3113         "System.IO.MonoIO::CopyFile(string,string,bool,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_CopyFile,
3114         "System.IO.MonoIO::DeleteFile(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_DeleteFile,
3115         "System.IO.MonoIO::GetFileAttributes(string,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetFileAttributes,
3116         "System.IO.MonoIO::SetFileAttributes(string,System.IO.FileAttributes,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetFileAttributes,
3117         "System.IO.MonoIO::GetFileType(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetFileType,
3118         "System.IO.MonoIO::GetFileStat(string,System.IO.MonoIOStat&,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetFileStat,
3119         "System.IO.MonoIO::Open(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Open,
3120         "System.IO.MonoIO::Close(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Close,
3121         "System.IO.MonoIO::Read(intptr,byte[],int,int,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Read,
3122         "System.IO.MonoIO::Write(intptr,byte[],int,int,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Write,
3123         "System.IO.MonoIO::Seek(intptr,long,System.IO.SeekOrigin,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Seek,
3124         "System.IO.MonoIO::GetLength(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_GetLength,
3125         "System.IO.MonoIO::SetLength(intptr,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetLength,
3126         "System.IO.MonoIO::SetFileTime(intptr,long,long,long,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_SetFileTime,
3127         "System.IO.MonoIO::Flush(intptr,System.IO.MonoIOError&)", ves_icall_System_IO_MonoIO_Flush,
3128         "System.IO.MonoIO::get_ConsoleOutput", ves_icall_System_IO_MonoIO_get_ConsoleOutput,
3129         "System.IO.MonoIO::get_ConsoleInput", ves_icall_System_IO_MonoIO_get_ConsoleInput,
3130         "System.IO.MonoIO::get_ConsoleError", ves_icall_System_IO_MonoIO_get_ConsoleError,
3131         "System.IO.MonoIO::CreatePipe(intptr&,intptr&)", ves_icall_System_IO_MonoIO_CreatePipe,
3132         "System.IO.MonoIO::get_VolumeSeparatorChar", ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar,
3133         "System.IO.MonoIO::get_DirectorySeparatorChar", ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar,
3134         "System.IO.MonoIO::get_AltDirectorySeparatorChar", ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar,
3135         "System.IO.MonoIO::get_PathSeparator", ves_icall_System_IO_MonoIO_get_PathSeparator,
3136         "System.IO.MonoIO::get_InvalidPathChars", ves_icall_System_IO_MonoIO_get_InvalidPathChars,
3137
3138         /*
3139          * System.Math
3140          */
3141         "System.Math::Sin", ves_icall_System_Math_Sin,
3142     "System.Math::Cos", ves_icall_System_Math_Cos,
3143     "System.Math::Tan", ves_icall_System_Math_Tan,
3144     "System.Math::Sinh", ves_icall_System_Math_Sinh,
3145     "System.Math::Cosh", ves_icall_System_Math_Cosh,
3146     "System.Math::Tanh", ves_icall_System_Math_Tanh,
3147     "System.Math::Acos", ves_icall_System_Math_Acos,
3148     "System.Math::Asin", ves_icall_System_Math_Asin,
3149     "System.Math::Atan", ves_icall_System_Math_Atan,
3150     "System.Math::Atan2", ves_icall_System_Math_Atan2,
3151     "System.Math::Exp", ves_icall_System_Math_Exp,
3152     "System.Math::Log", ves_icall_System_Math_Log,
3153     "System.Math::Log10", ves_icall_System_Math_Log10,
3154     "System.Math::PowImpl", ves_icall_System_Math_Pow,
3155     "System.Math::Sqrt", ves_icall_System_Math_Sqrt,
3156
3157         /*
3158          * System.Environment
3159          */
3160         "System.Environment::get_MachineName", ves_icall_System_Environment_get_MachineName,
3161         "System.Environment::get_NewLine", ves_icall_System_Environment_get_NewLine,
3162         "System.Environment::GetEnvironmentVariable", ves_icall_System_Environment_GetEnvironmentVariable,
3163         "System.Environment::GetEnvironmentVariableNames", ves_icall_System_Environment_GetEnvironmentVariableNames,
3164         "System.Environment::GetCommandLineArgs", mono_runtime_get_main_args,
3165         "System.Environment::get_TickCount", ves_icall_System_Environment_get_TickCount,
3166         "System.Environment::Exit", ves_icall_System_Environment_Exit,
3167         "System.Environment::get_Platform", ves_icall_System_Environment_get_Platform,
3168
3169         /*
3170          * System.Runtime.Remoting
3171          */     
3172         "System.Runtime.Remoting.RemotingServices::InternalExecute",
3173         ves_icall_InternalExecute,
3174         "System.Runtime.Remoting.RemotingServices::IsTransparentProxy",
3175         ves_icall_IsTransparentProxy,
3176
3177         /*
3178          * System.Runtime.Remoting.Messaging
3179          */     
3180         "System.Runtime.Remoting.Messaging.MonoMethodMessage::InitMessage",
3181         ves_icall_MonoMethodMessage_InitMessage,
3182         
3183         /*
3184          * System.Runtime.Remoting.Proxies
3185          */     
3186         "System.Runtime.Remoting.Proxies.RealProxy::GetTransparentProxy", 
3187         ves_icall_Remoting_RealProxy_GetTransparentProxy,
3188
3189         /*
3190          * System.Threading.Interlocked
3191          */
3192         "System.Threading.Interlocked::Increment(int&)", ves_icall_System_Threading_Interlocked_Increment_Int,
3193         "System.Threading.Interlocked::Increment(long&)", ves_icall_System_Threading_Interlocked_Increment_Long,
3194         "System.Threading.Interlocked::Decrement(int&)", ves_icall_System_Threading_Interlocked_Decrement_Int,
3195         "System.Threading.Interlocked::Decrement(long&)", ves_icall_System_Threading_Interlocked_Decrement_Long,
3196         "System.Threading.Interlocked::CompareExchange(int&,int,int)", ves_icall_System_Threading_Interlocked_CompareExchange_Int,
3197         "System.Threading.Interlocked::CompareExchange(object&,object,object)", ves_icall_System_Threading_Interlocked_CompareExchange_Object,
3198         "System.Threading.Interlocked::CompareExchange(single&,single,single)", ves_icall_System_Threading_Interlocked_CompareExchange_Single,
3199         "System.Threading.Interlocked::Exchange(int&,int)", ves_icall_System_Threading_Interlocked_Exchange_Int,
3200         "System.Threading.Interlocked::Exchange(object&,object)", ves_icall_System_Threading_Interlocked_Exchange_Object,
3201         "System.Threading.Interlocked::Exchange(single&,single)", ves_icall_System_Threading_Interlocked_Exchange_Single,
3202
3203         /*
3204          * System.Diagnostics.Process
3205          */
3206         "System.Diagnostics.Process::GetProcess_internal(int)", ves_icall_System_Diagnostics_Process_GetProcess_internal,
3207         "System.Diagnostics.Process::GetProcesses_internal()", ves_icall_System_Diagnostics_Process_GetProcesses_internal,
3208         "System.Diagnostics.Process::GetPid_internal()", ves_icall_System_Diagnostics_Process_GetPid_internal,
3209         "System.Diagnostics.Process::Process_free_internal(intptr)", ves_icall_System_Diagnostics_Process_Process_free_internal,
3210         "System.Diagnostics.Process::GetModules_internal()", ves_icall_System_Diagnostics_Process_GetModules_internal,
3211         "System.Diagnostics.Process::Start_internal(string,string,intptr,intptr,intptr,ProcInfo&)", ves_icall_System_Diagnostics_Process_Start_internal,
3212         "System.Diagnostics.Process::WaitForExit_internal(intptr,int)", ves_icall_System_Diagnostics_Process_WaitForExit_internal,
3213         "System.Diagnostics.Process::ExitTime_internal(intptr)", ves_icall_System_Diagnostics_Process_ExitTime_internal,
3214         "System.Diagnostics.Process::StartTime_internal(intptr)", ves_icall_System_Diagnostics_Process_StartTime_internal,
3215         "System.Diagnostics.Process::ExitCode_internal(intptr)", ves_icall_System_Diagnostics_Process_ExitCode_internal,
3216         "System.Diagnostics.Process::ProcessName_internal(intptr)", ves_icall_System_Diagnostics_Process_ProcessName_internal,
3217         "System.Diagnostics.Process::GetWorkingSet_internal(intptr,int&,int&)", ves_icall_System_Diagnostics_Process_GetWorkingSet_internal,
3218         "System.Diagnostics.Process::SetWorkingSet_internal(intptr,int,int,bool)", ves_icall_System_Diagnostics_Process_SetWorkingSet_internal,
3219         "System.Diagnostics.FileVersionInfo::GetVersionInfo_internal(string)", ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal,
3220
3221         /* 
3222          * System.Delegate
3223          */
3224         "System.Delegate::CreateDelegate_internal", ves_icall_System_Delegate_CreateDelegate_internal,
3225
3226         /* 
3227          * System.Runtime.Serialization
3228          */
3229         "System.Runtime.Serialization.FormatterServices::GetUninitializedObjectInternal",
3230         ves_icall_System_Runtime_Serialization_FormatterServices_GetUninitializedObject_Internal,
3231
3232         /*
3233          * System.IO.Path
3234          */
3235         "System.IO.Path::get_temp_path", ves_icall_System_IO_get_temp_path,
3236
3237         /*
3238          * Private icalls for the Mono Debugger
3239          */
3240         "System.Reflection.Assembly::MonoDebugger_GetMethod",
3241         ves_icall_MonoDebugger_GetMethod,
3242
3243         "System.Reflection.Assembly::MonoDebugger_GetLocalTypeFromSignature",
3244         ves_icall_MonoDebugger_GetLocalTypeFromSignature,
3245
3246         "System.Reflection.Assembly::MonoDebugger_GetType",
3247         ves_icall_MonoDebugger_GetType,
3248
3249         /*
3250          * System.Configuration
3251          */
3252         "System.Configuration.DefaultConfig::get_machine_config_path",
3253         ves_icall_System_Configuration_DefaultConfig_get_machine_config_path,
3254
3255         /*
3256          * add other internal calls here
3257          */
3258         NULL, NULL
3259 };
3260
3261 void
3262 mono_init_icall (void)
3263 {
3264         const char *name;
3265         int i = 0;
3266
3267         while ((name = icall_map [i])) {
3268                 mono_add_internal_call (name, icall_map [i+1]);
3269                 i += 2;
3270         }
3271        
3272 }
3273
3274